civetweb.c 566 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121
  1. /* Copyright (c) 2013-2020 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE 8096
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #ifndef DEBUG_TRACE_STREAM
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. /********************************************************************/
  369. /* CivetWeb configuration defines */
  370. /********************************************************************/
  371. /* Maximum number of threads that can be configured.
  372. * The number of threads actually created depends on the "num_threads"
  373. * configuration parameter, but this is the upper limit. */
  374. #if !defined(MAX_WORKER_THREADS)
  375. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  376. #endif
  377. /* Timeout interval for select/poll calls.
  378. * The timeouts depend on "*_timeout_ms" configuration values, but long
  379. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  380. * This reduces the time required to stop the server. */
  381. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  382. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  383. #endif
  384. /* Do not try to compress files smaller than this limit. */
  385. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  386. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  387. #endif
  388. #if !defined(PASSWORDS_FILE_NAME)
  389. #define PASSWORDS_FILE_NAME ".htpasswd"
  390. #endif
  391. /* Initial buffer size for all CGI environment variables. In case there is
  392. * not enough space, another block is allocated. */
  393. #if !defined(CGI_ENVIRONMENT_SIZE)
  394. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  395. #endif
  396. /* Maximum number of environment variables. */
  397. #if !defined(MAX_CGI_ENVIR_VARS)
  398. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  399. #endif
  400. /* General purpose buffer size. */
  401. #if !defined(MG_BUF_LEN) /* in bytes */
  402. #define MG_BUF_LEN (1024 * 8)
  403. #endif
  404. /********************************************************************/
  405. /* Helper makros */
  406. #if !defined(ARRAY_SIZE)
  407. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  408. #endif
  409. #include <stdint.h>
  410. /* Standard defines */
  411. #if !defined(INT64_MAX)
  412. #define INT64_MAX (9223372036854775807)
  413. #endif
  414. #define SHUTDOWN_RD (0)
  415. #define SHUTDOWN_WR (1)
  416. #define SHUTDOWN_BOTH (2)
  417. mg_static_assert(MAX_WORKER_THREADS >= 1,
  418. "worker threads must be a positive number");
  419. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  420. "size_t data type size check");
  421. #if defined(_WIN32) /* WINDOWS include block */
  422. #include <malloc.h> /* *alloc( */
  423. #include <stdlib.h> /* *alloc( */
  424. #include <time.h> /* struct timespec */
  425. #include <windows.h>
  426. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  427. #include <ws2tcpip.h>
  428. typedef const char *SOCK_OPT_TYPE;
  429. #if !defined(PATH_MAX)
  430. #define W_PATH_MAX (MAX_PATH)
  431. /* at most three UTF-8 chars per wchar_t */
  432. #define PATH_MAX (W_PATH_MAX * 3)
  433. #else
  434. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  435. #endif
  436. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  437. #if !defined(_IN_PORT_T)
  438. #if !defined(in_port_t)
  439. #define in_port_t u_short
  440. #endif
  441. #endif
  442. #if !defined(_WIN32_WCE)
  443. #include <direct.h>
  444. #include <io.h>
  445. #include <process.h>
  446. #else /* _WIN32_WCE */
  447. #define NO_CGI /* WinCE has no pipes */
  448. #define NO_POPEN /* WinCE has no popen */
  449. typedef long off_t;
  450. #define errno ((int)(GetLastError()))
  451. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  452. #endif /* _WIN32_WCE */
  453. #define MAKEUQUAD(lo, hi) \
  454. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  455. #define RATE_DIFF (10000000) /* 100 nsecs */
  456. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  457. #define SYS2UNIX_TIME(lo, hi) \
  458. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  459. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  460. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  461. * Also use _strtoui64 on modern M$ compilers */
  462. #if defined(_MSC_VER)
  463. #if (_MSC_VER < 1300)
  464. #define STRX(x) #x
  465. #define STR(x) STRX(x)
  466. #define __func__ __FILE__ ":" STR(__LINE__)
  467. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  468. #define strtoll(x, y, z) (_atoi64(x))
  469. #else
  470. #define __func__ __FUNCTION__
  471. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  472. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  473. #endif
  474. #endif /* _MSC_VER */
  475. #define ERRNO ((int)(GetLastError()))
  476. #define NO_SOCKLEN_T
  477. #if defined(_WIN64) || defined(__MINGW64__)
  478. #if !defined(SSL_LIB)
  479. #if defined(OPENSSL_API_1_1)
  480. #define SSL_LIB "libssl-1_1-x64.dll"
  481. #else /* OPENSSL_API_1_1 */
  482. #define SSL_LIB "ssleay64.dll"
  483. #endif /* OPENSSL_API_1_1 */
  484. #endif /* SSL_LIB */
  485. #if !defined(CRYPTO_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  488. #else /* OPENSSL_API_1_1 */
  489. #define CRYPTO_LIB "libeay64.dll"
  490. #endif /* OPENSSL_API_1_1 */
  491. #endif /* CRYPTO_LIB */
  492. #else /* defined(_WIN64) || defined(__MINGW64__) */
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1.dll"
  496. #else
  497. #define SSL_LIB "ssleay32.dll"
  498. #endif
  499. #endif /* SSL_LIB */
  500. #if !defined(CRYPTO_LIB)
  501. #if defined(OPENSSL_API_1_1)
  502. #define CRYPTO_LIB "libcrypto-1_1.dll"
  503. #else
  504. #define CRYPTO_LIB "libeay32.dll"
  505. #endif
  506. #endif /* CRYPTO_LIB */
  507. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  508. #define O_NONBLOCK (0)
  509. #if !defined(W_OK)
  510. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  511. #endif
  512. #define _POSIX_
  513. #define INT64_FMT "I64d"
  514. #define UINT64_FMT "I64u"
  515. #define WINCDECL __cdecl
  516. #define vsnprintf_impl _vsnprintf
  517. #define access _access
  518. #define mg_sleep(x) (Sleep(x))
  519. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  520. #if !defined(popen)
  521. #define popen(x, y) (_popen(x, y))
  522. #endif
  523. #if !defined(pclose)
  524. #define pclose(x) (_pclose(x))
  525. #endif
  526. #define close(x) (_close(x))
  527. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  528. #define RTLD_LAZY (0)
  529. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  530. #define fdopen(x, y) (_fdopen((x), (y)))
  531. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  532. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  533. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  534. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  535. #define sleep(x) (Sleep((x)*1000))
  536. #define rmdir(x) (_rmdir(x))
  537. #if defined(_WIN64) || !defined(__MINGW32__)
  538. /* Only MinGW 32 bit is missing this function */
  539. #define timegm(x) (_mkgmtime(x))
  540. #else
  541. time_t timegm(struct tm *tm);
  542. #define NEED_TIMEGM
  543. #endif
  544. #if !defined(fileno)
  545. #define fileno(x) (_fileno(x))
  546. #endif /* !fileno MINGW #defines fileno */
  547. typedef struct {
  548. CRITICAL_SECTION sec; /* Immovable */
  549. } pthread_mutex_t;
  550. typedef DWORD pthread_key_t;
  551. typedef HANDLE pthread_t;
  552. typedef struct {
  553. pthread_mutex_t threadIdSec;
  554. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  555. } pthread_cond_t;
  556. #if !defined(__clockid_t_defined)
  557. typedef DWORD clockid_t;
  558. #endif
  559. #if !defined(CLOCK_MONOTONIC)
  560. #define CLOCK_MONOTONIC (1)
  561. #endif
  562. #if !defined(CLOCK_REALTIME)
  563. #define CLOCK_REALTIME (2)
  564. #endif
  565. #if !defined(CLOCK_THREAD)
  566. #define CLOCK_THREAD (3)
  567. #endif
  568. #if !defined(CLOCK_PROCESS)
  569. #define CLOCK_PROCESS (4)
  570. #endif
  571. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  572. #define _TIMESPEC_DEFINED
  573. #endif
  574. #if !defined(_TIMESPEC_DEFINED)
  575. struct timespec {
  576. time_t tv_sec; /* seconds */
  577. long tv_nsec; /* nanoseconds */
  578. };
  579. #endif
  580. #if !defined(WIN_PTHREADS_TIME_H)
  581. #define MUST_IMPLEMENT_CLOCK_GETTIME
  582. #endif
  583. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  584. #define clock_gettime mg_clock_gettime
  585. static int
  586. clock_gettime(clockid_t clk_id, struct timespec *tp)
  587. {
  588. FILETIME ft;
  589. ULARGE_INTEGER li, li2;
  590. BOOL ok = FALSE;
  591. double d;
  592. static double perfcnt_per_sec = 0.0;
  593. static BOOL initialized = FALSE;
  594. if (!initialized) {
  595. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  596. perfcnt_per_sec = 1.0 / li.QuadPart;
  597. initialized = TRUE;
  598. }
  599. if (tp) {
  600. memset(tp, 0, sizeof(*tp));
  601. if (clk_id == CLOCK_REALTIME) {
  602. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  603. GetSystemTimeAsFileTime(&ft);
  604. li.LowPart = ft.dwLowDateTime;
  605. li.HighPart = ft.dwHighDateTime;
  606. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  607. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  608. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  609. ok = TRUE;
  610. /* END: CLOCK_REALTIME */
  611. } else if (clk_id == CLOCK_MONOTONIC) {
  612. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  613. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  614. d = li.QuadPart * perfcnt_per_sec;
  615. tp->tv_sec = (time_t)d;
  616. d -= (double)tp->tv_sec;
  617. tp->tv_nsec = (long)(d * 1.0E9);
  618. ok = TRUE;
  619. /* END: CLOCK_MONOTONIC */
  620. } else if (clk_id == CLOCK_THREAD) {
  621. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  622. FILETIME t_create, t_exit, t_kernel, t_user;
  623. if (GetThreadTimes(GetCurrentThread(),
  624. &t_create,
  625. &t_exit,
  626. &t_kernel,
  627. &t_user)) {
  628. li.LowPart = t_user.dwLowDateTime;
  629. li.HighPart = t_user.dwHighDateTime;
  630. li2.LowPart = t_kernel.dwLowDateTime;
  631. li2.HighPart = t_kernel.dwHighDateTime;
  632. li.QuadPart += li2.QuadPart;
  633. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  634. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  635. ok = TRUE;
  636. }
  637. /* END: CLOCK_THREAD */
  638. } else if (clk_id == CLOCK_PROCESS) {
  639. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetProcessTimes(GetCurrentProcess(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_PROCESS */
  656. } else {
  657. /* BEGIN: unknown clock */
  658. /* ok = FALSE; already set by init */
  659. /* END: unknown clock */
  660. }
  661. }
  662. return ok ? 0 : -1;
  663. }
  664. #endif
  665. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  666. static int pthread_mutex_lock(pthread_mutex_t *);
  667. static int pthread_mutex_unlock(pthread_mutex_t *);
  668. static void path_to_unicode(const struct mg_connection *conn,
  669. const char *path,
  670. wchar_t *wbuf,
  671. size_t wbuf_len);
  672. /* All file operations need to be rewritten to solve #246. */
  673. struct mg_file;
  674. static const char *
  675. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  676. /* POSIX dirent interface */
  677. struct dirent {
  678. char d_name[PATH_MAX];
  679. };
  680. typedef struct DIR {
  681. HANDLE handle;
  682. WIN32_FIND_DATAW info;
  683. struct dirent result;
  684. } DIR;
  685. #if defined(HAVE_POLL)
  686. #define mg_pollfd pollfd
  687. #else
  688. struct mg_pollfd {
  689. SOCKET fd;
  690. short events;
  691. short revents;
  692. };
  693. #endif
  694. /* Mark required libraries */
  695. #if defined(_MSC_VER)
  696. #pragma comment(lib, "Ws2_32.lib")
  697. #endif
  698. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  699. #include <inttypes.h>
  700. typedef const void *SOCK_OPT_TYPE;
  701. #if defined(ANDROID)
  702. typedef unsigned short int in_port_t;
  703. #endif
  704. #if !defined(__ZEPHYR__)
  705. #include <arpa/inet.h>
  706. #include <ctype.h>
  707. #include <dirent.h>
  708. #include <grp.h>
  709. #include <limits.h>
  710. #include <netdb.h>
  711. #include <netinet/in.h>
  712. #include <netinet/tcp.h>
  713. #include <pthread.h>
  714. #include <pwd.h>
  715. #include <stdarg.h>
  716. #include <stddef.h>
  717. #include <stdio.h>
  718. #include <stdlib.h>
  719. #include <string.h>
  720. #include <sys/poll.h>
  721. #include <sys/socket.h>
  722. #include <sys/time.h>
  723. #include <sys/utsname.h>
  724. #include <sys/wait.h>
  725. #include <time.h>
  726. #include <unistd.h>
  727. #endif
  728. #define vsnprintf_impl vsnprintf
  729. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  730. #include <dlfcn.h>
  731. #endif
  732. #if defined(__MACH__)
  733. #define SSL_LIB "libssl.dylib"
  734. #define CRYPTO_LIB "libcrypto.dylib"
  735. #else
  736. #if !defined(SSL_LIB)
  737. #define SSL_LIB "libssl.so"
  738. #endif
  739. #if !defined(CRYPTO_LIB)
  740. #define CRYPTO_LIB "libcrypto.so"
  741. #endif
  742. #endif
  743. #if !defined(O_BINARY)
  744. #define O_BINARY (0)
  745. #endif /* O_BINARY */
  746. #define closesocket(a) (close(a))
  747. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  748. #define mg_remove(conn, x) (remove(x))
  749. #define mg_sleep(x) (usleep((x)*1000))
  750. #define mg_opendir(conn, x) (opendir(x))
  751. #define mg_closedir(x) (closedir(x))
  752. #define mg_readdir(x) (readdir(x))
  753. #define ERRNO (errno)
  754. #define INVALID_SOCKET (-1)
  755. #define INT64_FMT PRId64
  756. #define UINT64_FMT PRIu64
  757. typedef int SOCKET;
  758. #define WINCDECL
  759. #if defined(__hpux)
  760. /* HPUX 11 does not have monotonic, fall back to realtime */
  761. #if !defined(CLOCK_MONOTONIC)
  762. #define CLOCK_MONOTONIC CLOCK_REALTIME
  763. #endif
  764. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  765. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  766. * the prototypes use int* rather than socklen_t* which matches the
  767. * actual library expectation. When called with the wrong size arg
  768. * accept() returns a zero client inet addr and check_acl() always
  769. * fails. Since socklen_t is widely used below, just force replace
  770. * their typedef with int. - DTL
  771. */
  772. #define socklen_t int
  773. #endif /* hpux */
  774. #define mg_pollfd pollfd
  775. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  776. /* In case our C library is missing "timegm", provide an implementation */
  777. #if defined(NEED_TIMEGM)
  778. static inline int
  779. is_leap(int y)
  780. {
  781. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  782. }
  783. static inline int
  784. count_leap(int y)
  785. {
  786. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  787. }
  788. time_t
  789. timegm(struct tm *tm)
  790. {
  791. static const unsigned short ydays[] = {
  792. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  793. int year = tm->tm_year + 1900;
  794. int mon = tm->tm_mon;
  795. int mday = tm->tm_mday - 1;
  796. int hour = tm->tm_hour;
  797. int min = tm->tm_min;
  798. int sec = tm->tm_sec;
  799. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  800. || (mday >= ydays[mon + 1] - ydays[mon]
  801. + (mon == 1 && is_leap(year) ? 1 : 0))
  802. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  803. return -1;
  804. time_t res = year - 1970;
  805. res *= 365;
  806. res += mday;
  807. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  808. res += count_leap(year);
  809. res *= 24;
  810. res += hour;
  811. res *= 60;
  812. res += min;
  813. res *= 60;
  814. res += sec;
  815. return res;
  816. }
  817. #endif /* NEED_TIMEGM */
  818. /* va_copy should always be a macro, C99 and C++11 - DTL */
  819. #if !defined(va_copy)
  820. #define va_copy(x, y) ((x) = (y))
  821. #endif
  822. #if defined(_WIN32)
  823. /* Create substitutes for POSIX functions in Win32. */
  824. #if defined(GCC_DIAGNOSTIC)
  825. /* Show no warning in case system functions are not used. */
  826. #pragma GCC diagnostic push
  827. #pragma GCC diagnostic ignored "-Wunused-function"
  828. #endif
  829. static pthread_mutex_t global_log_file_lock;
  830. FUNCTION_MAY_BE_UNUSED
  831. static DWORD
  832. pthread_self(void)
  833. {
  834. return GetCurrentThreadId();
  835. }
  836. FUNCTION_MAY_BE_UNUSED
  837. static int
  838. pthread_key_create(
  839. pthread_key_t *key,
  840. void (*_ignored)(void *) /* destructor not supported for Windows */
  841. )
  842. {
  843. (void)_ignored;
  844. if ((key != 0)) {
  845. *key = TlsAlloc();
  846. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  847. }
  848. return -2;
  849. }
  850. FUNCTION_MAY_BE_UNUSED
  851. static int
  852. pthread_key_delete(pthread_key_t key)
  853. {
  854. return TlsFree(key) ? 0 : 1;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. pthread_setspecific(pthread_key_t key, void *value)
  859. {
  860. return TlsSetValue(key, value) ? 0 : 1;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static void *
  864. pthread_getspecific(pthread_key_t key)
  865. {
  866. return TlsGetValue(key);
  867. }
  868. #if defined(GCC_DIAGNOSTIC)
  869. /* Enable unused function warning again */
  870. #pragma GCC diagnostic pop
  871. #endif
  872. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  873. #else
  874. static pthread_mutexattr_t pthread_mutex_attr;
  875. #endif /* _WIN32 */
  876. #if defined(_WIN32_WCE)
  877. /* Create substitutes for POSIX functions in Win32. */
  878. #if defined(GCC_DIAGNOSTIC)
  879. /* Show no warning in case system functions are not used. */
  880. #pragma GCC diagnostic push
  881. #pragma GCC diagnostic ignored "-Wunused-function"
  882. #endif
  883. FUNCTION_MAY_BE_UNUSED
  884. static time_t
  885. time(time_t *ptime)
  886. {
  887. time_t t;
  888. SYSTEMTIME st;
  889. FILETIME ft;
  890. GetSystemTime(&st);
  891. SystemTimeToFileTime(&st, &ft);
  892. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  893. if (ptime != NULL) {
  894. *ptime = t;
  895. }
  896. return t;
  897. }
  898. FUNCTION_MAY_BE_UNUSED
  899. static struct tm *
  900. localtime_s(const time_t *ptime, struct tm *ptm)
  901. {
  902. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  903. FILETIME ft, lft;
  904. SYSTEMTIME st;
  905. TIME_ZONE_INFORMATION tzinfo;
  906. if (ptm == NULL) {
  907. return NULL;
  908. }
  909. *(int64_t *)&ft = t;
  910. FileTimeToLocalFileTime(&ft, &lft);
  911. FileTimeToSystemTime(&lft, &st);
  912. ptm->tm_year = st.wYear - 1900;
  913. ptm->tm_mon = st.wMonth - 1;
  914. ptm->tm_wday = st.wDayOfWeek;
  915. ptm->tm_mday = st.wDay;
  916. ptm->tm_hour = st.wHour;
  917. ptm->tm_min = st.wMinute;
  918. ptm->tm_sec = st.wSecond;
  919. ptm->tm_yday = 0; /* hope nobody uses this */
  920. ptm->tm_isdst =
  921. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  922. return ptm;
  923. }
  924. FUNCTION_MAY_BE_UNUSED
  925. static struct tm *
  926. gmtime_s(const time_t *ptime, struct tm *ptm)
  927. {
  928. /* FIXME(lsm): fix this. */
  929. return localtime_s(ptime, ptm);
  930. }
  931. static int mg_atomic_inc(volatile int *addr);
  932. static struct tm tm_array[MAX_WORKER_THREADS];
  933. static int tm_index = 0;
  934. FUNCTION_MAY_BE_UNUSED
  935. static struct tm *
  936. localtime(const time_t *ptime)
  937. {
  938. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  939. return localtime_s(ptime, tm_array + i);
  940. }
  941. FUNCTION_MAY_BE_UNUSED
  942. static struct tm *
  943. gmtime(const time_t *ptime)
  944. {
  945. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  946. return gmtime_s(ptime, tm_array + i);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static size_t
  950. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  951. {
  952. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  953. * for WinCE"); */
  954. return 0;
  955. }
  956. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  957. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  958. #define remove(f) mg_remove(NULL, f)
  959. FUNCTION_MAY_BE_UNUSED
  960. static int
  961. rename(const char *a, const char *b)
  962. {
  963. wchar_t wa[W_PATH_MAX];
  964. wchar_t wb[W_PATH_MAX];
  965. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  966. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  967. return MoveFileW(wa, wb) ? 0 : -1;
  968. }
  969. struct stat {
  970. int64_t st_size;
  971. time_t st_mtime;
  972. };
  973. FUNCTION_MAY_BE_UNUSED
  974. static int
  975. stat(const char *name, struct stat *st)
  976. {
  977. wchar_t wbuf[W_PATH_MAX];
  978. WIN32_FILE_ATTRIBUTE_DATA attr;
  979. time_t creation_time, write_time;
  980. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  981. memset(&attr, 0, sizeof(attr));
  982. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  983. st->st_size =
  984. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  985. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  986. attr.ftLastWriteTime.dwHighDateTime);
  987. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  988. attr.ftCreationTime.dwHighDateTime);
  989. if (creation_time > write_time) {
  990. st->st_mtime = creation_time;
  991. } else {
  992. st->st_mtime = write_time;
  993. }
  994. return 0;
  995. }
  996. #define access(x, a) 1 /* not required anyway */
  997. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  998. /* Values from errno.h in Windows SDK (Visual Studio). */
  999. #define EEXIST 17
  1000. #define EACCES 13
  1001. #define ENOENT 2
  1002. #if defined(GCC_DIAGNOSTIC)
  1003. /* Enable unused function warning again */
  1004. #pragma GCC diagnostic pop
  1005. #endif
  1006. #endif /* defined(_WIN32_WCE) */
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Show no warning in case system functions are not used. */
  1009. #pragma GCC diagnostic push
  1010. #pragma GCC diagnostic ignored "-Wunused-function"
  1011. #endif /* defined(GCC_DIAGNOSTIC) */
  1012. #if defined(__clang__)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma clang diagnostic push
  1015. #pragma clang diagnostic ignored "-Wunused-function"
  1016. #endif
  1017. static pthread_mutex_t global_lock_mutex;
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static void
  1020. mg_global_lock(void)
  1021. {
  1022. (void)pthread_mutex_lock(&global_lock_mutex);
  1023. }
  1024. FUNCTION_MAY_BE_UNUSED
  1025. static void
  1026. mg_global_unlock(void)
  1027. {
  1028. (void)pthread_mutex_unlock(&global_lock_mutex);
  1029. }
  1030. FUNCTION_MAY_BE_UNUSED
  1031. static int
  1032. mg_atomic_inc(volatile int *addr)
  1033. {
  1034. int ret;
  1035. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1036. /* Depending on the SDK, this function uses either
  1037. * (volatile unsigned int *) or (volatile LONG *),
  1038. * so whatever you use, the other SDK is likely to raise a warning. */
  1039. ret = InterlockedIncrement((volatile long *)addr);
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. ret = __sync_add_and_fetch(addr, 1);
  1044. #else
  1045. mg_global_lock();
  1046. ret = (++(*addr));
  1047. mg_global_unlock();
  1048. #endif
  1049. return ret;
  1050. }
  1051. FUNCTION_MAY_BE_UNUSED
  1052. static int
  1053. mg_atomic_dec(volatile int *addr)
  1054. {
  1055. int ret;
  1056. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1057. /* Depending on the SDK, this function uses either
  1058. * (volatile unsigned int *) or (volatile LONG *),
  1059. * so whatever you use, the other SDK is likely to raise a warning. */
  1060. ret = InterlockedDecrement((volatile long *)addr);
  1061. #elif defined(__GNUC__) \
  1062. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1063. && !defined(NO_ATOMICS)
  1064. ret = __sync_sub_and_fetch(addr, 1);
  1065. #else
  1066. mg_global_lock();
  1067. ret = (--(*addr));
  1068. mg_global_unlock();
  1069. #endif
  1070. return ret;
  1071. }
  1072. #if defined(USE_SERVER_STATS)
  1073. static int64_t
  1074. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1075. {
  1076. int64_t ret;
  1077. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1078. ret = InterlockedAdd64(addr, value);
  1079. #elif defined(__GNUC__) \
  1080. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1081. && !defined(NO_ATOMICS)
  1082. ret = __sync_add_and_fetch(addr, value);
  1083. #else
  1084. mg_global_lock();
  1085. *addr += value;
  1086. ret = (*addr);
  1087. mg_global_unlock();
  1088. #endif
  1089. return ret;
  1090. }
  1091. #endif
  1092. #if defined(GCC_DIAGNOSTIC)
  1093. /* Show no warning in case system functions are not used. */
  1094. #pragma GCC diagnostic pop
  1095. #endif /* defined(GCC_DIAGNOSTIC) */
  1096. #if defined(__clang__)
  1097. /* Show no warning in case system functions are not used. */
  1098. #pragma clang diagnostic pop
  1099. #endif
  1100. #if defined(USE_SERVER_STATS)
  1101. struct mg_memory_stat {
  1102. volatile int64_t totalMemUsed;
  1103. volatile int64_t maxMemUsed;
  1104. volatile int blockCount;
  1105. };
  1106. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1107. static void *
  1108. mg_malloc_ex(size_t size,
  1109. struct mg_context *ctx,
  1110. const char *file,
  1111. unsigned line)
  1112. {
  1113. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1114. void *memory = 0;
  1115. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1116. #if defined(MEMORY_DEBUGGING)
  1117. char mallocStr[256];
  1118. #else
  1119. (void)file;
  1120. (void)line;
  1121. #endif
  1122. if (data) {
  1123. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1124. if (mmem > mstat->maxMemUsed) {
  1125. /* could use atomic compare exchange, but this
  1126. * seems overkill for statistics data */
  1127. mstat->maxMemUsed = mmem;
  1128. }
  1129. mg_atomic_inc(&mstat->blockCount);
  1130. ((uintptr_t *)data)[0] = size;
  1131. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1132. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1133. }
  1134. #if defined(MEMORY_DEBUGGING)
  1135. sprintf(mallocStr,
  1136. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1137. memory,
  1138. (unsigned long)size,
  1139. (unsigned long)mstat->totalMemUsed,
  1140. (unsigned long)mstat->blockCount,
  1141. file,
  1142. line);
  1143. #if defined(_WIN32)
  1144. OutputDebugStringA(mallocStr);
  1145. #else
  1146. DEBUG_TRACE("%s", mallocStr);
  1147. #endif
  1148. #endif
  1149. return memory;
  1150. }
  1151. static void *
  1152. mg_calloc_ex(size_t count,
  1153. size_t size,
  1154. struct mg_context *ctx,
  1155. const char *file,
  1156. unsigned line)
  1157. {
  1158. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1159. if (data) {
  1160. memset(data, 0, size * count);
  1161. }
  1162. return data;
  1163. }
  1164. static void
  1165. mg_free_ex(void *memory, const char *file, unsigned line)
  1166. {
  1167. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1168. #if defined(MEMORY_DEBUGGING)
  1169. char mallocStr[256];
  1170. #else
  1171. (void)file;
  1172. (void)line;
  1173. #endif
  1174. if (memory) {
  1175. uintptr_t size = ((uintptr_t *)data)[0];
  1176. struct mg_memory_stat *mstat =
  1177. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1178. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1179. mg_atomic_dec(&mstat->blockCount);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)size,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. #if defined(_WIN32)
  1190. OutputDebugStringA(mallocStr);
  1191. #else
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. #endif
  1195. free(data);
  1196. }
  1197. }
  1198. static void *
  1199. mg_realloc_ex(void *memory,
  1200. size_t newsize,
  1201. struct mg_context *ctx,
  1202. const char *file,
  1203. unsigned line)
  1204. {
  1205. void *data;
  1206. void *_realloc;
  1207. uintptr_t oldsize;
  1208. #if defined(MEMORY_DEBUGGING)
  1209. char mallocStr[256];
  1210. #else
  1211. (void)file;
  1212. (void)line;
  1213. #endif
  1214. if (newsize) {
  1215. if (memory) {
  1216. /* Reallocate existing block */
  1217. struct mg_memory_stat *mstat;
  1218. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1219. oldsize = ((uintptr_t *)data)[0];
  1220. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1221. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1222. if (_realloc) {
  1223. data = _realloc;
  1224. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1225. #if defined(MEMORY_DEBUGGING)
  1226. sprintf(mallocStr,
  1227. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1228. memory,
  1229. (unsigned long)oldsize,
  1230. (unsigned long)mstat->totalMemUsed,
  1231. (unsigned long)mstat->blockCount,
  1232. file,
  1233. line);
  1234. #if defined(_WIN32)
  1235. OutputDebugStringA(mallocStr);
  1236. #else
  1237. DEBUG_TRACE("%s", mallocStr);
  1238. #endif
  1239. #endif
  1240. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1241. #if defined(MEMORY_DEBUGGING)
  1242. sprintf(mallocStr,
  1243. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1244. memory,
  1245. (unsigned long)newsize,
  1246. (unsigned long)mstat->totalMemUsed,
  1247. (unsigned long)mstat->blockCount,
  1248. file,
  1249. line);
  1250. #if defined(_WIN32)
  1251. OutputDebugStringA(mallocStr);
  1252. #else
  1253. DEBUG_TRACE("%s", mallocStr);
  1254. #endif
  1255. #endif
  1256. *(uintptr_t *)data = newsize;
  1257. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1258. } else {
  1259. #if defined(MEMORY_DEBUGGING)
  1260. #if defined(_WIN32)
  1261. OutputDebugStringA("MEM: realloc failed\n");
  1262. #else
  1263. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1264. #endif
  1265. #endif
  1266. return _realloc;
  1267. }
  1268. } else {
  1269. /* Allocate new block */
  1270. data = mg_malloc_ex(newsize, ctx, file, line);
  1271. }
  1272. } else {
  1273. /* Free existing block */
  1274. data = 0;
  1275. mg_free_ex(memory, file, line);
  1276. }
  1277. return data;
  1278. }
  1279. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1280. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1281. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1282. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1283. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1284. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1285. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1286. #else /* USE_SERVER_STATS */
  1287. static __inline void *
  1288. mg_malloc(size_t a)
  1289. {
  1290. return malloc(a);
  1291. }
  1292. static __inline void *
  1293. mg_calloc(size_t a, size_t b)
  1294. {
  1295. return calloc(a, b);
  1296. }
  1297. static __inline void *
  1298. mg_realloc(void *a, size_t b)
  1299. {
  1300. return realloc(a, b);
  1301. }
  1302. static __inline void
  1303. mg_free(void *a)
  1304. {
  1305. free(a);
  1306. }
  1307. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1308. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1309. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1310. #define mg_free_ctx(a, c) mg_free(a)
  1311. #endif /* USE_SERVER_STATS */
  1312. static void mg_vsnprintf(const struct mg_connection *conn,
  1313. int *truncated,
  1314. char *buf,
  1315. size_t buflen,
  1316. const char *fmt,
  1317. va_list ap);
  1318. static void mg_snprintf(const struct mg_connection *conn,
  1319. int *truncated,
  1320. char *buf,
  1321. size_t buflen,
  1322. PRINTF_FORMAT_STRING(const char *fmt),
  1323. ...) PRINTF_ARGS(5, 6);
  1324. /* This following lines are just meant as a reminder to use the mg-functions
  1325. * for memory management */
  1326. #if defined(malloc)
  1327. #undef malloc
  1328. #endif
  1329. #if defined(calloc)
  1330. #undef calloc
  1331. #endif
  1332. #if defined(realloc)
  1333. #undef realloc
  1334. #endif
  1335. #if defined(free)
  1336. #undef free
  1337. #endif
  1338. #if defined(snprintf)
  1339. #undef snprintf
  1340. #endif
  1341. #if defined(vsnprintf)
  1342. #undef vsnprintf
  1343. #endif
  1344. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1345. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1346. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1347. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1348. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1349. #if defined(_WIN32)
  1350. /* vsnprintf must not be used in any system,
  1351. * but this define only works well for Windows. */
  1352. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1353. #endif
  1354. /* mg_init_library counter */
  1355. static int mg_init_library_called = 0;
  1356. #if !defined(NO_SSL)
  1357. static int mg_ssl_initialized = 0;
  1358. #endif
  1359. static pthread_key_t sTlsKey; /* Thread local storage index */
  1360. static int thread_idx_max = 0;
  1361. #if defined(MG_LEGACY_INTERFACE)
  1362. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1363. #endif
  1364. struct mg_workerTLS {
  1365. int is_master;
  1366. unsigned long thread_idx;
  1367. void *user_ptr;
  1368. #if defined(_WIN32)
  1369. HANDLE pthread_cond_helper_mutex;
  1370. struct mg_workerTLS *next_waiting_thread;
  1371. #endif
  1372. const char *alpn_proto;
  1373. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1374. char txtbuf[4];
  1375. #endif
  1376. };
  1377. #if defined(GCC_DIAGNOSTIC)
  1378. /* Show no warning in case system functions are not used. */
  1379. #pragma GCC diagnostic push
  1380. #pragma GCC diagnostic ignored "-Wunused-function"
  1381. #endif /* defined(GCC_DIAGNOSTIC) */
  1382. #if defined(__clang__)
  1383. /* Show no warning in case system functions are not used. */
  1384. #pragma clang diagnostic push
  1385. #pragma clang diagnostic ignored "-Wunused-function"
  1386. #endif
  1387. /* Get a unique thread ID as unsigned long, independent from the data type
  1388. * of thread IDs defined by the operating system API.
  1389. * If two calls to mg_current_thread_id return the same value, they calls
  1390. * are done from the same thread. If they return different values, they are
  1391. * done from different threads. (Provided this function is used in the same
  1392. * process context and threads are not repeatedly created and deleted, but
  1393. * CivetWeb does not do that).
  1394. * This function must match the signature required for SSL id callbacks:
  1395. * CRYPTO_set_id_callback
  1396. */
  1397. FUNCTION_MAY_BE_UNUSED
  1398. static unsigned long
  1399. mg_current_thread_id(void)
  1400. {
  1401. #if defined(_WIN32)
  1402. return GetCurrentThreadId();
  1403. #else
  1404. #if defined(__clang__)
  1405. #pragma clang diagnostic push
  1406. #pragma clang diagnostic ignored "-Wunreachable-code"
  1407. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1408. * or not, so one of the two conditions will be unreachable by construction.
  1409. * Unfortunately the C standard does not define a way to check this at
  1410. * compile time, since the #if preprocessor conditions can not use the sizeof
  1411. * operator as an argument. */
  1412. #endif
  1413. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1414. /* This is the problematic case for CRYPTO_set_id_callback:
  1415. * The OS pthread_t can not be cast to unsigned long. */
  1416. struct mg_workerTLS *tls =
  1417. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1418. if (tls == NULL) {
  1419. /* SSL called from an unknown thread: Create some thread index.
  1420. */
  1421. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1422. tls->is_master = -2; /* -2 means "3rd party thread" */
  1423. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1424. pthread_setspecific(sTlsKey, tls);
  1425. }
  1426. return tls->thread_idx;
  1427. } else {
  1428. /* pthread_t may be any data type, so a simple cast to unsigned long
  1429. * can rise a warning/error, depending on the platform.
  1430. * Here memcpy is used as an anything-to-anything cast. */
  1431. unsigned long ret = 0;
  1432. pthread_t t = pthread_self();
  1433. memcpy(&ret, &t, sizeof(pthread_t));
  1434. return ret;
  1435. }
  1436. #if defined(__clang__)
  1437. #pragma clang diagnostic pop
  1438. #endif
  1439. #endif
  1440. }
  1441. FUNCTION_MAY_BE_UNUSED
  1442. static uint64_t
  1443. mg_get_current_time_ns(void)
  1444. {
  1445. struct timespec tsnow;
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1448. }
  1449. #if defined(GCC_DIAGNOSTIC)
  1450. /* Show no warning in case system functions are not used. */
  1451. #pragma GCC diagnostic pop
  1452. #endif /* defined(GCC_DIAGNOSTIC) */
  1453. #if defined(__clang__)
  1454. /* Show no warning in case system functions are not used. */
  1455. #pragma clang diagnostic pop
  1456. #endif
  1457. #if defined(NEED_DEBUG_TRACE_FUNC)
  1458. static void
  1459. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1460. {
  1461. va_list args;
  1462. struct timespec tsnow;
  1463. /* Get some operating system independent thread id */
  1464. unsigned long thread_id = mg_current_thread_id();
  1465. clock_gettime(CLOCK_REALTIME, &tsnow);
  1466. flockfile(DEBUG_TRACE_STREAM);
  1467. fprintf(DEBUG_TRACE_STREAM,
  1468. "*** %lu.%09lu %lu %s:%u: ",
  1469. (unsigned long)tsnow.tv_sec,
  1470. (unsigned long)tsnow.tv_nsec,
  1471. thread_id,
  1472. func,
  1473. line);
  1474. va_start(args, fmt);
  1475. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1476. va_end(args);
  1477. putc('\n', DEBUG_TRACE_STREAM);
  1478. fflush(DEBUG_TRACE_STREAM);
  1479. funlockfile(DEBUG_TRACE_STREAM);
  1480. }
  1481. #endif /* NEED_DEBUG_TRACE_FUNC */
  1482. #define MD5_STATIC static
  1483. #include "md5.inl"
  1484. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1485. #if defined(NO_SOCKLEN_T)
  1486. typedef int socklen_t;
  1487. #endif /* NO_SOCKLEN_T */
  1488. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1489. #if !defined(MSG_NOSIGNAL)
  1490. #define MSG_NOSIGNAL (0)
  1491. #endif
  1492. #if defined(NO_SSL)
  1493. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1494. typedef struct SSL_CTX SSL_CTX;
  1495. #else
  1496. #if defined(NO_SSL_DL)
  1497. #include <openssl/bn.h>
  1498. #include <openssl/conf.h>
  1499. #include <openssl/crypto.h>
  1500. #include <openssl/dh.h>
  1501. #include <openssl/engine.h>
  1502. #include <openssl/err.h>
  1503. #include <openssl/opensslv.h>
  1504. #include <openssl/pem.h>
  1505. #include <openssl/ssl.h>
  1506. #include <openssl/tls1.h>
  1507. #include <openssl/x509.h>
  1508. #if defined(WOLFSSL_VERSION)
  1509. /* Additional defines for WolfSSL, see
  1510. * https://github.com/civetweb/civetweb/issues/583 */
  1511. #include "wolfssl_extras.inl"
  1512. #endif
  1513. #if defined(OPENSSL_IS_BORINGSSL)
  1514. /* From boringssl/src/include/openssl/mem.h:
  1515. *
  1516. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1517. * However, that was written in a time before Valgrind and ASAN. Since we now
  1518. * have those tools, the OpenSSL allocation functions are simply macros around
  1519. * the standard memory functions.
  1520. *
  1521. * #define OPENSSL_free free */
  1522. #define free free
  1523. // disable for boringssl
  1524. #define CONF_modules_unload(a) ((void)0)
  1525. #define ENGINE_cleanup() ((void)0)
  1526. #endif
  1527. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1528. /* If OpenSSL headers are included, automatically select the API version */
  1529. #if !defined(OPENSSL_API_1_1)
  1530. #define OPENSSL_API_1_1
  1531. #endif
  1532. #define OPENSSL_REMOVE_THREAD_STATE()
  1533. #else
  1534. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1535. #endif
  1536. #else
  1537. /* SSL loaded dynamically from DLL.
  1538. * I put the prototypes here to be independent from OpenSSL source
  1539. * installation. */
  1540. typedef struct ssl_st SSL;
  1541. typedef struct ssl_method_st SSL_METHOD;
  1542. typedef struct ssl_ctx_st SSL_CTX;
  1543. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1544. typedef struct x509_name X509_NAME;
  1545. typedef struct asn1_integer ASN1_INTEGER;
  1546. typedef struct bignum BIGNUM;
  1547. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1548. typedef struct evp_md EVP_MD;
  1549. typedef struct x509 X509;
  1550. #define SSL_CTRL_OPTIONS (32)
  1551. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1552. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1553. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1554. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1555. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1556. #define SSL_VERIFY_NONE (0)
  1557. #define SSL_VERIFY_PEER (1)
  1558. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1559. #define SSL_VERIFY_CLIENT_ONCE (4)
  1560. #define SSL_OP_ALL (0x80000BFFul)
  1561. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1562. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1563. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1564. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1565. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1566. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1567. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1568. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1569. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1570. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1571. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1572. #define SSL_CB_HANDSHAKE_START (0x10)
  1573. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1574. #define SSL_ERROR_NONE (0)
  1575. #define SSL_ERROR_SSL (1)
  1576. #define SSL_ERROR_WANT_READ (2)
  1577. #define SSL_ERROR_WANT_WRITE (3)
  1578. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1579. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1580. #define SSL_ERROR_ZERO_RETURN (6)
  1581. #define SSL_ERROR_WANT_CONNECT (7)
  1582. #define SSL_ERROR_WANT_ACCEPT (8)
  1583. #define TLSEXT_TYPE_server_name (0)
  1584. #define TLSEXT_NAMETYPE_host_name (0)
  1585. #define SSL_TLSEXT_ERR_OK (0)
  1586. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1587. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1588. #define SSL_TLSEXT_ERR_NOACK (3)
  1589. enum ssl_func_category {
  1590. TLS_Mandatory, /* required for HTTPS */
  1591. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1592. TLS_END_OF_LIST
  1593. };
  1594. /* Check if all TLS functions/features are available */
  1595. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1596. struct ssl_func {
  1597. const char *name; /* SSL function name */
  1598. union {
  1599. enum ssl_func_category required; /* Mandatory or optional */
  1600. void (*ptr)(void); /* Function pointer */
  1601. };
  1602. };
  1603. #if defined(OPENSSL_API_1_1)
  1604. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1605. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1606. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1607. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1608. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1609. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1610. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1611. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1612. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1613. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1614. #define OPENSSL_init_ssl \
  1615. (*(int (*)(uint64_t opts, \
  1616. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1617. .ptr)
  1618. #define SSL_CTX_use_PrivateKey_file \
  1619. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1620. #define SSL_CTX_use_certificate_file \
  1621. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1622. #define SSL_CTX_set_default_passwd_cb \
  1623. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1624. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1625. #define SSL_CTX_use_certificate_chain_file \
  1626. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1627. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1628. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1629. #define SSL_CTX_set_verify \
  1630. (*(void (*)(SSL_CTX *, \
  1631. int, \
  1632. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1633. .ptr)
  1634. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1635. #define SSL_CTX_load_verify_locations \
  1636. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1637. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1638. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1639. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1640. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1641. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1642. #define SSL_CIPHER_get_name \
  1643. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1644. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1645. #define SSL_CTX_set_session_id_context \
  1646. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1647. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1648. #define SSL_CTX_set_cipher_list \
  1649. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1650. #define SSL_CTX_set_options \
  1651. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1652. #define SSL_CTX_set_info_callback \
  1653. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1654. ssl_sw[32] \
  1655. .ptr)
  1656. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1657. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1658. #define SSL_CTX_callback_ctrl \
  1659. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1660. #define SSL_get_servername \
  1661. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1662. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1663. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1664. #define SSL_CTX_set_alpn_protos \
  1665. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1666. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1667. const unsigned char **out,
  1668. unsigned char *outlen,
  1669. const unsigned char *in,
  1670. unsigned int inlen,
  1671. void *arg);
  1672. #define SSL_CTX_set_alpn_select_cb \
  1673. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1674. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1675. const unsigned char **out,
  1676. unsigned int *outlen,
  1677. void *arg);
  1678. #define SSL_CTX_set_next_protos_advertised_cb \
  1679. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1680. .ptr)
  1681. #define SSL_CTX_clear_options(ctx, op) \
  1682. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1683. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1684. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1685. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1686. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1687. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1688. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1689. SSL_CTX_callback_ctrl(ctx, \
  1690. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1691. (void (*)(void))cb)
  1692. #define SSL_set_tlsext_host_name(ctx, arg) \
  1693. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1694. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1695. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1696. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1697. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1698. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1699. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1700. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1701. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1702. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1703. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1704. #define X509_NAME_oneline \
  1705. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1706. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1707. #define EVP_get_digestbyname \
  1708. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1709. #define EVP_Digest \
  1710. (*(int (*)( \
  1711. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1712. crypto_sw[9] \
  1713. .ptr)
  1714. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1715. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1716. #define ASN1_INTEGER_to_BN \
  1717. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1718. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1719. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1720. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1721. #define OPENSSL_free(a) CRYPTO_free(a)
  1722. #define OPENSSL_REMOVE_THREAD_STATE()
  1723. /* init_ssl_ctx() function updates this array.
  1724. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1725. * of respective functions. The macros above (like SSL_connect()) are really
  1726. * just calling these functions indirectly via the pointer. */
  1727. static struct ssl_func ssl_sw[] = {
  1728. {"SSL_free", {TLS_Mandatory}},
  1729. {"SSL_accept", {TLS_Mandatory}},
  1730. {"SSL_connect", {TLS_Mandatory}},
  1731. {"SSL_read", {TLS_Mandatory}},
  1732. {"SSL_write", {TLS_Mandatory}},
  1733. {"SSL_get_error", {TLS_Mandatory}},
  1734. {"SSL_set_fd", {TLS_Mandatory}},
  1735. {"SSL_new", {TLS_Mandatory}},
  1736. {"SSL_CTX_new", {TLS_Mandatory}},
  1737. {"TLS_server_method", {TLS_Mandatory}},
  1738. {"OPENSSL_init_ssl", {TLS_Mandatory}},
  1739. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1740. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1741. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1742. {"SSL_CTX_free", {TLS_Mandatory}},
  1743. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1744. {"TLS_client_method", {TLS_Mandatory}},
  1745. {"SSL_pending", {TLS_Mandatory}},
  1746. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1747. {"SSL_shutdown", {TLS_Mandatory}},
  1748. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1749. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1750. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1751. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1752. {"SSL_get_version", {TLS_Mandatory}},
  1753. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1754. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1755. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1756. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1757. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1758. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1759. {"SSL_CTX_set_options", {TLS_Mandatory}},
  1760. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1761. {"SSL_get_ex_data", {TLS_Mandatory}},
  1762. {"SSL_set_ex_data", {TLS_Mandatory}},
  1763. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1764. {"SSL_get_servername", {TLS_Mandatory}},
  1765. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1766. {"SSL_ctrl", {TLS_Mandatory}},
  1767. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1768. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1769. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1770. {NULL, {TLS_END_OF_LIST}}};
  1771. /* Similar array as ssl_sw. These functions could be located in different
  1772. * lib. */
  1773. static struct ssl_func crypto_sw[] = {{"ERR_get_error", {TLS_Mandatory}},
  1774. {"ERR_error_string", {TLS_Mandatory}},
  1775. {"CONF_modules_unload", {TLS_Mandatory}},
  1776. {"X509_free", {TLS_Mandatory}},
  1777. {"X509_get_subject_name",
  1778. {TLS_Mandatory}},
  1779. {"X509_get_issuer_name", {TLS_Mandatory}},
  1780. {"X509_NAME_oneline", {TLS_Mandatory}},
  1781. {"X509_get_serialNumber",
  1782. {TLS_Mandatory}},
  1783. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1784. {"EVP_Digest", {TLS_Mandatory}},
  1785. {"i2d_X509", {TLS_Mandatory}},
  1786. {"BN_bn2hex", {TLS_Mandatory}},
  1787. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1788. {"BN_free", {TLS_Mandatory}},
  1789. {"CRYPTO_free", {TLS_Mandatory}},
  1790. {"ERR_clear_error", {TLS_Mandatory}},
  1791. {NULL, {TLS_END_OF_LIST}}};
  1792. #else
  1793. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1794. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1795. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1796. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1797. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1798. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1799. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1800. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1801. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1802. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1803. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1804. #define SSL_CTX_use_PrivateKey_file \
  1805. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1806. #define SSL_CTX_use_certificate_file \
  1807. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1808. #define SSL_CTX_set_default_passwd_cb \
  1809. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1810. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1811. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1812. #define SSL_CTX_use_certificate_chain_file \
  1813. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1814. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1815. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1816. #define SSL_CTX_set_verify \
  1817. (*(void (*)(SSL_CTX *, \
  1818. int, \
  1819. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1820. .ptr)
  1821. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1822. #define SSL_CTX_load_verify_locations \
  1823. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1824. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1825. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1826. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1827. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1828. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1829. #define SSL_CIPHER_get_name \
  1830. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1831. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1832. #define SSL_CTX_set_session_id_context \
  1833. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1834. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1835. #define SSL_CTX_set_cipher_list \
  1836. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1837. #define SSL_CTX_set_info_callback \
  1838. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1839. .ptr)
  1840. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1841. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1842. #define SSL_CTX_callback_ctrl \
  1843. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1844. #define SSL_get_servername \
  1845. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1846. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1847. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1848. #define SSL_CTX_set_alpn_protos \
  1849. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1850. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1851. const unsigned char **out,
  1852. unsigned char *outlen,
  1853. const unsigned char *in,
  1854. unsigned int inlen,
  1855. void *arg);
  1856. #define SSL_CTX_set_alpn_select_cb \
  1857. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1858. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1859. const unsigned char **out,
  1860. unsigned int *outlen,
  1861. void *arg);
  1862. #define SSL_CTX_set_next_protos_advertised_cb \
  1863. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1864. .ptr)
  1865. #define SSL_CTX_set_options(ctx, op) \
  1866. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1867. #define SSL_CTX_clear_options(ctx, op) \
  1868. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1869. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1870. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1871. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1872. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1873. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1874. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1875. SSL_CTX_callback_ctrl(ctx, \
  1876. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1877. (void (*)(void))cb)
  1878. #define SSL_set_tlsext_host_name(ctx, arg) \
  1879. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1880. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1881. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1882. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1883. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1884. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1885. #define CRYPTO_set_locking_callback \
  1886. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1887. #define CRYPTO_set_id_callback \
  1888. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1889. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1890. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1891. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1892. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1893. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1894. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1895. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1896. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1897. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1898. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1899. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1900. #define X509_NAME_oneline \
  1901. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1902. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1903. #define i2c_ASN1_INTEGER \
  1904. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1905. #define EVP_get_digestbyname \
  1906. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1907. #define EVP_Digest \
  1908. (*(int (*)( \
  1909. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1910. crypto_sw[18] \
  1911. .ptr)
  1912. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1913. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1914. #define ASN1_INTEGER_to_BN \
  1915. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1916. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1917. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1918. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1919. #define OPENSSL_free(a) CRYPTO_free(a)
  1920. /* use here ERR_remove_state,
  1921. * while on some platforms function is not included into library due to
  1922. * deprication */
  1923. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1924. /* init_ssl_ctx() function updates this array.
  1925. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1926. * of respective functions. The macros above (like SSL_connect()) are really
  1927. * just calling these functions indirectly via the pointer. */
  1928. static struct ssl_func ssl_sw[] = {
  1929. {"SSL_free", {TLS_Mandatory}},
  1930. {"SSL_accept", {TLS_Mandatory}},
  1931. {"SSL_connect", {TLS_Mandatory}},
  1932. {"SSL_read", {TLS_Mandatory}},
  1933. {"SSL_write", {TLS_Mandatory}},
  1934. {"SSL_get_error", {TLS_Mandatory}},
  1935. {"SSL_set_fd", {TLS_Mandatory}},
  1936. {"SSL_new", {TLS_Mandatory}},
  1937. {"SSL_CTX_new", {TLS_Mandatory}},
  1938. {"SSLv23_server_method", {TLS_Mandatory}},
  1939. {"SSL_library_init", {TLS_Mandatory}},
  1940. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1941. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1942. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1943. {"SSL_CTX_free", {TLS_Mandatory}},
  1944. {"SSL_load_error_strings", {TLS_Mandatory}},
  1945. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1946. {"SSLv23_client_method", {TLS_Mandatory}},
  1947. {"SSL_pending", {TLS_Mandatory}},
  1948. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1949. {"SSL_shutdown", {TLS_Mandatory}},
  1950. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1951. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1952. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1953. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1954. {"SSL_get_version", {TLS_Mandatory}},
  1955. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1956. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1957. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1958. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1959. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1960. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1961. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1962. {"SSL_get_ex_data", {TLS_Mandatory}},
  1963. {"SSL_set_ex_data", {TLS_Mandatory}},
  1964. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1965. {"SSL_get_servername", {TLS_Mandatory}},
  1966. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1967. {"SSL_ctrl", {TLS_Mandatory}},
  1968. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1969. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1970. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1971. {NULL, {TLS_END_OF_LIST}}};
  1972. /* Similar array as ssl_sw. These functions could be located in different
  1973. * lib. */
  1974. static struct ssl_func crypto_sw[] = {
  1975. {"CRYPTO_num_locks", {TLS_Mandatory}},
  1976. {"CRYPTO_set_locking_callback", {TLS_Mandatory}},
  1977. {"CRYPTO_set_id_callback", {TLS_Mandatory}},
  1978. {"ERR_get_error", {TLS_Mandatory}},
  1979. {"ERR_error_string", {TLS_Mandatory}},
  1980. {"ERR_remove_state", {TLS_Mandatory}},
  1981. {"ERR_free_strings", {TLS_Mandatory}},
  1982. {"ENGINE_cleanup", {TLS_Mandatory}},
  1983. {"CONF_modules_unload", {TLS_Mandatory}},
  1984. {"CRYPTO_cleanup_all_ex_data", {TLS_Mandatory}},
  1985. {"EVP_cleanup", {TLS_Mandatory}},
  1986. {"X509_free", {TLS_Mandatory}},
  1987. {"X509_get_subject_name", {TLS_Mandatory}},
  1988. {"X509_get_issuer_name", {TLS_Mandatory}},
  1989. {"X509_NAME_oneline", {TLS_Mandatory}},
  1990. {"X509_get_serialNumber", {TLS_Mandatory}},
  1991. {"i2c_ASN1_INTEGER", {TLS_Mandatory}},
  1992. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1993. {"EVP_Digest", {TLS_Mandatory}},
  1994. {"i2d_X509", {TLS_Mandatory}},
  1995. {"BN_bn2hex", {TLS_Mandatory}},
  1996. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1997. {"BN_free", {TLS_Mandatory}},
  1998. {"CRYPTO_free", {TLS_Mandatory}},
  1999. {"ERR_clear_error", {TLS_Mandatory}},
  2000. {NULL, {TLS_END_OF_LIST}}};
  2001. #endif /* OPENSSL_API_1_1 */
  2002. #endif /* NO_SSL_DL */
  2003. #endif /* NO_SSL */
  2004. #if !defined(NO_CACHING)
  2005. static const char month_names[][4] = {"Jan",
  2006. "Feb",
  2007. "Mar",
  2008. "Apr",
  2009. "May",
  2010. "Jun",
  2011. "Jul",
  2012. "Aug",
  2013. "Sep",
  2014. "Oct",
  2015. "Nov",
  2016. "Dec"};
  2017. #endif /* !NO_CACHING */
  2018. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2019. * the union u. */
  2020. union usa {
  2021. struct sockaddr sa;
  2022. struct sockaddr_in sin;
  2023. #if defined(USE_IPV6)
  2024. struct sockaddr_in6 sin6;
  2025. #endif
  2026. };
  2027. /* Describes a string (chunk of memory). */
  2028. struct vec {
  2029. const char *ptr;
  2030. size_t len;
  2031. };
  2032. struct mg_file_stat {
  2033. /* File properties filled by mg_stat: */
  2034. uint64_t size;
  2035. time_t last_modified;
  2036. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2037. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2038. * case we need a "Content-Eencoding: gzip" header */
  2039. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2040. };
  2041. struct mg_file_in_memory {
  2042. char *p;
  2043. uint32_t pos;
  2044. char mode;
  2045. };
  2046. struct mg_file_access {
  2047. /* File properties filled by mg_fopen: */
  2048. FILE *fp;
  2049. #if defined(MG_USE_OPEN_FILE)
  2050. /* TODO (low): Remove obsolete "file in memory" implementation.
  2051. * In an "early 2017" discussion at Google groups
  2052. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2053. * we decided to get rid of this feature (after some fade-out
  2054. * phase). */
  2055. const char *membuf;
  2056. #endif
  2057. };
  2058. struct mg_file {
  2059. struct mg_file_stat stat;
  2060. struct mg_file_access access;
  2061. };
  2062. #if defined(MG_USE_OPEN_FILE)
  2063. #define STRUCT_FILE_INITIALIZER \
  2064. { \
  2065. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2066. { \
  2067. (FILE *)NULL, (const char *)NULL \
  2068. } \
  2069. }
  2070. #else
  2071. #define STRUCT_FILE_INITIALIZER \
  2072. { \
  2073. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2074. { \
  2075. (FILE *)NULL \
  2076. } \
  2077. }
  2078. #endif
  2079. /* Describes listening socket, or socket which was accept()-ed by the master
  2080. * thread and queued for future handling by the worker thread. */
  2081. struct socket {
  2082. SOCKET sock; /* Listening socket */
  2083. union usa lsa; /* Local socket address */
  2084. union usa rsa; /* Remote socket address */
  2085. unsigned char is_ssl; /* Is port SSL-ed */
  2086. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2087. * port */
  2088. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2089. };
  2090. /* Enum const for all options must be in sync with
  2091. * static struct mg_option config_options[]
  2092. * This is tested in the unit test (test/private.c)
  2093. * "Private Config Options"
  2094. */
  2095. enum {
  2096. /* Once for each server */
  2097. LISTENING_PORTS,
  2098. NUM_THREADS,
  2099. RUN_AS_USER,
  2100. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2101. * socket option typedef TCP_NODELAY. */
  2102. MAX_REQUEST_SIZE,
  2103. LINGER_TIMEOUT,
  2104. CONNECTION_QUEUE_SIZE,
  2105. LISTEN_BACKLOG_SIZE,
  2106. #if defined(__linux__)
  2107. ALLOW_SENDFILE_CALL,
  2108. #endif
  2109. #if defined(_WIN32)
  2110. CASE_SENSITIVE_FILES,
  2111. #endif
  2112. THROTTLE,
  2113. ACCESS_LOG_FILE,
  2114. ERROR_LOG_FILE,
  2115. ENABLE_KEEP_ALIVE,
  2116. REQUEST_TIMEOUT,
  2117. KEEP_ALIVE_TIMEOUT,
  2118. #if defined(USE_WEBSOCKET)
  2119. WEBSOCKET_TIMEOUT,
  2120. ENABLE_WEBSOCKET_PING_PONG,
  2121. #endif
  2122. DECODE_URL,
  2123. #if defined(USE_LUA)
  2124. LUA_BACKGROUND_SCRIPT,
  2125. LUA_BACKGROUND_SCRIPT_PARAMS,
  2126. #endif
  2127. #if defined(USE_TIMERS)
  2128. CGI_TIMEOUT,
  2129. #endif
  2130. /* Once for each domain */
  2131. DOCUMENT_ROOT,
  2132. CGI_EXTENSIONS,
  2133. CGI_ENVIRONMENT,
  2134. PUT_DELETE_PASSWORDS_FILE,
  2135. CGI_INTERPRETER,
  2136. CGI_INTERPRETER_ARGS,
  2137. PROTECT_URI,
  2138. AUTHENTICATION_DOMAIN,
  2139. ENABLE_AUTH_DOMAIN_CHECK,
  2140. SSI_EXTENSIONS,
  2141. ENABLE_DIRECTORY_LISTING,
  2142. GLOBAL_PASSWORDS_FILE,
  2143. INDEX_FILES,
  2144. ACCESS_CONTROL_LIST,
  2145. EXTRA_MIME_TYPES,
  2146. SSL_CERTIFICATE,
  2147. SSL_CERTIFICATE_CHAIN,
  2148. URL_REWRITE_PATTERN,
  2149. HIDE_FILES,
  2150. SSL_DO_VERIFY_PEER,
  2151. SSL_CA_PATH,
  2152. SSL_CA_FILE,
  2153. SSL_VERIFY_DEPTH,
  2154. SSL_DEFAULT_VERIFY_PATHS,
  2155. SSL_CIPHER_LIST,
  2156. SSL_PROTOCOL_VERSION,
  2157. SSL_SHORT_TRUST,
  2158. #if defined(USE_LUA)
  2159. LUA_PRELOAD_FILE,
  2160. LUA_SCRIPT_EXTENSIONS,
  2161. LUA_SERVER_PAGE_EXTENSIONS,
  2162. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2163. LUA_DEBUG_PARAMS,
  2164. #endif
  2165. #endif
  2166. #if defined(USE_DUKTAPE)
  2167. DUKTAPE_SCRIPT_EXTENSIONS,
  2168. #endif
  2169. #if defined(USE_WEBSOCKET)
  2170. WEBSOCKET_ROOT,
  2171. #endif
  2172. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2173. LUA_WEBSOCKET_EXTENSIONS,
  2174. #endif
  2175. ACCESS_CONTROL_ALLOW_ORIGIN,
  2176. ACCESS_CONTROL_ALLOW_METHODS,
  2177. ACCESS_CONTROL_ALLOW_HEADERS,
  2178. ERROR_PAGES,
  2179. #if !defined(NO_CACHING)
  2180. STATIC_FILE_MAX_AGE,
  2181. STATIC_FILE_CACHE_CONTROL,
  2182. #endif
  2183. #if !defined(NO_SSL)
  2184. STRICT_HTTPS_MAX_AGE,
  2185. #endif
  2186. ADDITIONAL_HEADER,
  2187. ALLOW_INDEX_SCRIPT_SUB_RES,
  2188. #if defined(DAEMONIZE)
  2189. ENABLE_DAEMONIZE,
  2190. #endif
  2191. NUM_OPTIONS
  2192. };
  2193. /* Config option name, config types, default value.
  2194. * Must be in the same order as the enum const above.
  2195. */
  2196. static const struct mg_option config_options[] = {
  2197. /* Once for each server */
  2198. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2199. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2200. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2201. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2202. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2203. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2204. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2205. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2206. #if defined(__linux__)
  2207. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2208. #endif
  2209. #if defined(_WIN32)
  2210. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2211. #endif
  2212. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2213. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2214. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2215. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2216. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2217. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2218. #if defined(USE_WEBSOCKET)
  2219. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2220. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2221. #endif
  2222. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2223. #if defined(USE_LUA)
  2224. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2225. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2226. #endif
  2227. #if defined(USE_TIMERS)
  2228. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2229. #endif
  2230. /* Once for each domain */
  2231. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2232. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2233. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2234. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2235. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2236. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2237. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2238. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2239. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2240. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2241. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2242. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2243. {"index_files",
  2244. MG_CONFIG_TYPE_STRING_LIST,
  2245. #if defined(USE_LUA)
  2246. "index.xhtml,index.html,index.htm,"
  2247. "index.lp,index.lsp,index.lua,index.cgi,"
  2248. "index.shtml,index.php"},
  2249. #else
  2250. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2251. #endif
  2252. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2253. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2254. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2255. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2256. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2257. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2258. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2259. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2260. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2261. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2262. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2263. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2264. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2265. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2266. #if defined(USE_LUA)
  2267. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2268. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2269. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2270. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2271. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2272. #endif
  2273. #endif
  2274. #if defined(USE_DUKTAPE)
  2275. /* The support for duktape is still in alpha version state.
  2276. * The name of this config option might change. */
  2277. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2278. #endif
  2279. #if defined(USE_WEBSOCKET)
  2280. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2281. #endif
  2282. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2283. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2284. #endif
  2285. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2286. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2287. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2288. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2289. #if !defined(NO_CACHING)
  2290. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2291. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2292. #endif
  2293. #if !defined(NO_SSL)
  2294. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2295. #endif
  2296. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2297. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2298. #if defined(DAEMONIZE)
  2299. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2300. #endif
  2301. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2302. /* Check if the config_options and the corresponding enum have compatible
  2303. * sizes. */
  2304. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2305. == (NUM_OPTIONS + 1),
  2306. "config_options and enum not sync");
  2307. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2308. struct mg_handler_info {
  2309. /* Name/Pattern of the URI. */
  2310. char *uri;
  2311. size_t uri_len;
  2312. /* handler type */
  2313. int handler_type;
  2314. /* Handler for http/https or authorization requests. */
  2315. mg_request_handler handler;
  2316. unsigned int refcount;
  2317. int removing;
  2318. /* Handler for ws/wss (websocket) requests. */
  2319. mg_websocket_connect_handler connect_handler;
  2320. mg_websocket_ready_handler ready_handler;
  2321. mg_websocket_data_handler data_handler;
  2322. mg_websocket_close_handler close_handler;
  2323. /* accepted subprotocols for ws/wss requests. */
  2324. struct mg_websocket_subprotocols *subprotocols;
  2325. /* Handler for authorization requests */
  2326. mg_authorization_handler auth_handler;
  2327. /* User supplied argument for the handler function. */
  2328. void *cbdata;
  2329. /* next handler in a linked list */
  2330. struct mg_handler_info *next;
  2331. };
  2332. enum {
  2333. CONTEXT_INVALID,
  2334. CONTEXT_SERVER,
  2335. CONTEXT_HTTP_CLIENT,
  2336. CONTEXT_WS_CLIENT
  2337. };
  2338. struct mg_domain_context {
  2339. SSL_CTX *ssl_ctx; /* SSL context */
  2340. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2341. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2342. int64_t ssl_cert_last_mtime;
  2343. /* Server nonce */
  2344. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2345. unsigned long nonce_count; /* Used nonces, used for authentication */
  2346. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2347. /* linked list of shared lua websockets */
  2348. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2349. #endif
  2350. /* Linked list of domains */
  2351. struct mg_domain_context *next;
  2352. };
  2353. /* Stop flag can be "volatile" or require a lock */
  2354. typedef int volatile stop_flag_t;
  2355. #ifdef STOP_FLAG_NEEDS_LOCK
  2356. static int
  2357. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2358. {
  2359. int r;
  2360. mg_global_lock();
  2361. r = ((*f) == 0);
  2362. mg_global_unlock();
  2363. return r;
  2364. }
  2365. static int
  2366. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2367. {
  2368. int r;
  2369. mg_global_lock();
  2370. r = ((*f) == 2);
  2371. mg_global_unlock();
  2372. return r;
  2373. }
  2374. static void
  2375. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2376. {
  2377. mg_global_lock();
  2378. (*f) = v;
  2379. mg_global_unlock();
  2380. }
  2381. #else /* STOP_FLAG_NEEDS_LOCK */
  2382. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2383. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2384. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2385. #endif /* STOP_FLAG_NEEDS_LOCK */
  2386. struct mg_context {
  2387. /* Part 1 - Physical context:
  2388. * This holds threads, ports, timeouts, ...
  2389. * set for the entire server, independent from the
  2390. * addressed hostname.
  2391. */
  2392. /* Connection related */
  2393. int context_type; /* See CONTEXT_* above */
  2394. struct socket *listening_sockets;
  2395. struct mg_pollfd *listening_socket_fds;
  2396. unsigned int num_listening_sockets;
  2397. struct mg_connection *worker_connections; /* The connection struct, pre-
  2398. * allocated for each worker */
  2399. #if defined(USE_SERVER_STATS)
  2400. int active_connections;
  2401. int max_active_connections;
  2402. int64_t total_connections;
  2403. int64_t total_requests;
  2404. int64_t total_data_read;
  2405. int64_t total_data_written;
  2406. #endif
  2407. /* Thread related */
  2408. stop_flag_t stop_flag; /* Should we stop event loop */
  2409. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2410. pthread_t masterthreadid; /* The master thread ID */
  2411. unsigned int
  2412. cfg_worker_threads; /* The number of configured worker threads. */
  2413. pthread_t *worker_threadids; /* The worker thread IDs */
  2414. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2415. /* Connection to thread dispatching */
  2416. #if defined(ALTERNATIVE_QUEUE)
  2417. struct socket *client_socks;
  2418. void **client_wait_events;
  2419. #else
  2420. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2421. worker thread */
  2422. volatile int sq_head; /* Head of the socket queue */
  2423. volatile int sq_tail; /* Tail of the socket queue */
  2424. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2425. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2426. volatile int sq_blocked; /* Status information: sq is full */
  2427. int sq_size; /* No of elements in socket queue */
  2428. #if defined(USE_SERVER_STATS)
  2429. int sq_max_fill;
  2430. #endif /* USE_SERVER_STATS */
  2431. #endif /* ALTERNATIVE_QUEUE */
  2432. /* Memory related */
  2433. unsigned int max_request_size; /* The max request size */
  2434. #if defined(USE_SERVER_STATS)
  2435. struct mg_memory_stat ctx_memory;
  2436. #endif
  2437. /* Operating system related */
  2438. char *systemName; /* What operating system is running */
  2439. time_t start_time; /* Server start time, used for authentication
  2440. * and for diagnstics. */
  2441. #if defined(USE_TIMERS)
  2442. struct ttimers *timers;
  2443. #endif
  2444. /* Lua specific: Background operations and shared websockets */
  2445. #if defined(USE_LUA)
  2446. void *lua_background_state;
  2447. #endif
  2448. /* Server nonce */
  2449. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2450. * ssl_cert_last_mtime, nonce_count, and
  2451. * next (linked list) */
  2452. /* Server callbacks */
  2453. struct mg_callbacks callbacks; /* User-defined callback function */
  2454. void *user_data; /* User-defined data */
  2455. /* Part 2 - Logical domain:
  2456. * This holds hostname, TLS certificate, document root, ...
  2457. * set for a domain hosted at the server.
  2458. * There may be multiple domains hosted at one physical server.
  2459. * The default domain "dd" is the first element of a list of
  2460. * domains.
  2461. */
  2462. struct mg_domain_context dd; /* default domain */
  2463. };
  2464. #if defined(USE_SERVER_STATS)
  2465. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2466. static struct mg_memory_stat *
  2467. get_memory_stat(struct mg_context *ctx)
  2468. {
  2469. if (ctx) {
  2470. return &(ctx->ctx_memory);
  2471. }
  2472. return &mg_common_memory;
  2473. }
  2474. #endif
  2475. enum {
  2476. CONNECTION_TYPE_INVALID,
  2477. CONNECTION_TYPE_REQUEST,
  2478. CONNECTION_TYPE_RESPONSE
  2479. };
  2480. enum {
  2481. PROTOCOL_TYPE_HTTP1 = 0,
  2482. PROTOCOL_TYPE_WEBSOCKET = 1,
  2483. PROTOCOL_TYPE_HTTP2 = 2
  2484. };
  2485. struct mg_connection {
  2486. int connection_type; /* see CONNECTION_TYPE_* above */
  2487. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2488. struct mg_request_info request_info;
  2489. struct mg_response_info response_info;
  2490. struct mg_context *phys_ctx;
  2491. struct mg_domain_context *dom_ctx;
  2492. #if defined(USE_SERVER_STATS)
  2493. int conn_state; /* 0 = undef, numerical value may change in different
  2494. * versions. For the current definition, see
  2495. * mg_get_connection_info_impl */
  2496. #endif
  2497. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2498. SSL *ssl; /* SSL descriptor */
  2499. struct socket client; /* Connected client */
  2500. time_t conn_birth_time; /* Time (wall clock) when connection was
  2501. * established */
  2502. #if defined(USE_SERVER_STATS)
  2503. time_t conn_close_time; /* Time (wall clock) when connection was
  2504. * closed (or 0 if still open) */
  2505. #endif
  2506. struct timespec req_time; /* Time (since system start) when the request
  2507. * was received */
  2508. int64_t num_bytes_sent; /* Total bytes sent to client */
  2509. int64_t content_len; /* How many bytes of content can be read
  2510. * !is_chunked: Content-Length header value
  2511. * or -1 (until connection closed,
  2512. * not allowed for a request)
  2513. * is_chunked: >= 0, appended gradually
  2514. */
  2515. int64_t consumed_content; /* How many bytes of content have been read */
  2516. int is_chunked; /* Transfer-Encoding is chunked:
  2517. * 0 = not chunked,
  2518. * 1 = chunked, not yet, or some data read,
  2519. * 2 = chunked, has error,
  2520. * 3 = chunked, all data read except trailer,
  2521. * 4 = chunked, all data read
  2522. */
  2523. char *buf; /* Buffer for received data */
  2524. char *path_info; /* PATH_INFO part of the URL */
  2525. int must_close; /* 1 if connection must be closed */
  2526. int accept_gzip; /* 1 if gzip encoding is accepted */
  2527. int in_error_handler; /* 1 if in handler for user defined error
  2528. * pages */
  2529. #if defined(USE_WEBSOCKET)
  2530. int in_websocket_handling; /* 1 if in read_websocket */
  2531. #endif
  2532. int handled_requests; /* Number of requests handled by this connection
  2533. */
  2534. int buf_size; /* Buffer size */
  2535. int request_len; /* Size of the request + headers in a buffer */
  2536. int data_len; /* Total size of data in a buffer */
  2537. int status_code; /* HTTP reply status code, e.g. 200 */
  2538. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2539. * throttle */
  2540. time_t last_throttle_time; /* Last time throttled data was sent */
  2541. int last_throttle_bytes; /* Bytes sent this second */
  2542. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2543. * atomic transmissions for websockets */
  2544. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2545. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2546. #endif
  2547. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2548. * for quick access */
  2549. };
  2550. /* Directory entry */
  2551. struct de {
  2552. struct mg_connection *conn;
  2553. char *file_name;
  2554. struct mg_file_stat file;
  2555. };
  2556. #define mg_cry_internal(conn, fmt, ...) \
  2557. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2558. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2559. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2560. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2561. struct mg_context *ctx,
  2562. const char *func,
  2563. unsigned line,
  2564. const char *fmt,
  2565. ...) PRINTF_ARGS(5, 6);
  2566. #if !defined(NO_THREAD_NAME)
  2567. #if defined(_WIN32) && defined(_MSC_VER)
  2568. /* Set the thread name for debugging purposes in Visual Studio
  2569. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2570. */
  2571. #pragma pack(push, 8)
  2572. typedef struct tagTHREADNAME_INFO {
  2573. DWORD dwType; /* Must be 0x1000. */
  2574. LPCSTR szName; /* Pointer to name (in user addr space). */
  2575. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2576. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2577. } THREADNAME_INFO;
  2578. #pragma pack(pop)
  2579. #elif defined(__linux__)
  2580. #include <sys/prctl.h>
  2581. #include <sys/sendfile.h>
  2582. #if defined(ALTERNATIVE_QUEUE)
  2583. #include <sys/eventfd.h>
  2584. #endif /* ALTERNATIVE_QUEUE */
  2585. #if defined(ALTERNATIVE_QUEUE)
  2586. static void *
  2587. event_create(void)
  2588. {
  2589. int evhdl = eventfd(0, EFD_CLOEXEC);
  2590. int *ret;
  2591. if (evhdl == -1) {
  2592. /* Linux uses -1 on error, Windows NULL. */
  2593. /* However, Linux does not return 0 on success either. */
  2594. return 0;
  2595. }
  2596. ret = (int *)mg_malloc(sizeof(int));
  2597. if (ret) {
  2598. *ret = evhdl;
  2599. } else {
  2600. (void)close(evhdl);
  2601. }
  2602. return (void *)ret;
  2603. }
  2604. static int
  2605. event_wait(void *eventhdl)
  2606. {
  2607. uint64_t u;
  2608. int evhdl, s;
  2609. if (!eventhdl) {
  2610. /* error */
  2611. return 0;
  2612. }
  2613. evhdl = *(int *)eventhdl;
  2614. s = (int)read(evhdl, &u, sizeof(u));
  2615. if (s != sizeof(u)) {
  2616. /* error */
  2617. return 0;
  2618. }
  2619. (void)u; /* the value is not required */
  2620. return 1;
  2621. }
  2622. static int
  2623. event_signal(void *eventhdl)
  2624. {
  2625. uint64_t u = 1;
  2626. int evhdl, s;
  2627. if (!eventhdl) {
  2628. /* error */
  2629. return 0;
  2630. }
  2631. evhdl = *(int *)eventhdl;
  2632. s = (int)write(evhdl, &u, sizeof(u));
  2633. if (s != sizeof(u)) {
  2634. /* error */
  2635. return 0;
  2636. }
  2637. return 1;
  2638. }
  2639. static void
  2640. event_destroy(void *eventhdl)
  2641. {
  2642. int evhdl;
  2643. if (!eventhdl) {
  2644. /* error */
  2645. return;
  2646. }
  2647. evhdl = *(int *)eventhdl;
  2648. close(evhdl);
  2649. mg_free(eventhdl);
  2650. }
  2651. #endif
  2652. #endif
  2653. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2654. struct posix_event {
  2655. pthread_mutex_t mutex;
  2656. pthread_cond_t cond;
  2657. int signaled;
  2658. };
  2659. static void *
  2660. event_create(void)
  2661. {
  2662. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2663. if (ret == 0) {
  2664. /* out of memory */
  2665. return 0;
  2666. }
  2667. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2668. /* pthread mutex not available */
  2669. mg_free(ret);
  2670. return 0;
  2671. }
  2672. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2673. /* pthread cond not available */
  2674. pthread_mutex_destroy(&(ret->mutex));
  2675. mg_free(ret);
  2676. return 0;
  2677. }
  2678. ret->signaled = 0;
  2679. return (void *)ret;
  2680. }
  2681. static int
  2682. event_wait(void *eventhdl)
  2683. {
  2684. struct posix_event *ev = (struct posix_event *)eventhdl;
  2685. pthread_mutex_lock(&(ev->mutex));
  2686. while (!ev->signaled) {
  2687. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2688. }
  2689. ev->signaled = 0;
  2690. pthread_mutex_unlock(&(ev->mutex));
  2691. return 1;
  2692. }
  2693. static int
  2694. event_signal(void *eventhdl)
  2695. {
  2696. struct posix_event *ev = (struct posix_event *)eventhdl;
  2697. pthread_mutex_lock(&(ev->mutex));
  2698. pthread_cond_signal(&(ev->cond));
  2699. ev->signaled = 1;
  2700. pthread_mutex_unlock(&(ev->mutex));
  2701. return 1;
  2702. }
  2703. static void
  2704. event_destroy(void *eventhdl)
  2705. {
  2706. struct posix_event *ev = (struct posix_event *)eventhdl;
  2707. pthread_cond_destroy(&(ev->cond));
  2708. pthread_mutex_destroy(&(ev->mutex));
  2709. mg_free(ev);
  2710. }
  2711. #endif
  2712. static void
  2713. mg_set_thread_name(const char *name)
  2714. {
  2715. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2716. mg_snprintf(
  2717. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2718. #if defined(_WIN32)
  2719. #if defined(_MSC_VER)
  2720. /* Windows and Visual Studio Compiler */
  2721. __try {
  2722. THREADNAME_INFO info;
  2723. info.dwType = 0x1000;
  2724. info.szName = threadName;
  2725. info.dwThreadID = ~0U;
  2726. info.dwFlags = 0;
  2727. RaiseException(0x406D1388,
  2728. 0,
  2729. sizeof(info) / sizeof(ULONG_PTR),
  2730. (ULONG_PTR *)&info);
  2731. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2732. }
  2733. #elif defined(__MINGW32__)
  2734. /* No option known to set thread name for MinGW known */
  2735. #endif
  2736. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2737. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2738. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2739. #if defined(__MACH__)
  2740. /* OS X only current thread name can be changed */
  2741. (void)pthread_setname_np(threadName);
  2742. #else
  2743. (void)pthread_setname_np(pthread_self(), threadName);
  2744. #endif
  2745. #elif defined(__linux__)
  2746. /* On Linux we can use the prctl function.
  2747. * When building for Linux Standard Base (LSB) use
  2748. * NO_THREAD_NAME. However, thread names are a big
  2749. * help for debugging, so the stadard is to set them.
  2750. */
  2751. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2752. #endif
  2753. }
  2754. #else /* !defined(NO_THREAD_NAME) */
  2755. void
  2756. mg_set_thread_name(const char *threadName)
  2757. {
  2758. }
  2759. #endif
  2760. #if defined(MG_LEGACY_INTERFACE)
  2761. const char **
  2762. mg_get_valid_option_names(void)
  2763. {
  2764. /* This function is deprecated. Use mg_get_valid_options instead. */
  2765. static const char
  2766. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2767. int i;
  2768. for (i = 0; config_options[i].name != NULL; i++) {
  2769. data[i * 2] = config_options[i].name;
  2770. data[i * 2 + 1] = config_options[i].default_value;
  2771. }
  2772. return data;
  2773. }
  2774. #endif
  2775. const struct mg_option *
  2776. mg_get_valid_options(void)
  2777. {
  2778. return config_options;
  2779. }
  2780. /* Do not open file (used in is_file_in_memory) */
  2781. #define MG_FOPEN_MODE_NONE (0)
  2782. /* Open file for read only access */
  2783. #define MG_FOPEN_MODE_READ (1)
  2784. /* Open file for writing, create and overwrite */
  2785. #define MG_FOPEN_MODE_WRITE (2)
  2786. /* Open file for writing, create and append */
  2787. #define MG_FOPEN_MODE_APPEND (4)
  2788. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2789. * output filep and return 1, otherwise return 0 and don't modify anything.
  2790. */
  2791. static int
  2792. open_file_in_memory(const struct mg_connection *conn,
  2793. const char *path,
  2794. struct mg_file *filep,
  2795. int mode)
  2796. {
  2797. #if defined(MG_USE_OPEN_FILE)
  2798. size_t size = 0;
  2799. const char *buf = NULL;
  2800. if (!conn) {
  2801. return 0;
  2802. }
  2803. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2804. return 0;
  2805. }
  2806. if (conn->phys_ctx->callbacks.open_file) {
  2807. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2808. if (buf != NULL) {
  2809. if (filep == NULL) {
  2810. /* This is a file in memory, but we cannot store the
  2811. * properties
  2812. * now.
  2813. * Called from "is_file_in_memory" function. */
  2814. return 1;
  2815. }
  2816. /* NOTE: override filep->size only on success. Otherwise, it
  2817. * might
  2818. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2819. filep->access.membuf = buf;
  2820. filep->access.fp = NULL;
  2821. /* Size was set by the callback */
  2822. filep->stat.size = size;
  2823. /* Assume the data may change during runtime by setting
  2824. * last_modified = now */
  2825. filep->stat.last_modified = time(NULL);
  2826. filep->stat.is_directory = 0;
  2827. filep->stat.is_gzipped = 0;
  2828. }
  2829. }
  2830. return (buf != NULL);
  2831. #else
  2832. (void)conn;
  2833. (void)path;
  2834. (void)filep;
  2835. (void)mode;
  2836. return 0;
  2837. #endif
  2838. }
  2839. static int
  2840. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2841. {
  2842. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2843. }
  2844. static int
  2845. is_file_opened(const struct mg_file_access *fileacc)
  2846. {
  2847. if (!fileacc) {
  2848. return 0;
  2849. }
  2850. #if defined(MG_USE_OPEN_FILE)
  2851. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2852. #else
  2853. return (fileacc->fp != NULL);
  2854. #endif
  2855. }
  2856. #if !defined(NO_FILESYSTEMS)
  2857. static int mg_stat(const struct mg_connection *conn,
  2858. const char *path,
  2859. struct mg_file_stat *filep);
  2860. /* mg_fopen will open a file either in memory or on the disk.
  2861. * The input parameter path is a string in UTF-8 encoding.
  2862. * The input parameter mode is MG_FOPEN_MODE_*
  2863. * On success, either fp or membuf will be set in the output
  2864. * struct file. All status members will also be set.
  2865. * The function returns 1 on success, 0 on error. */
  2866. static int
  2867. mg_fopen(const struct mg_connection *conn,
  2868. const char *path,
  2869. int mode,
  2870. struct mg_file *filep)
  2871. {
  2872. int found;
  2873. if (!filep) {
  2874. return 0;
  2875. }
  2876. filep->access.fp = NULL;
  2877. #if defined(MG_USE_OPEN_FILE)
  2878. filep->access.membuf = NULL;
  2879. #endif
  2880. if (!is_file_in_memory(conn, path)) {
  2881. /* filep is initialized in mg_stat: all fields with memset to,
  2882. * some fields like size and modification date with values */
  2883. found = mg_stat(conn, path, &(filep->stat));
  2884. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2885. /* file does not exist and will not be created */
  2886. return 0;
  2887. }
  2888. #if defined(_WIN32)
  2889. {
  2890. wchar_t wbuf[W_PATH_MAX];
  2891. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2892. switch (mode) {
  2893. case MG_FOPEN_MODE_READ:
  2894. filep->access.fp = _wfopen(wbuf, L"rb");
  2895. break;
  2896. case MG_FOPEN_MODE_WRITE:
  2897. filep->access.fp = _wfopen(wbuf, L"wb");
  2898. break;
  2899. case MG_FOPEN_MODE_APPEND:
  2900. filep->access.fp = _wfopen(wbuf, L"ab");
  2901. break;
  2902. }
  2903. }
  2904. #else
  2905. /* Linux et al already use unicode. No need to convert. */
  2906. switch (mode) {
  2907. case MG_FOPEN_MODE_READ:
  2908. filep->access.fp = fopen(path, "r");
  2909. break;
  2910. case MG_FOPEN_MODE_WRITE:
  2911. filep->access.fp = fopen(path, "w");
  2912. break;
  2913. case MG_FOPEN_MODE_APPEND:
  2914. filep->access.fp = fopen(path, "a");
  2915. break;
  2916. }
  2917. #endif
  2918. if (!found) {
  2919. /* File did not exist before fopen was called.
  2920. * Maybe it has been created now. Get stat info
  2921. * like creation time now. */
  2922. found = mg_stat(conn, path, &(filep->stat));
  2923. (void)found;
  2924. }
  2925. /* file is on disk */
  2926. return (filep->access.fp != NULL);
  2927. } else {
  2928. #if defined(MG_USE_OPEN_FILE)
  2929. /* is_file_in_memory returned true */
  2930. if (open_file_in_memory(conn, path, filep, mode)) {
  2931. /* file is in memory */
  2932. return (filep->access.membuf != NULL);
  2933. }
  2934. #endif
  2935. }
  2936. /* Open failed */
  2937. return 0;
  2938. }
  2939. /* return 0 on success, just like fclose */
  2940. static int
  2941. mg_fclose(struct mg_file_access *fileacc)
  2942. {
  2943. int ret = -1;
  2944. if (fileacc != NULL) {
  2945. if (fileacc->fp != NULL) {
  2946. ret = fclose(fileacc->fp);
  2947. #if defined(MG_USE_OPEN_FILE)
  2948. } else if (fileacc->membuf != NULL) {
  2949. ret = 0;
  2950. #endif
  2951. }
  2952. /* reset all members of fileacc */
  2953. memset(fileacc, 0, sizeof(*fileacc));
  2954. }
  2955. return ret;
  2956. }
  2957. #endif /* NO_FILESYSTEMS */
  2958. static void
  2959. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2960. {
  2961. for (; *src != '\0' && n > 1; n--) {
  2962. *dst++ = *src++;
  2963. }
  2964. *dst = '\0';
  2965. }
  2966. static int
  2967. lowercase(const char *s)
  2968. {
  2969. return tolower((unsigned char)*s);
  2970. }
  2971. int
  2972. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2973. {
  2974. int diff = 0;
  2975. if (len > 0) {
  2976. do {
  2977. diff = lowercase(s1++) - lowercase(s2++);
  2978. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2979. }
  2980. return diff;
  2981. }
  2982. int
  2983. mg_strcasecmp(const char *s1, const char *s2)
  2984. {
  2985. int diff;
  2986. do {
  2987. diff = lowercase(s1++) - lowercase(s2++);
  2988. } while (diff == 0 && s1[-1] != '\0');
  2989. return diff;
  2990. }
  2991. static char *
  2992. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2993. {
  2994. char *p;
  2995. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2996. * defined */
  2997. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2998. mg_strlcpy(p, ptr, len + 1);
  2999. }
  3000. return p;
  3001. }
  3002. static char *
  3003. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3004. {
  3005. return mg_strndup_ctx(str, strlen(str), ctx);
  3006. }
  3007. static char *
  3008. mg_strdup(const char *str)
  3009. {
  3010. return mg_strndup_ctx(str, strlen(str), NULL);
  3011. }
  3012. static const char *
  3013. mg_strcasestr(const char *big_str, const char *small_str)
  3014. {
  3015. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3016. if (big_len >= small_len) {
  3017. for (i = 0; i <= (big_len - small_len); i++) {
  3018. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3019. return big_str + i;
  3020. }
  3021. }
  3022. }
  3023. return NULL;
  3024. }
  3025. /* Return null terminated string of given maximum length.
  3026. * Report errors if length is exceeded. */
  3027. static void
  3028. mg_vsnprintf(const struct mg_connection *conn,
  3029. int *truncated,
  3030. char *buf,
  3031. size_t buflen,
  3032. const char *fmt,
  3033. va_list ap)
  3034. {
  3035. int n, ok;
  3036. if (buflen == 0) {
  3037. if (truncated) {
  3038. *truncated = 1;
  3039. }
  3040. return;
  3041. }
  3042. #if defined(__clang__)
  3043. #pragma clang diagnostic push
  3044. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3045. /* Using fmt as a non-literal is intended here, since it is mostly called
  3046. * indirectly by mg_snprintf */
  3047. #endif
  3048. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3049. ok = (n >= 0) && ((size_t)n < buflen);
  3050. #if defined(__clang__)
  3051. #pragma clang diagnostic pop
  3052. #endif
  3053. if (ok) {
  3054. if (truncated) {
  3055. *truncated = 0;
  3056. }
  3057. } else {
  3058. if (truncated) {
  3059. *truncated = 1;
  3060. }
  3061. mg_cry_internal(conn,
  3062. "truncating vsnprintf buffer: [%.*s]",
  3063. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3064. buf);
  3065. n = (int)buflen - 1;
  3066. }
  3067. buf[n] = '\0';
  3068. }
  3069. static void
  3070. mg_snprintf(const struct mg_connection *conn,
  3071. int *truncated,
  3072. char *buf,
  3073. size_t buflen,
  3074. const char *fmt,
  3075. ...)
  3076. {
  3077. va_list ap;
  3078. va_start(ap, fmt);
  3079. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3080. va_end(ap);
  3081. }
  3082. static int
  3083. get_option_index(const char *name)
  3084. {
  3085. int i;
  3086. for (i = 0; config_options[i].name != NULL; i++) {
  3087. if (strcmp(config_options[i].name, name) == 0) {
  3088. return i;
  3089. }
  3090. }
  3091. return -1;
  3092. }
  3093. const char *
  3094. mg_get_option(const struct mg_context *ctx, const char *name)
  3095. {
  3096. int i;
  3097. if ((i = get_option_index(name)) == -1) {
  3098. return NULL;
  3099. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3100. return "";
  3101. } else {
  3102. return ctx->dd.config[i];
  3103. }
  3104. }
  3105. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3106. struct mg_context *
  3107. mg_get_context(const struct mg_connection *conn)
  3108. {
  3109. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3110. }
  3111. void *
  3112. mg_get_user_data(const struct mg_context *ctx)
  3113. {
  3114. return (ctx == NULL) ? NULL : ctx->user_data;
  3115. }
  3116. void *
  3117. mg_get_user_context_data(const struct mg_connection *conn)
  3118. {
  3119. return mg_get_user_data(mg_get_context(conn));
  3120. }
  3121. void *
  3122. mg_get_thread_pointer(const struct mg_connection *conn)
  3123. {
  3124. /* both methods should return the same pointer */
  3125. if (conn) {
  3126. /* quick access, in case conn is known */
  3127. return conn->tls_user_ptr;
  3128. } else {
  3129. /* otherwise get pointer from thread local storage (TLS) */
  3130. struct mg_workerTLS *tls =
  3131. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3132. return tls->user_ptr;
  3133. }
  3134. }
  3135. void
  3136. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3137. {
  3138. if (conn != NULL) {
  3139. conn->request_info.conn_data = data;
  3140. }
  3141. }
  3142. void *
  3143. mg_get_user_connection_data(const struct mg_connection *conn)
  3144. {
  3145. if (conn != NULL) {
  3146. return conn->request_info.conn_data;
  3147. }
  3148. return NULL;
  3149. }
  3150. #if defined(MG_LEGACY_INTERFACE)
  3151. /* Deprecated: Use mg_get_server_ports instead. */
  3152. size_t
  3153. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3154. {
  3155. size_t i;
  3156. if (!ctx) {
  3157. return 0;
  3158. }
  3159. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3160. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3161. ports[i] =
  3162. #if defined(USE_IPV6)
  3163. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3164. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3165. :
  3166. #endif
  3167. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3168. }
  3169. return i;
  3170. }
  3171. #endif
  3172. int
  3173. mg_get_server_ports(const struct mg_context *ctx,
  3174. int size,
  3175. struct mg_server_port *ports)
  3176. {
  3177. int i, cnt = 0;
  3178. if (size <= 0) {
  3179. return -1;
  3180. }
  3181. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3182. if (!ctx) {
  3183. return -1;
  3184. }
  3185. if (!ctx->listening_sockets) {
  3186. return -1;
  3187. }
  3188. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3189. ports[cnt].port =
  3190. #if defined(USE_IPV6)
  3191. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3192. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3193. :
  3194. #endif
  3195. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3196. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3197. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3198. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3199. /* IPv4 */
  3200. ports[cnt].protocol = 1;
  3201. cnt++;
  3202. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3203. /* IPv6 */
  3204. ports[cnt].protocol = 3;
  3205. cnt++;
  3206. }
  3207. }
  3208. return cnt;
  3209. }
  3210. static void
  3211. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3212. {
  3213. buf[0] = '\0';
  3214. if (!usa) {
  3215. return;
  3216. }
  3217. if (usa->sa.sa_family == AF_INET) {
  3218. getnameinfo(&usa->sa,
  3219. sizeof(usa->sin),
  3220. buf,
  3221. (unsigned)len,
  3222. NULL,
  3223. 0,
  3224. NI_NUMERICHOST);
  3225. }
  3226. #if defined(USE_IPV6)
  3227. else if (usa->sa.sa_family == AF_INET6) {
  3228. getnameinfo(&usa->sa,
  3229. sizeof(usa->sin6),
  3230. buf,
  3231. (unsigned)len,
  3232. NULL,
  3233. 0,
  3234. NI_NUMERICHOST);
  3235. }
  3236. #endif
  3237. }
  3238. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3239. * included in all responses other than 100, 101, 5xx. */
  3240. static void
  3241. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3242. {
  3243. #if !defined(REENTRANT_TIME)
  3244. struct tm *tm;
  3245. tm = ((t != NULL) ? gmtime(t) : NULL);
  3246. if (tm != NULL) {
  3247. #else
  3248. struct tm _tm;
  3249. struct tm *tm = &_tm;
  3250. if (t != NULL) {
  3251. gmtime_r(t, tm);
  3252. #endif
  3253. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3254. } else {
  3255. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3256. buf[buf_len - 1] = '\0';
  3257. }
  3258. }
  3259. /* difftime for struct timespec. Return value is in seconds. */
  3260. static double
  3261. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3262. {
  3263. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3264. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3265. }
  3266. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3267. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3268. const char *func,
  3269. unsigned line,
  3270. const char *fmt,
  3271. va_list ap);
  3272. #include "external_mg_cry_internal_impl.inl"
  3273. #elif !defined(NO_FILESYSTEMS)
  3274. /* Print error message to the opened error log stream. */
  3275. static void
  3276. mg_cry_internal_impl(const struct mg_connection *conn,
  3277. const char *func,
  3278. unsigned line,
  3279. const char *fmt,
  3280. va_list ap)
  3281. {
  3282. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3283. struct mg_file fi;
  3284. time_t timestamp;
  3285. /* Unused, in the RELEASE build */
  3286. (void)func;
  3287. (void)line;
  3288. #if defined(GCC_DIAGNOSTIC)
  3289. #pragma GCC diagnostic push
  3290. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3291. #endif
  3292. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3293. #if defined(GCC_DIAGNOSTIC)
  3294. #pragma GCC diagnostic pop
  3295. #endif
  3296. buf[sizeof(buf) - 1] = 0;
  3297. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3298. if (!conn) {
  3299. puts(buf);
  3300. return;
  3301. }
  3302. /* Do not lock when getting the callback value, here and below.
  3303. * I suppose this is fine, since function cannot disappear in the
  3304. * same way string option can. */
  3305. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3306. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3307. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3308. if (mg_fopen(conn,
  3309. conn->dom_ctx->config[ERROR_LOG_FILE],
  3310. MG_FOPEN_MODE_APPEND,
  3311. &fi)
  3312. == 0) {
  3313. fi.access.fp = NULL;
  3314. }
  3315. } else {
  3316. fi.access.fp = NULL;
  3317. }
  3318. if (fi.access.fp != NULL) {
  3319. flockfile(fi.access.fp);
  3320. timestamp = time(NULL);
  3321. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3322. fprintf(fi.access.fp,
  3323. "[%010lu] [error] [client %s] ",
  3324. (unsigned long)timestamp,
  3325. src_addr);
  3326. if (conn->request_info.request_method != NULL) {
  3327. fprintf(fi.access.fp,
  3328. "%s %s: ",
  3329. conn->request_info.request_method,
  3330. conn->request_info.request_uri
  3331. ? conn->request_info.request_uri
  3332. : "");
  3333. }
  3334. fprintf(fi.access.fp, "%s", buf);
  3335. fputc('\n', fi.access.fp);
  3336. fflush(fi.access.fp);
  3337. funlockfile(fi.access.fp);
  3338. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3339. * mg_cry here anyway ;-) */
  3340. }
  3341. }
  3342. }
  3343. #else
  3344. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3345. #endif /* Externally provided function */
  3346. /* Construct fake connection structure. Used for logging, if connection
  3347. * is not applicable at the moment of logging. */
  3348. static struct mg_connection *
  3349. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3350. {
  3351. static const struct mg_connection conn_zero = {0};
  3352. *fc = conn_zero;
  3353. fc->phys_ctx = ctx;
  3354. fc->dom_ctx = &(ctx->dd);
  3355. return fc;
  3356. }
  3357. static void
  3358. mg_cry_internal_wrap(const struct mg_connection *conn,
  3359. struct mg_context *ctx,
  3360. const char *func,
  3361. unsigned line,
  3362. const char *fmt,
  3363. ...)
  3364. {
  3365. va_list ap;
  3366. va_start(ap, fmt);
  3367. if (!conn && ctx) {
  3368. struct mg_connection fc;
  3369. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3370. } else {
  3371. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3372. }
  3373. va_end(ap);
  3374. }
  3375. void
  3376. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3377. {
  3378. va_list ap;
  3379. va_start(ap, fmt);
  3380. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3381. va_end(ap);
  3382. }
  3383. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3384. const char *
  3385. mg_version(void)
  3386. {
  3387. return CIVETWEB_VERSION;
  3388. }
  3389. const struct mg_request_info *
  3390. mg_get_request_info(const struct mg_connection *conn)
  3391. {
  3392. if (!conn) {
  3393. return NULL;
  3394. }
  3395. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3396. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3397. char txt[16];
  3398. struct mg_workerTLS *tls =
  3399. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3400. sprintf(txt, "%03i", conn->response_info.status_code);
  3401. if (strlen(txt) == 3) {
  3402. memcpy(tls->txtbuf, txt, 4);
  3403. } else {
  3404. strcpy(tls->txtbuf, "ERR");
  3405. }
  3406. ((struct mg_connection *)conn)->request_info.local_uri =
  3407. ((struct mg_connection *)conn)->request_info.request_uri =
  3408. tls->txtbuf; /* use thread safe buffer */
  3409. ((struct mg_connection *)conn)->request_info.num_headers =
  3410. conn->response_info.num_headers;
  3411. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3412. conn->response_info.http_headers,
  3413. sizeof(conn->response_info.http_headers));
  3414. } else
  3415. #endif
  3416. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3417. return NULL;
  3418. }
  3419. return &conn->request_info;
  3420. }
  3421. const struct mg_response_info *
  3422. mg_get_response_info(const struct mg_connection *conn)
  3423. {
  3424. if (!conn) {
  3425. return NULL;
  3426. }
  3427. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3428. return NULL;
  3429. }
  3430. return &conn->response_info;
  3431. }
  3432. static const char *
  3433. get_proto_name(const struct mg_connection *conn)
  3434. {
  3435. #if defined(__clang__)
  3436. #pragma clang diagnostic push
  3437. #pragma clang diagnostic ignored "-Wunreachable-code"
  3438. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3439. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3440. * unreachable, but splitting into four different #ifdef clauses here is more
  3441. * complicated.
  3442. */
  3443. #endif
  3444. const struct mg_request_info *ri = &conn->request_info;
  3445. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3446. ? (ri->is_ssl ? "wss" : "ws")
  3447. : (ri->is_ssl ? "https" : "http"));
  3448. return proto;
  3449. #if defined(__clang__)
  3450. #pragma clang diagnostic pop
  3451. #endif
  3452. }
  3453. int
  3454. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3455. {
  3456. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3457. return -1;
  3458. } else {
  3459. int truncated = 0;
  3460. const struct mg_request_info *ri = &conn->request_info;
  3461. const char *proto = get_proto_name(conn);
  3462. if (ri->local_uri == NULL) {
  3463. return -1;
  3464. }
  3465. if ((ri->request_uri != NULL)
  3466. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3467. /* The request uri is different from the local uri.
  3468. * This is usually if an absolute URI, including server
  3469. * name has been provided. */
  3470. mg_snprintf(conn,
  3471. &truncated,
  3472. buf,
  3473. buflen,
  3474. "%s://%s",
  3475. proto,
  3476. ri->request_uri);
  3477. if (truncated) {
  3478. return -1;
  3479. }
  3480. return 0;
  3481. } else {
  3482. /* The common case is a relative URI, so we have to
  3483. * construct an absolute URI from server name and port */
  3484. #if defined(USE_IPV6)
  3485. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3486. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3487. : htons(conn->client.lsa.sin.sin_port);
  3488. #else
  3489. int port = htons(conn->client.lsa.sin.sin_port);
  3490. #endif
  3491. int def_port = ri->is_ssl ? 443 : 80;
  3492. int auth_domain_check_enabled =
  3493. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3494. && (!mg_strcasecmp(
  3495. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3496. const char *server_domain =
  3497. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3498. char portstr[16];
  3499. char server_ip[48];
  3500. if (port != def_port) {
  3501. sprintf(portstr, ":%u", (unsigned)port);
  3502. } else {
  3503. portstr[0] = 0;
  3504. }
  3505. if (!auth_domain_check_enabled || !server_domain) {
  3506. sockaddr_to_string(server_ip,
  3507. sizeof(server_ip),
  3508. &conn->client.lsa);
  3509. server_domain = server_ip;
  3510. }
  3511. mg_snprintf(conn,
  3512. &truncated,
  3513. buf,
  3514. buflen,
  3515. "%s://%s%s%s",
  3516. proto,
  3517. server_domain,
  3518. portstr,
  3519. ri->local_uri);
  3520. if (truncated) {
  3521. return -1;
  3522. }
  3523. return 0;
  3524. }
  3525. }
  3526. }
  3527. /* Skip the characters until one of the delimiters characters found.
  3528. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3529. * Advance pointer to buffer to the next word. Return found 0-terminated
  3530. * word.
  3531. * Delimiters can be quoted with quotechar. */
  3532. static char *
  3533. skip_quoted(char **buf,
  3534. const char *delimiters,
  3535. const char *whitespace,
  3536. char quotechar)
  3537. {
  3538. char *p, *begin_word, *end_word, *end_whitespace;
  3539. begin_word = *buf;
  3540. end_word = begin_word + strcspn(begin_word, delimiters);
  3541. /* Check for quotechar */
  3542. if (end_word > begin_word) {
  3543. p = end_word - 1;
  3544. while (*p == quotechar) {
  3545. /* While the delimiter is quoted, look for the next delimiter.
  3546. */
  3547. /* This happens, e.g., in calls from parse_auth_header,
  3548. * if the user name contains a " character. */
  3549. /* If there is anything beyond end_word, copy it. */
  3550. if (*end_word != '\0') {
  3551. size_t end_off = strcspn(end_word + 1, delimiters);
  3552. memmove(p, end_word, end_off + 1);
  3553. p += end_off; /* p must correspond to end_word - 1 */
  3554. end_word += end_off + 1;
  3555. } else {
  3556. *p = '\0';
  3557. break;
  3558. }
  3559. }
  3560. for (p++; p < end_word; p++) {
  3561. *p = '\0';
  3562. }
  3563. }
  3564. if (*end_word == '\0') {
  3565. *buf = end_word;
  3566. } else {
  3567. #if defined(GCC_DIAGNOSTIC)
  3568. /* Disable spurious conversion warning for GCC */
  3569. #pragma GCC diagnostic push
  3570. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3571. #endif /* defined(GCC_DIAGNOSTIC) */
  3572. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3573. #if defined(GCC_DIAGNOSTIC)
  3574. #pragma GCC diagnostic pop
  3575. #endif /* defined(GCC_DIAGNOSTIC) */
  3576. for (p = end_word; p < end_whitespace; p++) {
  3577. *p = '\0';
  3578. }
  3579. *buf = end_whitespace;
  3580. }
  3581. return begin_word;
  3582. }
  3583. /* Return HTTP header value, or NULL if not found. */
  3584. static const char *
  3585. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3586. {
  3587. int i;
  3588. for (i = 0; i < num_hdr; i++) {
  3589. if (!mg_strcasecmp(name, hdr[i].name)) {
  3590. return hdr[i].value;
  3591. }
  3592. }
  3593. return NULL;
  3594. }
  3595. #if defined(USE_WEBSOCKET)
  3596. /* Retrieve requested HTTP header multiple values, and return the number of
  3597. * found occurrences */
  3598. static int
  3599. get_req_headers(const struct mg_request_info *ri,
  3600. const char *name,
  3601. const char **output,
  3602. int output_max_size)
  3603. {
  3604. int i;
  3605. int cnt = 0;
  3606. if (ri) {
  3607. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3608. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3609. output[cnt++] = ri->http_headers[i].value;
  3610. }
  3611. }
  3612. }
  3613. return cnt;
  3614. }
  3615. #endif
  3616. const char *
  3617. mg_get_header(const struct mg_connection *conn, const char *name)
  3618. {
  3619. if (!conn) {
  3620. return NULL;
  3621. }
  3622. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3623. return get_header(conn->request_info.http_headers,
  3624. conn->request_info.num_headers,
  3625. name);
  3626. }
  3627. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3628. return get_header(conn->response_info.http_headers,
  3629. conn->response_info.num_headers,
  3630. name);
  3631. }
  3632. return NULL;
  3633. }
  3634. static const char *
  3635. get_http_version(const struct mg_connection *conn)
  3636. {
  3637. if (!conn) {
  3638. return NULL;
  3639. }
  3640. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3641. return conn->request_info.http_version;
  3642. }
  3643. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3644. return conn->response_info.http_version;
  3645. }
  3646. return NULL;
  3647. }
  3648. /* A helper function for traversing a comma separated list of values.
  3649. * It returns a list pointer shifted to the next value, or NULL if the end
  3650. * of the list found.
  3651. * Value is stored in val vector. If value has form "x=y", then eq_val
  3652. * vector is initialized to point to the "y" part, and val vector length
  3653. * is adjusted to point only to "x". */
  3654. static const char *
  3655. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3656. {
  3657. int end;
  3658. reparse:
  3659. if (val == NULL || list == NULL || *list == '\0') {
  3660. /* End of the list */
  3661. return NULL;
  3662. }
  3663. /* Skip over leading LWS */
  3664. while (*list == ' ' || *list == '\t')
  3665. list++;
  3666. val->ptr = list;
  3667. if ((list = strchr(val->ptr, ',')) != NULL) {
  3668. /* Comma found. Store length and shift the list ptr */
  3669. val->len = ((size_t)(list - val->ptr));
  3670. list++;
  3671. } else {
  3672. /* This value is the last one */
  3673. list = val->ptr + strlen(val->ptr);
  3674. val->len = ((size_t)(list - val->ptr));
  3675. }
  3676. /* Adjust length for trailing LWS */
  3677. end = (int)val->len - 1;
  3678. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3679. end--;
  3680. val->len = (size_t)(end) + (size_t)(1);
  3681. if (val->len == 0) {
  3682. /* Ignore any empty entries. */
  3683. goto reparse;
  3684. }
  3685. if (eq_val != NULL) {
  3686. /* Value has form "x=y", adjust pointers and lengths
  3687. * so that val points to "x", and eq_val points to "y". */
  3688. eq_val->len = 0;
  3689. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3690. if (eq_val->ptr != NULL) {
  3691. eq_val->ptr++; /* Skip over '=' character */
  3692. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3693. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3694. }
  3695. }
  3696. return list;
  3697. }
  3698. /* A helper function for checking if a comma separated list of values
  3699. * contains
  3700. * the given option (case insensitvely).
  3701. * 'header' can be NULL, in which case false is returned. */
  3702. static int
  3703. header_has_option(const char *header, const char *option)
  3704. {
  3705. struct vec opt_vec;
  3706. struct vec eq_vec;
  3707. DEBUG_ASSERT(option != NULL);
  3708. DEBUG_ASSERT(option[0] != '\0');
  3709. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3710. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3711. return 1;
  3712. }
  3713. return 0;
  3714. }
  3715. /* Perform case-insensitive match of string against pattern */
  3716. static ptrdiff_t
  3717. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3718. {
  3719. const char *or_str;
  3720. ptrdiff_t i, j, len, res;
  3721. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3722. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3723. return (res > 0) ? res
  3724. : match_prefix(or_str + 1,
  3725. (size_t)((pattern + pattern_len)
  3726. - (or_str + 1)),
  3727. str);
  3728. }
  3729. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3730. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3731. continue;
  3732. } else if (pattern[i] == '$') {
  3733. return (str[j] == '\0') ? j : -1;
  3734. } else if (pattern[i] == '*') {
  3735. i++;
  3736. if (pattern[i] == '*') {
  3737. i++;
  3738. len = (ptrdiff_t)strlen(str + j);
  3739. } else {
  3740. len = (ptrdiff_t)strcspn(str + j, "/");
  3741. }
  3742. if (i == (ptrdiff_t)pattern_len) {
  3743. return j + len;
  3744. }
  3745. do {
  3746. res = match_prefix(pattern + i,
  3747. (pattern_len - (size_t)i),
  3748. str + j + len);
  3749. } while (res == -1 && len-- > 0);
  3750. return (res == -1) ? -1 : j + res + len;
  3751. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3752. return -1;
  3753. }
  3754. }
  3755. return (ptrdiff_t)j;
  3756. }
  3757. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3758. * This function must tolerate situations when connection info is not
  3759. * set up, for example if request parsing failed. */
  3760. static int
  3761. should_keep_alive(const struct mg_connection *conn)
  3762. {
  3763. const char *http_version;
  3764. const char *header;
  3765. /* First satisfy needs of the server */
  3766. if ((conn == NULL) || conn->must_close) {
  3767. /* Close, if civetweb framework needs to close */
  3768. return 0;
  3769. }
  3770. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3771. /* Close, if keep alive is not enabled */
  3772. return 0;
  3773. }
  3774. /* Check explicit wish of the client */
  3775. header = mg_get_header(conn, "Connection");
  3776. if (header) {
  3777. /* If there is a connection header from the client, obey */
  3778. if (header_has_option(header, "keep-alive")) {
  3779. return 1;
  3780. }
  3781. return 0;
  3782. }
  3783. /* Use default of the standard */
  3784. http_version = get_http_version(conn);
  3785. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3786. /* HTTP 1.1 default is keep alive */
  3787. return 1;
  3788. }
  3789. /* HTTP 1.0 (and earlier) default is to close the connection */
  3790. return 0;
  3791. }
  3792. static int
  3793. should_decode_url(const struct mg_connection *conn)
  3794. {
  3795. if (!conn || !conn->dom_ctx) {
  3796. return 0;
  3797. }
  3798. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3799. }
  3800. static const char *
  3801. suggest_connection_header(const struct mg_connection *conn)
  3802. {
  3803. return should_keep_alive(conn) ? "keep-alive" : "close";
  3804. }
  3805. static int
  3806. send_no_cache_header(struct mg_connection *conn)
  3807. {
  3808. /* Send all current and obsolete cache opt-out directives. */
  3809. return mg_printf(conn,
  3810. "Cache-Control: no-cache, no-store, "
  3811. "must-revalidate, private, max-age=0\r\n"
  3812. "Pragma: no-cache\r\n"
  3813. "Expires: 0\r\n");
  3814. }
  3815. static int
  3816. send_static_cache_header(struct mg_connection *conn)
  3817. {
  3818. #if !defined(NO_CACHING)
  3819. int max_age;
  3820. const char *cache_control =
  3821. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3822. if (cache_control != NULL) {
  3823. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3824. }
  3825. /* Read the server config to check how long a file may be cached.
  3826. * The configuration is in seconds. */
  3827. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3828. if (max_age <= 0) {
  3829. /* 0 means "do not cache". All values <0 are reserved
  3830. * and may be used differently in the future. */
  3831. /* If a file should not be cached, do not only send
  3832. * max-age=0, but also pragmas and Expires headers. */
  3833. return send_no_cache_header(conn);
  3834. }
  3835. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3836. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3837. /* See also https://www.mnot.net/cache_docs/ */
  3838. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3839. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3840. * leap
  3841. * year to 31622400 seconds. For the moment, we just send whatever has
  3842. * been configured, still the behavior for >1 year should be considered
  3843. * as undefined. */
  3844. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3845. #else /* NO_CACHING */
  3846. return send_no_cache_header(conn);
  3847. #endif /* !NO_CACHING */
  3848. }
  3849. static int
  3850. send_additional_header(struct mg_connection *conn)
  3851. {
  3852. int i = 0;
  3853. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3854. #if !defined(NO_SSL)
  3855. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3856. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3857. if (max_age >= 0) {
  3858. i += mg_printf(conn,
  3859. "Strict-Transport-Security: max-age=%u\r\n",
  3860. (unsigned)max_age);
  3861. }
  3862. }
  3863. #endif
  3864. if (header && header[0]) {
  3865. i += mg_printf(conn, "%s\r\n", header);
  3866. }
  3867. return i;
  3868. }
  3869. #if !defined(NO_FILESYSTEMS)
  3870. static void handle_file_based_request(struct mg_connection *conn,
  3871. const char *path,
  3872. struct mg_file *filep);
  3873. #endif /* NO_FILESYSTEMS */
  3874. const char *
  3875. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3876. {
  3877. /* See IANA HTTP status code assignment:
  3878. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3879. */
  3880. switch (response_code) {
  3881. /* RFC2616 Section 10.1 - Informational 1xx */
  3882. case 100:
  3883. return "Continue"; /* RFC2616 Section 10.1.1 */
  3884. case 101:
  3885. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3886. case 102:
  3887. return "Processing"; /* RFC2518 Section 10.1 */
  3888. /* RFC2616 Section 10.2 - Successful 2xx */
  3889. case 200:
  3890. return "OK"; /* RFC2616 Section 10.2.1 */
  3891. case 201:
  3892. return "Created"; /* RFC2616 Section 10.2.2 */
  3893. case 202:
  3894. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3895. case 203:
  3896. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3897. case 204:
  3898. return "No Content"; /* RFC2616 Section 10.2.5 */
  3899. case 205:
  3900. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3901. case 206:
  3902. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3903. case 207:
  3904. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3905. */
  3906. case 208:
  3907. return "Already Reported"; /* RFC5842 Section 7.1 */
  3908. case 226:
  3909. return "IM used"; /* RFC3229 Section 10.4.1 */
  3910. /* RFC2616 Section 10.3 - Redirection 3xx */
  3911. case 300:
  3912. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3913. case 301:
  3914. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3915. case 302:
  3916. return "Found"; /* RFC2616 Section 10.3.3 */
  3917. case 303:
  3918. return "See Other"; /* RFC2616 Section 10.3.4 */
  3919. case 304:
  3920. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3921. case 305:
  3922. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3923. case 307:
  3924. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3925. case 308:
  3926. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3927. /* RFC2616 Section 10.4 - Client Error 4xx */
  3928. case 400:
  3929. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3930. case 401:
  3931. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3932. case 402:
  3933. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3934. case 403:
  3935. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3936. case 404:
  3937. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3938. case 405:
  3939. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3940. case 406:
  3941. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3942. case 407:
  3943. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3944. case 408:
  3945. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3946. case 409:
  3947. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3948. case 410:
  3949. return "Gone"; /* RFC2616 Section 10.4.11 */
  3950. case 411:
  3951. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3952. case 412:
  3953. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3954. case 413:
  3955. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3956. case 414:
  3957. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3958. case 415:
  3959. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3960. case 416:
  3961. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3962. */
  3963. case 417:
  3964. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3965. case 421:
  3966. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3967. case 422:
  3968. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3969. * Section 11.2 */
  3970. case 423:
  3971. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3972. case 424:
  3973. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3974. * Section 11.4 */
  3975. case 426:
  3976. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3977. case 428:
  3978. return "Precondition Required"; /* RFC 6585, Section 3 */
  3979. case 429:
  3980. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3981. case 431:
  3982. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3983. case 451:
  3984. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3985. * Section 3 */
  3986. /* RFC2616 Section 10.5 - Server Error 5xx */
  3987. case 500:
  3988. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3989. case 501:
  3990. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3991. case 502:
  3992. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3993. case 503:
  3994. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3995. case 504:
  3996. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3997. case 505:
  3998. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3999. case 506:
  4000. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4001. case 507:
  4002. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4003. * Section 11.5 */
  4004. case 508:
  4005. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4006. case 510:
  4007. return "Not Extended"; /* RFC 2774, Section 7 */
  4008. case 511:
  4009. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4010. /* Other status codes, not shown in the IANA HTTP status code
  4011. * assignment.
  4012. * E.g., "de facto" standards due to common use, ... */
  4013. case 418:
  4014. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4015. case 419:
  4016. return "Authentication Timeout"; /* common use */
  4017. case 420:
  4018. return "Enhance Your Calm"; /* common use */
  4019. case 440:
  4020. return "Login Timeout"; /* common use */
  4021. case 509:
  4022. return "Bandwidth Limit Exceeded"; /* common use */
  4023. default:
  4024. /* This error code is unknown. This should not happen. */
  4025. if (conn) {
  4026. mg_cry_internal(conn,
  4027. "Unknown HTTP response code: %u",
  4028. response_code);
  4029. }
  4030. /* Return at least a category according to RFC 2616 Section 10. */
  4031. if (response_code >= 100 && response_code < 200) {
  4032. /* Unknown informational status code */
  4033. return "Information";
  4034. }
  4035. if (response_code >= 200 && response_code < 300) {
  4036. /* Unknown success code */
  4037. return "Success";
  4038. }
  4039. if (response_code >= 300 && response_code < 400) {
  4040. /* Unknown redirection code */
  4041. return "Redirection";
  4042. }
  4043. if (response_code >= 400 && response_code < 500) {
  4044. /* Unknown request error code */
  4045. return "Client Error";
  4046. }
  4047. if (response_code >= 500 && response_code < 600) {
  4048. /* Unknown server error code */
  4049. return "Server Error";
  4050. }
  4051. /* Response code not even within reasonable range */
  4052. return "";
  4053. }
  4054. }
  4055. static int
  4056. mg_send_http_error_impl(struct mg_connection *conn,
  4057. int status,
  4058. const char *fmt,
  4059. va_list args)
  4060. {
  4061. char errmsg_buf[MG_BUF_LEN];
  4062. va_list ap;
  4063. int has_body;
  4064. char date[64];
  4065. time_t curtime = time(NULL);
  4066. #if !defined(NO_FILESYSTEMS)
  4067. char path_buf[PATH_MAX];
  4068. int len, i, page_handler_found, scope, truncated;
  4069. const char *error_handler = NULL;
  4070. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4071. const char *error_page_file_ext, *tstr;
  4072. #endif /* NO_FILESYSTEMS */
  4073. int handled_by_callback = 0;
  4074. const char *status_text = mg_get_response_code_text(conn, status);
  4075. if ((conn == NULL) || (fmt == NULL)) {
  4076. return -2;
  4077. }
  4078. /* Set status (for log) */
  4079. conn->status_code = status;
  4080. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4081. has_body = ((status > 199) && (status != 204) && (status != 304));
  4082. /* Prepare message in buf, if required */
  4083. if (has_body
  4084. || (!conn->in_error_handler
  4085. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4086. /* Store error message in errmsg_buf */
  4087. va_copy(ap, args);
  4088. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4089. va_end(ap);
  4090. /* In a debug build, print all html errors */
  4091. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4092. }
  4093. /* If there is a http_error callback, call it.
  4094. * But don't do it recursively, if callback calls mg_send_http_error again.
  4095. */
  4096. if (!conn->in_error_handler
  4097. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4098. /* Mark in_error_handler to avoid recursion and call user callback. */
  4099. conn->in_error_handler = 1;
  4100. handled_by_callback =
  4101. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4102. == 0);
  4103. conn->in_error_handler = 0;
  4104. }
  4105. if (!handled_by_callback) {
  4106. /* Check for recursion */
  4107. if (conn->in_error_handler) {
  4108. DEBUG_TRACE(
  4109. "Recursion when handling error %u - fall back to default",
  4110. status);
  4111. #if !defined(NO_FILESYSTEMS)
  4112. } else {
  4113. /* Send user defined error pages, if defined */
  4114. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4115. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4116. page_handler_found = 0;
  4117. if (error_handler != NULL) {
  4118. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4119. switch (scope) {
  4120. case 1: /* Handler for specific error, e.g. 404 error */
  4121. mg_snprintf(conn,
  4122. &truncated,
  4123. path_buf,
  4124. sizeof(path_buf) - 32,
  4125. "%serror%03u.",
  4126. error_handler,
  4127. status);
  4128. break;
  4129. case 2: /* Handler for error group, e.g., 5xx error
  4130. * handler
  4131. * for all server errors (500-599) */
  4132. mg_snprintf(conn,
  4133. &truncated,
  4134. path_buf,
  4135. sizeof(path_buf) - 32,
  4136. "%serror%01uxx.",
  4137. error_handler,
  4138. status / 100);
  4139. break;
  4140. default: /* Handler for all errors */
  4141. mg_snprintf(conn,
  4142. &truncated,
  4143. path_buf,
  4144. sizeof(path_buf) - 32,
  4145. "%serror.",
  4146. error_handler);
  4147. break;
  4148. }
  4149. /* String truncation in buf may only occur if
  4150. * error_handler is too long. This string is
  4151. * from the config, not from a client. */
  4152. (void)truncated;
  4153. /* The following code is redundant, but it should avoid
  4154. * false positives in static source code analyzers and
  4155. * vulnerability scanners.
  4156. */
  4157. path_buf[sizeof(path_buf) - 32] = 0;
  4158. len = (int)strlen(path_buf);
  4159. if (len > (int)sizeof(path_buf) - 32) {
  4160. len = (int)sizeof(path_buf) - 32;
  4161. }
  4162. /* Start with the file extenstion from the configuration. */
  4163. tstr = strchr(error_page_file_ext, '.');
  4164. while (tstr) {
  4165. for (i = 1;
  4166. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4167. i++) {
  4168. /* buffer overrun is not possible here, since
  4169. * (i < 32) && (len < sizeof(path_buf) - 32)
  4170. * ==> (i + len) < sizeof(path_buf) */
  4171. path_buf[len + i - 1] = tstr[i];
  4172. }
  4173. /* buffer overrun is not possible here, since
  4174. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4175. * ==> (i + len) <= sizeof(path_buf) */
  4176. path_buf[len + i - 1] = 0;
  4177. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4178. DEBUG_TRACE("Check error page %s - found",
  4179. path_buf);
  4180. page_handler_found = 1;
  4181. break;
  4182. }
  4183. DEBUG_TRACE("Check error page %s - not found",
  4184. path_buf);
  4185. /* Continue with the next file extenstion from the
  4186. * configuration (if there is a next one). */
  4187. tstr = strchr(tstr + i, '.');
  4188. }
  4189. }
  4190. }
  4191. if (page_handler_found) {
  4192. conn->in_error_handler = 1;
  4193. handle_file_based_request(conn, path_buf, &error_page_file);
  4194. conn->in_error_handler = 0;
  4195. return 0;
  4196. }
  4197. #endif /* NO_FILESYSTEMS */
  4198. }
  4199. /* No custom error page. Send default error page. */
  4200. gmt_time_string(date, sizeof(date), &curtime);
  4201. conn->must_close = 1;
  4202. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4203. send_no_cache_header(conn);
  4204. send_additional_header(conn);
  4205. if (has_body) {
  4206. mg_printf(conn,
  4207. "%s",
  4208. "Content-Type: text/plain; charset=utf-8\r\n");
  4209. }
  4210. mg_printf(conn,
  4211. "Date: %s\r\n"
  4212. "Connection: close\r\n\r\n",
  4213. date);
  4214. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4215. if (has_body) {
  4216. /* For other errors, send a generic error message. */
  4217. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4218. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4219. } else {
  4220. /* No body allowed. Close the connection. */
  4221. DEBUG_TRACE("Error %i", status);
  4222. }
  4223. }
  4224. return 0;
  4225. }
  4226. int
  4227. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4228. {
  4229. va_list ap;
  4230. int ret;
  4231. va_start(ap, fmt);
  4232. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4233. va_end(ap);
  4234. return ret;
  4235. }
  4236. int
  4237. mg_send_http_ok(struct mg_connection *conn,
  4238. const char *mime_type,
  4239. long long content_length)
  4240. {
  4241. char date[64];
  4242. time_t curtime = time(NULL);
  4243. if ((mime_type == NULL) || (*mime_type == 0)) {
  4244. /* No content type defined: default to text/html */
  4245. mime_type = "text/html";
  4246. }
  4247. gmt_time_string(date, sizeof(date), &curtime);
  4248. mg_printf(conn,
  4249. "HTTP/1.1 200 OK\r\n"
  4250. "Content-Type: %s\r\n"
  4251. "Date: %s\r\n"
  4252. "Connection: %s\r\n",
  4253. mime_type,
  4254. date,
  4255. suggest_connection_header(conn));
  4256. send_no_cache_header(conn);
  4257. send_additional_header(conn);
  4258. if (content_length < 0) {
  4259. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4260. } else {
  4261. mg_printf(conn,
  4262. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4263. (uint64_t)content_length);
  4264. }
  4265. return 0;
  4266. }
  4267. int
  4268. mg_send_http_redirect(struct mg_connection *conn,
  4269. const char *target_url,
  4270. int redirect_code)
  4271. {
  4272. /* Send a 30x redirect response.
  4273. *
  4274. * Redirect types (status codes):
  4275. *
  4276. * Status | Perm/Temp | Method | Version
  4277. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4278. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4279. * 303 | temporary | always use GET | HTTP/1.1
  4280. * 307 | temporary | always keep method | HTTP/1.1
  4281. * 308 | permanent | always keep method | HTTP/1.1
  4282. */
  4283. const char *redirect_text;
  4284. int ret;
  4285. size_t content_len = 0;
  4286. char reply[MG_BUF_LEN];
  4287. /* In case redirect_code=0, use 307. */
  4288. if (redirect_code == 0) {
  4289. redirect_code = 307;
  4290. }
  4291. /* In case redirect_code is none of the above, return error. */
  4292. if ((redirect_code != 301) && (redirect_code != 302)
  4293. && (redirect_code != 303) && (redirect_code != 307)
  4294. && (redirect_code != 308)) {
  4295. /* Parameter error */
  4296. return -2;
  4297. }
  4298. /* Get proper text for response code */
  4299. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4300. /* If target_url is not defined, redirect to "/". */
  4301. if ((target_url == NULL) || (*target_url == 0)) {
  4302. target_url = "/";
  4303. }
  4304. #if defined(MG_SEND_REDIRECT_BODY)
  4305. /* TODO: condition name? */
  4306. /* Prepare a response body with a hyperlink.
  4307. *
  4308. * According to RFC2616 (and RFC1945 before):
  4309. * Unless the request method was HEAD, the entity of the
  4310. * response SHOULD contain a short hypertext note with a hyperlink to
  4311. * the new URI(s).
  4312. *
  4313. * However, this response body is not useful in M2M communication.
  4314. * Probably the original reason in the RFC was, clients not supporting
  4315. * a 30x HTTP redirect could still show the HTML page and let the user
  4316. * press the link. Since current browsers support 30x HTTP, the additional
  4317. * HTML body does not seem to make sense anymore.
  4318. *
  4319. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4320. * but it only notes:
  4321. * The server's response payload usually contains a short
  4322. * hypertext note with a hyperlink to the new URI(s).
  4323. *
  4324. * Deactivated by default. If you need the 30x body, set the define.
  4325. */
  4326. mg_snprintf(
  4327. conn,
  4328. NULL /* ignore truncation */,
  4329. reply,
  4330. sizeof(reply),
  4331. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4332. redirect_text,
  4333. target_url,
  4334. target_url);
  4335. content_len = strlen(reply);
  4336. #else
  4337. reply[0] = 0;
  4338. #endif
  4339. /* Do not send any additional header. For all other options,
  4340. * including caching, there are suitable defaults. */
  4341. ret = mg_printf(conn,
  4342. "HTTP/1.1 %i %s\r\n"
  4343. "Location: %s\r\n"
  4344. "Content-Length: %u\r\n"
  4345. "Connection: %s\r\n\r\n",
  4346. redirect_code,
  4347. redirect_text,
  4348. target_url,
  4349. (unsigned int)content_len,
  4350. suggest_connection_header(conn));
  4351. /* Send response body */
  4352. if (ret > 0) {
  4353. /* ... unless it is a HEAD request */
  4354. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4355. ret = mg_write(conn, reply, content_len);
  4356. }
  4357. }
  4358. return (ret > 0) ? ret : -1;
  4359. }
  4360. #if defined(_WIN32)
  4361. /* Create substitutes for POSIX functions in Win32. */
  4362. #if defined(GCC_DIAGNOSTIC)
  4363. /* Show no warning in case system functions are not used. */
  4364. #pragma GCC diagnostic push
  4365. #pragma GCC diagnostic ignored "-Wunused-function"
  4366. #endif
  4367. static int
  4368. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4369. {
  4370. (void)unused;
  4371. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4372. InitializeCriticalSection(&mutex->sec);
  4373. return 0;
  4374. }
  4375. static int
  4376. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4377. {
  4378. DeleteCriticalSection(&mutex->sec);
  4379. return 0;
  4380. }
  4381. static int
  4382. pthread_mutex_lock(pthread_mutex_t *mutex)
  4383. {
  4384. EnterCriticalSection(&mutex->sec);
  4385. return 0;
  4386. }
  4387. static int
  4388. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4389. {
  4390. LeaveCriticalSection(&mutex->sec);
  4391. return 0;
  4392. }
  4393. FUNCTION_MAY_BE_UNUSED
  4394. static int
  4395. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4396. {
  4397. (void)unused;
  4398. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4399. cv->waiting_thread = NULL;
  4400. return 0;
  4401. }
  4402. FUNCTION_MAY_BE_UNUSED
  4403. static int
  4404. pthread_cond_timedwait(pthread_cond_t *cv,
  4405. pthread_mutex_t *mutex,
  4406. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4407. {
  4408. struct mg_workerTLS **ptls,
  4409. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4410. int ok;
  4411. int64_t nsnow, nswaitabs, nswaitrel;
  4412. DWORD mswaitrel;
  4413. pthread_mutex_lock(&cv->threadIdSec);
  4414. /* Add this thread to cv's waiting list */
  4415. ptls = &cv->waiting_thread;
  4416. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4417. ;
  4418. tls->next_waiting_thread = NULL;
  4419. *ptls = tls;
  4420. pthread_mutex_unlock(&cv->threadIdSec);
  4421. if (abstime) {
  4422. nsnow = mg_get_current_time_ns();
  4423. nswaitabs =
  4424. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4425. nswaitrel = nswaitabs - nsnow;
  4426. if (nswaitrel < 0) {
  4427. nswaitrel = 0;
  4428. }
  4429. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4430. } else {
  4431. mswaitrel = (DWORD)INFINITE;
  4432. }
  4433. pthread_mutex_unlock(mutex);
  4434. ok = (WAIT_OBJECT_0
  4435. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4436. if (!ok) {
  4437. ok = 1;
  4438. pthread_mutex_lock(&cv->threadIdSec);
  4439. ptls = &cv->waiting_thread;
  4440. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4441. if (*ptls == tls) {
  4442. *ptls = tls->next_waiting_thread;
  4443. ok = 0;
  4444. break;
  4445. }
  4446. }
  4447. pthread_mutex_unlock(&cv->threadIdSec);
  4448. if (ok) {
  4449. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4450. (DWORD)INFINITE);
  4451. }
  4452. }
  4453. /* This thread has been removed from cv's waiting list */
  4454. pthread_mutex_lock(mutex);
  4455. return ok ? 0 : -1;
  4456. }
  4457. FUNCTION_MAY_BE_UNUSED
  4458. static int
  4459. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4460. {
  4461. return pthread_cond_timedwait(cv, mutex, NULL);
  4462. }
  4463. FUNCTION_MAY_BE_UNUSED
  4464. static int
  4465. pthread_cond_signal(pthread_cond_t *cv)
  4466. {
  4467. HANDLE wkup = NULL;
  4468. BOOL ok = FALSE;
  4469. pthread_mutex_lock(&cv->threadIdSec);
  4470. if (cv->waiting_thread) {
  4471. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4472. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4473. ok = SetEvent(wkup);
  4474. DEBUG_ASSERT(ok);
  4475. }
  4476. pthread_mutex_unlock(&cv->threadIdSec);
  4477. return ok ? 0 : 1;
  4478. }
  4479. FUNCTION_MAY_BE_UNUSED
  4480. static int
  4481. pthread_cond_broadcast(pthread_cond_t *cv)
  4482. {
  4483. pthread_mutex_lock(&cv->threadIdSec);
  4484. while (cv->waiting_thread) {
  4485. pthread_cond_signal(cv);
  4486. }
  4487. pthread_mutex_unlock(&cv->threadIdSec);
  4488. return 0;
  4489. }
  4490. FUNCTION_MAY_BE_UNUSED
  4491. static int
  4492. pthread_cond_destroy(pthread_cond_t *cv)
  4493. {
  4494. pthread_mutex_lock(&cv->threadIdSec);
  4495. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4496. pthread_mutex_unlock(&cv->threadIdSec);
  4497. pthread_mutex_destroy(&cv->threadIdSec);
  4498. return 0;
  4499. }
  4500. #if defined(ALTERNATIVE_QUEUE)
  4501. FUNCTION_MAY_BE_UNUSED
  4502. static void *
  4503. event_create(void)
  4504. {
  4505. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4506. }
  4507. FUNCTION_MAY_BE_UNUSED
  4508. static int
  4509. event_wait(void *eventhdl)
  4510. {
  4511. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4512. return (res == WAIT_OBJECT_0);
  4513. }
  4514. FUNCTION_MAY_BE_UNUSED
  4515. static int
  4516. event_signal(void *eventhdl)
  4517. {
  4518. return (int)SetEvent((HANDLE)eventhdl);
  4519. }
  4520. FUNCTION_MAY_BE_UNUSED
  4521. static void
  4522. event_destroy(void *eventhdl)
  4523. {
  4524. CloseHandle((HANDLE)eventhdl);
  4525. }
  4526. #endif
  4527. #if defined(GCC_DIAGNOSTIC)
  4528. /* Enable unused function warning again */
  4529. #pragma GCC diagnostic pop
  4530. #endif
  4531. /* For Windows, change all slashes to backslashes in path names. */
  4532. static void
  4533. change_slashes_to_backslashes(char *path)
  4534. {
  4535. int i;
  4536. for (i = 0; path[i] != '\0'; i++) {
  4537. if (path[i] == '/') {
  4538. path[i] = '\\';
  4539. }
  4540. /* remove double backslash (check i > 0 to preserve UNC paths,
  4541. * like \\server\file.txt) */
  4542. if ((i > 0) && (path[i] == '\\')) {
  4543. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4544. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4545. }
  4546. }
  4547. }
  4548. }
  4549. static int
  4550. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4551. {
  4552. int diff;
  4553. do {
  4554. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4555. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4556. s1++;
  4557. s2++;
  4558. } while ((diff == 0) && (s1[-1] != L'\0'));
  4559. return diff;
  4560. }
  4561. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4562. * wbuf and wbuf_len is a target buffer and its length. */
  4563. static void
  4564. path_to_unicode(const struct mg_connection *conn,
  4565. const char *path,
  4566. wchar_t *wbuf,
  4567. size_t wbuf_len)
  4568. {
  4569. char buf[PATH_MAX], buf2[PATH_MAX];
  4570. wchar_t wbuf2[W_PATH_MAX + 1];
  4571. DWORD long_len, err;
  4572. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4573. mg_strlcpy(buf, path, sizeof(buf));
  4574. change_slashes_to_backslashes(buf);
  4575. /* Convert to Unicode and back. If doubly-converted string does not
  4576. * match the original, something is fishy, reject. */
  4577. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4578. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4579. WideCharToMultiByte(
  4580. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4581. if (strcmp(buf, buf2) != 0) {
  4582. wbuf[0] = L'\0';
  4583. }
  4584. /* Windows file systems are not case sensitive, but you can still use
  4585. * uppercase and lowercase letters (on all modern file systems).
  4586. * The server can check if the URI uses the same upper/lowercase
  4587. * letters an the file system, effectively making Windows servers
  4588. * case sensitive (like Linux servers are). It is still not possible
  4589. * to use two files with the same name in different cases on Windows
  4590. * (like /a and /A) - this would be possible in Linux.
  4591. * As a default, Windows is not case sensitive, but the case sensitive
  4592. * file name check can be activated by an additional configuration. */
  4593. if (conn) {
  4594. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4595. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4596. "yes")) {
  4597. /* Use case sensitive compare function */
  4598. fcompare = wcscmp;
  4599. }
  4600. }
  4601. (void)conn; /* conn is currently unused */
  4602. #if !defined(_WIN32_WCE)
  4603. /* Only accept a full file path, not a Windows short (8.3) path. */
  4604. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4605. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4606. if (long_len == 0) {
  4607. err = GetLastError();
  4608. if (err == ERROR_FILE_NOT_FOUND) {
  4609. /* File does not exist. This is not always a problem here. */
  4610. return;
  4611. }
  4612. }
  4613. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4614. /* Short name is used. */
  4615. wbuf[0] = L'\0';
  4616. }
  4617. #else
  4618. (void)long_len;
  4619. (void)wbuf2;
  4620. (void)err;
  4621. if (strchr(path, '~')) {
  4622. wbuf[0] = L'\0';
  4623. }
  4624. #endif
  4625. }
  4626. #if !defined(NO_FILESYSTEMS)
  4627. static int
  4628. mg_stat(const struct mg_connection *conn,
  4629. const char *path,
  4630. struct mg_file_stat *filep)
  4631. {
  4632. wchar_t wbuf[W_PATH_MAX];
  4633. WIN32_FILE_ATTRIBUTE_DATA info;
  4634. time_t creation_time;
  4635. size_t len;
  4636. if (!filep) {
  4637. return 0;
  4638. }
  4639. memset(filep, 0, sizeof(*filep));
  4640. if (conn && is_file_in_memory(conn, path)) {
  4641. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4642. * memset */
  4643. /* Quick fix (for 1.9.x): */
  4644. /* mg_stat must fill all fields, also for files in memory */
  4645. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4646. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4647. filep->size = tmp_file.stat.size;
  4648. filep->location = 2;
  4649. /* TODO: for 1.10: restructure how files in memory are handled */
  4650. /* The "file in memory" feature is a candidate for deletion.
  4651. * Please join the discussion at
  4652. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4653. */
  4654. filep->last_modified = time(NULL); /* TODO */
  4655. /* last_modified = now ... assumes the file may change during
  4656. * runtime,
  4657. * so every mg_fopen call may return different data */
  4658. /* last_modified = conn->phys_ctx.start_time;
  4659. * May be used it the data does not change during runtime. This
  4660. * allows
  4661. * browser caching. Since we do not know, we have to assume the file
  4662. * in memory may change. */
  4663. return 1;
  4664. }
  4665. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4666. /* Windows happily opens files with some garbage at the end of file name.
  4667. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4668. * "a.cgi", despite one would expect an error back. */
  4669. len = strlen(path);
  4670. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4671. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4672. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4673. filep->last_modified =
  4674. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4675. info.ftLastWriteTime.dwHighDateTime);
  4676. /* On Windows, the file creation time can be higher than the
  4677. * modification time, e.g. when a file is copied.
  4678. * Since the Last-Modified timestamp is used for caching
  4679. * it should be based on the most recent timestamp. */
  4680. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4681. info.ftCreationTime.dwHighDateTime);
  4682. if (creation_time > filep->last_modified) {
  4683. filep->last_modified = creation_time;
  4684. }
  4685. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4686. return 1;
  4687. }
  4688. return 0;
  4689. }
  4690. #endif
  4691. static int
  4692. mg_remove(const struct mg_connection *conn, const char *path)
  4693. {
  4694. wchar_t wbuf[W_PATH_MAX];
  4695. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4696. return DeleteFileW(wbuf) ? 0 : -1;
  4697. }
  4698. static int
  4699. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4700. {
  4701. wchar_t wbuf[W_PATH_MAX];
  4702. (void)mode;
  4703. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4704. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4705. }
  4706. /* Create substitutes for POSIX functions in Win32. */
  4707. #if defined(GCC_DIAGNOSTIC)
  4708. /* Show no warning in case system functions are not used. */
  4709. #pragma GCC diagnostic push
  4710. #pragma GCC diagnostic ignored "-Wunused-function"
  4711. #endif
  4712. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4713. FUNCTION_MAY_BE_UNUSED
  4714. static DIR *
  4715. mg_opendir(const struct mg_connection *conn, const char *name)
  4716. {
  4717. DIR *dir = NULL;
  4718. wchar_t wpath[W_PATH_MAX];
  4719. DWORD attrs;
  4720. if (name == NULL) {
  4721. SetLastError(ERROR_BAD_ARGUMENTS);
  4722. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4723. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4724. } else {
  4725. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4726. attrs = GetFileAttributesW(wpath);
  4727. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4728. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4729. (void)wcscat(wpath, L"\\*");
  4730. dir->handle = FindFirstFileW(wpath, &dir->info);
  4731. dir->result.d_name[0] = '\0';
  4732. } else {
  4733. mg_free(dir);
  4734. dir = NULL;
  4735. }
  4736. }
  4737. return dir;
  4738. }
  4739. FUNCTION_MAY_BE_UNUSED
  4740. static int
  4741. mg_closedir(DIR *dir)
  4742. {
  4743. int result = 0;
  4744. if (dir != NULL) {
  4745. if (dir->handle != INVALID_HANDLE_VALUE)
  4746. result = FindClose(dir->handle) ? 0 : -1;
  4747. mg_free(dir);
  4748. } else {
  4749. result = -1;
  4750. SetLastError(ERROR_BAD_ARGUMENTS);
  4751. }
  4752. return result;
  4753. }
  4754. FUNCTION_MAY_BE_UNUSED
  4755. static struct dirent *
  4756. mg_readdir(DIR *dir)
  4757. {
  4758. struct dirent *result = 0;
  4759. if (dir) {
  4760. if (dir->handle != INVALID_HANDLE_VALUE) {
  4761. result = &dir->result;
  4762. (void)WideCharToMultiByte(CP_UTF8,
  4763. 0,
  4764. dir->info.cFileName,
  4765. -1,
  4766. result->d_name,
  4767. sizeof(result->d_name),
  4768. NULL,
  4769. NULL);
  4770. if (!FindNextFileW(dir->handle, &dir->info)) {
  4771. (void)FindClose(dir->handle);
  4772. dir->handle = INVALID_HANDLE_VALUE;
  4773. }
  4774. } else {
  4775. SetLastError(ERROR_FILE_NOT_FOUND);
  4776. }
  4777. } else {
  4778. SetLastError(ERROR_BAD_ARGUMENTS);
  4779. }
  4780. return result;
  4781. }
  4782. #if !defined(HAVE_POLL)
  4783. #undef POLLIN
  4784. #undef POLLPRI
  4785. #undef POLLOUT
  4786. #define POLLIN (1) /* Data ready - read will not block. */
  4787. #define POLLPRI (2) /* Priority data ready. */
  4788. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4789. FUNCTION_MAY_BE_UNUSED
  4790. static int
  4791. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4792. {
  4793. struct timeval tv;
  4794. fd_set rset;
  4795. fd_set wset;
  4796. unsigned int i;
  4797. int result;
  4798. SOCKET maxfd = 0;
  4799. memset(&tv, 0, sizeof(tv));
  4800. tv.tv_sec = milliseconds / 1000;
  4801. tv.tv_usec = (milliseconds % 1000) * 1000;
  4802. FD_ZERO(&rset);
  4803. FD_ZERO(&wset);
  4804. for (i = 0; i < n; i++) {
  4805. if (pfd[i].events & POLLIN) {
  4806. FD_SET(pfd[i].fd, &rset);
  4807. }
  4808. if (pfd[i].events & POLLOUT) {
  4809. FD_SET(pfd[i].fd, &wset);
  4810. }
  4811. pfd[i].revents = 0;
  4812. if (pfd[i].fd > maxfd) {
  4813. maxfd = pfd[i].fd;
  4814. }
  4815. }
  4816. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4817. for (i = 0; i < n; i++) {
  4818. if (FD_ISSET(pfd[i].fd, &rset)) {
  4819. pfd[i].revents |= POLLIN;
  4820. }
  4821. if (FD_ISSET(pfd[i].fd, &wset)) {
  4822. pfd[i].revents |= POLLOUT;
  4823. }
  4824. }
  4825. }
  4826. /* We should subtract the time used in select from remaining
  4827. * "milliseconds", in particular if called from mg_poll with a
  4828. * timeout quantum.
  4829. * Unfortunately, the remaining time is not stored in "tv" in all
  4830. * implementations, so the result in "tv" must be considered undefined.
  4831. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4832. return result;
  4833. }
  4834. #endif /* HAVE_POLL */
  4835. #if defined(GCC_DIAGNOSTIC)
  4836. /* Enable unused function warning again */
  4837. #pragma GCC diagnostic pop
  4838. #endif
  4839. static void
  4840. set_close_on_exec(SOCKET sock,
  4841. const struct mg_connection *conn /* may be null */,
  4842. struct mg_context *ctx /* may be null */)
  4843. {
  4844. (void)conn; /* Unused. */
  4845. (void)ctx;
  4846. #if defined(_WIN32_WCE)
  4847. (void)sock;
  4848. #else
  4849. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4850. #endif
  4851. }
  4852. int
  4853. mg_start_thread(mg_thread_func_t f, void *p)
  4854. {
  4855. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4856. /* Compile-time option to control stack size, e.g.
  4857. * -DUSE_STACK_SIZE=16384
  4858. */
  4859. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4860. == ((uintptr_t)(-1L)))
  4861. ? -1
  4862. : 0);
  4863. #else
  4864. return (
  4865. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4866. ? -1
  4867. : 0);
  4868. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4869. }
  4870. /* Start a thread storing the thread context. */
  4871. static int
  4872. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4873. void *p,
  4874. pthread_t *threadidptr)
  4875. {
  4876. uintptr_t uip;
  4877. HANDLE threadhandle;
  4878. int result = -1;
  4879. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4880. threadhandle = (HANDLE)uip;
  4881. if ((uip != 0) && (threadidptr != NULL)) {
  4882. *threadidptr = threadhandle;
  4883. result = 0;
  4884. }
  4885. return result;
  4886. }
  4887. /* Wait for a thread to finish. */
  4888. static int
  4889. mg_join_thread(pthread_t threadid)
  4890. {
  4891. int result;
  4892. DWORD dwevent;
  4893. result = -1;
  4894. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4895. if (dwevent == WAIT_FAILED) {
  4896. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4897. } else {
  4898. if (dwevent == WAIT_OBJECT_0) {
  4899. CloseHandle(threadid);
  4900. result = 0;
  4901. }
  4902. }
  4903. return result;
  4904. }
  4905. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4906. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4907. /* Create substitutes for POSIX functions in Win32. */
  4908. #if defined(GCC_DIAGNOSTIC)
  4909. /* Show no warning in case system functions are not used. */
  4910. #pragma GCC diagnostic push
  4911. #pragma GCC diagnostic ignored "-Wunused-function"
  4912. #endif
  4913. FUNCTION_MAY_BE_UNUSED
  4914. static HANDLE
  4915. dlopen(const char *dll_name, int flags)
  4916. {
  4917. wchar_t wbuf[W_PATH_MAX];
  4918. (void)flags;
  4919. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4920. return LoadLibraryW(wbuf);
  4921. }
  4922. FUNCTION_MAY_BE_UNUSED
  4923. static int
  4924. dlclose(void *handle)
  4925. {
  4926. int result;
  4927. if (FreeLibrary((HMODULE)handle) != 0) {
  4928. result = 0;
  4929. } else {
  4930. result = -1;
  4931. }
  4932. return result;
  4933. }
  4934. #if defined(GCC_DIAGNOSTIC)
  4935. /* Enable unused function warning again */
  4936. #pragma GCC diagnostic pop
  4937. #endif
  4938. #endif
  4939. #if !defined(NO_CGI)
  4940. #define SIGKILL (0)
  4941. static int
  4942. kill(pid_t pid, int sig_num)
  4943. {
  4944. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4945. (void)CloseHandle((HANDLE)pid);
  4946. return 0;
  4947. }
  4948. #if !defined(WNOHANG)
  4949. #define WNOHANG (1)
  4950. #endif
  4951. static pid_t
  4952. waitpid(pid_t pid, int *status, int flags)
  4953. {
  4954. DWORD timeout = INFINITE;
  4955. DWORD waitres;
  4956. (void)status; /* Currently not used by any client here */
  4957. if ((flags | WNOHANG) == WNOHANG) {
  4958. timeout = 0;
  4959. }
  4960. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4961. if (waitres == WAIT_OBJECT_0) {
  4962. return pid;
  4963. }
  4964. if (waitres == WAIT_TIMEOUT) {
  4965. return 0;
  4966. }
  4967. return (pid_t)-1;
  4968. }
  4969. static void
  4970. trim_trailing_whitespaces(char *s)
  4971. {
  4972. char *e = s + strlen(s);
  4973. while ((e > s) && isspace((unsigned char)e[-1])) {
  4974. *(--e) = '\0';
  4975. }
  4976. }
  4977. static pid_t
  4978. spawn_process(struct mg_connection *conn,
  4979. const char *prog,
  4980. char *envblk,
  4981. char *envp[],
  4982. int fdin[2],
  4983. int fdout[2],
  4984. int fderr[2],
  4985. const char *dir)
  4986. {
  4987. HANDLE me;
  4988. char *p, *interp;
  4989. char *interp_arg = 0;
  4990. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4991. buf[PATH_MAX];
  4992. int truncated;
  4993. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4994. STARTUPINFOA si;
  4995. PROCESS_INFORMATION pi = {0};
  4996. (void)envp;
  4997. memset(&si, 0, sizeof(si));
  4998. si.cb = sizeof(si);
  4999. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5000. si.wShowWindow = SW_HIDE;
  5001. me = GetCurrentProcess();
  5002. DuplicateHandle(me,
  5003. (HANDLE)_get_osfhandle(fdin[0]),
  5004. me,
  5005. &si.hStdInput,
  5006. 0,
  5007. TRUE,
  5008. DUPLICATE_SAME_ACCESS);
  5009. DuplicateHandle(me,
  5010. (HANDLE)_get_osfhandle(fdout[1]),
  5011. me,
  5012. &si.hStdOutput,
  5013. 0,
  5014. TRUE,
  5015. DUPLICATE_SAME_ACCESS);
  5016. DuplicateHandle(me,
  5017. (HANDLE)_get_osfhandle(fderr[1]),
  5018. me,
  5019. &si.hStdError,
  5020. 0,
  5021. TRUE,
  5022. DUPLICATE_SAME_ACCESS);
  5023. /* Mark handles that should not be inherited. See
  5024. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5025. */
  5026. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5027. HANDLE_FLAG_INHERIT,
  5028. 0);
  5029. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5030. HANDLE_FLAG_INHERIT,
  5031. 0);
  5032. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5033. HANDLE_FLAG_INHERIT,
  5034. 0);
  5035. /* First check, if there is a CGI interpreter configured for all CGI
  5036. * scripts. */
  5037. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5038. if (interp != NULL) {
  5039. /* If there is a configured interpreter, check for additional arguments
  5040. */
  5041. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5042. } else {
  5043. /* Otherwise, the interpreter must be stated in the first line of the
  5044. * CGI script file, after a #! (shebang) mark. */
  5045. buf[0] = buf[1] = '\0';
  5046. /* Get the full script path */
  5047. mg_snprintf(
  5048. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5049. if (truncated) {
  5050. pi.hProcess = (pid_t)-1;
  5051. goto spawn_cleanup;
  5052. }
  5053. /* Open the script file, to read the first line */
  5054. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5055. #if defined(MG_USE_OPEN_FILE)
  5056. p = (char *)file.access.membuf;
  5057. #else
  5058. p = (char *)NULL;
  5059. #endif
  5060. /* Read the first line of the script into the buffer */
  5061. mg_fgets(buf, sizeof(buf), &file, &p);
  5062. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5063. buf[sizeof(buf) - 1] = '\0';
  5064. }
  5065. if ((buf[0] == '#') && (buf[1] == '!')) {
  5066. trim_trailing_whitespaces(buf + 2);
  5067. } else {
  5068. buf[2] = '\0';
  5069. }
  5070. interp = buf + 2;
  5071. }
  5072. if (interp[0] != '\0') {
  5073. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5074. interp = full_interp;
  5075. }
  5076. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5077. if (interp[0] != '\0') {
  5078. /* This is an interpreted script file. We must call the interpreter. */
  5079. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5080. mg_snprintf(conn,
  5081. &truncated,
  5082. cmdline,
  5083. sizeof(cmdline),
  5084. "\"%s\" %s \"%s\\%s\"",
  5085. interp,
  5086. interp_arg,
  5087. full_dir,
  5088. prog);
  5089. } else {
  5090. mg_snprintf(conn,
  5091. &truncated,
  5092. cmdline,
  5093. sizeof(cmdline),
  5094. "\"%s\" \"%s\\%s\"",
  5095. interp,
  5096. full_dir,
  5097. prog);
  5098. }
  5099. } else {
  5100. /* This is (probably) a compiled program. We call it directly. */
  5101. mg_snprintf(conn,
  5102. &truncated,
  5103. cmdline,
  5104. sizeof(cmdline),
  5105. "\"%s\\%s\"",
  5106. full_dir,
  5107. prog);
  5108. }
  5109. if (truncated) {
  5110. pi.hProcess = (pid_t)-1;
  5111. goto spawn_cleanup;
  5112. }
  5113. DEBUG_TRACE("Running [%s]", cmdline);
  5114. if (CreateProcessA(NULL,
  5115. cmdline,
  5116. NULL,
  5117. NULL,
  5118. TRUE,
  5119. CREATE_NEW_PROCESS_GROUP,
  5120. envblk,
  5121. NULL,
  5122. &si,
  5123. &pi)
  5124. == 0) {
  5125. mg_cry_internal(
  5126. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5127. pi.hProcess = (pid_t)-1;
  5128. /* goto spawn_cleanup; */
  5129. }
  5130. spawn_cleanup:
  5131. (void)CloseHandle(si.hStdOutput);
  5132. (void)CloseHandle(si.hStdError);
  5133. (void)CloseHandle(si.hStdInput);
  5134. if (pi.hThread != NULL) {
  5135. (void)CloseHandle(pi.hThread);
  5136. }
  5137. return (pid_t)pi.hProcess;
  5138. }
  5139. #endif /* !NO_CGI */
  5140. static int
  5141. set_blocking_mode(SOCKET sock)
  5142. {
  5143. unsigned long non_blocking = 0;
  5144. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5145. }
  5146. static int
  5147. set_non_blocking_mode(SOCKET sock)
  5148. {
  5149. unsigned long non_blocking = 1;
  5150. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5151. }
  5152. #else
  5153. #if !defined(NO_FILESYSTEMS)
  5154. static int
  5155. mg_stat(const struct mg_connection *conn,
  5156. const char *path,
  5157. struct mg_file_stat *filep)
  5158. {
  5159. struct stat st;
  5160. if (!filep) {
  5161. return 0;
  5162. }
  5163. memset(filep, 0, sizeof(*filep));
  5164. if (conn && is_file_in_memory(conn, path)) {
  5165. /* Quick fix (for 1.9.x): */
  5166. /* mg_stat must fill all fields, also for files in memory */
  5167. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5168. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5169. filep->size = tmp_file.stat.size;
  5170. filep->last_modified = time(NULL);
  5171. filep->location = 2;
  5172. /* TODO: remove legacy "files in memory" feature */
  5173. return 1;
  5174. }
  5175. if (0 == stat(path, &st)) {
  5176. filep->size = (uint64_t)(st.st_size);
  5177. filep->last_modified = st.st_mtime;
  5178. filep->is_directory = S_ISDIR(st.st_mode);
  5179. return 1;
  5180. }
  5181. return 0;
  5182. }
  5183. #endif /* NO_FILESYSTEMS */
  5184. static void
  5185. set_close_on_exec(int fd,
  5186. const struct mg_connection *conn /* may be null */,
  5187. struct mg_context *ctx /* may be null */)
  5188. {
  5189. #if defined(__ZEPHYR__)
  5190. (void)fd;
  5191. (void)conn;
  5192. (void)ctx;
  5193. #else
  5194. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5195. if (conn || ctx) {
  5196. struct mg_connection fc;
  5197. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5198. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5199. __func__,
  5200. strerror(ERRNO));
  5201. }
  5202. }
  5203. #endif
  5204. }
  5205. int
  5206. mg_start_thread(mg_thread_func_t func, void *param)
  5207. {
  5208. pthread_t thread_id;
  5209. pthread_attr_t attr;
  5210. int result;
  5211. (void)pthread_attr_init(&attr);
  5212. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5213. #if defined(__ZEPHYR__)
  5214. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5215. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5216. /* Compile-time option to control stack size,
  5217. * e.g. -DUSE_STACK_SIZE=16384 */
  5218. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5219. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5220. result = pthread_create(&thread_id, &attr, func, param);
  5221. pthread_attr_destroy(&attr);
  5222. return result;
  5223. }
  5224. /* Start a thread storing the thread context. */
  5225. static int
  5226. mg_start_thread_with_id(mg_thread_func_t func,
  5227. void *param,
  5228. pthread_t *threadidptr)
  5229. {
  5230. pthread_t thread_id;
  5231. pthread_attr_t attr;
  5232. int result;
  5233. (void)pthread_attr_init(&attr);
  5234. #if defined(__ZEPHYR__)
  5235. pthread_attr_setstack(&attr,
  5236. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5237. ZEPHYR_STACK_SIZE);
  5238. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5239. /* Compile-time option to control stack size,
  5240. * e.g. -DUSE_STACK_SIZE=16384 */
  5241. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5242. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5243. result = pthread_create(&thread_id, &attr, func, param);
  5244. pthread_attr_destroy(&attr);
  5245. if ((result == 0) && (threadidptr != NULL)) {
  5246. *threadidptr = thread_id;
  5247. }
  5248. return result;
  5249. }
  5250. /* Wait for a thread to finish. */
  5251. static int
  5252. mg_join_thread(pthread_t threadid)
  5253. {
  5254. int result;
  5255. result = pthread_join(threadid, NULL);
  5256. return result;
  5257. }
  5258. #if !defined(NO_CGI)
  5259. static pid_t
  5260. spawn_process(struct mg_connection *conn,
  5261. const char *prog,
  5262. char *envblk,
  5263. char *envp[],
  5264. int fdin[2],
  5265. int fdout[2],
  5266. int fderr[2],
  5267. const char *dir)
  5268. {
  5269. pid_t pid;
  5270. const char *interp;
  5271. (void)envblk;
  5272. if ((pid = fork()) == -1) {
  5273. /* Parent */
  5274. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5275. } else if (pid != 0) {
  5276. /* Make sure children close parent-side descriptors.
  5277. * The caller will close the child-side immediately. */
  5278. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5279. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5280. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5281. } else {
  5282. /* Child */
  5283. if (chdir(dir) != 0) {
  5284. mg_cry_internal(
  5285. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5286. } else if (dup2(fdin[0], 0) == -1) {
  5287. mg_cry_internal(conn,
  5288. "%s: dup2(%d, 0): %s",
  5289. __func__,
  5290. fdin[0],
  5291. strerror(ERRNO));
  5292. } else if (dup2(fdout[1], 1) == -1) {
  5293. mg_cry_internal(conn,
  5294. "%s: dup2(%d, 1): %s",
  5295. __func__,
  5296. fdout[1],
  5297. strerror(ERRNO));
  5298. } else if (dup2(fderr[1], 2) == -1) {
  5299. mg_cry_internal(conn,
  5300. "%s: dup2(%d, 2): %s",
  5301. __func__,
  5302. fderr[1],
  5303. strerror(ERRNO));
  5304. } else {
  5305. struct sigaction sa;
  5306. /* Keep stderr and stdout in two different pipes.
  5307. * Stdout will be sent back to the client,
  5308. * stderr should go into a server error log. */
  5309. (void)close(fdin[0]);
  5310. (void)close(fdout[1]);
  5311. (void)close(fderr[1]);
  5312. /* Close write end fdin and read end fdout and fderr */
  5313. (void)close(fdin[1]);
  5314. (void)close(fdout[0]);
  5315. (void)close(fderr[0]);
  5316. /* After exec, all signal handlers are restored to their default
  5317. * values, with one exception of SIGCHLD. According to
  5318. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5319. * will leave unchanged after exec if it was set to be ignored.
  5320. * Restore it to default action. */
  5321. memset(&sa, 0, sizeof(sa));
  5322. sa.sa_handler = SIG_DFL;
  5323. sigaction(SIGCHLD, &sa, NULL);
  5324. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5325. if (interp == NULL) {
  5326. /* no interpreter configured, call the programm directly */
  5327. (void)execle(prog, prog, NULL, envp);
  5328. mg_cry_internal(conn,
  5329. "%s: execle(%s): %s",
  5330. __func__,
  5331. prog,
  5332. strerror(ERRNO));
  5333. } else {
  5334. /* call the configured interpreter */
  5335. const char *interp_args =
  5336. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5337. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5338. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5339. } else {
  5340. (void)execle(interp, interp, prog, NULL, envp);
  5341. }
  5342. mg_cry_internal(conn,
  5343. "%s: execle(%s %s): %s",
  5344. __func__,
  5345. interp,
  5346. prog,
  5347. strerror(ERRNO));
  5348. }
  5349. }
  5350. exit(EXIT_FAILURE);
  5351. }
  5352. return pid;
  5353. }
  5354. #endif /* !NO_CGI */
  5355. static int
  5356. set_non_blocking_mode(SOCKET sock)
  5357. {
  5358. int flags = fcntl(sock, F_GETFL, 0);
  5359. if (flags < 0) {
  5360. return -1;
  5361. }
  5362. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5363. return -1;
  5364. }
  5365. return 0;
  5366. }
  5367. static int
  5368. set_blocking_mode(SOCKET sock)
  5369. {
  5370. int flags = fcntl(sock, F_GETFL, 0);
  5371. if (flags < 0) {
  5372. return -1;
  5373. }
  5374. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5375. return -1;
  5376. }
  5377. return 0;
  5378. }
  5379. #endif /* _WIN32 / else */
  5380. /* End of initial operating system specific define block. */
  5381. /* Get a random number (independent of C rand function) */
  5382. static uint64_t
  5383. get_random(void)
  5384. {
  5385. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5386. static uint64_t lcg = 0; /* Linear congruential generator */
  5387. uint64_t now = mg_get_current_time_ns();
  5388. if (lfsr == 0) {
  5389. /* lfsr will be only 0 if has not been initialized,
  5390. * so this code is called only once. */
  5391. lfsr = mg_get_current_time_ns();
  5392. lcg = mg_get_current_time_ns();
  5393. } else {
  5394. /* Get the next step of both random number generators. */
  5395. lfsr = (lfsr >> 1)
  5396. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5397. << 63);
  5398. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5399. }
  5400. /* Combining two pseudo-random number generators and a high resolution
  5401. * part
  5402. * of the current server time will make it hard (impossible?) to guess
  5403. * the
  5404. * next number. */
  5405. return (lfsr ^ lcg ^ now);
  5406. }
  5407. static int
  5408. mg_poll(struct mg_pollfd *pfd,
  5409. unsigned int n,
  5410. int milliseconds,
  5411. stop_flag_t *stop_flag)
  5412. {
  5413. /* Call poll, but only for a maximum time of a few seconds.
  5414. * This will allow to stop the server after some seconds, instead
  5415. * of having to wait for a long socket timeout. */
  5416. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5417. do {
  5418. int result;
  5419. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5420. /* Shut down signal */
  5421. return -2;
  5422. }
  5423. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5424. ms_now = milliseconds;
  5425. }
  5426. result = poll(pfd, n, ms_now);
  5427. if (result != 0) {
  5428. /* Poll returned either success (1) or error (-1).
  5429. * Forward both to the caller. */
  5430. return result;
  5431. }
  5432. /* Poll returned timeout (0). */
  5433. if (milliseconds > 0) {
  5434. milliseconds -= ms_now;
  5435. }
  5436. } while (milliseconds != 0);
  5437. /* timeout: return 0 */
  5438. return 0;
  5439. }
  5440. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5441. * descriptor.
  5442. * Return value:
  5443. * >=0 .. number of bytes successfully written
  5444. * -1 .. timeout
  5445. * -2 .. error
  5446. */
  5447. static int
  5448. push_inner(struct mg_context *ctx,
  5449. FILE *fp,
  5450. SOCKET sock,
  5451. SSL *ssl,
  5452. const char *buf,
  5453. int len,
  5454. double timeout)
  5455. {
  5456. uint64_t start = 0, now = 0, timeout_ns = 0;
  5457. int n, err;
  5458. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5459. #if defined(_WIN32)
  5460. typedef int len_t;
  5461. #else
  5462. typedef size_t len_t;
  5463. #endif
  5464. if (timeout > 0) {
  5465. now = mg_get_current_time_ns();
  5466. start = now;
  5467. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5468. }
  5469. if (ctx == NULL) {
  5470. return -2;
  5471. }
  5472. #if defined(NO_SSL)
  5473. if (ssl) {
  5474. return -2;
  5475. }
  5476. #endif
  5477. /* Try to read until it succeeds, fails, times out, or the server
  5478. * shuts down. */
  5479. for (;;) {
  5480. #if !defined(NO_SSL)
  5481. if (ssl != NULL) {
  5482. ERR_clear_error();
  5483. n = SSL_write(ssl, buf, len);
  5484. if (n <= 0) {
  5485. err = SSL_get_error(ssl, n);
  5486. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5487. err = ERRNO;
  5488. } else if ((err == SSL_ERROR_WANT_READ)
  5489. || (err == SSL_ERROR_WANT_WRITE)) {
  5490. n = 0;
  5491. } else {
  5492. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5493. ERR_clear_error();
  5494. return -2;
  5495. }
  5496. ERR_clear_error();
  5497. } else {
  5498. err = 0;
  5499. }
  5500. } else
  5501. #endif
  5502. if (fp != NULL) {
  5503. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5504. if (ferror(fp)) {
  5505. n = -1;
  5506. err = ERRNO;
  5507. } else {
  5508. err = 0;
  5509. }
  5510. } else {
  5511. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5512. err = (n < 0) ? ERRNO : 0;
  5513. #if defined(_WIN32)
  5514. if (err == WSAEWOULDBLOCK) {
  5515. err = 0;
  5516. n = 0;
  5517. }
  5518. #else
  5519. if (err == EWOULDBLOCK) {
  5520. err = 0;
  5521. n = 0;
  5522. }
  5523. #endif
  5524. if (n < 0) {
  5525. /* shutdown of the socket at client side */
  5526. return -2;
  5527. }
  5528. }
  5529. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5530. return -2;
  5531. }
  5532. if ((n > 0) || ((n == 0) && (len == 0))) {
  5533. /* some data has been read, or no data was requested */
  5534. return n;
  5535. }
  5536. if (n < 0) {
  5537. /* socket error - check errno */
  5538. DEBUG_TRACE("send() failed, error %d", err);
  5539. /* TODO (mid): error handling depending on the error code.
  5540. * These codes are different between Windows and Linux.
  5541. * Currently there is no problem with failing send calls,
  5542. * if there is a reproducible situation, it should be
  5543. * investigated in detail.
  5544. */
  5545. return -2;
  5546. }
  5547. /* Only in case n=0 (timeout), repeat calling the write function */
  5548. /* If send failed, wait before retry */
  5549. if (fp != NULL) {
  5550. /* For files, just wait a fixed time.
  5551. * Maybe it helps, maybe not. */
  5552. mg_sleep(5);
  5553. } else {
  5554. /* For sockets, wait for the socket using poll */
  5555. struct mg_pollfd pfd[1];
  5556. int pollres;
  5557. pfd[0].fd = sock;
  5558. pfd[0].events = POLLOUT;
  5559. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5560. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5561. return -2;
  5562. }
  5563. if (pollres > 0) {
  5564. continue;
  5565. }
  5566. }
  5567. if (timeout > 0) {
  5568. now = mg_get_current_time_ns();
  5569. if ((now - start) > timeout_ns) {
  5570. /* Timeout */
  5571. break;
  5572. }
  5573. }
  5574. }
  5575. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5576. used */
  5577. return -1;
  5578. }
  5579. static int
  5580. push_all(struct mg_context *ctx,
  5581. FILE *fp,
  5582. SOCKET sock,
  5583. SSL *ssl,
  5584. const char *buf,
  5585. int len)
  5586. {
  5587. double timeout = -1.0;
  5588. int n, nwritten = 0;
  5589. if (ctx == NULL) {
  5590. return -1;
  5591. }
  5592. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5593. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5594. }
  5595. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5596. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5597. if (n < 0) {
  5598. if (nwritten == 0) {
  5599. nwritten = -1; /* Propagate the error */
  5600. }
  5601. break;
  5602. } else if (n == 0) {
  5603. break; /* No more data to write */
  5604. } else {
  5605. nwritten += n;
  5606. len -= n;
  5607. }
  5608. }
  5609. return nwritten;
  5610. }
  5611. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5612. * Return value:
  5613. * >=0 .. number of bytes successfully read
  5614. * -1 .. timeout
  5615. * -2 .. error
  5616. */
  5617. static int
  5618. pull_inner(FILE *fp,
  5619. struct mg_connection *conn,
  5620. char *buf,
  5621. int len,
  5622. double timeout)
  5623. {
  5624. int nread, err = 0;
  5625. #if defined(_WIN32)
  5626. typedef int len_t;
  5627. #else
  5628. typedef size_t len_t;
  5629. #endif
  5630. /* We need an additional wait loop around this, because in some cases
  5631. * with TLSwe may get data from the socket but not from SSL_read.
  5632. * In this case we need to repeat at least once.
  5633. */
  5634. if (fp != NULL) {
  5635. #if !defined(_WIN32_WCE)
  5636. /* Use read() instead of fread(), because if we're reading from the
  5637. * CGI pipe, fread() may block until IO buffer is filled up. We
  5638. * cannot afford to block and must pass all read bytes immediately
  5639. * to the client. */
  5640. nread = (int)read(fileno(fp), buf, (size_t)len);
  5641. #else
  5642. /* WinCE does not support CGI pipes */
  5643. nread = (int)fread(buf, 1, (size_t)len, fp);
  5644. #endif
  5645. err = (nread < 0) ? ERRNO : 0;
  5646. if ((nread == 0) && (len > 0)) {
  5647. /* Should get data, but got EOL */
  5648. return -2;
  5649. }
  5650. #if !defined(NO_SSL)
  5651. } else if (conn->ssl != NULL) {
  5652. int ssl_pending;
  5653. struct mg_pollfd pfd[1];
  5654. int pollres;
  5655. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5656. /* We already know there is no more data buffered in conn->buf
  5657. * but there is more available in the SSL layer. So don't poll
  5658. * conn->client.sock yet. */
  5659. if (ssl_pending > len) {
  5660. ssl_pending = len;
  5661. }
  5662. pollres = 1;
  5663. } else {
  5664. pfd[0].fd = conn->client.sock;
  5665. pfd[0].events = POLLIN;
  5666. pollres = mg_poll(pfd,
  5667. 1,
  5668. (int)(timeout * 1000.0),
  5669. &(conn->phys_ctx->stop_flag));
  5670. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5671. return -2;
  5672. }
  5673. }
  5674. if (pollres > 0) {
  5675. ERR_clear_error();
  5676. nread =
  5677. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5678. if (nread <= 0) {
  5679. err = SSL_get_error(conn->ssl, nread);
  5680. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5681. err = ERRNO;
  5682. } else if ((err == SSL_ERROR_WANT_READ)
  5683. || (err == SSL_ERROR_WANT_WRITE)) {
  5684. nread = 0;
  5685. } else {
  5686. /* All errors should return -2 */
  5687. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5688. ERR_clear_error();
  5689. return -2;
  5690. }
  5691. ERR_clear_error();
  5692. } else {
  5693. err = 0;
  5694. }
  5695. } else if (pollres < 0) {
  5696. /* Error */
  5697. return -2;
  5698. } else {
  5699. /* pollres = 0 means timeout */
  5700. nread = 0;
  5701. }
  5702. #endif
  5703. } else {
  5704. struct mg_pollfd pfd[1];
  5705. int pollres;
  5706. pfd[0].fd = conn->client.sock;
  5707. pfd[0].events = POLLIN;
  5708. pollres = mg_poll(pfd,
  5709. 1,
  5710. (int)(timeout * 1000.0),
  5711. &(conn->phys_ctx->stop_flag));
  5712. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5713. return -2;
  5714. }
  5715. if (pollres > 0) {
  5716. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5717. err = (nread < 0) ? ERRNO : 0;
  5718. if (nread <= 0) {
  5719. /* shutdown of the socket at client side */
  5720. return -2;
  5721. }
  5722. } else if (pollres < 0) {
  5723. /* error callint poll */
  5724. return -2;
  5725. } else {
  5726. /* pollres = 0 means timeout */
  5727. nread = 0;
  5728. }
  5729. }
  5730. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5731. return -2;
  5732. }
  5733. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5734. /* some data has been read, or no data was requested */
  5735. return nread;
  5736. }
  5737. if (nread < 0) {
  5738. /* socket error - check errno */
  5739. #if defined(_WIN32)
  5740. if (err == WSAEWOULDBLOCK) {
  5741. /* TODO (low): check if this is still required */
  5742. /* standard case if called from close_socket_gracefully */
  5743. return -2;
  5744. } else if (err == WSAETIMEDOUT) {
  5745. /* TODO (low): check if this is still required */
  5746. /* timeout is handled by the while loop */
  5747. return 0;
  5748. } else if (err == WSAECONNABORTED) {
  5749. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5750. return -2;
  5751. } else {
  5752. DEBUG_TRACE("recv() failed, error %d", err);
  5753. return -2;
  5754. }
  5755. #else
  5756. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5757. * if the timeout is reached and if the socket was set to non-
  5758. * blocking in close_socket_gracefully, so we can not distinguish
  5759. * here. We have to wait for the timeout in both cases for now.
  5760. */
  5761. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5762. /* TODO (low): check if this is still required */
  5763. /* EAGAIN/EWOULDBLOCK:
  5764. * standard case if called from close_socket_gracefully
  5765. * => should return -1 */
  5766. /* or timeout occurred
  5767. * => the code must stay in the while loop */
  5768. /* EINTR can be generated on a socket with a timeout set even
  5769. * when SA_RESTART is effective for all relevant signals
  5770. * (see signal(7)).
  5771. * => stay in the while loop */
  5772. } else {
  5773. DEBUG_TRACE("recv() failed, error %d", err);
  5774. return -2;
  5775. }
  5776. #endif
  5777. }
  5778. /* Timeout occurred, but no data available. */
  5779. return -1;
  5780. }
  5781. static int
  5782. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5783. {
  5784. int n, nread = 0;
  5785. double timeout = -1.0;
  5786. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5787. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5788. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5789. }
  5790. if (timeout >= 0.0) {
  5791. start_time = mg_get_current_time_ns();
  5792. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5793. }
  5794. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5795. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5796. if (n == -2) {
  5797. if (nread == 0) {
  5798. nread = -1; /* Propagate the error */
  5799. }
  5800. break;
  5801. } else if (n == -1) {
  5802. /* timeout */
  5803. if (timeout >= 0.0) {
  5804. now = mg_get_current_time_ns();
  5805. if ((now - start_time) <= timeout_ns) {
  5806. continue;
  5807. }
  5808. }
  5809. break;
  5810. } else if (n == 0) {
  5811. break; /* No more data to read */
  5812. } else {
  5813. nread += n;
  5814. len -= n;
  5815. }
  5816. }
  5817. return nread;
  5818. }
  5819. static void
  5820. discard_unread_request_data(struct mg_connection *conn)
  5821. {
  5822. char buf[MG_BUF_LEN];
  5823. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5824. ;
  5825. }
  5826. static int
  5827. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5828. {
  5829. int64_t content_len, n, buffered_len, nread;
  5830. int64_t len64 =
  5831. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5832. * int, we may not read more
  5833. * bytes */
  5834. const char *body;
  5835. if (conn == NULL) {
  5836. return 0;
  5837. }
  5838. /* If Content-Length is not set for a response with body data,
  5839. * we do not know in advance how much data should be read. */
  5840. content_len = conn->content_len;
  5841. if (content_len < 0) {
  5842. /* The body data is completed when the connection is closed. */
  5843. content_len = INT64_MAX;
  5844. }
  5845. nread = 0;
  5846. if (conn->consumed_content < content_len) {
  5847. /* Adjust number of bytes to read. */
  5848. int64_t left_to_read = content_len - conn->consumed_content;
  5849. if (left_to_read < len64) {
  5850. /* Do not read more than the total content length of the
  5851. * request.
  5852. */
  5853. len64 = left_to_read;
  5854. }
  5855. /* Return buffered data */
  5856. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5857. - conn->consumed_content;
  5858. if (buffered_len > 0) {
  5859. if (len64 < buffered_len) {
  5860. buffered_len = len64;
  5861. }
  5862. body = conn->buf + conn->request_len + conn->consumed_content;
  5863. memcpy(buf, body, (size_t)buffered_len);
  5864. len64 -= buffered_len;
  5865. conn->consumed_content += buffered_len;
  5866. nread += buffered_len;
  5867. buf = (char *)buf + buffered_len;
  5868. }
  5869. /* We have returned all buffered data. Read new data from the remote
  5870. * socket.
  5871. */
  5872. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5873. conn->consumed_content += n;
  5874. nread += n;
  5875. } else {
  5876. nread = ((nread > 0) ? nread : n);
  5877. }
  5878. }
  5879. return (int)nread;
  5880. }
  5881. int
  5882. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5883. {
  5884. if (len > INT_MAX) {
  5885. len = INT_MAX;
  5886. }
  5887. if (conn == NULL) {
  5888. return 0;
  5889. }
  5890. if (conn->is_chunked) {
  5891. size_t all_read = 0;
  5892. while (len > 0) {
  5893. if (conn->is_chunked >= 3) {
  5894. /* No more data left to read */
  5895. return 0;
  5896. }
  5897. if (conn->is_chunked != 1) {
  5898. /* Has error */
  5899. return -1;
  5900. }
  5901. if (conn->consumed_content != conn->content_len) {
  5902. /* copy from the current chunk */
  5903. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5904. if (read_ret < 1) {
  5905. /* read error */
  5906. conn->is_chunked = 2;
  5907. return -1;
  5908. }
  5909. all_read += (size_t)read_ret;
  5910. len -= (size_t)read_ret;
  5911. if (conn->consumed_content == conn->content_len) {
  5912. /* Add data bytes in the current chunk have been read,
  5913. * so we are expecting \r\n now. */
  5914. char x[2];
  5915. conn->content_len += 2;
  5916. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5917. || (x[1] != '\n')) {
  5918. /* Protocol violation */
  5919. conn->is_chunked = 2;
  5920. return -1;
  5921. }
  5922. }
  5923. } else {
  5924. /* fetch a new chunk */
  5925. size_t i;
  5926. char lenbuf[64];
  5927. char *end = NULL;
  5928. unsigned long chunkSize = 0;
  5929. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5930. conn->content_len++;
  5931. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5932. lenbuf[i] = 0;
  5933. }
  5934. if ((i > 0) && (lenbuf[i] == '\r')
  5935. && (lenbuf[i - 1] != '\r')) {
  5936. continue;
  5937. }
  5938. if ((i > 1) && (lenbuf[i] == '\n')
  5939. && (lenbuf[i - 1] == '\r')) {
  5940. lenbuf[i + 1] = 0;
  5941. chunkSize = strtoul(lenbuf, &end, 16);
  5942. if (chunkSize == 0) {
  5943. /* regular end of content */
  5944. conn->is_chunked = 3;
  5945. }
  5946. break;
  5947. }
  5948. if (!isxdigit((unsigned char)lenbuf[i])) {
  5949. /* illegal character for chunk length */
  5950. conn->is_chunked = 2;
  5951. return -1;
  5952. }
  5953. }
  5954. if ((end == NULL) || (*end != '\r')) {
  5955. /* chunksize not set correctly */
  5956. conn->is_chunked = 2;
  5957. return -1;
  5958. }
  5959. if (chunkSize == 0) {
  5960. /* try discarding trailer for keep-alive */
  5961. conn->content_len += 2;
  5962. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5963. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5964. conn->is_chunked = 4;
  5965. }
  5966. break;
  5967. }
  5968. /* append a new chunk */
  5969. conn->content_len += (int64_t)chunkSize;
  5970. }
  5971. }
  5972. return (int)all_read;
  5973. }
  5974. return mg_read_inner(conn, buf, len);
  5975. }
  5976. int
  5977. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5978. {
  5979. time_t now;
  5980. int n, total, allowed;
  5981. if (conn == NULL) {
  5982. return 0;
  5983. }
  5984. if (len > INT_MAX) {
  5985. return -1;
  5986. }
  5987. if (conn->throttle > 0) {
  5988. if ((now = time(NULL)) != conn->last_throttle_time) {
  5989. conn->last_throttle_time = now;
  5990. conn->last_throttle_bytes = 0;
  5991. }
  5992. allowed = conn->throttle - conn->last_throttle_bytes;
  5993. if (allowed > (int)len) {
  5994. allowed = (int)len;
  5995. }
  5996. if ((total = push_all(conn->phys_ctx,
  5997. NULL,
  5998. conn->client.sock,
  5999. conn->ssl,
  6000. (const char *)buf,
  6001. allowed))
  6002. == allowed) {
  6003. buf = (const char *)buf + total;
  6004. conn->last_throttle_bytes += total;
  6005. while ((total < (int)len)
  6006. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6007. allowed = (conn->throttle > ((int)len - total))
  6008. ? (int)len - total
  6009. : conn->throttle;
  6010. if ((n = push_all(conn->phys_ctx,
  6011. NULL,
  6012. conn->client.sock,
  6013. conn->ssl,
  6014. (const char *)buf,
  6015. allowed))
  6016. != allowed) {
  6017. break;
  6018. }
  6019. sleep(1);
  6020. conn->last_throttle_bytes = allowed;
  6021. conn->last_throttle_time = time(NULL);
  6022. buf = (const char *)buf + n;
  6023. total += n;
  6024. }
  6025. }
  6026. } else {
  6027. total = push_all(conn->phys_ctx,
  6028. NULL,
  6029. conn->client.sock,
  6030. conn->ssl,
  6031. (const char *)buf,
  6032. (int)len);
  6033. }
  6034. if (total > 0) {
  6035. conn->num_bytes_sent += total;
  6036. }
  6037. return total;
  6038. }
  6039. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6040. int
  6041. mg_send_chunk(struct mg_connection *conn,
  6042. const char *chunk,
  6043. unsigned int chunk_len)
  6044. {
  6045. char lenbuf[16];
  6046. size_t lenbuf_len;
  6047. int ret;
  6048. int t;
  6049. /* First store the length information in a text buffer. */
  6050. sprintf(lenbuf, "%x\r\n", chunk_len);
  6051. lenbuf_len = strlen(lenbuf);
  6052. /* Then send length information, chunk and terminating \r\n. */
  6053. ret = mg_write(conn, lenbuf, lenbuf_len);
  6054. if (ret != (int)lenbuf_len) {
  6055. return -1;
  6056. }
  6057. t = ret;
  6058. ret = mg_write(conn, chunk, chunk_len);
  6059. if (ret != (int)chunk_len) {
  6060. return -1;
  6061. }
  6062. t += ret;
  6063. ret = mg_write(conn, "\r\n", 2);
  6064. if (ret != 2) {
  6065. return -1;
  6066. }
  6067. t += ret;
  6068. return t;
  6069. }
  6070. #if defined(GCC_DIAGNOSTIC)
  6071. /* This block forwards format strings to printf implementations,
  6072. * so we need to disable the format-nonliteral warning. */
  6073. #pragma GCC diagnostic push
  6074. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6075. #endif
  6076. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6077. static int
  6078. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6079. {
  6080. va_list ap_copy;
  6081. size_t size = MG_BUF_LEN / 4;
  6082. int len = -1;
  6083. *buf = NULL;
  6084. while (len < 0) {
  6085. if (*buf) {
  6086. mg_free(*buf);
  6087. }
  6088. size *= 4;
  6089. *buf = (char *)mg_malloc(size);
  6090. if (!*buf) {
  6091. break;
  6092. }
  6093. va_copy(ap_copy, ap);
  6094. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6095. va_end(ap_copy);
  6096. (*buf)[size - 1] = 0;
  6097. }
  6098. return len;
  6099. }
  6100. /* Print message to buffer. If buffer is large enough to hold the message,
  6101. * return buffer. If buffer is to small, allocate large enough buffer on
  6102. * heap,
  6103. * and return allocated buffer. */
  6104. static int
  6105. alloc_vprintf(char **out_buf,
  6106. char *prealloc_buf,
  6107. size_t prealloc_size,
  6108. const char *fmt,
  6109. va_list ap)
  6110. {
  6111. va_list ap_copy;
  6112. int len;
  6113. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6114. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6115. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6116. * Therefore, we make two passes: on first pass, get required message
  6117. * length.
  6118. * On second pass, actually print the message. */
  6119. va_copy(ap_copy, ap);
  6120. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6121. va_end(ap_copy);
  6122. if (len < 0) {
  6123. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6124. * Switch to alternative code path that uses incremental
  6125. * allocations.
  6126. */
  6127. va_copy(ap_copy, ap);
  6128. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6129. va_end(ap_copy);
  6130. } else if ((size_t)(len) >= prealloc_size) {
  6131. /* The pre-allocated buffer not large enough. */
  6132. /* Allocate a new buffer. */
  6133. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6134. if (!*out_buf) {
  6135. /* Allocation failed. Return -1 as "out of memory" error. */
  6136. return -1;
  6137. }
  6138. /* Buffer allocation successful. Store the string there. */
  6139. va_copy(ap_copy, ap);
  6140. IGNORE_UNUSED_RESULT(
  6141. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6142. va_end(ap_copy);
  6143. } else {
  6144. /* The pre-allocated buffer is large enough.
  6145. * Use it to store the string and return the address. */
  6146. va_copy(ap_copy, ap);
  6147. IGNORE_UNUSED_RESULT(
  6148. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6149. va_end(ap_copy);
  6150. *out_buf = prealloc_buf;
  6151. }
  6152. return len;
  6153. }
  6154. #if defined(GCC_DIAGNOSTIC)
  6155. /* Enable format-nonliteral warning again. */
  6156. #pragma GCC diagnostic pop
  6157. #endif
  6158. static int
  6159. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6160. {
  6161. char mem[MG_BUF_LEN];
  6162. char *buf = NULL;
  6163. int len;
  6164. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6165. len = mg_write(conn, buf, (size_t)len);
  6166. }
  6167. if (buf != mem) {
  6168. mg_free(buf);
  6169. }
  6170. return len;
  6171. }
  6172. int
  6173. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6174. {
  6175. va_list ap;
  6176. int result;
  6177. va_start(ap, fmt);
  6178. result = mg_vprintf(conn, fmt, ap);
  6179. va_end(ap);
  6180. return result;
  6181. }
  6182. int
  6183. mg_url_decode(const char *src,
  6184. int src_len,
  6185. char *dst,
  6186. int dst_len,
  6187. int is_form_url_encoded)
  6188. {
  6189. int i, j, a, b;
  6190. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6191. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6192. if ((i < src_len - 2) && (src[i] == '%')
  6193. && isxdigit((unsigned char)src[i + 1])
  6194. && isxdigit((unsigned char)src[i + 2])) {
  6195. a = tolower((unsigned char)src[i + 1]);
  6196. b = tolower((unsigned char)src[i + 2]);
  6197. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6198. i += 2;
  6199. } else if (is_form_url_encoded && (src[i] == '+')) {
  6200. dst[j] = ' ';
  6201. } else {
  6202. dst[j] = src[i];
  6203. }
  6204. }
  6205. dst[j] = '\0'; /* Null-terminate the destination */
  6206. return (i >= src_len) ? j : -1;
  6207. }
  6208. /* form url decoding of an entire string */
  6209. static void
  6210. url_decode_in_place(char *buf)
  6211. {
  6212. int len = (int)strlen(buf);
  6213. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6214. }
  6215. int
  6216. mg_get_var(const char *data,
  6217. size_t data_len,
  6218. const char *name,
  6219. char *dst,
  6220. size_t dst_len)
  6221. {
  6222. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6223. }
  6224. int
  6225. mg_get_var2(const char *data,
  6226. size_t data_len,
  6227. const char *name,
  6228. char *dst,
  6229. size_t dst_len,
  6230. size_t occurrence)
  6231. {
  6232. const char *p, *e, *s;
  6233. size_t name_len;
  6234. int len;
  6235. if ((dst == NULL) || (dst_len == 0)) {
  6236. len = -2;
  6237. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6238. len = -1;
  6239. dst[0] = '\0';
  6240. } else {
  6241. name_len = strlen(name);
  6242. e = data + data_len;
  6243. len = -1;
  6244. dst[0] = '\0';
  6245. /* data is "var1=val1&var2=val2...". Find variable first */
  6246. for (p = data; p + name_len < e; p++) {
  6247. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6248. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6249. /* Point p to variable value */
  6250. p += name_len + 1;
  6251. /* Point s to the end of the value */
  6252. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6253. if (s == NULL) {
  6254. s = e;
  6255. }
  6256. DEBUG_ASSERT(s >= p);
  6257. if (s < p) {
  6258. return -3;
  6259. }
  6260. /* Decode variable into destination buffer */
  6261. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6262. /* Redirect error code from -1 to -2 (destination buffer too
  6263. * small). */
  6264. if (len == -1) {
  6265. len = -2;
  6266. }
  6267. break;
  6268. }
  6269. }
  6270. }
  6271. return len;
  6272. }
  6273. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6274. int
  6275. mg_split_form_urlencoded(char *data,
  6276. struct mg_header *form_fields,
  6277. unsigned num_form_fields)
  6278. {
  6279. char *b;
  6280. int i;
  6281. int num = 0;
  6282. if (data == NULL) {
  6283. /* parameter error */
  6284. return -1;
  6285. }
  6286. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6287. /* determine the number of expected fields */
  6288. if (data[0] == 0) {
  6289. return 0;
  6290. }
  6291. /* count number of & to return the number of key-value-pairs */
  6292. num = 1;
  6293. while (*data) {
  6294. if (*data == '&') {
  6295. num++;
  6296. }
  6297. data++;
  6298. }
  6299. return num;
  6300. }
  6301. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6302. /* parameter error */
  6303. return -1;
  6304. }
  6305. for (i = 0; i < (int)num_form_fields; i++) {
  6306. /* extract key-value pairs from input data */
  6307. while ((*data == ' ') || (*data == '\t')) {
  6308. /* skip initial spaces */
  6309. data++;
  6310. }
  6311. if (*data == 0) {
  6312. /* end of string reached */
  6313. break;
  6314. }
  6315. form_fields[num].name = data;
  6316. /* find & or = */
  6317. b = data;
  6318. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6319. b++;
  6320. }
  6321. if (*b == 0) {
  6322. /* last key without value */
  6323. form_fields[num].value = NULL;
  6324. } else if (*b == '&') {
  6325. /* mid key without value */
  6326. form_fields[num].value = NULL;
  6327. } else {
  6328. /* terminate string */
  6329. *b = 0;
  6330. /* value starts after '=' */
  6331. data = b + 1;
  6332. form_fields[num].value = data;
  6333. }
  6334. /* new field is stored */
  6335. num++;
  6336. /* find a next key */
  6337. b = strchr(data, '&');
  6338. if (b == 0) {
  6339. /* no more data */
  6340. break;
  6341. } else {
  6342. /* terminate value of last field at '&' */
  6343. *b = 0;
  6344. /* next key-value-pairs starts after '&' */
  6345. data = b + 1;
  6346. }
  6347. }
  6348. /* Decode all values */
  6349. for (i = 0; i < num; i++) {
  6350. if (form_fields[i].name) {
  6351. url_decode_in_place((char *)form_fields[i].name);
  6352. }
  6353. if (form_fields[i].value) {
  6354. url_decode_in_place((char *)form_fields[i].value);
  6355. }
  6356. }
  6357. /* return number of fields found */
  6358. return num;
  6359. }
  6360. /* HCP24: some changes to compare hole var_name */
  6361. int
  6362. mg_get_cookie(const char *cookie_header,
  6363. const char *var_name,
  6364. char *dst,
  6365. size_t dst_size)
  6366. {
  6367. const char *s, *p, *end;
  6368. int name_len, len = -1;
  6369. if ((dst == NULL) || (dst_size == 0)) {
  6370. return -2;
  6371. }
  6372. dst[0] = '\0';
  6373. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6374. return -1;
  6375. }
  6376. name_len = (int)strlen(var_name);
  6377. end = s + strlen(s);
  6378. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6379. if (s[name_len] == '=') {
  6380. /* HCP24: now check is it a substring or a full cookie name */
  6381. if ((s == cookie_header) || (s[-1] == ' ')) {
  6382. s += name_len + 1;
  6383. if ((p = strchr(s, ' ')) == NULL) {
  6384. p = end;
  6385. }
  6386. if (p[-1] == ';') {
  6387. p--;
  6388. }
  6389. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6390. s++;
  6391. p--;
  6392. }
  6393. if ((size_t)(p - s) < dst_size) {
  6394. len = (int)(p - s);
  6395. mg_strlcpy(dst, s, (size_t)len + 1);
  6396. } else {
  6397. len = -3;
  6398. }
  6399. break;
  6400. }
  6401. }
  6402. }
  6403. return len;
  6404. }
  6405. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6406. static void
  6407. base64_encode(const unsigned char *src, int src_len, char *dst)
  6408. {
  6409. static const char *b64 =
  6410. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6411. int i, j, a, b, c;
  6412. for (i = j = 0; i < src_len; i += 3) {
  6413. a = src[i];
  6414. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6415. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6416. dst[j++] = b64[a >> 2];
  6417. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6418. if (i + 1 < src_len) {
  6419. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6420. }
  6421. if (i + 2 < src_len) {
  6422. dst[j++] = b64[c & 63];
  6423. }
  6424. }
  6425. while (j % 4 != 0) {
  6426. dst[j++] = '=';
  6427. }
  6428. dst[j++] = '\0';
  6429. }
  6430. #endif
  6431. #if defined(USE_LUA)
  6432. static unsigned char
  6433. b64reverse(char letter)
  6434. {
  6435. if ((letter >= 'A') && (letter <= 'Z')) {
  6436. return letter - 'A';
  6437. }
  6438. if ((letter >= 'a') && (letter <= 'z')) {
  6439. return letter - 'a' + 26;
  6440. }
  6441. if ((letter >= '0') && (letter <= '9')) {
  6442. return letter - '0' + 52;
  6443. }
  6444. if (letter == '+') {
  6445. return 62;
  6446. }
  6447. if (letter == '/') {
  6448. return 63;
  6449. }
  6450. if (letter == '=') {
  6451. return 255; /* normal end */
  6452. }
  6453. return 254; /* error */
  6454. }
  6455. static int
  6456. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6457. {
  6458. int i;
  6459. unsigned char a, b, c, d;
  6460. *dst_len = 0;
  6461. for (i = 0; i < src_len; i += 4) {
  6462. a = b64reverse(src[i]);
  6463. if (a >= 254) {
  6464. return i;
  6465. }
  6466. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6467. if (b >= 254) {
  6468. return i + 1;
  6469. }
  6470. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6471. if (c == 254) {
  6472. return i + 2;
  6473. }
  6474. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6475. if (d == 254) {
  6476. return i + 3;
  6477. }
  6478. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6479. if (c != 255) {
  6480. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6481. if (d != 255) {
  6482. dst[(*dst_len)++] = (c << 6) + d;
  6483. }
  6484. }
  6485. }
  6486. return -1;
  6487. }
  6488. #endif
  6489. static int
  6490. is_put_or_delete_method(const struct mg_connection *conn)
  6491. {
  6492. if (conn) {
  6493. const char *s = conn->request_info.request_method;
  6494. return (s != NULL)
  6495. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6496. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6497. }
  6498. return 0;
  6499. }
  6500. #if !defined(NO_FILES)
  6501. static int
  6502. extention_matches_script(
  6503. struct mg_connection *conn, /* in: request (must be valid) */
  6504. const char *filename /* in: filename (must be valid) */
  6505. )
  6506. {
  6507. #if !defined(NO_CGI)
  6508. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6509. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6510. filename)
  6511. > 0) {
  6512. return 1;
  6513. }
  6514. #endif
  6515. #if defined(USE_LUA)
  6516. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6517. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6518. filename)
  6519. > 0) {
  6520. return 1;
  6521. }
  6522. #endif
  6523. #if defined(USE_DUKTAPE)
  6524. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6525. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6526. filename)
  6527. > 0) {
  6528. return 1;
  6529. }
  6530. #endif
  6531. /* filename and conn could be unused, if all preocessor conditions
  6532. * are false (no script language supported). */
  6533. (void)filename;
  6534. (void)conn;
  6535. return 0;
  6536. }
  6537. /* For given directory path, substitute it to valid index file.
  6538. * Return 1 if index file has been found, 0 if not found.
  6539. * If the file is found, it's stats is returned in stp. */
  6540. static int
  6541. substitute_index_file(struct mg_connection *conn,
  6542. char *path,
  6543. size_t path_len,
  6544. struct mg_file_stat *filestat)
  6545. {
  6546. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6547. struct vec filename_vec;
  6548. size_t n = strlen(path);
  6549. int found = 0;
  6550. /* The 'path' given to us points to the directory. Remove all trailing
  6551. * directory separator characters from the end of the path, and
  6552. * then append single directory separator character. */
  6553. while ((n > 0) && (path[n - 1] == '/')) {
  6554. n--;
  6555. }
  6556. path[n] = '/';
  6557. /* Traverse index files list. For each entry, append it to the given
  6558. * path and see if the file exists. If it exists, break the loop */
  6559. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6560. /* Ignore too long entries that may overflow path buffer */
  6561. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6562. continue;
  6563. }
  6564. /* Prepare full path to the index file */
  6565. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6566. /* Does it exist? */
  6567. if (mg_stat(conn, path, filestat)) {
  6568. /* Yes it does, break the loop */
  6569. found = 1;
  6570. break;
  6571. }
  6572. }
  6573. /* If no index file exists, restore directory path */
  6574. if (!found) {
  6575. path[n] = '\0';
  6576. }
  6577. return found;
  6578. }
  6579. #endif
  6580. static void
  6581. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6582. char *filename, /* out: filename */
  6583. size_t filename_buf_len, /* in: size of filename buffer */
  6584. struct mg_file_stat *filestat, /* out: file status structure */
  6585. int *is_found, /* out: file found (directly) */
  6586. int *is_script_resource, /* out: handled by a script? */
  6587. int *is_websocket_request, /* out: websocket connetion? */
  6588. int *is_put_or_delete_request /* out: put/delete a file? */
  6589. )
  6590. {
  6591. char const *accept_encoding;
  6592. #if !defined(NO_FILES)
  6593. const char *uri = conn->request_info.local_uri;
  6594. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6595. const char *rewrite;
  6596. struct vec a, b;
  6597. ptrdiff_t match_len;
  6598. char gz_path[PATH_MAX];
  6599. int truncated;
  6600. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6601. char *tmp_str;
  6602. size_t tmp_str_len, sep_pos;
  6603. int allow_substitute_script_subresources;
  6604. #endif
  6605. #else
  6606. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6607. #endif
  6608. /* Step 1: Set all initially unknown outputs to zero */
  6609. memset(filestat, 0, sizeof(*filestat));
  6610. *filename = 0;
  6611. *is_found = 0;
  6612. *is_script_resource = 0;
  6613. /* Step 2: Check if the request attempts to modify the file system */
  6614. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6615. /* Step 3: Check if it is a websocket request, and modify the document
  6616. * root if required */
  6617. #if defined(USE_WEBSOCKET)
  6618. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6619. #if !defined(NO_FILES)
  6620. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6621. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6622. }
  6623. #endif /* !NO_FILES */
  6624. #else /* USE_WEBSOCKET */
  6625. *is_websocket_request = 0;
  6626. #endif /* USE_WEBSOCKET */
  6627. /* Step 4: Check if gzip encoded response is allowed */
  6628. conn->accept_gzip = 0;
  6629. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6630. if (strstr(accept_encoding, "gzip") != NULL) {
  6631. conn->accept_gzip = 1;
  6632. }
  6633. }
  6634. #if !defined(NO_FILES)
  6635. /* Step 5: If there is no root directory, don't look for files. */
  6636. /* Note that root == NULL is a regular use case here. This occurs,
  6637. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6638. * config is not required. */
  6639. if (root == NULL) {
  6640. /* all file related outputs have already been set to 0, just return
  6641. */
  6642. return;
  6643. }
  6644. /* Step 6: Determine the local file path from the root path and the
  6645. * request uri. */
  6646. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6647. * part of the path one byte on the right. */
  6648. mg_snprintf(
  6649. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6650. if (truncated) {
  6651. goto interpret_cleanup;
  6652. }
  6653. /* Step 7: URI rewriting */
  6654. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6655. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6656. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6657. mg_snprintf(conn,
  6658. &truncated,
  6659. filename,
  6660. filename_buf_len - 1,
  6661. "%.*s%s",
  6662. (int)b.len,
  6663. b.ptr,
  6664. uri + match_len);
  6665. break;
  6666. }
  6667. }
  6668. if (truncated) {
  6669. goto interpret_cleanup;
  6670. }
  6671. /* Step 8: Check if the file exists at the server */
  6672. /* Local file path and name, corresponding to requested URI
  6673. * is now stored in "filename" variable. */
  6674. if (mg_stat(conn, filename, filestat)) {
  6675. int uri_len = (int)strlen(uri);
  6676. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6677. /* 8.1: File exists. */
  6678. *is_found = 1;
  6679. /* 8.2: Check if it is a script type. */
  6680. if (extention_matches_script(conn, filename)) {
  6681. /* The request addresses a CGI resource, Lua script or
  6682. * server-side javascript.
  6683. * The URI corresponds to the script itself (like
  6684. * /path/script.cgi), and there is no additional resource
  6685. * path (like /path/script.cgi/something).
  6686. * Requests that modify (replace or delete) a resource, like
  6687. * PUT and DELETE requests, should replace/delete the script
  6688. * file.
  6689. * Requests that read or write from/to a resource, like GET and
  6690. * POST requests, should call the script and return the
  6691. * generated response. */
  6692. *is_script_resource = (!*is_put_or_delete_request);
  6693. }
  6694. /* 8.3: If the request target is a directory, there could be
  6695. * a substitute file (index.html, index.cgi, ...). */
  6696. if (filestat->is_directory && is_uri_end_slash) {
  6697. /* Use a local copy here, since substitute_index_file will
  6698. * change the content of the file status */
  6699. struct mg_file_stat tmp_filestat;
  6700. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6701. if (substitute_index_file(
  6702. conn, filename, filename_buf_len, &tmp_filestat)) {
  6703. /* Substitute file found. Copy stat to the output, then
  6704. * check if the file is a script file */
  6705. *filestat = tmp_filestat;
  6706. if (extention_matches_script(conn, filename)) {
  6707. /* Substitute file is a script file */
  6708. *is_script_resource = 1;
  6709. } else {
  6710. /* Substitute file is a regular file */
  6711. *is_script_resource = 0;
  6712. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6713. }
  6714. }
  6715. /* If there is no substitute file, the server could return
  6716. * a directory listing in a later step */
  6717. }
  6718. return;
  6719. }
  6720. /* Step 9: Check for zipped files: */
  6721. /* If we can't find the actual file, look for the file
  6722. * with the same name but a .gz extension. If we find it,
  6723. * use that and set the gzipped flag in the file struct
  6724. * to indicate that the response need to have the content-
  6725. * encoding: gzip header.
  6726. * We can only do this if the browser declares support. */
  6727. if (conn->accept_gzip) {
  6728. mg_snprintf(
  6729. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6730. if (truncated) {
  6731. goto interpret_cleanup;
  6732. }
  6733. if (mg_stat(conn, gz_path, filestat)) {
  6734. if (filestat) {
  6735. filestat->is_gzipped = 1;
  6736. *is_found = 1;
  6737. }
  6738. /* Currently gz files can not be scripts. */
  6739. return;
  6740. }
  6741. }
  6742. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6743. /* Step 10: Script resources may handle sub-resources */
  6744. /* Support PATH_INFO for CGI scripts. */
  6745. tmp_str_len = strlen(filename);
  6746. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6747. if (!tmp_str) {
  6748. /* Out of memory */
  6749. goto interpret_cleanup;
  6750. }
  6751. memcpy(tmp_str, filename, tmp_str_len + 1);
  6752. /* Check config, if index scripts may have sub-resources */
  6753. allow_substitute_script_subresources =
  6754. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6755. "yes");
  6756. sep_pos = tmp_str_len;
  6757. while (sep_pos > 0) {
  6758. sep_pos--;
  6759. if (tmp_str[sep_pos] == '/') {
  6760. int is_script = 0, does_exist = 0;
  6761. tmp_str[sep_pos] = 0;
  6762. if (tmp_str[0]) {
  6763. is_script = extention_matches_script(conn, tmp_str);
  6764. does_exist = mg_stat(conn, tmp_str, filestat);
  6765. }
  6766. if (does_exist && is_script) {
  6767. filename[sep_pos] = 0;
  6768. memmove(filename + sep_pos + 2,
  6769. filename + sep_pos + 1,
  6770. strlen(filename + sep_pos + 1) + 1);
  6771. conn->path_info = filename + sep_pos + 1;
  6772. filename[sep_pos + 1] = '/';
  6773. *is_script_resource = 1;
  6774. *is_found = 1;
  6775. break;
  6776. }
  6777. if (allow_substitute_script_subresources) {
  6778. if (substitute_index_file(
  6779. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6780. /* some intermediate directory has an index file */
  6781. if (extention_matches_script(conn, tmp_str)) {
  6782. DEBUG_TRACE("Substitute script %s serving path %s",
  6783. tmp_str,
  6784. filename);
  6785. /* this index file is a script */
  6786. mg_snprintf(conn,
  6787. &truncated,
  6788. filename,
  6789. filename_buf_len,
  6790. "%s//%s",
  6791. tmp_str,
  6792. filename + sep_pos + 1);
  6793. if (truncated) {
  6794. mg_free(tmp_str);
  6795. goto interpret_cleanup;
  6796. }
  6797. sep_pos = strlen(tmp_str);
  6798. filename[sep_pos] = 0;
  6799. conn->path_info = filename + sep_pos + 1;
  6800. *is_script_resource = 1;
  6801. *is_found = 1;
  6802. break;
  6803. } else {
  6804. DEBUG_TRACE("Substitute file %s serving path %s",
  6805. tmp_str,
  6806. filename);
  6807. /* non-script files will not have sub-resources */
  6808. filename[sep_pos] = 0;
  6809. conn->path_info = 0;
  6810. *is_script_resource = 0;
  6811. *is_found = 0;
  6812. break;
  6813. }
  6814. }
  6815. }
  6816. tmp_str[sep_pos] = '/';
  6817. }
  6818. }
  6819. mg_free(tmp_str);
  6820. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6821. #endif /* !defined(NO_FILES) */
  6822. return;
  6823. #if !defined(NO_FILES)
  6824. /* Reset all outputs */
  6825. interpret_cleanup:
  6826. memset(filestat, 0, sizeof(*filestat));
  6827. *filename = 0;
  6828. *is_found = 0;
  6829. *is_script_resource = 0;
  6830. *is_websocket_request = 0;
  6831. *is_put_or_delete_request = 0;
  6832. #endif /* !defined(NO_FILES) */
  6833. }
  6834. /* Check whether full request is buffered. Return:
  6835. * -1 if request or response is malformed
  6836. * 0 if request or response is not yet fully buffered
  6837. * >0 actual request length, including last \r\n\r\n */
  6838. static int
  6839. get_http_header_len(const char *buf, int buflen)
  6840. {
  6841. int i;
  6842. for (i = 0; i < buflen; i++) {
  6843. /* Do an unsigned comparison in some conditions below */
  6844. const unsigned char c = (unsigned char)buf[i];
  6845. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6846. && !isprint(c)) {
  6847. /* abort scan as soon as one malformed character is found */
  6848. return -1;
  6849. }
  6850. if (i < buflen - 1) {
  6851. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6852. /* Two newline, no carriage return - not standard compliant,
  6853. * but it should be accepted */
  6854. return i + 2;
  6855. }
  6856. }
  6857. if (i < buflen - 3) {
  6858. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6859. && (buf[i + 3] == '\n')) {
  6860. /* Two \r\n - standard compliant */
  6861. return i + 4;
  6862. }
  6863. }
  6864. }
  6865. return 0;
  6866. }
  6867. #if !defined(NO_CACHING)
  6868. /* Convert month to the month number. Return -1 on error, or month number */
  6869. static int
  6870. get_month_index(const char *s)
  6871. {
  6872. size_t i;
  6873. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6874. if (!strcmp(s, month_names[i])) {
  6875. return (int)i;
  6876. }
  6877. }
  6878. return -1;
  6879. }
  6880. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6881. static time_t
  6882. parse_date_string(const char *datetime)
  6883. {
  6884. char month_str[32] = {0};
  6885. int second, minute, hour, day, month, year;
  6886. time_t result = (time_t)0;
  6887. struct tm tm;
  6888. if ((sscanf(datetime,
  6889. "%d/%3s/%d %d:%d:%d",
  6890. &day,
  6891. month_str,
  6892. &year,
  6893. &hour,
  6894. &minute,
  6895. &second)
  6896. == 6)
  6897. || (sscanf(datetime,
  6898. "%d %3s %d %d:%d:%d",
  6899. &day,
  6900. month_str,
  6901. &year,
  6902. &hour,
  6903. &minute,
  6904. &second)
  6905. == 6)
  6906. || (sscanf(datetime,
  6907. "%*3s, %d %3s %d %d:%d:%d",
  6908. &day,
  6909. month_str,
  6910. &year,
  6911. &hour,
  6912. &minute,
  6913. &second)
  6914. == 6)
  6915. || (sscanf(datetime,
  6916. "%d-%3s-%d %d:%d:%d",
  6917. &day,
  6918. month_str,
  6919. &year,
  6920. &hour,
  6921. &minute,
  6922. &second)
  6923. == 6)) {
  6924. month = get_month_index(month_str);
  6925. if ((month >= 0) && (year >= 1970)) {
  6926. memset(&tm, 0, sizeof(tm));
  6927. tm.tm_year = year - 1900;
  6928. tm.tm_mon = month;
  6929. tm.tm_mday = day;
  6930. tm.tm_hour = hour;
  6931. tm.tm_min = minute;
  6932. tm.tm_sec = second;
  6933. result = timegm(&tm);
  6934. }
  6935. }
  6936. return result;
  6937. }
  6938. #endif /* !NO_CACHING */
  6939. /* Pre-process URIs according to RFC + protect against directory disclosure
  6940. * attacks by removing '..', excessive '/' and '\' characters */
  6941. static void
  6942. remove_dot_segments(char *inout)
  6943. {
  6944. /* Windows backend protection
  6945. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6946. * in URI by slash */
  6947. char *out_end = inout;
  6948. char *in = inout;
  6949. if (!in) {
  6950. /* Param error. */
  6951. return;
  6952. }
  6953. while (*in) {
  6954. if (*in == '\\') {
  6955. *in = '/';
  6956. }
  6957. in++;
  6958. }
  6959. /* Algorithm "remove_dot_segments" from
  6960. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6961. /* Step 1:
  6962. * The input buffer is initialized.
  6963. * The output buffer is initialized to the empty string.
  6964. */
  6965. in = inout;
  6966. /* Step 2:
  6967. * While the input buffer is not empty, loop as follows:
  6968. */
  6969. /* Less than out_end of the inout buffer is used as output, so keep
  6970. * condition: out_end <= in */
  6971. while (*in) {
  6972. /* Step 2a:
  6973. * If the input buffer begins with a prefix of "../" or "./",
  6974. * then remove that prefix from the input buffer;
  6975. */
  6976. if (!strncmp(in, "../", 3)) {
  6977. in += 3;
  6978. } else if (!strncmp(in, "./", 2)) {
  6979. in += 2;
  6980. }
  6981. /* otherwise */
  6982. /* Step 2b:
  6983. * if the input buffer begins with a prefix of "/./" or "/.",
  6984. * where "." is a complete path segment, then replace that
  6985. * prefix with "/" in the input buffer;
  6986. */
  6987. else if (!strncmp(in, "/./", 3)) {
  6988. in += 2;
  6989. } else if (!strcmp(in, "/.")) {
  6990. in[1] = 0;
  6991. }
  6992. /* otherwise */
  6993. /* Step 2c:
  6994. * if the input buffer begins with a prefix of "/../" or "/..",
  6995. * where ".." is a complete path segment, then replace that
  6996. * prefix with "/" in the input buffer and remove the last
  6997. * segment and its preceding "/" (if any) from the output
  6998. * buffer;
  6999. */
  7000. else if (!strncmp(in, "/../", 4)) {
  7001. in += 3;
  7002. if (inout != out_end) {
  7003. /* remove last segment */
  7004. do {
  7005. out_end--;
  7006. } while ((inout != out_end) && (*out_end != '/'));
  7007. }
  7008. } else if (!strcmp(in, "/..")) {
  7009. in[1] = 0;
  7010. if (inout != out_end) {
  7011. /* remove last segment */
  7012. do {
  7013. out_end--;
  7014. } while ((inout != out_end) && (*out_end != '/'));
  7015. }
  7016. }
  7017. /* otherwise */
  7018. /* Step 2d:
  7019. * if the input buffer consists only of "." or "..", then remove
  7020. * that from the input buffer;
  7021. */
  7022. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7023. *in = 0;
  7024. }
  7025. /* otherwise */
  7026. /* Step 2e:
  7027. * move the first path segment in the input buffer to the end of
  7028. * the output buffer, including the initial "/" character (if
  7029. * any) and any subsequent characters up to, but not including,
  7030. * the next "/" character or the end of the input buffer.
  7031. */
  7032. else {
  7033. do {
  7034. *out_end = *in;
  7035. out_end++;
  7036. in++;
  7037. } while ((*in != 0) && (*in != '/'));
  7038. }
  7039. }
  7040. /* Step 3:
  7041. * Finally, the output buffer is returned as the result of
  7042. * remove_dot_segments.
  7043. */
  7044. /* Terminate output */
  7045. *out_end = 0;
  7046. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7047. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7048. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7049. * or "//" anymore.
  7050. */
  7051. out_end = in = inout;
  7052. while (*in) {
  7053. if (*in == '.') {
  7054. /* remove . at the end or preceding of / */
  7055. char *in_ahead = in;
  7056. do {
  7057. in_ahead++;
  7058. } while (*in_ahead == '.');
  7059. if (*in_ahead == '/') {
  7060. in = in_ahead;
  7061. if ((out_end != inout) && (out_end[-1] == '/')) {
  7062. /* remove generated // */
  7063. out_end--;
  7064. }
  7065. } else if (*in_ahead == 0) {
  7066. in = in_ahead;
  7067. } else {
  7068. do {
  7069. *out_end++ = '.';
  7070. in++;
  7071. } while (in != in_ahead);
  7072. }
  7073. } else if (*in == '/') {
  7074. /* replace // by / */
  7075. *out_end++ = '/';
  7076. do {
  7077. in++;
  7078. } while (*in == '/');
  7079. } else {
  7080. *out_end++ = *in;
  7081. in++;
  7082. }
  7083. }
  7084. *out_end = 0;
  7085. }
  7086. static const struct {
  7087. const char *extension;
  7088. size_t ext_len;
  7089. const char *mime_type;
  7090. } builtin_mime_types[] = {
  7091. /* IANA registered MIME types
  7092. * (http://www.iana.org/assignments/media-types)
  7093. * application types */
  7094. {".doc", 4, "application/msword"},
  7095. {".eps", 4, "application/postscript"},
  7096. {".exe", 4, "application/octet-stream"},
  7097. {".js", 3, "application/javascript"},
  7098. {".json", 5, "application/json"},
  7099. {".pdf", 4, "application/pdf"},
  7100. {".ps", 3, "application/postscript"},
  7101. {".rtf", 4, "application/rtf"},
  7102. {".xhtml", 6, "application/xhtml+xml"},
  7103. {".xsl", 4, "application/xml"},
  7104. {".xslt", 5, "application/xml"},
  7105. /* fonts */
  7106. {".ttf", 4, "application/font-sfnt"},
  7107. {".cff", 4, "application/font-sfnt"},
  7108. {".otf", 4, "application/font-sfnt"},
  7109. {".aat", 4, "application/font-sfnt"},
  7110. {".sil", 4, "application/font-sfnt"},
  7111. {".pfr", 4, "application/font-tdpfr"},
  7112. {".woff", 5, "application/font-woff"},
  7113. /* audio */
  7114. {".mp3", 4, "audio/mpeg"},
  7115. {".oga", 4, "audio/ogg"},
  7116. {".ogg", 4, "audio/ogg"},
  7117. /* image */
  7118. {".gif", 4, "image/gif"},
  7119. {".ief", 4, "image/ief"},
  7120. {".jpeg", 5, "image/jpeg"},
  7121. {".jpg", 4, "image/jpeg"},
  7122. {".jpm", 4, "image/jpm"},
  7123. {".jpx", 4, "image/jpx"},
  7124. {".png", 4, "image/png"},
  7125. {".svg", 4, "image/svg+xml"},
  7126. {".tif", 4, "image/tiff"},
  7127. {".tiff", 5, "image/tiff"},
  7128. /* model */
  7129. {".wrl", 4, "model/vrml"},
  7130. /* text */
  7131. {".css", 4, "text/css"},
  7132. {".csv", 4, "text/csv"},
  7133. {".htm", 4, "text/html"},
  7134. {".html", 5, "text/html"},
  7135. {".sgm", 4, "text/sgml"},
  7136. {".shtm", 5, "text/html"},
  7137. {".shtml", 6, "text/html"},
  7138. {".txt", 4, "text/plain"},
  7139. {".xml", 4, "text/xml"},
  7140. /* video */
  7141. {".mov", 4, "video/quicktime"},
  7142. {".mp4", 4, "video/mp4"},
  7143. {".mpeg", 5, "video/mpeg"},
  7144. {".mpg", 4, "video/mpeg"},
  7145. {".ogv", 4, "video/ogg"},
  7146. {".qt", 3, "video/quicktime"},
  7147. /* not registered types
  7148. * (http://reference.sitepoint.com/html/mime-types-full,
  7149. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7150. {".arj", 4, "application/x-arj-compressed"},
  7151. {".gz", 3, "application/x-gunzip"},
  7152. {".rar", 4, "application/x-arj-compressed"},
  7153. {".swf", 4, "application/x-shockwave-flash"},
  7154. {".tar", 4, "application/x-tar"},
  7155. {".tgz", 4, "application/x-tar-gz"},
  7156. {".torrent", 8, "application/x-bittorrent"},
  7157. {".ppt", 4, "application/x-mspowerpoint"},
  7158. {".xls", 4, "application/x-msexcel"},
  7159. {".zip", 4, "application/x-zip-compressed"},
  7160. {".aac",
  7161. 4,
  7162. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7163. {".aif", 4, "audio/x-aif"},
  7164. {".m3u", 4, "audio/x-mpegurl"},
  7165. {".mid", 4, "audio/x-midi"},
  7166. {".ra", 3, "audio/x-pn-realaudio"},
  7167. {".ram", 4, "audio/x-pn-realaudio"},
  7168. {".wav", 4, "audio/x-wav"},
  7169. {".bmp", 4, "image/bmp"},
  7170. {".ico", 4, "image/x-icon"},
  7171. {".pct", 4, "image/x-pct"},
  7172. {".pict", 5, "image/pict"},
  7173. {".rgb", 4, "image/x-rgb"},
  7174. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7175. {".asf", 4, "video/x-ms-asf"},
  7176. {".avi", 4, "video/x-msvideo"},
  7177. {".m4v", 4, "video/x-m4v"},
  7178. {NULL, 0, NULL}};
  7179. const char *
  7180. mg_get_builtin_mime_type(const char *path)
  7181. {
  7182. const char *ext;
  7183. size_t i, path_len;
  7184. path_len = strlen(path);
  7185. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7186. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7187. if ((path_len > builtin_mime_types[i].ext_len)
  7188. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7189. return builtin_mime_types[i].mime_type;
  7190. }
  7191. }
  7192. return "text/plain";
  7193. }
  7194. /* Look at the "path" extension and figure what mime type it has.
  7195. * Store mime type in the vector. */
  7196. static void
  7197. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7198. {
  7199. struct vec ext_vec, mime_vec;
  7200. const char *list, *ext;
  7201. size_t path_len;
  7202. path_len = strlen(path);
  7203. if ((conn == NULL) || (vec == NULL)) {
  7204. if (vec != NULL) {
  7205. memset(vec, '\0', sizeof(struct vec));
  7206. }
  7207. return;
  7208. }
  7209. /* Scan user-defined mime types first, in case user wants to
  7210. * override default mime types. */
  7211. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7212. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7213. /* ext now points to the path suffix */
  7214. ext = path + path_len - ext_vec.len;
  7215. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7216. *vec = mime_vec;
  7217. return;
  7218. }
  7219. }
  7220. vec->ptr = mg_get_builtin_mime_type(path);
  7221. vec->len = strlen(vec->ptr);
  7222. }
  7223. /* Stringify binary data. Output buffer must be twice as big as input,
  7224. * because each byte takes 2 bytes in string representation */
  7225. static void
  7226. bin2str(char *to, const unsigned char *p, size_t len)
  7227. {
  7228. static const char *hex = "0123456789abcdef";
  7229. for (; len--; p++) {
  7230. *to++ = hex[p[0] >> 4];
  7231. *to++ = hex[p[0] & 0x0f];
  7232. }
  7233. *to = '\0';
  7234. }
  7235. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7236. */
  7237. char *
  7238. mg_md5(char buf[33], ...)
  7239. {
  7240. md5_byte_t hash[16];
  7241. const char *p;
  7242. va_list ap;
  7243. md5_state_t ctx;
  7244. md5_init(&ctx);
  7245. va_start(ap, buf);
  7246. while ((p = va_arg(ap, const char *)) != NULL) {
  7247. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7248. }
  7249. va_end(ap);
  7250. md5_finish(&ctx, hash);
  7251. bin2str(buf, hash, sizeof(hash));
  7252. return buf;
  7253. }
  7254. /* Check the user's password, return 1 if OK */
  7255. static int
  7256. check_password(const char *method,
  7257. const char *ha1,
  7258. const char *uri,
  7259. const char *nonce,
  7260. const char *nc,
  7261. const char *cnonce,
  7262. const char *qop,
  7263. const char *response)
  7264. {
  7265. char ha2[32 + 1], expected_response[32 + 1];
  7266. /* Some of the parameters may be NULL */
  7267. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7268. || (qop == NULL) || (response == NULL)) {
  7269. return 0;
  7270. }
  7271. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7272. if (strlen(response) != 32) {
  7273. return 0;
  7274. }
  7275. mg_md5(ha2, method, ":", uri, NULL);
  7276. mg_md5(expected_response,
  7277. ha1,
  7278. ":",
  7279. nonce,
  7280. ":",
  7281. nc,
  7282. ":",
  7283. cnonce,
  7284. ":",
  7285. qop,
  7286. ":",
  7287. ha2,
  7288. NULL);
  7289. return mg_strcasecmp(response, expected_response) == 0;
  7290. }
  7291. #if !defined(NO_FILESYSTEMS)
  7292. /* Use the global passwords file, if specified by auth_gpass option,
  7293. * or search for .htpasswd in the requested directory. */
  7294. static void
  7295. open_auth_file(struct mg_connection *conn,
  7296. const char *path,
  7297. struct mg_file *filep)
  7298. {
  7299. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7300. char name[PATH_MAX];
  7301. const char *p, *e,
  7302. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7303. int truncated;
  7304. if (gpass != NULL) {
  7305. /* Use global passwords file */
  7306. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7307. #if defined(DEBUG)
  7308. /* Use mg_cry_internal here, since gpass has been
  7309. * configured. */
  7310. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7311. #endif
  7312. }
  7313. /* Important: using local struct mg_file to test path for
  7314. * is_directory flag. If filep is used, mg_stat() makes it
  7315. * appear as if auth file was opened.
  7316. * TODO(mid): Check if this is still required after rewriting
  7317. * mg_stat */
  7318. } else if (mg_stat(conn, path, &filep->stat)
  7319. && filep->stat.is_directory) {
  7320. mg_snprintf(conn,
  7321. &truncated,
  7322. name,
  7323. sizeof(name),
  7324. "%s/%s",
  7325. path,
  7326. PASSWORDS_FILE_NAME);
  7327. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7328. #if defined(DEBUG)
  7329. /* Don't use mg_cry_internal here, but only a trace, since
  7330. * this is a typical case. It will occur for every directory
  7331. * without a password file. */
  7332. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7333. #endif
  7334. }
  7335. } else {
  7336. /* Try to find .htpasswd in requested directory. */
  7337. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7338. if (e[0] == '/') {
  7339. break;
  7340. }
  7341. }
  7342. mg_snprintf(conn,
  7343. &truncated,
  7344. name,
  7345. sizeof(name),
  7346. "%.*s/%s",
  7347. (int)(e - p),
  7348. p,
  7349. PASSWORDS_FILE_NAME);
  7350. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7351. #if defined(DEBUG)
  7352. /* Don't use mg_cry_internal here, but only a trace, since
  7353. * this is a typical case. It will occur for every directory
  7354. * without a password file. */
  7355. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7356. #endif
  7357. }
  7358. }
  7359. }
  7360. }
  7361. #endif /* NO_FILESYSTEMS */
  7362. /* Parsed Authorization header */
  7363. struct ah {
  7364. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7365. };
  7366. /* Return 1 on success. Always initializes the ah structure. */
  7367. static int
  7368. parse_auth_header(struct mg_connection *conn,
  7369. char *buf,
  7370. size_t buf_size,
  7371. struct ah *ah)
  7372. {
  7373. char *name, *value, *s;
  7374. const char *auth_header;
  7375. uint64_t nonce;
  7376. if (!ah || !conn) {
  7377. return 0;
  7378. }
  7379. (void)memset(ah, 0, sizeof(*ah));
  7380. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7381. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7382. return 0;
  7383. }
  7384. /* Make modifiable copy of the auth header */
  7385. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7386. s = buf;
  7387. /* Parse authorization header */
  7388. for (;;) {
  7389. /* Gobble initial spaces */
  7390. while (isspace((unsigned char)*s)) {
  7391. s++;
  7392. }
  7393. name = skip_quoted(&s, "=", " ", 0);
  7394. /* Value is either quote-delimited, or ends at first comma or space.
  7395. */
  7396. if (s[0] == '\"') {
  7397. s++;
  7398. value = skip_quoted(&s, "\"", " ", '\\');
  7399. if (s[0] == ',') {
  7400. s++;
  7401. }
  7402. } else {
  7403. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7404. * uses spaces */
  7405. }
  7406. if (*name == '\0') {
  7407. break;
  7408. }
  7409. if (!strcmp(name, "username")) {
  7410. ah->user = value;
  7411. } else if (!strcmp(name, "cnonce")) {
  7412. ah->cnonce = value;
  7413. } else if (!strcmp(name, "response")) {
  7414. ah->response = value;
  7415. } else if (!strcmp(name, "uri")) {
  7416. ah->uri = value;
  7417. } else if (!strcmp(name, "qop")) {
  7418. ah->qop = value;
  7419. } else if (!strcmp(name, "nc")) {
  7420. ah->nc = value;
  7421. } else if (!strcmp(name, "nonce")) {
  7422. ah->nonce = value;
  7423. }
  7424. }
  7425. #if !defined(NO_NONCE_CHECK)
  7426. /* Read the nonce from the response. */
  7427. if (ah->nonce == NULL) {
  7428. return 0;
  7429. }
  7430. s = NULL;
  7431. nonce = strtoull(ah->nonce, &s, 10);
  7432. if ((s == NULL) || (*s != 0)) {
  7433. return 0;
  7434. }
  7435. /* Convert the nonce from the client to a number. */
  7436. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7437. /* The converted number corresponds to the time the nounce has been
  7438. * created. This should not be earlier than the server start. */
  7439. /* Server side nonce check is valuable in all situations but one:
  7440. * if the server restarts frequently, but the client should not see
  7441. * that, so the server should accept nonces from previous starts. */
  7442. /* However, the reasonable default is to not accept a nonce from a
  7443. * previous start, so if anyone changed the access rights between
  7444. * two restarts, a new login is required. */
  7445. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7446. /* nonce is from a previous start of the server and no longer valid
  7447. * (replay attack?) */
  7448. return 0;
  7449. }
  7450. /* Check if the nonce is too high, so it has not (yet) been used by the
  7451. * server. */
  7452. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7453. + conn->dom_ctx->nonce_count)) {
  7454. return 0;
  7455. }
  7456. #else
  7457. (void)nonce;
  7458. #endif
  7459. /* CGI needs it as REMOTE_USER */
  7460. if (ah->user != NULL) {
  7461. conn->request_info.remote_user =
  7462. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7463. } else {
  7464. return 0;
  7465. }
  7466. return 1;
  7467. }
  7468. static const char *
  7469. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7470. {
  7471. #if defined(MG_USE_OPEN_FILE)
  7472. const char *eof;
  7473. size_t len;
  7474. const char *memend;
  7475. #else
  7476. (void)p; /* parameter is unused */
  7477. #endif
  7478. if (!filep) {
  7479. return NULL;
  7480. }
  7481. #if defined(MG_USE_OPEN_FILE)
  7482. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7483. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7484. /* Search for \n from p till the end of stream */
  7485. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7486. if (eof != NULL) {
  7487. eof += 1; /* Include \n */
  7488. } else {
  7489. eof = memend; /* Copy remaining data */
  7490. }
  7491. len =
  7492. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7493. memcpy(buf, *p, len);
  7494. buf[len] = '\0';
  7495. *p += len;
  7496. return len ? eof : NULL;
  7497. } else /* filep->access.fp block below */
  7498. #endif
  7499. if (filep->access.fp != NULL) {
  7500. return fgets(buf, (int)size, filep->access.fp);
  7501. } else {
  7502. return NULL;
  7503. }
  7504. }
  7505. /* Define the initial recursion depth for procesesing htpasswd files that
  7506. * include other htpasswd
  7507. * (or even the same) files. It is not difficult to provide a file or files
  7508. * s.t. they force civetweb
  7509. * to infinitely recurse and then crash.
  7510. */
  7511. #define INITIAL_DEPTH 9
  7512. #if INITIAL_DEPTH <= 0
  7513. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7514. #endif
  7515. #if !defined(NO_FILESYSTEMS)
  7516. struct read_auth_file_struct {
  7517. struct mg_connection *conn;
  7518. struct ah ah;
  7519. const char *domain;
  7520. char buf[256 + 256 + 40];
  7521. const char *f_user;
  7522. const char *f_domain;
  7523. const char *f_ha1;
  7524. };
  7525. static int
  7526. read_auth_file(struct mg_file *filep,
  7527. struct read_auth_file_struct *workdata,
  7528. int depth)
  7529. {
  7530. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7531. int is_authorized = 0;
  7532. struct mg_file fp;
  7533. size_t l;
  7534. if (!filep || !workdata || (0 == depth)) {
  7535. return 0;
  7536. }
  7537. /* Loop over passwords file */
  7538. #if defined(MG_USE_OPEN_FILE)
  7539. p = (char *)filep->access.membuf;
  7540. #endif
  7541. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7542. l = strlen(workdata->buf);
  7543. while (l > 0) {
  7544. if (isspace((unsigned char)workdata->buf[l - 1])
  7545. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7546. l--;
  7547. workdata->buf[l] = 0;
  7548. } else
  7549. break;
  7550. }
  7551. if (l < 1) {
  7552. continue;
  7553. }
  7554. workdata->f_user = workdata->buf;
  7555. if (workdata->f_user[0] == ':') {
  7556. /* user names may not contain a ':' and may not be empty,
  7557. * so lines starting with ':' may be used for a special purpose
  7558. */
  7559. if (workdata->f_user[1] == '#') {
  7560. /* :# is a comment */
  7561. continue;
  7562. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7563. if (mg_fopen(workdata->conn,
  7564. workdata->f_user + 9,
  7565. MG_FOPEN_MODE_READ,
  7566. &fp)) {
  7567. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7568. (void)mg_fclose(
  7569. &fp.access); /* ignore error on read only file */
  7570. /* No need to continue processing files once we have a
  7571. * match, since nothing will reset it back
  7572. * to 0.
  7573. */
  7574. if (is_authorized) {
  7575. return is_authorized;
  7576. }
  7577. } else {
  7578. mg_cry_internal(workdata->conn,
  7579. "%s: cannot open authorization file: %s",
  7580. __func__,
  7581. workdata->buf);
  7582. }
  7583. continue;
  7584. }
  7585. /* everything is invalid for the moment (might change in the
  7586. * future) */
  7587. mg_cry_internal(workdata->conn,
  7588. "%s: syntax error in authorization file: %s",
  7589. __func__,
  7590. workdata->buf);
  7591. continue;
  7592. }
  7593. workdata->f_domain = strchr(workdata->f_user, ':');
  7594. if (workdata->f_domain == NULL) {
  7595. mg_cry_internal(workdata->conn,
  7596. "%s: syntax error in authorization file: %s",
  7597. __func__,
  7598. workdata->buf);
  7599. continue;
  7600. }
  7601. *(char *)(workdata->f_domain) = 0;
  7602. (workdata->f_domain)++;
  7603. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7604. if (workdata->f_ha1 == NULL) {
  7605. mg_cry_internal(workdata->conn,
  7606. "%s: syntax error in authorization file: %s",
  7607. __func__,
  7608. workdata->buf);
  7609. continue;
  7610. }
  7611. *(char *)(workdata->f_ha1) = 0;
  7612. (workdata->f_ha1)++;
  7613. if (!strcmp(workdata->ah.user, workdata->f_user)
  7614. && !strcmp(workdata->domain, workdata->f_domain)) {
  7615. return check_password(workdata->conn->request_info.request_method,
  7616. workdata->f_ha1,
  7617. workdata->ah.uri,
  7618. workdata->ah.nonce,
  7619. workdata->ah.nc,
  7620. workdata->ah.cnonce,
  7621. workdata->ah.qop,
  7622. workdata->ah.response);
  7623. }
  7624. }
  7625. return is_authorized;
  7626. }
  7627. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7628. static int
  7629. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7630. {
  7631. struct read_auth_file_struct workdata;
  7632. char buf[MG_BUF_LEN];
  7633. if (!conn || !conn->dom_ctx) {
  7634. return 0;
  7635. }
  7636. memset(&workdata, 0, sizeof(workdata));
  7637. workdata.conn = conn;
  7638. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7639. return 0;
  7640. }
  7641. if (realm) {
  7642. workdata.domain = realm;
  7643. } else {
  7644. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7645. }
  7646. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7647. }
  7648. /* Public function to check http digest authentication header */
  7649. int
  7650. mg_check_digest_access_authentication(struct mg_connection *conn,
  7651. const char *realm,
  7652. const char *filename)
  7653. {
  7654. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7655. int auth;
  7656. if (!conn || !filename) {
  7657. return -1;
  7658. }
  7659. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7660. return -2;
  7661. }
  7662. auth = authorize(conn, &file, realm);
  7663. mg_fclose(&file.access);
  7664. return auth;
  7665. }
  7666. #endif /* NO_FILESYSTEMS */
  7667. /* Return 1 if request is authorised, 0 otherwise. */
  7668. static int
  7669. check_authorization(struct mg_connection *conn, const char *path)
  7670. {
  7671. #if !defined(NO_FILESYSTEMS)
  7672. char fname[PATH_MAX];
  7673. struct vec uri_vec, filename_vec;
  7674. const char *list;
  7675. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7676. int authorized = 1, truncated;
  7677. if (!conn || !conn->dom_ctx) {
  7678. return 0;
  7679. }
  7680. list = conn->dom_ctx->config[PROTECT_URI];
  7681. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7682. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7683. mg_snprintf(conn,
  7684. &truncated,
  7685. fname,
  7686. sizeof(fname),
  7687. "%.*s",
  7688. (int)filename_vec.len,
  7689. filename_vec.ptr);
  7690. if (truncated
  7691. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7692. mg_cry_internal(conn,
  7693. "%s: cannot open %s: %s",
  7694. __func__,
  7695. fname,
  7696. strerror(errno));
  7697. }
  7698. break;
  7699. }
  7700. }
  7701. if (!is_file_opened(&file.access)) {
  7702. open_auth_file(conn, path, &file);
  7703. }
  7704. if (is_file_opened(&file.access)) {
  7705. authorized = authorize(conn, &file, NULL);
  7706. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7707. }
  7708. return authorized;
  7709. #else
  7710. (void)conn;
  7711. (void)path;
  7712. return 1;
  7713. #endif /* NO_FILESYSTEMS */
  7714. }
  7715. /* Internal function. Assumes conn is valid */
  7716. static void
  7717. send_authorization_request(struct mg_connection *conn, const char *realm)
  7718. {
  7719. char date[64];
  7720. time_t curtime = time(NULL);
  7721. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7722. if (!realm) {
  7723. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7724. }
  7725. mg_lock_context(conn->phys_ctx);
  7726. nonce += conn->dom_ctx->nonce_count;
  7727. ++conn->dom_ctx->nonce_count;
  7728. mg_unlock_context(conn->phys_ctx);
  7729. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7730. conn->status_code = 401;
  7731. conn->must_close = 1;
  7732. gmt_time_string(date, sizeof(date), &curtime);
  7733. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7734. send_no_cache_header(conn);
  7735. send_additional_header(conn);
  7736. mg_printf(conn,
  7737. "Date: %s\r\n"
  7738. "Connection: %s\r\n"
  7739. "Content-Length: 0\r\n"
  7740. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7741. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7742. date,
  7743. suggest_connection_header(conn),
  7744. realm,
  7745. nonce);
  7746. }
  7747. /* Interface function. Parameters are provided by the user, so do
  7748. * at least some basic checks.
  7749. */
  7750. int
  7751. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7752. const char *realm)
  7753. {
  7754. if (conn && conn->dom_ctx) {
  7755. send_authorization_request(conn, realm);
  7756. return 0;
  7757. }
  7758. return -1;
  7759. }
  7760. #if !defined(NO_FILES)
  7761. static int
  7762. is_authorized_for_put(struct mg_connection *conn)
  7763. {
  7764. if (conn) {
  7765. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7766. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7767. int ret = 0;
  7768. if (passfile != NULL
  7769. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7770. ret = authorize(conn, &file, NULL);
  7771. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7772. }
  7773. return ret;
  7774. }
  7775. return 0;
  7776. }
  7777. #endif
  7778. int
  7779. mg_modify_passwords_file(const char *fname,
  7780. const char *domain,
  7781. const char *user,
  7782. const char *pass)
  7783. {
  7784. int found, i;
  7785. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7786. FILE *fp, *fp2;
  7787. found = 0;
  7788. fp = fp2 = NULL;
  7789. /* Regard empty password as no password - remove user record. */
  7790. if ((pass != NULL) && (pass[0] == '\0')) {
  7791. pass = NULL;
  7792. }
  7793. /* Other arguments must not be empty */
  7794. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7795. return 0;
  7796. }
  7797. /* Using the given file format, user name and domain must not contain
  7798. * ':'
  7799. */
  7800. if (strchr(user, ':') != NULL) {
  7801. return 0;
  7802. }
  7803. if (strchr(domain, ':') != NULL) {
  7804. return 0;
  7805. }
  7806. /* Do not allow control characters like newline in user name and domain.
  7807. * Do not allow excessively long names either. */
  7808. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7809. if (iscntrl((unsigned char)user[i])) {
  7810. return 0;
  7811. }
  7812. }
  7813. if (user[i]) {
  7814. return 0;
  7815. }
  7816. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7817. if (iscntrl((unsigned char)domain[i])) {
  7818. return 0;
  7819. }
  7820. }
  7821. if (domain[i]) {
  7822. return 0;
  7823. }
  7824. /* The maximum length of the path to the password file is limited */
  7825. if ((strlen(fname) + 4) >= PATH_MAX) {
  7826. return 0;
  7827. }
  7828. /* Create a temporary file name. Length has been checked before. */
  7829. strcpy(tmp, fname);
  7830. strcat(tmp, ".tmp");
  7831. /* Create the file if does not exist */
  7832. /* Use of fopen here is OK, since fname is only ASCII */
  7833. if ((fp = fopen(fname, "a+")) != NULL) {
  7834. (void)fclose(fp);
  7835. }
  7836. /* Open the given file and temporary file */
  7837. if ((fp = fopen(fname, "r")) == NULL) {
  7838. return 0;
  7839. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7840. fclose(fp);
  7841. return 0;
  7842. }
  7843. /* Copy the stuff to temporary file */
  7844. while (fgets(line, sizeof(line), fp) != NULL) {
  7845. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7846. continue;
  7847. }
  7848. u[255] = 0;
  7849. d[255] = 0;
  7850. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7851. found++;
  7852. if (pass != NULL) {
  7853. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7854. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7855. }
  7856. } else {
  7857. fprintf(fp2, "%s", line);
  7858. }
  7859. }
  7860. /* If new user, just add it */
  7861. if (!found && (pass != NULL)) {
  7862. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7863. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7864. }
  7865. /* Close files */
  7866. fclose(fp);
  7867. fclose(fp2);
  7868. /* Put the temp file in place of real file */
  7869. IGNORE_UNUSED_RESULT(remove(fname));
  7870. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7871. return 1;
  7872. }
  7873. static int
  7874. is_valid_port(unsigned long port)
  7875. {
  7876. return (port <= 0xffff);
  7877. }
  7878. static int
  7879. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7880. {
  7881. struct addrinfo hints, *res, *ressave;
  7882. int func_ret = 0;
  7883. int gai_ret;
  7884. memset(&hints, 0, sizeof(struct addrinfo));
  7885. hints.ai_family = af;
  7886. if (!resolve_src) {
  7887. hints.ai_flags = AI_NUMERICHOST;
  7888. }
  7889. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7890. if (gai_ret != 0) {
  7891. /* gai_strerror could be used to convert gai_ret to a string */
  7892. /* POSIX return values: see
  7893. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7894. */
  7895. /* Windows return values: see
  7896. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7897. */
  7898. return 0;
  7899. }
  7900. ressave = res;
  7901. while (res) {
  7902. if ((dstlen >= (size_t)res->ai_addrlen)
  7903. && (res->ai_addr->sa_family == af)) {
  7904. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7905. func_ret = 1;
  7906. }
  7907. res = res->ai_next;
  7908. }
  7909. freeaddrinfo(ressave);
  7910. return func_ret;
  7911. }
  7912. static int
  7913. connect_socket(struct mg_context *ctx /* may be NULL */,
  7914. const char *host,
  7915. int port,
  7916. int use_ssl,
  7917. char *ebuf,
  7918. size_t ebuf_len,
  7919. SOCKET *sock /* output: socket, must not be NULL */,
  7920. union usa *sa /* output: socket address, must not be NULL */
  7921. )
  7922. {
  7923. int ip_ver = 0;
  7924. int conn_ret = -1;
  7925. int sockerr = 0;
  7926. *sock = INVALID_SOCKET;
  7927. memset(sa, 0, sizeof(*sa));
  7928. if (ebuf_len > 0) {
  7929. *ebuf = 0;
  7930. }
  7931. if (host == NULL) {
  7932. mg_snprintf(NULL,
  7933. NULL, /* No truncation check for ebuf */
  7934. ebuf,
  7935. ebuf_len,
  7936. "%s",
  7937. "NULL host");
  7938. return 0;
  7939. }
  7940. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7941. mg_snprintf(NULL,
  7942. NULL, /* No truncation check for ebuf */
  7943. ebuf,
  7944. ebuf_len,
  7945. "%s",
  7946. "invalid port");
  7947. return 0;
  7948. }
  7949. #if !defined(NO_SSL)
  7950. #if !defined(NO_SSL_DL)
  7951. #if defined(OPENSSL_API_1_1)
  7952. if (use_ssl && (TLS_client_method == NULL)) {
  7953. mg_snprintf(NULL,
  7954. NULL, /* No truncation check for ebuf */
  7955. ebuf,
  7956. ebuf_len,
  7957. "%s",
  7958. "SSL is not initialized");
  7959. return 0;
  7960. }
  7961. #else
  7962. if (use_ssl && (SSLv23_client_method == NULL)) {
  7963. mg_snprintf(NULL,
  7964. NULL, /* No truncation check for ebuf */
  7965. ebuf,
  7966. ebuf_len,
  7967. "%s",
  7968. "SSL is not initialized");
  7969. return 0;
  7970. }
  7971. #endif /* OPENSSL_API_1_1 */
  7972. #else
  7973. (void)use_ssl;
  7974. #endif /* NO_SSL_DL */
  7975. #else
  7976. (void)use_ssl;
  7977. #endif /* !defined(NO_SSL) */
  7978. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7979. sa->sin.sin_port = htons((uint16_t)port);
  7980. ip_ver = 4;
  7981. #if defined(USE_IPV6)
  7982. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7983. sa->sin6.sin6_port = htons((uint16_t)port);
  7984. ip_ver = 6;
  7985. } else if (host[0] == '[') {
  7986. /* While getaddrinfo on Windows will work with [::1],
  7987. * getaddrinfo on Linux only works with ::1 (without []). */
  7988. size_t l = strlen(host + 1);
  7989. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7990. if (h) {
  7991. h[l - 1] = 0;
  7992. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7993. sa->sin6.sin6_port = htons((uint16_t)port);
  7994. ip_ver = 6;
  7995. }
  7996. mg_free(h);
  7997. }
  7998. #endif
  7999. }
  8000. if (ip_ver == 0) {
  8001. mg_snprintf(NULL,
  8002. NULL, /* No truncation check for ebuf */
  8003. ebuf,
  8004. ebuf_len,
  8005. "%s",
  8006. "host not found");
  8007. return 0;
  8008. }
  8009. if (ip_ver == 4) {
  8010. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8011. }
  8012. #if defined(USE_IPV6)
  8013. else if (ip_ver == 6) {
  8014. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8015. }
  8016. #endif
  8017. if (*sock == INVALID_SOCKET) {
  8018. mg_snprintf(NULL,
  8019. NULL, /* No truncation check for ebuf */
  8020. ebuf,
  8021. ebuf_len,
  8022. "socket(): %s",
  8023. strerror(ERRNO));
  8024. return 0;
  8025. }
  8026. if (0 != set_non_blocking_mode(*sock)) {
  8027. mg_snprintf(NULL,
  8028. NULL, /* No truncation check for ebuf */
  8029. ebuf,
  8030. ebuf_len,
  8031. "Cannot set socket to non-blocking: %s",
  8032. strerror(ERRNO));
  8033. closesocket(*sock);
  8034. *sock = INVALID_SOCKET;
  8035. return 0;
  8036. }
  8037. set_close_on_exec(*sock, NULL, ctx);
  8038. if (ip_ver == 4) {
  8039. /* connected with IPv4 */
  8040. conn_ret = connect(*sock,
  8041. (struct sockaddr *)((void *)&sa->sin),
  8042. sizeof(sa->sin));
  8043. }
  8044. #if defined(USE_IPV6)
  8045. else if (ip_ver == 6) {
  8046. /* connected with IPv6 */
  8047. conn_ret = connect(*sock,
  8048. (struct sockaddr *)((void *)&sa->sin6),
  8049. sizeof(sa->sin6));
  8050. }
  8051. #endif
  8052. if (conn_ret != 0) {
  8053. sockerr = ERRNO;
  8054. }
  8055. #if defined(_WIN32)
  8056. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8057. #else
  8058. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8059. #endif
  8060. /* Data for getsockopt */
  8061. void *psockerr = &sockerr;
  8062. int ret;
  8063. #if defined(_WIN32)
  8064. int len = (int)sizeof(sockerr);
  8065. #else
  8066. socklen_t len = (socklen_t)sizeof(sockerr);
  8067. #endif
  8068. /* Data for poll */
  8069. struct mg_pollfd pfd[1];
  8070. int pollres;
  8071. int ms_wait = 10000; /* 10 second timeout */
  8072. stop_flag_t nonstop;
  8073. STOP_FLAG_ASSIGN(&nonstop, 0);
  8074. /* For a non-blocking socket, the connect sequence is:
  8075. * 1) call connect (will not block)
  8076. * 2) wait until the socket is ready for writing (select or poll)
  8077. * 3) check connection state with getsockopt
  8078. */
  8079. pfd[0].fd = *sock;
  8080. pfd[0].events = POLLOUT;
  8081. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8082. if (pollres != 1) {
  8083. /* Not connected */
  8084. mg_snprintf(NULL,
  8085. NULL, /* No truncation check for ebuf */
  8086. ebuf,
  8087. ebuf_len,
  8088. "connect(%s:%d): timeout",
  8089. host,
  8090. port);
  8091. closesocket(*sock);
  8092. *sock = INVALID_SOCKET;
  8093. return 0;
  8094. }
  8095. #if defined(_WIN32)
  8096. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8097. #else
  8098. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8099. #endif
  8100. if ((ret == 0) && (sockerr == 0)) {
  8101. conn_ret = 0;
  8102. }
  8103. }
  8104. if (conn_ret != 0) {
  8105. /* Not connected */
  8106. mg_snprintf(NULL,
  8107. NULL, /* No truncation check for ebuf */
  8108. ebuf,
  8109. ebuf_len,
  8110. "connect(%s:%d): error %s",
  8111. host,
  8112. port,
  8113. strerror(sockerr));
  8114. closesocket(*sock);
  8115. *sock = INVALID_SOCKET;
  8116. return 0;
  8117. }
  8118. return 1;
  8119. }
  8120. int
  8121. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8122. {
  8123. static const char *dont_escape = "._-$,;~()";
  8124. static const char *hex = "0123456789abcdef";
  8125. char *pos = dst;
  8126. const char *end = dst + dst_len - 1;
  8127. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8128. if (isalnum((unsigned char)*src)
  8129. || (strchr(dont_escape, *src) != NULL)) {
  8130. *pos = *src;
  8131. } else if (pos + 2 < end) {
  8132. pos[0] = '%';
  8133. pos[1] = hex[(unsigned char)*src >> 4];
  8134. pos[2] = hex[(unsigned char)*src & 0xf];
  8135. pos += 2;
  8136. } else {
  8137. break;
  8138. }
  8139. }
  8140. *pos = '\0';
  8141. return (*src == '\0') ? (int)(pos - dst) : -1;
  8142. }
  8143. /* Return 0 on success, non-zero if an error occurs. */
  8144. static int
  8145. print_dir_entry(struct de *de)
  8146. {
  8147. size_t namesize, escsize, i;
  8148. char *href, *esc, *p;
  8149. char size[64], mod[64];
  8150. #if defined(REENTRANT_TIME)
  8151. struct tm _tm;
  8152. struct tm *tm = &_tm;
  8153. #else
  8154. struct tm *tm;
  8155. #endif
  8156. /* Estimate worst case size for encoding and escaping */
  8157. namesize = strlen(de->file_name) + 1;
  8158. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8159. href = (char *)mg_malloc(namesize * 3 + escsize);
  8160. if (href == NULL) {
  8161. return -1;
  8162. }
  8163. mg_url_encode(de->file_name, href, namesize * 3);
  8164. esc = NULL;
  8165. if (escsize > 0) {
  8166. /* HTML escaping needed */
  8167. esc = href + namesize * 3;
  8168. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8169. mg_strlcpy(p, de->file_name + i, 2);
  8170. if (*p == '&') {
  8171. strcpy(p, "&amp;");
  8172. } else if (*p == '<') {
  8173. strcpy(p, "&lt;");
  8174. } else if (*p == '>') {
  8175. strcpy(p, "&gt;");
  8176. }
  8177. }
  8178. }
  8179. if (de->file.is_directory) {
  8180. mg_snprintf(de->conn,
  8181. NULL, /* Buffer is big enough */
  8182. size,
  8183. sizeof(size),
  8184. "%s",
  8185. "[DIRECTORY]");
  8186. } else {
  8187. /* We use (signed) cast below because MSVC 6 compiler cannot
  8188. * convert unsigned __int64 to double. Sigh. */
  8189. if (de->file.size < 1024) {
  8190. mg_snprintf(de->conn,
  8191. NULL, /* Buffer is big enough */
  8192. size,
  8193. sizeof(size),
  8194. "%d",
  8195. (int)de->file.size);
  8196. } else if (de->file.size < 0x100000) {
  8197. mg_snprintf(de->conn,
  8198. NULL, /* Buffer is big enough */
  8199. size,
  8200. sizeof(size),
  8201. "%.1fk",
  8202. (double)de->file.size / 1024.0);
  8203. } else if (de->file.size < 0x40000000) {
  8204. mg_snprintf(de->conn,
  8205. NULL, /* Buffer is big enough */
  8206. size,
  8207. sizeof(size),
  8208. "%.1fM",
  8209. (double)de->file.size / 1048576);
  8210. } else {
  8211. mg_snprintf(de->conn,
  8212. NULL, /* Buffer is big enough */
  8213. size,
  8214. sizeof(size),
  8215. "%.1fG",
  8216. (double)de->file.size / 1073741824);
  8217. }
  8218. }
  8219. /* Note: mg_snprintf will not cause a buffer overflow above.
  8220. * So, string truncation checks are not required here. */
  8221. #if defined(REENTRANT_TIME)
  8222. localtime_r(&de->file.last_modified, tm);
  8223. #else
  8224. tm = localtime(&de->file.last_modified);
  8225. #endif
  8226. if (tm != NULL) {
  8227. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8228. } else {
  8229. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8230. mod[sizeof(mod) - 1] = '\0';
  8231. }
  8232. mg_printf(de->conn,
  8233. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8234. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8235. href,
  8236. de->file.is_directory ? "/" : "",
  8237. esc ? esc : de->file_name,
  8238. de->file.is_directory ? "/" : "",
  8239. mod,
  8240. size);
  8241. mg_free(href);
  8242. return 0;
  8243. }
  8244. /* This function is called from send_directory() and used for
  8245. * sorting directory entries by size, or name, or modification time.
  8246. * On windows, __cdecl specification is needed in case if project is built
  8247. * with __stdcall convention. qsort always requires __cdels callback. */
  8248. static int WINCDECL
  8249. compare_dir_entries(const void *p1, const void *p2)
  8250. {
  8251. if (p1 && p2) {
  8252. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8253. const char *query_string = a->conn->request_info.query_string;
  8254. int cmp_result = 0;
  8255. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8256. query_string = "n";
  8257. }
  8258. if (a->file.is_directory && !b->file.is_directory) {
  8259. return -1; /* Always put directories on top */
  8260. } else if (!a->file.is_directory && b->file.is_directory) {
  8261. return 1; /* Always put directories on top */
  8262. } else if (*query_string == 'n') {
  8263. cmp_result = strcmp(a->file_name, b->file_name);
  8264. } else if (*query_string == 's') {
  8265. cmp_result = (a->file.size == b->file.size)
  8266. ? 0
  8267. : ((a->file.size > b->file.size) ? 1 : -1);
  8268. } else if (*query_string == 'd') {
  8269. cmp_result =
  8270. (a->file.last_modified == b->file.last_modified)
  8271. ? 0
  8272. : ((a->file.last_modified > b->file.last_modified) ? 1
  8273. : -1);
  8274. }
  8275. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8276. }
  8277. return 0;
  8278. }
  8279. static int
  8280. must_hide_file(struct mg_connection *conn, const char *path)
  8281. {
  8282. if (conn && conn->dom_ctx) {
  8283. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8284. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8285. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8286. || ((pattern != NULL)
  8287. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8288. }
  8289. return 0;
  8290. }
  8291. #if !defined(NO_FILESYSTEMS)
  8292. static int
  8293. scan_directory(struct mg_connection *conn,
  8294. const char *dir,
  8295. void *data,
  8296. int (*cb)(struct de *, void *))
  8297. {
  8298. char path[PATH_MAX];
  8299. struct dirent *dp;
  8300. DIR *dirp;
  8301. struct de de;
  8302. int truncated;
  8303. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8304. return 0;
  8305. } else {
  8306. de.conn = conn;
  8307. while ((dp = mg_readdir(dirp)) != NULL) {
  8308. /* Do not show current dir and hidden files */
  8309. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8310. || must_hide_file(conn, dp->d_name)) {
  8311. continue;
  8312. }
  8313. mg_snprintf(
  8314. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8315. /* If we don't memset stat structure to zero, mtime will have
  8316. * garbage and strftime() will segfault later on in
  8317. * print_dir_entry(). memset is required only if mg_stat()
  8318. * fails. For more details, see
  8319. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8320. memset(&de.file, 0, sizeof(de.file));
  8321. if (truncated) {
  8322. /* If the path is not complete, skip processing. */
  8323. continue;
  8324. }
  8325. if (!mg_stat(conn, path, &de.file)) {
  8326. mg_cry_internal(conn,
  8327. "%s: mg_stat(%s) failed: %s",
  8328. __func__,
  8329. path,
  8330. strerror(ERRNO));
  8331. }
  8332. de.file_name = dp->d_name;
  8333. cb(&de, data);
  8334. }
  8335. (void)mg_closedir(dirp);
  8336. }
  8337. return 1;
  8338. }
  8339. #endif /* NO_FILESYSTEMS */
  8340. #if !defined(NO_FILES)
  8341. static int
  8342. remove_directory(struct mg_connection *conn, const char *dir)
  8343. {
  8344. char path[PATH_MAX];
  8345. struct dirent *dp;
  8346. DIR *dirp;
  8347. struct de de;
  8348. int truncated;
  8349. int ok = 1;
  8350. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8351. return 0;
  8352. } else {
  8353. de.conn = conn;
  8354. while ((dp = mg_readdir(dirp)) != NULL) {
  8355. /* Do not show current dir (but show hidden files as they will
  8356. * also be removed) */
  8357. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8358. continue;
  8359. }
  8360. mg_snprintf(
  8361. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8362. /* If we don't memset stat structure to zero, mtime will have
  8363. * garbage and strftime() will segfault later on in
  8364. * print_dir_entry(). memset is required only if mg_stat()
  8365. * fails. For more details, see
  8366. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8367. memset(&de.file, 0, sizeof(de.file));
  8368. if (truncated) {
  8369. /* Do not delete anything shorter */
  8370. ok = 0;
  8371. continue;
  8372. }
  8373. if (!mg_stat(conn, path, &de.file)) {
  8374. mg_cry_internal(conn,
  8375. "%s: mg_stat(%s) failed: %s",
  8376. __func__,
  8377. path,
  8378. strerror(ERRNO));
  8379. ok = 0;
  8380. }
  8381. if (de.file.is_directory) {
  8382. if (remove_directory(conn, path) == 0) {
  8383. ok = 0;
  8384. }
  8385. } else {
  8386. /* This will fail file is the file is in memory */
  8387. if (mg_remove(conn, path) == 0) {
  8388. ok = 0;
  8389. }
  8390. }
  8391. }
  8392. (void)mg_closedir(dirp);
  8393. IGNORE_UNUSED_RESULT(rmdir(dir));
  8394. }
  8395. return ok;
  8396. }
  8397. #endif
  8398. struct dir_scan_data {
  8399. struct de *entries;
  8400. unsigned int num_entries;
  8401. unsigned int arr_size;
  8402. };
  8403. /* Behaves like realloc(), but frees original pointer on failure */
  8404. static void *
  8405. realloc2(void *ptr, size_t size)
  8406. {
  8407. void *new_ptr = mg_realloc(ptr, size);
  8408. if ((new_ptr == NULL) && (size > 0)) {
  8409. mg_free(ptr);
  8410. }
  8411. return new_ptr;
  8412. }
  8413. #if !defined(NO_FILESYSTEMS)
  8414. static int
  8415. dir_scan_callback(struct de *de, void *data)
  8416. {
  8417. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8418. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8419. dsd->arr_size *= 2;
  8420. dsd->entries =
  8421. (struct de *)realloc2(dsd->entries,
  8422. dsd->arr_size * sizeof(dsd->entries[0]));
  8423. }
  8424. if (dsd->entries == NULL) {
  8425. /* TODO(lsm, low): propagate an error to the caller */
  8426. dsd->num_entries = 0;
  8427. } else {
  8428. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8429. dsd->entries[dsd->num_entries].file = de->file;
  8430. dsd->entries[dsd->num_entries].conn = de->conn;
  8431. dsd->num_entries++;
  8432. }
  8433. return 0;
  8434. }
  8435. static void
  8436. handle_directory_request(struct mg_connection *conn, const char *dir)
  8437. {
  8438. unsigned int i;
  8439. int sort_direction;
  8440. struct dir_scan_data data = {NULL, 0, 128};
  8441. char date[64], *esc, *p;
  8442. const char *title;
  8443. time_t curtime = time(NULL);
  8444. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8445. mg_send_http_error(conn,
  8446. 500,
  8447. "Error: Cannot open directory\nopendir(%s): %s",
  8448. dir,
  8449. strerror(ERRNO));
  8450. return;
  8451. }
  8452. gmt_time_string(date, sizeof(date), &curtime);
  8453. if (!conn) {
  8454. return;
  8455. }
  8456. esc = NULL;
  8457. title = conn->request_info.local_uri;
  8458. if (title[strcspn(title, "&<>")]) {
  8459. /* HTML escaping needed */
  8460. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8461. if (esc) {
  8462. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8463. mg_strlcpy(p, title + i, 2);
  8464. if (*p == '&') {
  8465. strcpy(p, "&amp;");
  8466. } else if (*p == '<') {
  8467. strcpy(p, "&lt;");
  8468. } else if (*p == '>') {
  8469. strcpy(p, "&gt;");
  8470. }
  8471. }
  8472. } else {
  8473. title = "";
  8474. }
  8475. }
  8476. sort_direction = ((conn->request_info.query_string != NULL)
  8477. && (conn->request_info.query_string[0] != '\0')
  8478. && (conn->request_info.query_string[1] == 'd'))
  8479. ? 'a'
  8480. : 'd';
  8481. conn->must_close = 1;
  8482. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8483. send_static_cache_header(conn);
  8484. send_additional_header(conn);
  8485. mg_printf(conn,
  8486. "Date: %s\r\n"
  8487. "Connection: close\r\n"
  8488. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8489. date);
  8490. mg_printf(conn,
  8491. "<html><head><title>Index of %s</title>"
  8492. "<style>th {text-align: left;}</style></head>"
  8493. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8494. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8495. "<th><a href=\"?d%c\">Modified</a></th>"
  8496. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8497. "<tr><td colspan=\"3\"><hr></td></tr>",
  8498. esc ? esc : title,
  8499. esc ? esc : title,
  8500. sort_direction,
  8501. sort_direction,
  8502. sort_direction);
  8503. mg_free(esc);
  8504. /* Print first entry - link to a parent directory */
  8505. mg_printf(conn,
  8506. "<tr><td><a href=\"%s\">%s</a></td>"
  8507. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8508. "..",
  8509. "Parent directory",
  8510. "-",
  8511. "-");
  8512. /* Sort and print directory entries */
  8513. if (data.entries != NULL) {
  8514. qsort(data.entries,
  8515. (size_t)data.num_entries,
  8516. sizeof(data.entries[0]),
  8517. compare_dir_entries);
  8518. for (i = 0; i < data.num_entries; i++) {
  8519. print_dir_entry(&data.entries[i]);
  8520. mg_free(data.entries[i].file_name);
  8521. }
  8522. mg_free(data.entries);
  8523. }
  8524. mg_printf(conn, "%s", "</table></pre></body></html>");
  8525. conn->status_code = 200;
  8526. }
  8527. #endif /* NO_FILESYSTEMS */
  8528. /* Send len bytes from the opened file to the client. */
  8529. static void
  8530. send_file_data(struct mg_connection *conn,
  8531. struct mg_file *filep,
  8532. int64_t offset,
  8533. int64_t len)
  8534. {
  8535. char buf[MG_BUF_LEN];
  8536. int to_read, num_read, num_written;
  8537. int64_t size;
  8538. if (!filep || !conn) {
  8539. return;
  8540. }
  8541. /* Sanity check the offset */
  8542. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8543. : (int64_t)(filep->stat.size);
  8544. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8545. #if defined(MG_USE_OPEN_FILE)
  8546. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8547. /* file stored in memory */
  8548. if (len > size - offset) {
  8549. len = size - offset;
  8550. }
  8551. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8552. } else /* else block below */
  8553. #endif
  8554. if (len > 0 && filep->access.fp != NULL) {
  8555. /* file stored on disk */
  8556. #if defined(__linux__)
  8557. /* sendfile is only available for Linux */
  8558. if ((conn->ssl == 0) && (conn->throttle == 0)
  8559. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8560. "yes"))) {
  8561. off_t sf_offs = (off_t)offset;
  8562. ssize_t sf_sent;
  8563. int sf_file = fileno(filep->access.fp);
  8564. int loop_cnt = 0;
  8565. do {
  8566. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8567. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8568. size_t sf_tosend =
  8569. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8570. sf_sent =
  8571. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8572. if (sf_sent > 0) {
  8573. len -= sf_sent;
  8574. offset += sf_sent;
  8575. } else if (loop_cnt == 0) {
  8576. /* This file can not be sent using sendfile.
  8577. * This might be the case for pseudo-files in the
  8578. * /sys/ and /proc/ file system.
  8579. * Use the regular user mode copy code instead. */
  8580. break;
  8581. } else if (sf_sent == 0) {
  8582. /* No error, but 0 bytes sent. May be EOF? */
  8583. return;
  8584. }
  8585. loop_cnt++;
  8586. } while ((len > 0) && (sf_sent >= 0));
  8587. if (sf_sent > 0) {
  8588. return; /* OK */
  8589. }
  8590. /* sf_sent<0 means error, thus fall back to the classic way */
  8591. /* This is always the case, if sf_file is not a "normal" file,
  8592. * e.g., for sending data from the output of a CGI process. */
  8593. offset = (int64_t)sf_offs;
  8594. }
  8595. #endif
  8596. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8597. mg_cry_internal(conn,
  8598. "%s: fseeko() failed: %s",
  8599. __func__,
  8600. strerror(ERRNO));
  8601. mg_send_http_error(
  8602. conn,
  8603. 500,
  8604. "%s",
  8605. "Error: Unable to access file at requested position.");
  8606. } else {
  8607. while (len > 0) {
  8608. /* Calculate how much to read from the file in the buffer */
  8609. to_read = sizeof(buf);
  8610. if ((int64_t)to_read > len) {
  8611. to_read = (int)len;
  8612. }
  8613. /* Read from file, exit the loop on error */
  8614. if ((num_read =
  8615. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8616. <= 0) {
  8617. break;
  8618. }
  8619. /* Send read bytes to the client, exit the loop on error */
  8620. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8621. != num_read) {
  8622. break;
  8623. }
  8624. /* Both read and were successful, adjust counters */
  8625. len -= num_written;
  8626. }
  8627. }
  8628. }
  8629. }
  8630. static int
  8631. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8632. {
  8633. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8634. }
  8635. static void
  8636. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8637. {
  8638. if ((filestat != NULL) && (buf != NULL)) {
  8639. mg_snprintf(NULL,
  8640. NULL, /* All calls to construct_etag use 64 byte buffer */
  8641. buf,
  8642. buf_len,
  8643. "\"%lx.%" INT64_FMT "\"",
  8644. (unsigned long)filestat->last_modified,
  8645. filestat->size);
  8646. }
  8647. }
  8648. static void
  8649. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8650. {
  8651. if (filep != NULL && filep->fp != NULL) {
  8652. #if defined(_WIN32)
  8653. (void)conn; /* Unused. */
  8654. #else
  8655. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8656. mg_cry_internal(conn,
  8657. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8658. __func__,
  8659. strerror(ERRNO));
  8660. }
  8661. #endif
  8662. }
  8663. }
  8664. #if defined(USE_ZLIB)
  8665. #include "mod_zlib.inl"
  8666. #endif
  8667. #if !defined(NO_FILESYSTEMS)
  8668. static void
  8669. handle_static_file_request(struct mg_connection *conn,
  8670. const char *path,
  8671. struct mg_file *filep,
  8672. const char *mime_type,
  8673. const char *additional_headers)
  8674. {
  8675. char date[64], lm[64], etag[64];
  8676. char range[128]; /* large enough, so there will be no overflow */
  8677. const char *msg = "OK";
  8678. const char *range_hdr;
  8679. time_t curtime = time(NULL);
  8680. int64_t cl, r1, r2;
  8681. struct vec mime_vec;
  8682. int n, truncated;
  8683. char gz_path[PATH_MAX];
  8684. const char *encoding = "";
  8685. const char *origin_hdr;
  8686. const char *cors_orig_cfg;
  8687. const char *cors1, *cors2, *cors3;
  8688. int is_head_request;
  8689. #if defined(USE_ZLIB)
  8690. /* Compression is allowed, unless there is a reason not to use
  8691. * compression. If the file is already compressed, too small or a
  8692. * "range" request was made, on the fly compression is not possible. */
  8693. int allow_on_the_fly_compression = 1;
  8694. #endif
  8695. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8696. return;
  8697. }
  8698. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8699. if (mime_type == NULL) {
  8700. get_mime_type(conn, path, &mime_vec);
  8701. } else {
  8702. mime_vec.ptr = mime_type;
  8703. mime_vec.len = strlen(mime_type);
  8704. }
  8705. if (filep->stat.size > INT64_MAX) {
  8706. mg_send_http_error(conn,
  8707. 500,
  8708. "Error: File size is too large to send\n%" INT64_FMT,
  8709. filep->stat.size);
  8710. return;
  8711. }
  8712. cl = (int64_t)filep->stat.size;
  8713. conn->status_code = 200;
  8714. range[0] = '\0';
  8715. #if defined(USE_ZLIB)
  8716. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8717. * it's important to rewrite the filename after resolving
  8718. * the mime type from it, to preserve the actual file's type */
  8719. if (!conn->accept_gzip) {
  8720. allow_on_the_fly_compression = 0;
  8721. }
  8722. #endif
  8723. /* Check if there is a range header */
  8724. range_hdr = mg_get_header(conn, "Range");
  8725. /* For gzipped files, add *.gz */
  8726. if (filep->stat.is_gzipped) {
  8727. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8728. if (truncated) {
  8729. mg_send_http_error(conn,
  8730. 500,
  8731. "Error: Path of zipped file too long (%s)",
  8732. path);
  8733. return;
  8734. }
  8735. path = gz_path;
  8736. encoding = "Content-Encoding: gzip\r\n";
  8737. #if defined(USE_ZLIB)
  8738. /* File is already compressed. No "on the fly" compression. */
  8739. allow_on_the_fly_compression = 0;
  8740. #endif
  8741. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8742. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8743. struct mg_file_stat file_stat;
  8744. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8745. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8746. && !file_stat.is_directory) {
  8747. file_stat.is_gzipped = 1;
  8748. filep->stat = file_stat;
  8749. cl = (int64_t)filep->stat.size;
  8750. path = gz_path;
  8751. encoding = "Content-Encoding: gzip\r\n";
  8752. #if defined(USE_ZLIB)
  8753. /* File is already compressed. No "on the fly" compression. */
  8754. allow_on_the_fly_compression = 0;
  8755. #endif
  8756. }
  8757. }
  8758. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8759. mg_send_http_error(conn,
  8760. 500,
  8761. "Error: Cannot open file\nfopen(%s): %s",
  8762. path,
  8763. strerror(ERRNO));
  8764. return;
  8765. }
  8766. fclose_on_exec(&filep->access, conn);
  8767. /* If "Range" request was made: parse header, send only selected part
  8768. * of the file. */
  8769. r1 = r2 = 0;
  8770. if ((range_hdr != NULL)
  8771. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8772. && (r2 >= 0)) {
  8773. /* actually, range requests don't play well with a pre-gzipped
  8774. * file (since the range is specified in the uncompressed space) */
  8775. if (filep->stat.is_gzipped) {
  8776. mg_send_http_error(
  8777. conn,
  8778. 416, /* 416 = Range Not Satisfiable */
  8779. "%s",
  8780. "Error: Range requests in gzipped files are not supported");
  8781. (void)mg_fclose(
  8782. &filep->access); /* ignore error on read only file */
  8783. return;
  8784. }
  8785. conn->status_code = 206;
  8786. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8787. mg_snprintf(conn,
  8788. NULL, /* range buffer is big enough */
  8789. range,
  8790. sizeof(range),
  8791. "Content-Range: bytes "
  8792. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8793. r1,
  8794. r1 + cl - 1,
  8795. filep->stat.size);
  8796. msg = "Partial Content";
  8797. #if defined(USE_ZLIB)
  8798. /* Do not compress ranges. */
  8799. allow_on_the_fly_compression = 0;
  8800. #endif
  8801. }
  8802. /* Do not compress small files. Small files do not benefit from file
  8803. * compression, but there is still some overhead. */
  8804. #if defined(USE_ZLIB)
  8805. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8806. /* File is below the size limit. */
  8807. allow_on_the_fly_compression = 0;
  8808. }
  8809. #endif
  8810. /* Standard CORS header */
  8811. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8812. origin_hdr = mg_get_header(conn, "Origin");
  8813. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8814. /* Cross-origin resource sharing (CORS), see
  8815. * http://www.html5rocks.com/en/tutorials/cors/,
  8816. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8817. * -
  8818. * preflight is not supported for files. */
  8819. cors1 = "Access-Control-Allow-Origin: ";
  8820. cors2 = cors_orig_cfg;
  8821. cors3 = "\r\n";
  8822. } else {
  8823. cors1 = cors2 = cors3 = "";
  8824. }
  8825. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8826. * according to
  8827. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8828. gmt_time_string(date, sizeof(date), &curtime);
  8829. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8830. construct_etag(etag, sizeof(etag), &filep->stat);
  8831. /* Send header */
  8832. (void)mg_printf(conn,
  8833. "HTTP/1.1 %d %s\r\n"
  8834. "%s%s%s" /* CORS */
  8835. "Date: %s\r\n"
  8836. "Last-Modified: %s\r\n"
  8837. "Etag: %s\r\n"
  8838. "Content-Type: %.*s\r\n"
  8839. "Connection: %s\r\n",
  8840. conn->status_code,
  8841. msg,
  8842. cors1,
  8843. cors2,
  8844. cors3,
  8845. date,
  8846. lm,
  8847. etag,
  8848. (int)mime_vec.len,
  8849. mime_vec.ptr,
  8850. suggest_connection_header(conn));
  8851. send_static_cache_header(conn);
  8852. send_additional_header(conn);
  8853. #if defined(USE_ZLIB)
  8854. /* On the fly compression allowed */
  8855. if (allow_on_the_fly_compression) {
  8856. /* For on the fly compression, we don't know the content size in
  8857. * advance, so we have to use chunked encoding */
  8858. (void)mg_printf(conn,
  8859. "Content-Encoding: gzip\r\n"
  8860. "Transfer-Encoding: chunked\r\n");
  8861. } else
  8862. #endif
  8863. {
  8864. /* Without on-the-fly compression, we know the content-length
  8865. * and we can use ranges (with on-the-fly compression we cannot).
  8866. * So we send these response headers only in this case. */
  8867. (void)mg_printf(conn,
  8868. "Content-Length: %" INT64_FMT "\r\n"
  8869. "Accept-Ranges: bytes\r\n"
  8870. "%s" /* range */
  8871. "%s" /* encoding */,
  8872. cl,
  8873. range,
  8874. encoding);
  8875. }
  8876. /* The previous code must not add any header starting with X- to make
  8877. * sure no one of the additional_headers is included twice */
  8878. if (additional_headers != NULL) {
  8879. (void)mg_printf(conn,
  8880. "%.*s\r\n\r\n",
  8881. (int)strlen(additional_headers),
  8882. additional_headers);
  8883. } else {
  8884. (void)mg_printf(conn, "\r\n");
  8885. }
  8886. if (!is_head_request) {
  8887. #if defined(USE_ZLIB)
  8888. if (allow_on_the_fly_compression) {
  8889. /* Compress and send */
  8890. send_compressed_data(conn, filep);
  8891. } else
  8892. #endif
  8893. {
  8894. /* Send file directly */
  8895. send_file_data(conn, filep, r1, cl);
  8896. }
  8897. }
  8898. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8899. }
  8900. int
  8901. mg_send_file_body(struct mg_connection *conn, const char *path)
  8902. {
  8903. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8904. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8905. return -1;
  8906. }
  8907. fclose_on_exec(&file.access, conn);
  8908. send_file_data(conn, &file, 0, INT64_MAX);
  8909. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8910. return 0; /* >= 0 for OK */
  8911. }
  8912. #endif /* NO_FILESYSTEMS */
  8913. #if !defined(NO_CACHING)
  8914. /* Return True if we should reply 304 Not Modified. */
  8915. static int
  8916. is_not_modified(const struct mg_connection *conn,
  8917. const struct mg_file_stat *filestat)
  8918. {
  8919. char etag[64];
  8920. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8921. const char *inm = mg_get_header(conn, "If-None-Match");
  8922. construct_etag(etag, sizeof(etag), filestat);
  8923. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8924. || ((ims != NULL)
  8925. && (filestat->last_modified <= parse_date_string(ims)));
  8926. }
  8927. static void
  8928. handle_not_modified_static_file_request(struct mg_connection *conn,
  8929. struct mg_file *filep)
  8930. {
  8931. char date[64], lm[64], etag[64];
  8932. time_t curtime = time(NULL);
  8933. if ((conn == NULL) || (filep == NULL)) {
  8934. return;
  8935. }
  8936. conn->status_code = 304;
  8937. gmt_time_string(date, sizeof(date), &curtime);
  8938. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8939. construct_etag(etag, sizeof(etag), &filep->stat);
  8940. (void)mg_printf(conn,
  8941. "HTTP/1.1 %d %s\r\n"
  8942. "Date: %s\r\n",
  8943. conn->status_code,
  8944. mg_get_response_code_text(conn, conn->status_code),
  8945. date);
  8946. send_static_cache_header(conn);
  8947. send_additional_header(conn);
  8948. (void)mg_printf(conn,
  8949. "Last-Modified: %s\r\n"
  8950. "Etag: %s\r\n"
  8951. "Connection: %s\r\n"
  8952. "\r\n",
  8953. lm,
  8954. etag,
  8955. suggest_connection_header(conn));
  8956. }
  8957. #endif
  8958. #if !defined(NO_FILESYSTEMS)
  8959. void
  8960. mg_send_file(struct mg_connection *conn, const char *path)
  8961. {
  8962. mg_send_mime_file2(conn, path, NULL, NULL);
  8963. }
  8964. void
  8965. mg_send_mime_file(struct mg_connection *conn,
  8966. const char *path,
  8967. const char *mime_type)
  8968. {
  8969. mg_send_mime_file2(conn, path, mime_type, NULL);
  8970. }
  8971. void
  8972. mg_send_mime_file2(struct mg_connection *conn,
  8973. const char *path,
  8974. const char *mime_type,
  8975. const char *additional_headers)
  8976. {
  8977. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8978. if (!conn) {
  8979. /* No conn */
  8980. return;
  8981. }
  8982. if (mg_stat(conn, path, &file.stat)) {
  8983. #if !defined(NO_CACHING)
  8984. if (is_not_modified(conn, &file.stat)) {
  8985. /* Send 304 "Not Modified" - this must not send any body data */
  8986. handle_not_modified_static_file_request(conn, &file);
  8987. } else
  8988. #endif /* NO_CACHING */
  8989. if (file.stat.is_directory) {
  8990. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8991. "yes")) {
  8992. handle_directory_request(conn, path);
  8993. } else {
  8994. mg_send_http_error(conn,
  8995. 403,
  8996. "%s",
  8997. "Error: Directory listing denied");
  8998. }
  8999. } else {
  9000. handle_static_file_request(
  9001. conn, path, &file, mime_type, additional_headers);
  9002. }
  9003. } else {
  9004. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9005. }
  9006. }
  9007. /* For a given PUT path, create all intermediate subdirectories.
  9008. * Return 0 if the path itself is a directory.
  9009. * Return 1 if the path leads to a file.
  9010. * Return -1 for if the path is too long.
  9011. * Return -2 if path can not be created.
  9012. */
  9013. static int
  9014. put_dir(struct mg_connection *conn, const char *path)
  9015. {
  9016. char buf[PATH_MAX];
  9017. const char *s, *p;
  9018. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9019. size_t len;
  9020. int res = 1;
  9021. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9022. len = (size_t)(p - path);
  9023. if (len >= sizeof(buf)) {
  9024. /* path too long */
  9025. res = -1;
  9026. break;
  9027. }
  9028. memcpy(buf, path, len);
  9029. buf[len] = '\0';
  9030. /* Try to create intermediate directory */
  9031. DEBUG_TRACE("mkdir(%s)", buf);
  9032. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9033. /* path does not exixt and can not be created */
  9034. res = -2;
  9035. break;
  9036. }
  9037. /* Is path itself a directory? */
  9038. if (p[1] == '\0') {
  9039. res = 0;
  9040. }
  9041. }
  9042. return res;
  9043. }
  9044. static void
  9045. remove_bad_file(const struct mg_connection *conn, const char *path)
  9046. {
  9047. int r = mg_remove(conn, path);
  9048. if (r != 0) {
  9049. mg_cry_internal(conn,
  9050. "%s: Cannot remove invalid file %s",
  9051. __func__,
  9052. path);
  9053. }
  9054. }
  9055. long long
  9056. mg_store_body(struct mg_connection *conn, const char *path)
  9057. {
  9058. char buf[MG_BUF_LEN];
  9059. long long len = 0;
  9060. int ret, n;
  9061. struct mg_file fi;
  9062. if (conn->consumed_content != 0) {
  9063. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9064. return -11;
  9065. }
  9066. ret = put_dir(conn, path);
  9067. if (ret < 0) {
  9068. /* -1 for path too long,
  9069. * -2 for path can not be created. */
  9070. return ret;
  9071. }
  9072. if (ret != 1) {
  9073. /* Return 0 means, path itself is a directory. */
  9074. return 0;
  9075. }
  9076. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9077. return -12;
  9078. }
  9079. ret = mg_read(conn, buf, sizeof(buf));
  9080. while (ret > 0) {
  9081. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9082. if (n != ret) {
  9083. (void)mg_fclose(
  9084. &fi.access); /* File is bad and will be removed anyway. */
  9085. remove_bad_file(conn, path);
  9086. return -13;
  9087. }
  9088. len += ret;
  9089. ret = mg_read(conn, buf, sizeof(buf));
  9090. }
  9091. /* File is open for writing. If fclose fails, there was probably an
  9092. * error flushing the buffer to disk, so the file on disk might be
  9093. * broken. Delete it and return an error to the caller. */
  9094. if (mg_fclose(&fi.access) != 0) {
  9095. remove_bad_file(conn, path);
  9096. return -14;
  9097. }
  9098. return len;
  9099. }
  9100. #endif /* NO_FILESYSTEMS */
  9101. /* Parse a buffer:
  9102. * Forward the string pointer till the end of a word, then
  9103. * terminate it and forward till the begin of the next word.
  9104. */
  9105. static int
  9106. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9107. {
  9108. /* Forward until a space is found - use isgraph here */
  9109. /* See http://www.cplusplus.com/reference/cctype/ */
  9110. while (isgraph((unsigned char)**ppw)) {
  9111. (*ppw)++;
  9112. }
  9113. /* Check end of word */
  9114. if (eol) {
  9115. /* must be a end of line */
  9116. if ((**ppw != '\r') && (**ppw != '\n')) {
  9117. return -1;
  9118. }
  9119. } else {
  9120. /* must be a end of a word, but not a line */
  9121. if (**ppw != ' ') {
  9122. return -1;
  9123. }
  9124. }
  9125. /* Terminate and forward to the next word */
  9126. do {
  9127. **ppw = 0;
  9128. (*ppw)++;
  9129. } while (isspace((unsigned char)**ppw));
  9130. /* Check after term */
  9131. if (!eol) {
  9132. /* if it's not the end of line, there must be a next word */
  9133. if (!isgraph((unsigned char)**ppw)) {
  9134. return -1;
  9135. }
  9136. }
  9137. /* ok */
  9138. return 1;
  9139. }
  9140. /* Parse HTTP headers from the given buffer, advance buf pointer
  9141. * to the point where parsing stopped.
  9142. * All parameters must be valid pointers (not NULL).
  9143. * Return <0 on error. */
  9144. static int
  9145. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9146. {
  9147. int i;
  9148. int num_headers = 0;
  9149. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9150. char *dp = *buf;
  9151. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9152. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9153. dp++;
  9154. }
  9155. if (dp == *buf) {
  9156. /* End of headers reached. */
  9157. break;
  9158. }
  9159. if (*dp != ':') {
  9160. /* This is not a valid field. */
  9161. return -1;
  9162. }
  9163. /* End of header key (*dp == ':') */
  9164. /* Truncate here and set the key name */
  9165. *dp = 0;
  9166. hdr[i].name = *buf;
  9167. /* Skip all spaces */
  9168. do {
  9169. dp++;
  9170. } while ((*dp == ' ') || (*dp == '\t'));
  9171. /* The rest of the line is the value */
  9172. hdr[i].value = dp;
  9173. /* Find end of line */
  9174. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9175. dp++;
  9176. };
  9177. /* eliminate \r */
  9178. if (*dp == '\r') {
  9179. *dp = 0;
  9180. dp++;
  9181. if (*dp != '\n') {
  9182. /* This is not a valid line. */
  9183. return -1;
  9184. }
  9185. }
  9186. /* here *dp is either 0 or '\n' */
  9187. /* in any case, we have a new header */
  9188. num_headers = i + 1;
  9189. if (*dp) {
  9190. *dp = 0;
  9191. dp++;
  9192. *buf = dp;
  9193. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9194. /* This is the end of the header */
  9195. break;
  9196. }
  9197. } else {
  9198. *buf = dp;
  9199. break;
  9200. }
  9201. }
  9202. return num_headers;
  9203. }
  9204. struct mg_http_method_info {
  9205. const char *name;
  9206. int request_has_body;
  9207. int response_has_body;
  9208. int is_safe;
  9209. int is_idempotent;
  9210. int is_cacheable;
  9211. };
  9212. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9213. static const struct mg_http_method_info http_methods[] = {
  9214. /* HTTP (RFC 2616) */
  9215. {"GET", 0, 1, 1, 1, 1},
  9216. {"POST", 1, 1, 0, 0, 0},
  9217. {"PUT", 1, 0, 0, 1, 0},
  9218. {"DELETE", 0, 0, 0, 1, 0},
  9219. {"HEAD", 0, 0, 1, 1, 1},
  9220. {"OPTIONS", 0, 0, 1, 1, 0},
  9221. {"CONNECT", 1, 1, 0, 0, 0},
  9222. /* TRACE method (RFC 2616) is not supported for security reasons */
  9223. /* PATCH method (RFC 5789) */
  9224. {"PATCH", 1, 0, 0, 0, 0},
  9225. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9226. /* WEBDAV (RFC 2518) */
  9227. {"PROPFIND", 0, 1, 1, 1, 0},
  9228. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9229. * Some PROPFIND results MAY be cached, with care,
  9230. * as there is no cache validation mechanism for
  9231. * most properties. This method is both safe and
  9232. * idempotent (see Section 9.1 of [RFC2616]). */
  9233. {"MKCOL", 0, 0, 0, 1, 0},
  9234. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9235. * When MKCOL is invoked without a request body,
  9236. * the newly created collection SHOULD have no
  9237. * members. A MKCOL request message may contain
  9238. * a message body. The precise behavior of a MKCOL
  9239. * request when the body is present is undefined,
  9240. * ... ==> We do not support MKCOL with body data.
  9241. * This method is idempotent, but not safe (see
  9242. * Section 9.1 of [RFC2616]). Responses to this
  9243. * method MUST NOT be cached. */
  9244. /* Unsupported WEBDAV Methods: */
  9245. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9246. /* + 11 methods from RFC 3253 */
  9247. /* ORDERPATCH (RFC 3648) */
  9248. /* ACL (RFC 3744) */
  9249. /* SEARCH (RFC 5323) */
  9250. /* + MicroSoft extensions
  9251. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9252. /* REPORT method (RFC 3253) */
  9253. {"REPORT", 1, 1, 1, 1, 1},
  9254. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9255. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9256. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9257. * to be useful for REST in case a "GET request with body" is
  9258. * required. */
  9259. {NULL, 0, 0, 0, 0, 0}
  9260. /* end of list */
  9261. };
  9262. static const struct mg_http_method_info *
  9263. get_http_method_info(const char *method)
  9264. {
  9265. /* Check if the method is known to the server. The list of all known
  9266. * HTTP methods can be found here at
  9267. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9268. */
  9269. const struct mg_http_method_info *m = http_methods;
  9270. while (m->name) {
  9271. if (!strcmp(m->name, method)) {
  9272. return m;
  9273. }
  9274. m++;
  9275. }
  9276. return NULL;
  9277. }
  9278. static int
  9279. is_valid_http_method(const char *method)
  9280. {
  9281. return (get_http_method_info(method) != NULL);
  9282. }
  9283. /* Parse HTTP request, fill in mg_request_info structure.
  9284. * This function modifies the buffer by NUL-terminating
  9285. * HTTP request components, header names and header values.
  9286. * Parameters:
  9287. * buf (in/out): pointer to the HTTP header to parse and split
  9288. * len (in): length of HTTP header buffer
  9289. * re (out): parsed header as mg_request_info
  9290. * buf and ri must be valid pointers (not NULL), len>0.
  9291. * Returns <0 on error. */
  9292. static int
  9293. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9294. {
  9295. int request_length;
  9296. int init_skip = 0;
  9297. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9298. * remote_port */
  9299. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9300. NULL;
  9301. ri->num_headers = 0;
  9302. /* RFC says that all initial whitespaces should be ingored */
  9303. /* This included all leading \r and \n (isspace) */
  9304. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9305. while ((len > 0) && isspace((unsigned char)*buf)) {
  9306. buf++;
  9307. len--;
  9308. init_skip++;
  9309. }
  9310. if (len == 0) {
  9311. /* Incomplete request */
  9312. return 0;
  9313. }
  9314. /* Control characters are not allowed, including zero */
  9315. if (iscntrl((unsigned char)*buf)) {
  9316. return -1;
  9317. }
  9318. /* Find end of HTTP header */
  9319. request_length = get_http_header_len(buf, len);
  9320. if (request_length <= 0) {
  9321. return request_length;
  9322. }
  9323. buf[request_length - 1] = '\0';
  9324. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9325. return -1;
  9326. }
  9327. /* The first word has to be the HTTP method */
  9328. ri->request_method = buf;
  9329. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9330. return -1;
  9331. }
  9332. /* Check for a valid http method */
  9333. if (!is_valid_http_method(ri->request_method)) {
  9334. return -1;
  9335. }
  9336. /* The second word is the URI */
  9337. ri->request_uri = buf;
  9338. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9339. return -1;
  9340. }
  9341. /* Next would be the HTTP version */
  9342. ri->http_version = buf;
  9343. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9344. return -1;
  9345. }
  9346. /* Check for a valid HTTP version key */
  9347. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9348. /* Invalid request */
  9349. return -1;
  9350. }
  9351. ri->http_version += 5;
  9352. /* Parse all HTTP headers */
  9353. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9354. if (ri->num_headers < 0) {
  9355. /* Error while parsing headers */
  9356. return -1;
  9357. }
  9358. return request_length + init_skip;
  9359. }
  9360. static int
  9361. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9362. {
  9363. int response_length;
  9364. int init_skip = 0;
  9365. char *tmp, *tmp2;
  9366. long l;
  9367. /* Initialize elements. */
  9368. ri->http_version = ri->status_text = NULL;
  9369. ri->num_headers = ri->status_code = 0;
  9370. /* RFC says that all initial whitespaces should be ingored */
  9371. /* This included all leading \r and \n (isspace) */
  9372. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9373. while ((len > 0) && isspace((unsigned char)*buf)) {
  9374. buf++;
  9375. len--;
  9376. init_skip++;
  9377. }
  9378. if (len == 0) {
  9379. /* Incomplete request */
  9380. return 0;
  9381. }
  9382. /* Control characters are not allowed, including zero */
  9383. if (iscntrl((unsigned char)*buf)) {
  9384. return -1;
  9385. }
  9386. /* Find end of HTTP header */
  9387. response_length = get_http_header_len(buf, len);
  9388. if (response_length <= 0) {
  9389. return response_length;
  9390. }
  9391. buf[response_length - 1] = '\0';
  9392. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9393. return -1;
  9394. }
  9395. /* The first word is the HTTP version */
  9396. /* Check for a valid HTTP version key */
  9397. if (strncmp(buf, "HTTP/", 5) != 0) {
  9398. /* Invalid request */
  9399. return -1;
  9400. }
  9401. buf += 5;
  9402. if (!isgraph((unsigned char)buf[0])) {
  9403. /* Invalid request */
  9404. return -1;
  9405. }
  9406. ri->http_version = buf;
  9407. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9408. return -1;
  9409. }
  9410. /* The second word is the status as a number */
  9411. tmp = buf;
  9412. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9413. return -1;
  9414. }
  9415. l = strtol(tmp, &tmp2, 10);
  9416. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9417. /* Everything else but a 3 digit code is invalid */
  9418. return -1;
  9419. }
  9420. ri->status_code = (int)l;
  9421. /* The rest of the line is the status text */
  9422. ri->status_text = buf;
  9423. /* Find end of status text */
  9424. /* isgraph or isspace = isprint */
  9425. while (isprint((unsigned char)*buf)) {
  9426. buf++;
  9427. }
  9428. if ((*buf != '\r') && (*buf != '\n')) {
  9429. return -1;
  9430. }
  9431. /* Terminate string and forward buf to next line */
  9432. do {
  9433. *buf = 0;
  9434. buf++;
  9435. } while (isspace((unsigned char)*buf));
  9436. /* Parse all HTTP headers */
  9437. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9438. if (ri->num_headers < 0) {
  9439. /* Error while parsing headers */
  9440. return -1;
  9441. }
  9442. return response_length + init_skip;
  9443. }
  9444. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9445. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9446. * buffer (which marks the end of HTTP request). Buffer buf may already
  9447. * have some data. The length of the data is stored in nread.
  9448. * Upon every read operation, increase nread by the number of bytes read. */
  9449. static int
  9450. read_message(FILE *fp,
  9451. struct mg_connection *conn,
  9452. char *buf,
  9453. int bufsiz,
  9454. int *nread)
  9455. {
  9456. int request_len, n = 0;
  9457. struct timespec last_action_time;
  9458. double request_timeout;
  9459. if (!conn) {
  9460. return 0;
  9461. }
  9462. memset(&last_action_time, 0, sizeof(last_action_time));
  9463. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9464. /* value of request_timeout is in seconds, config in milliseconds */
  9465. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9466. } else {
  9467. request_timeout = -1.0;
  9468. }
  9469. if (conn->handled_requests > 0) {
  9470. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9471. request_timeout =
  9472. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9473. }
  9474. }
  9475. request_len = get_http_header_len(buf, *nread);
  9476. while (request_len == 0) {
  9477. /* Full request not yet received */
  9478. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9479. /* Server is to be stopped. */
  9480. return -1;
  9481. }
  9482. if (*nread >= bufsiz) {
  9483. /* Request too long */
  9484. return -2;
  9485. }
  9486. n = pull_inner(
  9487. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9488. if (n == -2) {
  9489. /* Receive error */
  9490. return -1;
  9491. }
  9492. /* update clock after every read request */
  9493. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9494. if (n > 0) {
  9495. *nread += n;
  9496. request_len = get_http_header_len(buf, *nread);
  9497. }
  9498. if ((request_len == 0) && (request_timeout >= 0)) {
  9499. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9500. > request_timeout) {
  9501. /* Timeout */
  9502. return -1;
  9503. }
  9504. }
  9505. }
  9506. return request_len;
  9507. }
  9508. #if !defined(NO_CGI) || !defined(NO_FILES)
  9509. static int
  9510. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9511. {
  9512. const char *expect;
  9513. char buf[MG_BUF_LEN];
  9514. int success = 0;
  9515. if (!conn) {
  9516. return 0;
  9517. }
  9518. expect = mg_get_header(conn, "Expect");
  9519. DEBUG_ASSERT(fp != NULL);
  9520. if (!fp) {
  9521. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9522. return 0;
  9523. }
  9524. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9525. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9526. */
  9527. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9528. } else {
  9529. if (expect != NULL) {
  9530. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9531. conn->status_code = 100;
  9532. } else {
  9533. conn->status_code = 200;
  9534. }
  9535. DEBUG_ASSERT(conn->consumed_content == 0);
  9536. if (conn->consumed_content != 0) {
  9537. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9538. return 0;
  9539. }
  9540. for (;;) {
  9541. int nread = mg_read(conn, buf, sizeof(buf));
  9542. if (nread <= 0) {
  9543. success = (nread == 0);
  9544. break;
  9545. }
  9546. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9547. break;
  9548. }
  9549. }
  9550. /* Each error code path in this function must send an error */
  9551. if (!success) {
  9552. /* NOTE: Maybe some data has already been sent. */
  9553. /* TODO (low): If some data has been sent, a correct error
  9554. * reply can no longer be sent, so just close the connection */
  9555. mg_send_http_error(conn, 500, "%s", "");
  9556. }
  9557. }
  9558. return success;
  9559. }
  9560. #endif
  9561. #if defined(USE_TIMERS)
  9562. #define TIMER_API static
  9563. #include "timer.inl"
  9564. #endif /* USE_TIMERS */
  9565. #if !defined(NO_CGI)
  9566. /* This structure helps to create an environment for the spawned CGI
  9567. * program.
  9568. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9569. * last element must be NULL.
  9570. * However, on Windows there is a requirement that all these
  9571. * VARIABLE=VALUE\0
  9572. * strings must reside in a contiguous buffer. The end of the buffer is
  9573. * marked by two '\0' characters.
  9574. * We satisfy both worlds: we create an envp array (which is vars), all
  9575. * entries are actually pointers inside buf. */
  9576. struct cgi_environment {
  9577. struct mg_connection *conn;
  9578. /* Data block */
  9579. char *buf; /* Environment buffer */
  9580. size_t buflen; /* Space available in buf */
  9581. size_t bufused; /* Space taken in buf */
  9582. /* Index block */
  9583. char **var; /* char **envp */
  9584. size_t varlen; /* Number of variables available in var */
  9585. size_t varused; /* Number of variables stored in var */
  9586. };
  9587. static void addenv(struct cgi_environment *env,
  9588. PRINTF_FORMAT_STRING(const char *fmt),
  9589. ...) PRINTF_ARGS(2, 3);
  9590. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9591. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9592. static void
  9593. addenv(struct cgi_environment *env, const char *fmt, ...)
  9594. {
  9595. size_t i, n, space;
  9596. int truncated = 0;
  9597. char *added;
  9598. va_list ap;
  9599. if ((env->varlen - env->varused) < 2) {
  9600. mg_cry_internal(env->conn,
  9601. "%s: Cannot register CGI variable [%s]",
  9602. __func__,
  9603. fmt);
  9604. return;
  9605. }
  9606. /* Calculate how much space is left in the buffer */
  9607. space = (env->buflen - env->bufused);
  9608. do {
  9609. /* Space for "\0\0" is always needed. */
  9610. if (space <= 2) {
  9611. /* Allocate new buffer */
  9612. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9613. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9614. if (!added) {
  9615. /* Out of memory */
  9616. mg_cry_internal(
  9617. env->conn,
  9618. "%s: Cannot allocate memory for CGI variable [%s]",
  9619. __func__,
  9620. fmt);
  9621. return;
  9622. }
  9623. /* Retarget pointers */
  9624. env->buf = added;
  9625. env->buflen = n;
  9626. for (i = 0, n = 0; i < env->varused; i++) {
  9627. env->var[i] = added + n;
  9628. n += strlen(added + n) + 1;
  9629. }
  9630. space = (env->buflen - env->bufused);
  9631. }
  9632. /* Make a pointer to the free space int the buffer */
  9633. added = env->buf + env->bufused;
  9634. /* Copy VARIABLE=VALUE\0 string into the free space */
  9635. va_start(ap, fmt);
  9636. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9637. va_end(ap);
  9638. /* Do not add truncated strings to the environment */
  9639. if (truncated) {
  9640. /* Reallocate the buffer */
  9641. space = 0;
  9642. }
  9643. } while (truncated);
  9644. /* Calculate number of bytes added to the environment */
  9645. n = strlen(added) + 1;
  9646. env->bufused += n;
  9647. /* Append a pointer to the added string into the envp array */
  9648. env->var[env->varused] = added;
  9649. env->varused++;
  9650. }
  9651. /* Return 0 on success, non-zero if an error occurs. */
  9652. static int
  9653. prepare_cgi_environment(struct mg_connection *conn,
  9654. const char *prog,
  9655. struct cgi_environment *env)
  9656. {
  9657. const char *s;
  9658. struct vec var_vec;
  9659. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9660. int i, truncated, uri_len;
  9661. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9662. return -1;
  9663. }
  9664. env->conn = conn;
  9665. env->buflen = CGI_ENVIRONMENT_SIZE;
  9666. env->bufused = 0;
  9667. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9668. if (env->buf == NULL) {
  9669. mg_cry_internal(conn,
  9670. "%s: Not enough memory for environmental buffer",
  9671. __func__);
  9672. return -1;
  9673. }
  9674. env->varlen = MAX_CGI_ENVIR_VARS;
  9675. env->varused = 0;
  9676. env->var =
  9677. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9678. if (env->var == NULL) {
  9679. mg_cry_internal(conn,
  9680. "%s: Not enough memory for environmental variables",
  9681. __func__);
  9682. mg_free(env->buf);
  9683. return -1;
  9684. }
  9685. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9686. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9687. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9688. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9689. /* Prepare the environment block */
  9690. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9691. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9692. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9693. #if defined(USE_IPV6)
  9694. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9695. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9696. } else
  9697. #endif
  9698. {
  9699. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9700. }
  9701. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9702. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9703. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9704. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9705. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9706. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9707. /* SCRIPT_NAME */
  9708. uri_len = (int)strlen(conn->request_info.local_uri);
  9709. if (conn->path_info == NULL) {
  9710. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9711. /* URI: /path_to_script/script.cgi */
  9712. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9713. } else {
  9714. /* URI: /path_to_script/ ... using index.cgi */
  9715. const char *index_file = strrchr(prog, '/');
  9716. if (index_file) {
  9717. addenv(env,
  9718. "SCRIPT_NAME=%s%s",
  9719. conn->request_info.local_uri,
  9720. index_file + 1);
  9721. }
  9722. }
  9723. } else {
  9724. /* URI: /path_to_script/script.cgi/path_info */
  9725. addenv(env,
  9726. "SCRIPT_NAME=%.*s",
  9727. uri_len - (int)strlen(conn->path_info),
  9728. conn->request_info.local_uri);
  9729. }
  9730. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9731. if (conn->path_info == NULL) {
  9732. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9733. } else {
  9734. addenv(env,
  9735. "PATH_TRANSLATED=%s%s",
  9736. conn->dom_ctx->config[DOCUMENT_ROOT],
  9737. conn->path_info);
  9738. }
  9739. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9740. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9741. addenv(env, "CONTENT_TYPE=%s", s);
  9742. }
  9743. if (conn->request_info.query_string != NULL) {
  9744. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9745. }
  9746. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9747. addenv(env, "CONTENT_LENGTH=%s", s);
  9748. }
  9749. if ((s = getenv("PATH")) != NULL) {
  9750. addenv(env, "PATH=%s", s);
  9751. }
  9752. if (conn->path_info != NULL) {
  9753. addenv(env, "PATH_INFO=%s", conn->path_info);
  9754. }
  9755. if (conn->status_code > 0) {
  9756. /* CGI error handler should show the status code */
  9757. addenv(env, "STATUS=%d", conn->status_code);
  9758. }
  9759. #if defined(_WIN32)
  9760. if ((s = getenv("COMSPEC")) != NULL) {
  9761. addenv(env, "COMSPEC=%s", s);
  9762. }
  9763. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9764. addenv(env, "SYSTEMROOT=%s", s);
  9765. }
  9766. if ((s = getenv("SystemDrive")) != NULL) {
  9767. addenv(env, "SystemDrive=%s", s);
  9768. }
  9769. if ((s = getenv("ProgramFiles")) != NULL) {
  9770. addenv(env, "ProgramFiles=%s", s);
  9771. }
  9772. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9773. addenv(env, "ProgramFiles(x86)=%s", s);
  9774. }
  9775. #else
  9776. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9777. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9778. }
  9779. #endif /* _WIN32 */
  9780. if ((s = getenv("PERLLIB")) != NULL) {
  9781. addenv(env, "PERLLIB=%s", s);
  9782. }
  9783. if (conn->request_info.remote_user != NULL) {
  9784. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9785. addenv(env, "%s", "AUTH_TYPE=Digest");
  9786. }
  9787. /* Add all headers as HTTP_* variables */
  9788. for (i = 0; i < conn->request_info.num_headers; i++) {
  9789. (void)mg_snprintf(conn,
  9790. &truncated,
  9791. http_var_name,
  9792. sizeof(http_var_name),
  9793. "HTTP_%s",
  9794. conn->request_info.http_headers[i].name);
  9795. if (truncated) {
  9796. mg_cry_internal(conn,
  9797. "%s: HTTP header variable too long [%s]",
  9798. __func__,
  9799. conn->request_info.http_headers[i].name);
  9800. continue;
  9801. }
  9802. /* Convert variable name into uppercase, and change - to _ */
  9803. for (p = http_var_name; *p != '\0'; p++) {
  9804. if (*p == '-') {
  9805. *p = '_';
  9806. }
  9807. *p = (char)toupper((unsigned char)*p);
  9808. }
  9809. addenv(env,
  9810. "%s=%s",
  9811. http_var_name,
  9812. conn->request_info.http_headers[i].value);
  9813. }
  9814. /* Add user-specified variables */
  9815. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9816. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9817. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9818. }
  9819. env->var[env->varused] = NULL;
  9820. env->buf[env->bufused] = '\0';
  9821. return 0;
  9822. }
  9823. /* Data for CGI process control: PID and number of references */
  9824. struct process_control_data {
  9825. pid_t pid;
  9826. int references;
  9827. };
  9828. static int
  9829. abort_process(void *data)
  9830. {
  9831. /* Waitpid checks for child status and won't work for a pid that does
  9832. * not identify a child of the current process. Thus, if the pid is
  9833. * reused, we will not affect a different process. */
  9834. struct process_control_data *proc = (struct process_control_data *)data;
  9835. int status = 0;
  9836. int refs;
  9837. pid_t ret_pid;
  9838. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9839. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9840. /* Stop child process */
  9841. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9842. kill(proc->pid, SIGABRT);
  9843. /* Wait until process is terminated (don't leave zombies) */
  9844. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9845. ;
  9846. } else {
  9847. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9848. }
  9849. /* Dec reference counter */
  9850. refs = mg_atomic_dec(&proc->references);
  9851. if (refs == 0) {
  9852. /* no more references - free data */
  9853. mg_free(data);
  9854. }
  9855. return 0;
  9856. }
  9857. /* Local (static) function assumes all arguments are valid. */
  9858. static void
  9859. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9860. {
  9861. char *buf;
  9862. size_t buflen;
  9863. int headers_len, data_len, i, truncated;
  9864. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9865. const char *status, *status_text, *connection_state;
  9866. char *pbuf, dir[PATH_MAX], *p;
  9867. struct mg_request_info ri;
  9868. struct cgi_environment blk;
  9869. FILE *in = NULL, *out = NULL, *err = NULL;
  9870. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9871. pid_t pid = (pid_t)-1;
  9872. struct process_control_data *proc = NULL;
  9873. #if defined(USE_TIMERS)
  9874. double cgi_timeout = -1.0;
  9875. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9876. /* Get timeout in seconds */
  9877. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9878. }
  9879. #endif
  9880. buf = NULL;
  9881. buflen = conn->phys_ctx->max_request_size;
  9882. i = prepare_cgi_environment(conn, prog, &blk);
  9883. if (i != 0) {
  9884. blk.buf = NULL;
  9885. blk.var = NULL;
  9886. goto done;
  9887. }
  9888. /* CGI must be executed in its own directory. 'dir' must point to the
  9889. * directory containing executable program, 'p' must point to the
  9890. * executable program name relative to 'dir'. */
  9891. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9892. if (truncated) {
  9893. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9894. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9895. goto done;
  9896. }
  9897. if ((p = strrchr(dir, '/')) != NULL) {
  9898. *p++ = '\0';
  9899. } else {
  9900. dir[0] = '.';
  9901. dir[1] = '\0';
  9902. p = (char *)prog;
  9903. }
  9904. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9905. status = strerror(ERRNO);
  9906. mg_cry_internal(
  9907. conn,
  9908. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9909. prog,
  9910. status);
  9911. mg_send_http_error(conn,
  9912. 500,
  9913. "Error: Cannot create CGI pipe: %s",
  9914. status);
  9915. goto done;
  9916. }
  9917. proc = (struct process_control_data *)
  9918. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9919. if (proc == NULL) {
  9920. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9921. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9922. goto done;
  9923. }
  9924. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9925. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9926. if (pid == (pid_t)-1) {
  9927. status = strerror(ERRNO);
  9928. mg_cry_internal(
  9929. conn,
  9930. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9931. prog,
  9932. status);
  9933. mg_send_http_error(conn,
  9934. 500,
  9935. "Error: Cannot spawn CGI process [%s]: %s",
  9936. prog,
  9937. status);
  9938. mg_free(proc);
  9939. proc = NULL;
  9940. goto done;
  9941. }
  9942. /* Store data in shared process_control_data */
  9943. proc->pid = pid;
  9944. proc->references = 1;
  9945. #if defined(USE_TIMERS)
  9946. if (cgi_timeout > 0.0) {
  9947. proc->references = 2;
  9948. // Start a timer for CGI
  9949. timer_add(conn->phys_ctx,
  9950. cgi_timeout /* in seconds */,
  9951. 0.0,
  9952. 1,
  9953. abort_process,
  9954. (void *)proc);
  9955. }
  9956. #endif
  9957. /* Parent closes only one side of the pipes.
  9958. * If we don't mark them as closed, close() attempt before
  9959. * return from this function throws an exception on Windows.
  9960. * Windows does not like when closed descriptor is closed again. */
  9961. (void)close(fdin[0]);
  9962. (void)close(fdout[1]);
  9963. (void)close(fderr[1]);
  9964. fdin[0] = fdout[1] = fderr[1] = -1;
  9965. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9966. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9967. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9968. status = strerror(ERRNO);
  9969. mg_cry_internal(conn,
  9970. "Error: CGI program \"%s\": Can not open fd: %s",
  9971. prog,
  9972. status);
  9973. mg_send_http_error(conn,
  9974. 500,
  9975. "Error: CGI can not open fd\nfdopen: %s",
  9976. status);
  9977. goto done;
  9978. }
  9979. setbuf(in, NULL);
  9980. setbuf(out, NULL);
  9981. setbuf(err, NULL);
  9982. fout.access.fp = out;
  9983. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9984. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9985. conn->content_len);
  9986. /* This is a POST/PUT request, or another request with body data. */
  9987. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9988. /* Error sending the body data */
  9989. mg_cry_internal(
  9990. conn,
  9991. "Error: CGI program \"%s\": Forward body data failed",
  9992. prog);
  9993. goto done;
  9994. }
  9995. }
  9996. /* Close so child gets an EOF. */
  9997. fclose(in);
  9998. in = NULL;
  9999. fdin[1] = -1;
  10000. /* Now read CGI reply into a buffer. We need to set correct
  10001. * status code, thus we need to see all HTTP headers first.
  10002. * Do not send anything back to client, until we buffer in all
  10003. * HTTP headers. */
  10004. data_len = 0;
  10005. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10006. if (buf == NULL) {
  10007. mg_send_http_error(conn,
  10008. 500,
  10009. "Error: Not enough memory for CGI buffer (%u bytes)",
  10010. (unsigned int)buflen);
  10011. mg_cry_internal(
  10012. conn,
  10013. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10014. "bytes)",
  10015. prog,
  10016. (unsigned int)buflen);
  10017. goto done;
  10018. }
  10019. DEBUG_TRACE("CGI: %s", "wait for response");
  10020. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10021. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10022. if (headers_len <= 0) {
  10023. /* Could not parse the CGI response. Check if some error message on
  10024. * stderr. */
  10025. i = pull_all(err, conn, buf, (int)buflen);
  10026. if (i > 0) {
  10027. /* CGI program explicitly sent an error */
  10028. /* Write the error message to the internal log */
  10029. mg_cry_internal(conn,
  10030. "Error: CGI program \"%s\" sent error "
  10031. "message: [%.*s]",
  10032. prog,
  10033. i,
  10034. buf);
  10035. /* Don't send the error message back to the client */
  10036. mg_send_http_error(conn,
  10037. 500,
  10038. "Error: CGI program \"%s\" failed.",
  10039. prog);
  10040. } else {
  10041. /* CGI program did not explicitly send an error, but a broken
  10042. * respon header */
  10043. mg_cry_internal(conn,
  10044. "Error: CGI program sent malformed or too big "
  10045. "(>%u bytes) HTTP headers: [%.*s]",
  10046. (unsigned)buflen,
  10047. data_len,
  10048. buf);
  10049. mg_send_http_error(conn,
  10050. 500,
  10051. "Error: CGI program sent malformed or too big "
  10052. "(>%u bytes) HTTP headers: [%.*s]",
  10053. (unsigned)buflen,
  10054. data_len,
  10055. buf);
  10056. }
  10057. /* in both cases, abort processing CGI */
  10058. goto done;
  10059. }
  10060. pbuf = buf;
  10061. buf[headers_len - 1] = '\0';
  10062. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10063. /* Make up and send the status line */
  10064. status_text = "OK";
  10065. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10066. != NULL) {
  10067. conn->status_code = atoi(status);
  10068. status_text = status;
  10069. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10070. status_text++;
  10071. }
  10072. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10073. != NULL) {
  10074. conn->status_code = 307;
  10075. } else {
  10076. conn->status_code = 200;
  10077. }
  10078. connection_state =
  10079. get_header(ri.http_headers, ri.num_headers, "Connection");
  10080. if (!header_has_option(connection_state, "keep-alive")) {
  10081. conn->must_close = 1;
  10082. }
  10083. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10084. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10085. /* Send headers */
  10086. for (i = 0; i < ri.num_headers; i++) {
  10087. DEBUG_TRACE("CGI header: %s: %s",
  10088. ri.http_headers[i].name,
  10089. ri.http_headers[i].value);
  10090. mg_printf(conn,
  10091. "%s: %s\r\n",
  10092. ri.http_headers[i].name,
  10093. ri.http_headers[i].value);
  10094. }
  10095. mg_write(conn, "\r\n", 2);
  10096. /* Send chunk of data that may have been read after the headers */
  10097. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10098. /* Read the rest of CGI output and send to the client */
  10099. DEBUG_TRACE("CGI: %s", "forward all data");
  10100. send_file_data(conn, &fout, 0, INT64_MAX);
  10101. DEBUG_TRACE("CGI: %s", "all data sent");
  10102. done:
  10103. mg_free(blk.var);
  10104. mg_free(blk.buf);
  10105. if (pid != (pid_t)-1) {
  10106. abort_process((void *)proc);
  10107. }
  10108. if (fdin[0] != -1) {
  10109. close(fdin[0]);
  10110. }
  10111. if (fdout[1] != -1) {
  10112. close(fdout[1]);
  10113. }
  10114. if (fderr[1] != -1) {
  10115. close(fderr[1]);
  10116. }
  10117. if (in != NULL) {
  10118. fclose(in);
  10119. } else if (fdin[1] != -1) {
  10120. close(fdin[1]);
  10121. }
  10122. if (out != NULL) {
  10123. fclose(out);
  10124. } else if (fdout[0] != -1) {
  10125. close(fdout[0]);
  10126. }
  10127. if (err != NULL) {
  10128. fclose(err);
  10129. } else if (fderr[0] != -1) {
  10130. close(fderr[0]);
  10131. }
  10132. mg_free(buf);
  10133. }
  10134. #endif /* !NO_CGI */
  10135. #if !defined(NO_FILES)
  10136. static void
  10137. mkcol(struct mg_connection *conn, const char *path)
  10138. {
  10139. int rc, body_len;
  10140. struct de de;
  10141. char date[64];
  10142. time_t curtime = time(NULL);
  10143. if (conn == NULL) {
  10144. return;
  10145. }
  10146. /* TODO (mid): Check the mg_send_http_error situations in this function
  10147. */
  10148. memset(&de.file, 0, sizeof(de.file));
  10149. if (!mg_stat(conn, path, &de.file)) {
  10150. mg_cry_internal(conn,
  10151. "%s: mg_stat(%s) failed: %s",
  10152. __func__,
  10153. path,
  10154. strerror(ERRNO));
  10155. }
  10156. if (de.file.last_modified) {
  10157. /* TODO (mid): This check does not seem to make any sense ! */
  10158. /* TODO (mid): Add a webdav unit test first, before changing
  10159. * anything here. */
  10160. mg_send_http_error(
  10161. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10162. return;
  10163. }
  10164. body_len = conn->data_len - conn->request_len;
  10165. if (body_len > 0) {
  10166. mg_send_http_error(
  10167. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10168. return;
  10169. }
  10170. rc = mg_mkdir(conn, path, 0755);
  10171. if (rc == 0) {
  10172. conn->status_code = 201;
  10173. gmt_time_string(date, sizeof(date), &curtime);
  10174. mg_printf(conn,
  10175. "HTTP/1.1 %d Created\r\n"
  10176. "Date: %s\r\n",
  10177. conn->status_code,
  10178. date);
  10179. send_static_cache_header(conn);
  10180. send_additional_header(conn);
  10181. mg_printf(conn,
  10182. "Content-Length: 0\r\n"
  10183. "Connection: %s\r\n\r\n",
  10184. suggest_connection_header(conn));
  10185. } else {
  10186. if (errno == EEXIST) {
  10187. mg_send_http_error(
  10188. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10189. } else if (errno == EACCES) {
  10190. mg_send_http_error(
  10191. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10192. } else if (errno == ENOENT) {
  10193. mg_send_http_error(
  10194. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10195. } else {
  10196. mg_send_http_error(
  10197. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10198. }
  10199. }
  10200. }
  10201. static void
  10202. put_file(struct mg_connection *conn, const char *path)
  10203. {
  10204. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10205. const char *range;
  10206. int64_t r1, r2;
  10207. int rc;
  10208. char date[64];
  10209. time_t curtime = time(NULL);
  10210. if (conn == NULL) {
  10211. return;
  10212. }
  10213. if (mg_stat(conn, path, &file.stat)) {
  10214. /* File already exists */
  10215. conn->status_code = 200;
  10216. if (file.stat.is_directory) {
  10217. /* This is an already existing directory,
  10218. * so there is nothing to do for the server. */
  10219. rc = 0;
  10220. } else {
  10221. /* File exists and is not a directory. */
  10222. /* Can it be replaced? */
  10223. #if defined(MG_USE_OPEN_FILE)
  10224. if (file.access.membuf != NULL) {
  10225. /* This is an "in-memory" file, that can not be replaced */
  10226. mg_send_http_error(conn,
  10227. 405,
  10228. "Error: Put not possible\nReplacing %s "
  10229. "is not supported",
  10230. path);
  10231. return;
  10232. }
  10233. #endif
  10234. /* Check if the server may write this file */
  10235. if (access(path, W_OK) == 0) {
  10236. /* Access granted */
  10237. rc = 1;
  10238. } else {
  10239. mg_send_http_error(
  10240. conn,
  10241. 403,
  10242. "Error: Put not possible\nReplacing %s is not allowed",
  10243. path);
  10244. return;
  10245. }
  10246. }
  10247. } else {
  10248. /* File should be created */
  10249. conn->status_code = 201;
  10250. rc = put_dir(conn, path);
  10251. }
  10252. if (rc == 0) {
  10253. /* put_dir returns 0 if path is a directory */
  10254. gmt_time_string(date, sizeof(date), &curtime);
  10255. mg_printf(conn,
  10256. "HTTP/1.1 %d %s\r\n",
  10257. conn->status_code,
  10258. mg_get_response_code_text(NULL, conn->status_code));
  10259. send_no_cache_header(conn);
  10260. send_additional_header(conn);
  10261. mg_printf(conn,
  10262. "Date: %s\r\n"
  10263. "Content-Length: 0\r\n"
  10264. "Connection: %s\r\n\r\n",
  10265. date,
  10266. suggest_connection_header(conn));
  10267. /* Request to create a directory has been fulfilled successfully.
  10268. * No need to put a file. */
  10269. return;
  10270. }
  10271. if (rc == -1) {
  10272. /* put_dir returns -1 if the path is too long */
  10273. mg_send_http_error(conn,
  10274. 414,
  10275. "Error: Path too long\nput_dir(%s): %s",
  10276. path,
  10277. strerror(ERRNO));
  10278. return;
  10279. }
  10280. if (rc == -2) {
  10281. /* put_dir returns -2 if the directory can not be created */
  10282. mg_send_http_error(conn,
  10283. 500,
  10284. "Error: Can not create directory\nput_dir(%s): %s",
  10285. path,
  10286. strerror(ERRNO));
  10287. return;
  10288. }
  10289. /* A file should be created or overwritten. */
  10290. /* Currently CivetWeb does not nead read+write access. */
  10291. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10292. || file.access.fp == NULL) {
  10293. (void)mg_fclose(&file.access);
  10294. mg_send_http_error(conn,
  10295. 500,
  10296. "Error: Can not create file\nfopen(%s): %s",
  10297. path,
  10298. strerror(ERRNO));
  10299. return;
  10300. }
  10301. fclose_on_exec(&file.access, conn);
  10302. range = mg_get_header(conn, "Content-Range");
  10303. r1 = r2 = 0;
  10304. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10305. conn->status_code = 206; /* Partial content */
  10306. fseeko(file.access.fp, r1, SEEK_SET);
  10307. }
  10308. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10309. /* forward_body_data failed.
  10310. * The error code has already been sent to the client,
  10311. * and conn->status_code is already set. */
  10312. (void)mg_fclose(&file.access);
  10313. return;
  10314. }
  10315. if (mg_fclose(&file.access) != 0) {
  10316. /* fclose failed. This might have different reasons, but a likely
  10317. * one is "no space on disk", http 507. */
  10318. conn->status_code = 507;
  10319. }
  10320. gmt_time_string(date, sizeof(date), &curtime);
  10321. mg_printf(conn,
  10322. "HTTP/1.1 %d %s\r\n",
  10323. conn->status_code,
  10324. mg_get_response_code_text(NULL, conn->status_code));
  10325. send_no_cache_header(conn);
  10326. send_additional_header(conn);
  10327. mg_printf(conn,
  10328. "Date: %s\r\n"
  10329. "Content-Length: 0\r\n"
  10330. "Connection: %s\r\n\r\n",
  10331. date,
  10332. suggest_connection_header(conn));
  10333. }
  10334. static void
  10335. delete_file(struct mg_connection *conn, const char *path)
  10336. {
  10337. struct de de;
  10338. memset(&de.file, 0, sizeof(de.file));
  10339. if (!mg_stat(conn, path, &de.file)) {
  10340. /* mg_stat returns 0 if the file does not exist */
  10341. mg_send_http_error(conn,
  10342. 404,
  10343. "Error: Cannot delete file\nFile %s not found",
  10344. path);
  10345. return;
  10346. }
  10347. #if 0 /* Ignore if a file in memory is inside a folder */
  10348. if (de.access.membuf != NULL) {
  10349. /* the file is cached in memory */
  10350. mg_send_http_error(
  10351. conn,
  10352. 405,
  10353. "Error: Delete not possible\nDeleting %s is not supported",
  10354. path);
  10355. return;
  10356. }
  10357. #endif
  10358. if (de.file.is_directory) {
  10359. if (remove_directory(conn, path)) {
  10360. /* Delete is successful: Return 204 without content. */
  10361. mg_send_http_error(conn, 204, "%s", "");
  10362. } else {
  10363. /* Delete is not successful: Return 500 (Server error). */
  10364. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10365. }
  10366. return;
  10367. }
  10368. /* This is an existing file (not a directory).
  10369. * Check if write permission is granted. */
  10370. if (access(path, W_OK) != 0) {
  10371. /* File is read only */
  10372. mg_send_http_error(
  10373. conn,
  10374. 403,
  10375. "Error: Delete not possible\nDeleting %s is not allowed",
  10376. path);
  10377. return;
  10378. }
  10379. /* Try to delete it. */
  10380. if (mg_remove(conn, path) == 0) {
  10381. /* Delete was successful: Return 204 without content. */
  10382. mg_send_http_error(conn, 204, "%s", "");
  10383. } else {
  10384. /* Delete not successful (file locked). */
  10385. mg_send_http_error(conn,
  10386. 423,
  10387. "Error: Cannot delete file\nremove(%s): %s",
  10388. path,
  10389. strerror(ERRNO));
  10390. }
  10391. }
  10392. #endif /* !NO_FILES */
  10393. #if !defined(NO_FILESYSTEMS)
  10394. static void
  10395. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10396. static void
  10397. do_ssi_include(struct mg_connection *conn,
  10398. const char *ssi,
  10399. char *tag,
  10400. int include_level)
  10401. {
  10402. char file_name[MG_BUF_LEN], path[512], *p;
  10403. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10404. size_t len;
  10405. int truncated = 0;
  10406. if (conn == NULL) {
  10407. return;
  10408. }
  10409. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10410. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10411. * always < MG_BUF_LEN. */
  10412. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10413. /* File name is relative to the webserver root */
  10414. file_name[511] = 0;
  10415. (void)mg_snprintf(conn,
  10416. &truncated,
  10417. path,
  10418. sizeof(path),
  10419. "%s/%s",
  10420. conn->dom_ctx->config[DOCUMENT_ROOT],
  10421. file_name);
  10422. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10423. /* File name is relative to the webserver working directory
  10424. * or it is absolute system path */
  10425. file_name[511] = 0;
  10426. (void)
  10427. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10428. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10429. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10430. /* File name is relative to the currect document */
  10431. file_name[511] = 0;
  10432. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10433. if (!truncated) {
  10434. if ((p = strrchr(path, '/')) != NULL) {
  10435. p[1] = '\0';
  10436. }
  10437. len = strlen(path);
  10438. (void)mg_snprintf(conn,
  10439. &truncated,
  10440. path + len,
  10441. sizeof(path) - len,
  10442. "%s",
  10443. file_name);
  10444. }
  10445. } else {
  10446. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10447. return;
  10448. }
  10449. if (truncated) {
  10450. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10451. return;
  10452. }
  10453. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10454. mg_cry_internal(conn,
  10455. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10456. tag,
  10457. path,
  10458. strerror(ERRNO));
  10459. } else {
  10460. fclose_on_exec(&file.access, conn);
  10461. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10462. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10463. path)
  10464. > 0) {
  10465. send_ssi_file(conn, path, &file, include_level + 1);
  10466. } else {
  10467. send_file_data(conn, &file, 0, INT64_MAX);
  10468. }
  10469. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10470. }
  10471. }
  10472. #if !defined(NO_POPEN)
  10473. static void
  10474. do_ssi_exec(struct mg_connection *conn, char *tag)
  10475. {
  10476. char cmd[1024] = "";
  10477. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10478. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10479. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10480. } else {
  10481. cmd[1023] = 0;
  10482. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10483. mg_cry_internal(conn,
  10484. "Cannot SSI #exec: [%s]: %s",
  10485. cmd,
  10486. strerror(ERRNO));
  10487. } else {
  10488. send_file_data(conn, &file, 0, INT64_MAX);
  10489. pclose(file.access.fp);
  10490. }
  10491. }
  10492. }
  10493. #endif /* !NO_POPEN */
  10494. static int
  10495. mg_fgetc(struct mg_file *filep, int offset)
  10496. {
  10497. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10498. if (filep == NULL) {
  10499. return EOF;
  10500. }
  10501. #if defined(MG_USE_OPEN_FILE)
  10502. if ((filep->access.membuf != NULL) && (offset >= 0)
  10503. && (((unsigned int)(offset)) < filep->stat.size)) {
  10504. return ((const unsigned char *)filep->access.membuf)[offset];
  10505. } else /* else block below */
  10506. #endif
  10507. if (filep->access.fp != NULL) {
  10508. return fgetc(filep->access.fp);
  10509. } else {
  10510. return EOF;
  10511. }
  10512. }
  10513. static void
  10514. send_ssi_file(struct mg_connection *conn,
  10515. const char *path,
  10516. struct mg_file *filep,
  10517. int include_level)
  10518. {
  10519. char buf[MG_BUF_LEN];
  10520. int ch, offset, len, in_tag, in_ssi_tag;
  10521. if (include_level > 10) {
  10522. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10523. return;
  10524. }
  10525. in_tag = in_ssi_tag = len = offset = 0;
  10526. /* Read file, byte by byte, and look for SSI include tags */
  10527. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10528. if (in_tag) {
  10529. /* We are in a tag, either SSI tag or html tag */
  10530. if (ch == '>') {
  10531. /* Tag is closing */
  10532. buf[len++] = '>';
  10533. if (in_ssi_tag) {
  10534. /* Handle SSI tag */
  10535. buf[len] = 0;
  10536. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10537. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10538. #if !defined(NO_POPEN)
  10539. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10540. do_ssi_exec(conn, buf + 9);
  10541. #endif /* !NO_POPEN */
  10542. } else {
  10543. mg_cry_internal(conn,
  10544. "%s: unknown SSI "
  10545. "command: \"%s\"",
  10546. path,
  10547. buf);
  10548. }
  10549. len = 0;
  10550. in_ssi_tag = in_tag = 0;
  10551. } else {
  10552. /* Not an SSI tag */
  10553. /* Flush buffer */
  10554. (void)mg_write(conn, buf, (size_t)len);
  10555. len = 0;
  10556. in_tag = 0;
  10557. }
  10558. } else {
  10559. /* Tag is still open */
  10560. buf[len++] = (char)(ch & 0xff);
  10561. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10562. /* All SSI tags start with <!--# */
  10563. in_ssi_tag = 1;
  10564. }
  10565. if ((len + 2) > (int)sizeof(buf)) {
  10566. /* Tag to long for buffer */
  10567. mg_cry_internal(conn, "%s: tag is too large", path);
  10568. return;
  10569. }
  10570. }
  10571. } else {
  10572. /* We are not in a tag yet. */
  10573. if (ch == '<') {
  10574. /* Tag is opening */
  10575. in_tag = 1;
  10576. if (len > 0) {
  10577. /* Flush current buffer.
  10578. * Buffer is filled with "len" bytes. */
  10579. (void)mg_write(conn, buf, (size_t)len);
  10580. }
  10581. /* Store the < */
  10582. len = 1;
  10583. buf[0] = '<';
  10584. } else {
  10585. /* No Tag */
  10586. /* Add data to buffer */
  10587. buf[len++] = (char)(ch & 0xff);
  10588. /* Flush if buffer is full */
  10589. if (len == (int)sizeof(buf)) {
  10590. mg_write(conn, buf, (size_t)len);
  10591. len = 0;
  10592. }
  10593. }
  10594. }
  10595. }
  10596. /* Send the rest of buffered data */
  10597. if (len > 0) {
  10598. mg_write(conn, buf, (size_t)len);
  10599. }
  10600. }
  10601. static void
  10602. handle_ssi_file_request(struct mg_connection *conn,
  10603. const char *path,
  10604. struct mg_file *filep)
  10605. {
  10606. char date[64];
  10607. time_t curtime = time(NULL);
  10608. const char *cors_orig_cfg;
  10609. const char *cors1, *cors2, *cors3;
  10610. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10611. return;
  10612. }
  10613. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10614. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10615. /* Cross-origin resource sharing (CORS). */
  10616. cors1 = "Access-Control-Allow-Origin: ";
  10617. cors2 = cors_orig_cfg;
  10618. cors3 = "\r\n";
  10619. } else {
  10620. cors1 = cors2 = cors3 = "";
  10621. }
  10622. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10623. /* File exists (precondition for calling this function),
  10624. * but can not be opened by the server. */
  10625. mg_send_http_error(conn,
  10626. 500,
  10627. "Error: Cannot read file\nfopen(%s): %s",
  10628. path,
  10629. strerror(ERRNO));
  10630. } else {
  10631. conn->must_close = 1;
  10632. gmt_time_string(date, sizeof(date), &curtime);
  10633. fclose_on_exec(&filep->access, conn);
  10634. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10635. send_no_cache_header(conn);
  10636. send_additional_header(conn);
  10637. mg_printf(conn,
  10638. "%s%s%s"
  10639. "Date: %s\r\n"
  10640. "Content-Type: text/html\r\n"
  10641. "Connection: %s\r\n\r\n",
  10642. cors1,
  10643. cors2,
  10644. cors3,
  10645. date,
  10646. suggest_connection_header(conn));
  10647. send_ssi_file(conn, path, filep, 0);
  10648. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10649. }
  10650. }
  10651. #endif /* NO_FILESYSTEMS */
  10652. #if !defined(NO_FILES)
  10653. static void
  10654. send_options(struct mg_connection *conn)
  10655. {
  10656. char date[64];
  10657. time_t curtime = time(NULL);
  10658. if (!conn) {
  10659. return;
  10660. }
  10661. conn->status_code = 200;
  10662. conn->must_close = 1;
  10663. gmt_time_string(date, sizeof(date), &curtime);
  10664. /* We do not set a "Cache-Control" header here, but leave the default.
  10665. * Since browsers do not send an OPTIONS request, we can not test the
  10666. * effect anyway. */
  10667. mg_printf(conn,
  10668. "HTTP/1.1 200 OK\r\n"
  10669. "Date: %s\r\n"
  10670. "Connection: %s\r\n"
  10671. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10672. "PROPFIND, MKCOL\r\n"
  10673. "DAV: 1\r\n",
  10674. date,
  10675. suggest_connection_header(conn));
  10676. send_additional_header(conn);
  10677. mg_printf(conn, "\r\n");
  10678. }
  10679. /* Writes PROPFIND properties for a collection element */
  10680. static int
  10681. print_props(struct mg_connection *conn,
  10682. const char *uri,
  10683. const char *name,
  10684. struct mg_file_stat *filep)
  10685. {
  10686. size_t href_size, i, j;
  10687. int len;
  10688. char *href, mtime[64];
  10689. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10690. return 0;
  10691. }
  10692. /* Estimate worst case size for encoding */
  10693. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10694. href = (char *)mg_malloc(href_size);
  10695. if (href == NULL) {
  10696. return 0;
  10697. }
  10698. len = mg_url_encode(uri, href, href_size);
  10699. if (len >= 0) {
  10700. /* Append an extra string */
  10701. mg_url_encode(name, href + len, href_size - (size_t)len);
  10702. }
  10703. /* Directory separator should be preserved. */
  10704. for (i = j = 0; href[i]; j++) {
  10705. if (!strncmp(href + i, "%2f", 3)) {
  10706. href[j] = '/';
  10707. i += 3;
  10708. } else {
  10709. href[j] = href[i++];
  10710. }
  10711. }
  10712. href[j] = '\0';
  10713. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10714. mg_printf(conn,
  10715. "<d:response>"
  10716. "<d:href>%s</d:href>"
  10717. "<d:propstat>"
  10718. "<d:prop>"
  10719. "<d:resourcetype>%s</d:resourcetype>"
  10720. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10721. "<d:getlastmodified>%s</d:getlastmodified>"
  10722. "</d:prop>"
  10723. "<d:status>HTTP/1.1 200 OK</d:status>"
  10724. "</d:propstat>"
  10725. "</d:response>\n",
  10726. href,
  10727. filep->is_directory ? "<d:collection/>" : "",
  10728. filep->size,
  10729. mtime);
  10730. mg_free(href);
  10731. return 1;
  10732. }
  10733. static int
  10734. print_dav_dir_entry(struct de *de, void *data)
  10735. {
  10736. struct mg_connection *conn = (struct mg_connection *)data;
  10737. if (!de || !conn
  10738. || !print_props(
  10739. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10740. return -1;
  10741. }
  10742. return 0;
  10743. }
  10744. static void
  10745. handle_propfind(struct mg_connection *conn,
  10746. const char *path,
  10747. struct mg_file_stat *filep)
  10748. {
  10749. const char *depth = mg_get_header(conn, "Depth");
  10750. char date[64];
  10751. time_t curtime = time(NULL);
  10752. gmt_time_string(date, sizeof(date), &curtime);
  10753. if (!conn || !path || !filep || !conn->dom_ctx) {
  10754. return;
  10755. }
  10756. conn->must_close = 1;
  10757. conn->status_code = 207;
  10758. mg_printf(conn,
  10759. "HTTP/1.1 207 Multi-Status\r\n"
  10760. "Date: %s\r\n",
  10761. date);
  10762. send_static_cache_header(conn);
  10763. send_additional_header(conn);
  10764. mg_printf(conn,
  10765. "Connection: %s\r\n"
  10766. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10767. suggest_connection_header(conn));
  10768. mg_printf(conn,
  10769. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10770. "<d:multistatus xmlns:d='DAV:'>\n");
  10771. /* Print properties for the requested resource itself */
  10772. print_props(conn, conn->request_info.local_uri, "", filep);
  10773. /* If it is a directory, print directory entries too if Depth is not 0
  10774. */
  10775. if (filep->is_directory
  10776. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10777. "yes")
  10778. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10779. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10780. }
  10781. mg_printf(conn, "%s\n", "</d:multistatus>");
  10782. }
  10783. #endif
  10784. void
  10785. mg_lock_connection(struct mg_connection *conn)
  10786. {
  10787. if (conn) {
  10788. (void)pthread_mutex_lock(&conn->mutex);
  10789. }
  10790. }
  10791. void
  10792. mg_unlock_connection(struct mg_connection *conn)
  10793. {
  10794. if (conn) {
  10795. (void)pthread_mutex_unlock(&conn->mutex);
  10796. }
  10797. }
  10798. void
  10799. mg_lock_context(struct mg_context *ctx)
  10800. {
  10801. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10802. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10803. }
  10804. }
  10805. void
  10806. mg_unlock_context(struct mg_context *ctx)
  10807. {
  10808. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10809. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10810. }
  10811. }
  10812. #if defined(USE_LUA)
  10813. #include "mod_lua.inl"
  10814. #endif /* USE_LUA */
  10815. #if defined(USE_DUKTAPE)
  10816. #include "mod_duktape.inl"
  10817. #endif /* USE_DUKTAPE */
  10818. #if defined(USE_WEBSOCKET)
  10819. #if !defined(NO_SSL_DL)
  10820. #define SHA_API static
  10821. #include "sha1.inl"
  10822. #endif
  10823. static int
  10824. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10825. {
  10826. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10827. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10828. SHA_CTX sha_ctx;
  10829. int truncated;
  10830. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10831. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10832. if (truncated) {
  10833. conn->must_close = 1;
  10834. return 0;
  10835. }
  10836. DEBUG_TRACE("%s", "Send websocket handshake");
  10837. SHA1_Init(&sha_ctx);
  10838. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10839. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10840. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10841. mg_printf(conn,
  10842. "HTTP/1.1 101 Switching Protocols\r\n"
  10843. "Upgrade: websocket\r\n"
  10844. "Connection: Upgrade\r\n"
  10845. "Sec-WebSocket-Accept: %s\r\n",
  10846. b64_sha);
  10847. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10848. mg_printf(conn,
  10849. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10850. conn->request_info.acceptedWebSocketSubprotocol);
  10851. } else {
  10852. mg_printf(conn, "%s", "\r\n");
  10853. }
  10854. return 1;
  10855. }
  10856. #if !defined(MG_MAX_UNANSWERED_PING)
  10857. /* Configuration of the maximum number of websocket PINGs that might
  10858. * stay unanswered before the connection is considered broken.
  10859. * Note: The name of this define may still change (until it is
  10860. * defined as a compile parameter in a documentation).
  10861. */
  10862. #define MG_MAX_UNANSWERED_PING (5)
  10863. #endif
  10864. static void
  10865. read_websocket(struct mg_connection *conn,
  10866. mg_websocket_data_handler ws_data_handler,
  10867. void *callback_data)
  10868. {
  10869. /* Pointer to the beginning of the portion of the incoming websocket
  10870. * message queue.
  10871. * The original websocket upgrade request is never removed, so the queue
  10872. * begins after it. */
  10873. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10874. int n, error, exit_by_callback;
  10875. int ret;
  10876. /* body_len is the length of the entire queue in bytes
  10877. * len is the length of the current message
  10878. * data_len is the length of the current message's data payload
  10879. * header_len is the length of the current message's header */
  10880. size_t i, len, mask_len = 0, header_len, body_len;
  10881. uint64_t data_len = 0;
  10882. /* "The masking key is a 32-bit value chosen at random by the client."
  10883. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10884. */
  10885. unsigned char mask[4];
  10886. /* data points to the place where the message is stored when passed to
  10887. * the websocket_data callback. This is either mem on the stack, or a
  10888. * dynamically allocated buffer if it is too large. */
  10889. unsigned char mem[4096];
  10890. unsigned char mop; /* mask flag and opcode */
  10891. /* Variables used for connection monitoring */
  10892. double timeout = -1.0;
  10893. int enable_ping_pong = 0;
  10894. int ping_count = 0;
  10895. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10896. enable_ping_pong =
  10897. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10898. "yes");
  10899. }
  10900. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10901. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10902. }
  10903. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10904. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10905. }
  10906. /* Enter data processing loop */
  10907. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10908. conn->request_info.remote_addr,
  10909. conn->request_info.remote_port);
  10910. conn->in_websocket_handling = 1;
  10911. mg_set_thread_name("wsock");
  10912. /* Loop continuously, reading messages from the socket, invoking the
  10913. * callback, and waiting repeatedly until an error occurs. */
  10914. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10915. && (!conn->must_close)) {
  10916. header_len = 0;
  10917. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10918. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10919. len = buf[1] & 127;
  10920. mask_len = (buf[1] & 128) ? 4 : 0;
  10921. if ((len < 126) && (body_len >= mask_len)) {
  10922. /* inline 7-bit length field */
  10923. data_len = len;
  10924. header_len = 2 + mask_len;
  10925. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10926. /* 16-bit length field */
  10927. header_len = 4 + mask_len;
  10928. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10929. } else if (body_len >= (10 + mask_len)) {
  10930. /* 64-bit length field */
  10931. uint32_t l1, l2;
  10932. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10933. memcpy(&l2, &buf[6], 4);
  10934. header_len = 10 + mask_len;
  10935. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10936. if (data_len > (uint64_t)0x7FFF0000ul) {
  10937. /* no can do */
  10938. mg_cry_internal(
  10939. conn,
  10940. "%s",
  10941. "websocket out of memory; closing connection");
  10942. break;
  10943. }
  10944. }
  10945. }
  10946. if ((header_len > 0) && (body_len >= header_len)) {
  10947. /* Allocate space to hold websocket payload */
  10948. unsigned char *data = mem;
  10949. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10950. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10951. conn->phys_ctx);
  10952. if (data == NULL) {
  10953. /* Allocation failed, exit the loop and then close the
  10954. * connection */
  10955. mg_cry_internal(
  10956. conn,
  10957. "%s",
  10958. "websocket out of memory; closing connection");
  10959. break;
  10960. }
  10961. }
  10962. /* Copy the mask before we shift the queue and destroy it */
  10963. if (mask_len > 0) {
  10964. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10965. } else {
  10966. memset(mask, 0, sizeof(mask));
  10967. }
  10968. /* Read frame payload from the first message in the queue into
  10969. * data and advance the queue by moving the memory in place. */
  10970. DEBUG_ASSERT(body_len >= header_len);
  10971. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10972. mop = buf[0]; /* current mask and opcode */
  10973. /* Overflow case */
  10974. len = body_len - header_len;
  10975. memcpy(data, buf + header_len, len);
  10976. error = 0;
  10977. while ((uint64_t)len < data_len) {
  10978. n = pull_inner(NULL,
  10979. conn,
  10980. (char *)(data + len),
  10981. (int)(data_len - len),
  10982. timeout);
  10983. if (n <= -2) {
  10984. error = 1;
  10985. break;
  10986. } else if (n > 0) {
  10987. len += (size_t)n;
  10988. } else {
  10989. /* Timeout: should retry */
  10990. /* TODO: retry condition */
  10991. }
  10992. }
  10993. if (error) {
  10994. mg_cry_internal(
  10995. conn,
  10996. "%s",
  10997. "Websocket pull failed; closing connection");
  10998. if (data != mem) {
  10999. mg_free(data);
  11000. }
  11001. break;
  11002. }
  11003. conn->data_len = conn->request_len;
  11004. } else {
  11005. mop = buf[0]; /* current mask and opcode, overwritten by
  11006. * memmove() */
  11007. /* Length of the message being read at the front of the
  11008. * queue. Cast to 31 bit is OK, since we limited
  11009. * data_len before. */
  11010. len = (size_t)data_len + header_len;
  11011. /* Copy the data payload into the data pointer for the
  11012. * callback. Cast to 31 bit is OK, since we
  11013. * limited data_len */
  11014. memcpy(data, buf + header_len, (size_t)data_len);
  11015. /* Move the queue forward len bytes */
  11016. memmove(buf, buf + len, body_len - len);
  11017. /* Mark the queue as advanced */
  11018. conn->data_len -= (int)len;
  11019. }
  11020. /* Apply mask if necessary */
  11021. if (mask_len > 0) {
  11022. for (i = 0; i < (size_t)data_len; i++) {
  11023. data[i] ^= mask[i & 3];
  11024. }
  11025. }
  11026. exit_by_callback = 0;
  11027. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11028. /* filter PONG messages */
  11029. DEBUG_TRACE("PONG from %s:%u",
  11030. conn->request_info.remote_addr,
  11031. conn->request_info.remote_port);
  11032. /* No unanwered PINGs left */
  11033. ping_count = 0;
  11034. } else if (enable_ping_pong
  11035. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11036. /* reply PING messages */
  11037. DEBUG_TRACE("Reply PING from %s:%u",
  11038. conn->request_info.remote_addr,
  11039. conn->request_info.remote_port);
  11040. ret = mg_websocket_write(conn,
  11041. MG_WEBSOCKET_OPCODE_PONG,
  11042. (char *)data,
  11043. (size_t)data_len);
  11044. if (ret <= 0) {
  11045. /* Error: send failed */
  11046. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11047. break;
  11048. }
  11049. } else {
  11050. /* Exit the loop if callback signals to exit (server side),
  11051. * or "connection close" opcode received (client side). */
  11052. if ((ws_data_handler != NULL)
  11053. && !ws_data_handler(conn,
  11054. mop,
  11055. (char *)data,
  11056. (size_t)data_len,
  11057. callback_data)) {
  11058. exit_by_callback = 1;
  11059. }
  11060. }
  11061. /* It a buffer has been allocated, free it again */
  11062. if (data != mem) {
  11063. mg_free(data);
  11064. }
  11065. if (exit_by_callback) {
  11066. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11067. conn->request_info.remote_addr,
  11068. conn->request_info.remote_port);
  11069. break;
  11070. }
  11071. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11072. /* Opcode == 8, connection close */
  11073. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11074. conn->request_info.remote_addr,
  11075. conn->request_info.remote_port);
  11076. break;
  11077. }
  11078. /* Not breaking the loop, process next websocket frame. */
  11079. } else {
  11080. /* Read from the socket into the next available location in the
  11081. * message queue. */
  11082. n = pull_inner(NULL,
  11083. conn,
  11084. conn->buf + conn->data_len,
  11085. conn->buf_size - conn->data_len,
  11086. timeout);
  11087. if (n <= -2) {
  11088. /* Error, no bytes read */
  11089. DEBUG_TRACE("PULL from %s:%u failed",
  11090. conn->request_info.remote_addr,
  11091. conn->request_info.remote_port);
  11092. break;
  11093. }
  11094. if (n > 0) {
  11095. conn->data_len += n;
  11096. /* Reset open PING count */
  11097. ping_count = 0;
  11098. } else {
  11099. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11100. && (!conn->must_close)) {
  11101. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11102. /* Stop sending PING */
  11103. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11104. "- closing connection",
  11105. ping_count,
  11106. conn->request_info.remote_addr,
  11107. conn->request_info.remote_port);
  11108. break;
  11109. }
  11110. if (enable_ping_pong) {
  11111. /* Send Websocket PING message */
  11112. DEBUG_TRACE("PING to %s:%u",
  11113. conn->request_info.remote_addr,
  11114. conn->request_info.remote_port);
  11115. ret = mg_websocket_write(conn,
  11116. MG_WEBSOCKET_OPCODE_PING,
  11117. NULL,
  11118. 0);
  11119. if (ret <= 0) {
  11120. /* Error: send failed */
  11121. DEBUG_TRACE("Send PING failed (%i)", ret);
  11122. break;
  11123. }
  11124. ping_count++;
  11125. }
  11126. }
  11127. /* Timeout: should retry */
  11128. /* TODO: get timeout def */
  11129. }
  11130. }
  11131. }
  11132. /* Leave data processing loop */
  11133. mg_set_thread_name("worker");
  11134. conn->in_websocket_handling = 0;
  11135. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11136. conn->request_info.remote_addr,
  11137. conn->request_info.remote_port);
  11138. }
  11139. static int
  11140. mg_websocket_write_exec(struct mg_connection *conn,
  11141. int opcode,
  11142. const char *data,
  11143. size_t dataLen,
  11144. uint32_t masking_key)
  11145. {
  11146. unsigned char header[14];
  11147. size_t headerLen;
  11148. int retval;
  11149. #if defined(GCC_DIAGNOSTIC)
  11150. /* Disable spurious conversion warning for GCC */
  11151. #pragma GCC diagnostic push
  11152. #pragma GCC diagnostic ignored "-Wconversion"
  11153. #endif
  11154. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11155. #if defined(GCC_DIAGNOSTIC)
  11156. #pragma GCC diagnostic pop
  11157. #endif
  11158. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11159. if (dataLen < 126) {
  11160. /* inline 7-bit length field */
  11161. header[1] = (unsigned char)dataLen;
  11162. headerLen = 2;
  11163. } else if (dataLen <= 0xFFFF) {
  11164. /* 16-bit length field */
  11165. uint16_t len = htons((uint16_t)dataLen);
  11166. header[1] = 126;
  11167. memcpy(header + 2, &len, 2);
  11168. headerLen = 4;
  11169. } else {
  11170. /* 64-bit length field */
  11171. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11172. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11173. header[1] = 127;
  11174. memcpy(header + 2, &len1, 4);
  11175. memcpy(header + 6, &len2, 4);
  11176. headerLen = 10;
  11177. }
  11178. if (masking_key) {
  11179. /* add mask */
  11180. header[1] |= 0x80;
  11181. memcpy(header + headerLen, &masking_key, 4);
  11182. headerLen += 4;
  11183. }
  11184. /* Note that POSIX/Winsock's send() is threadsafe
  11185. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11186. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11187. * push(), although that is only a problem if the packet is large or
  11188. * outgoing buffer is full). */
  11189. /* TODO: Check if this lock should be moved to user land.
  11190. * Currently the server sets this lock for websockets, but
  11191. * not for any other connection. It must be set for every
  11192. * conn read/written by more than one thread, no matter if
  11193. * it is a websocket or regular connection. */
  11194. (void)mg_lock_connection(conn);
  11195. retval = mg_write(conn, header, headerLen);
  11196. if (retval != (int)headerLen) {
  11197. /* Did not send complete header */
  11198. retval = -1;
  11199. } else {
  11200. if (dataLen > 0) {
  11201. retval = mg_write(conn, data, dataLen);
  11202. }
  11203. /* if dataLen == 0, the header length (2) is returned */
  11204. }
  11205. /* TODO: Remove this unlock as well, when lock is removed. */
  11206. mg_unlock_connection(conn);
  11207. return retval;
  11208. }
  11209. int
  11210. mg_websocket_write(struct mg_connection *conn,
  11211. int opcode,
  11212. const char *data,
  11213. size_t dataLen)
  11214. {
  11215. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11216. }
  11217. static void
  11218. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11219. {
  11220. size_t i = 0;
  11221. i = 0;
  11222. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11223. /* Convert in 32 bit words, if data is 4 byte aligned */
  11224. while (i < (in_len - 3)) {
  11225. *(uint32_t *)(void *)(out + i) =
  11226. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11227. i += 4;
  11228. }
  11229. }
  11230. if (i != in_len) {
  11231. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11232. while (i < in_len) {
  11233. *(uint8_t *)(void *)(out + i) =
  11234. *(uint8_t *)(void *)(in + i)
  11235. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11236. i++;
  11237. }
  11238. }
  11239. }
  11240. int
  11241. mg_websocket_client_write(struct mg_connection *conn,
  11242. int opcode,
  11243. const char *data,
  11244. size_t dataLen)
  11245. {
  11246. int retval = -1;
  11247. char *masked_data =
  11248. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11249. uint32_t masking_key = 0;
  11250. if (masked_data == NULL) {
  11251. /* Return -1 in an error case */
  11252. mg_cry_internal(conn,
  11253. "%s",
  11254. "Cannot allocate buffer for masked websocket response: "
  11255. "Out of memory");
  11256. return -1;
  11257. }
  11258. do {
  11259. /* Get a masking key - but not 0 */
  11260. masking_key = (uint32_t)get_random();
  11261. } while (masking_key == 0);
  11262. mask_data(data, dataLen, masking_key, masked_data);
  11263. retval = mg_websocket_write_exec(
  11264. conn, opcode, masked_data, dataLen, masking_key);
  11265. mg_free(masked_data);
  11266. return retval;
  11267. }
  11268. static void
  11269. handle_websocket_request(struct mg_connection *conn,
  11270. const char *path,
  11271. int is_callback_resource,
  11272. struct mg_websocket_subprotocols *subprotocols,
  11273. mg_websocket_connect_handler ws_connect_handler,
  11274. mg_websocket_ready_handler ws_ready_handler,
  11275. mg_websocket_data_handler ws_data_handler,
  11276. mg_websocket_close_handler ws_close_handler,
  11277. void *cbData)
  11278. {
  11279. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11280. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11281. ptrdiff_t lua_websock = 0;
  11282. #if !defined(USE_LUA)
  11283. (void)path;
  11284. #endif
  11285. /* Step 1: Check websocket protocol version. */
  11286. /* Step 1.1: Check Sec-WebSocket-Key. */
  11287. if (!websock_key) {
  11288. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11289. * requires a Sec-WebSocket-Key header.
  11290. */
  11291. /* It could be the hixie draft version
  11292. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11293. */
  11294. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11295. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11296. char key3[8];
  11297. if ((key1 != NULL) && (key2 != NULL)) {
  11298. /* This version uses 8 byte body data in a GET request */
  11299. conn->content_len = 8;
  11300. if (8 == mg_read(conn, key3, 8)) {
  11301. /* This is the hixie version */
  11302. mg_send_http_error(conn,
  11303. 426,
  11304. "%s",
  11305. "Protocol upgrade to RFC 6455 required");
  11306. return;
  11307. }
  11308. }
  11309. /* This is an unknown version */
  11310. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11311. return;
  11312. }
  11313. /* Step 1.2: Check websocket protocol version. */
  11314. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11315. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11316. /* Reject wrong versions */
  11317. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11318. return;
  11319. }
  11320. /* Step 1.3: Could check for "Host", but we do not really nead this
  11321. * value for anything, so just ignore it. */
  11322. /* Step 2: If a callback is responsible, call it. */
  11323. if (is_callback_resource) {
  11324. /* Step 2.1 check and select subprotocol */
  11325. const char *protocols[64]; // max 64 headers
  11326. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11327. "Sec-WebSocket-Protocol",
  11328. protocols,
  11329. 64);
  11330. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11331. int cnt = 0;
  11332. int idx;
  11333. unsigned long len;
  11334. const char *sep, *curSubProtocol,
  11335. *acceptedWebSocketSubprotocol = NULL;
  11336. /* look for matching subprotocol */
  11337. do {
  11338. const char *protocol = protocols[cnt];
  11339. do {
  11340. sep = strchr(protocol, ',');
  11341. curSubProtocol = protocol;
  11342. len = sep ? (unsigned long)(sep - protocol)
  11343. : (unsigned long)strlen(protocol);
  11344. while (sep && isspace((unsigned char)*++sep))
  11345. ; // ignore leading whitespaces
  11346. protocol = sep;
  11347. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11348. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11349. && (strncmp(curSubProtocol,
  11350. subprotocols->subprotocols[idx],
  11351. len)
  11352. == 0)) {
  11353. acceptedWebSocketSubprotocol =
  11354. subprotocols->subprotocols[idx];
  11355. break;
  11356. }
  11357. }
  11358. } while (sep && !acceptedWebSocketSubprotocol);
  11359. } while (++cnt < nbSubprotocolHeader
  11360. && !acceptedWebSocketSubprotocol);
  11361. conn->request_info.acceptedWebSocketSubprotocol =
  11362. acceptedWebSocketSubprotocol;
  11363. } else if (nbSubprotocolHeader > 0) {
  11364. /* keep legacy behavior */
  11365. const char *protocol = protocols[0];
  11366. /* The protocol is a comma separated list of names. */
  11367. /* The server must only return one value from this list. */
  11368. /* First check if it is a list or just a single value. */
  11369. const char *sep = strrchr(protocol, ',');
  11370. if (sep == NULL) {
  11371. /* Just a single protocol -> accept it. */
  11372. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11373. } else {
  11374. /* Multiple protocols -> accept the last one. */
  11375. /* This is just a quick fix if the client offers multiple
  11376. * protocols. The handler should have a list of accepted
  11377. * protocols on his own
  11378. * and use it to select one protocol among those the client
  11379. * has
  11380. * offered.
  11381. */
  11382. while (isspace((unsigned char)*++sep)) {
  11383. ; /* ignore leading whitespaces */
  11384. }
  11385. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11386. }
  11387. }
  11388. if ((ws_connect_handler != NULL)
  11389. && (ws_connect_handler(conn, cbData) != 0)) {
  11390. /* C callback has returned non-zero, do not proceed with
  11391. * handshake.
  11392. */
  11393. /* Note that C callbacks are no longer called when Lua is
  11394. * responsible, so C can no longer filter callbacks for Lua. */
  11395. return;
  11396. }
  11397. }
  11398. #if defined(USE_LUA)
  11399. /* Step 3: No callback. Check if Lua is responsible. */
  11400. else {
  11401. /* Step 3.1: Check if Lua is responsible. */
  11402. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11403. lua_websock = match_prefix(
  11404. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11405. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11406. path);
  11407. }
  11408. if (lua_websock) {
  11409. /* Step 3.2: Lua is responsible: call it. */
  11410. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11411. if (!conn->lua_websocket_state) {
  11412. /* Lua rejected the new client */
  11413. return;
  11414. }
  11415. }
  11416. }
  11417. #endif
  11418. /* Step 4: Check if there is a responsible websocket handler. */
  11419. if (!is_callback_resource && !lua_websock) {
  11420. /* There is no callback, and Lua is not responsible either. */
  11421. /* Reply with a 404 Not Found. We are still at a standard
  11422. * HTTP request here, before the websocket handshake, so
  11423. * we can still send standard HTTP error replies. */
  11424. mg_send_http_error(conn, 404, "%s", "Not found");
  11425. return;
  11426. }
  11427. /* Step 5: The websocket connection has been accepted */
  11428. if (!send_websocket_handshake(conn, websock_key)) {
  11429. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11430. return;
  11431. }
  11432. /* Step 6: Call the ready handler */
  11433. if (is_callback_resource) {
  11434. if (ws_ready_handler != NULL) {
  11435. ws_ready_handler(conn, cbData);
  11436. }
  11437. #if defined(USE_LUA)
  11438. } else if (lua_websock) {
  11439. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11440. /* the ready handler returned false */
  11441. return;
  11442. }
  11443. #endif
  11444. }
  11445. /* Step 7: Enter the read loop */
  11446. if (is_callback_resource) {
  11447. read_websocket(conn, ws_data_handler, cbData);
  11448. #if defined(USE_LUA)
  11449. } else if (lua_websock) {
  11450. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11451. #endif
  11452. }
  11453. /* Step 8: Call the close handler */
  11454. if (ws_close_handler) {
  11455. ws_close_handler(conn, cbData);
  11456. }
  11457. }
  11458. #endif /* !USE_WEBSOCKET */
  11459. /* Is upgrade request:
  11460. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11461. * 1 = upgrade to websocket
  11462. * 2 = upgrade to HTTP/2
  11463. * -1 = upgrade to unknown protocol
  11464. */
  11465. static int
  11466. should_switch_to_protocol(const struct mg_connection *conn)
  11467. {
  11468. const char *upgrade, *connection;
  11469. /* A websocket protocoll has the following HTTP headers:
  11470. *
  11471. * Connection: Upgrade
  11472. * Upgrade: Websocket
  11473. */
  11474. connection = mg_get_header(conn, "Connection");
  11475. if (connection == NULL) {
  11476. return PROTOCOL_TYPE_HTTP1;
  11477. }
  11478. if (!mg_strcasestr(connection, "upgrade")) {
  11479. return PROTOCOL_TYPE_HTTP1;
  11480. }
  11481. upgrade = mg_get_header(conn, "Upgrade");
  11482. if (upgrade == NULL) {
  11483. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11484. return -1;
  11485. }
  11486. /* Upgrade to ... */
  11487. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11488. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11489. * "Sec-WebSocket-Version" are also required.
  11490. * Don't check them here, since even an unsupported websocket protocol
  11491. * request still IS a websocket request (in contrast to a standard HTTP
  11492. * request). It will fail later in handle_websocket_request.
  11493. */
  11494. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11495. }
  11496. if (0 != mg_strcasestr(upgrade, "h2")) {
  11497. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11498. }
  11499. /* Upgrade to another protocol */
  11500. return -1;
  11501. }
  11502. static int
  11503. isbyte(int n)
  11504. {
  11505. return (n >= 0) && (n <= 255);
  11506. }
  11507. static int
  11508. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11509. {
  11510. int n, a, b, c, d, slash = 32, len = 0;
  11511. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11512. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11513. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11514. && (slash < 33)) {
  11515. len = n;
  11516. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11517. | (uint32_t)d;
  11518. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11519. }
  11520. return len;
  11521. }
  11522. static int
  11523. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11524. {
  11525. int throttle = 0;
  11526. struct vec vec, val;
  11527. uint32_t net, mask;
  11528. char mult;
  11529. double v;
  11530. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11531. mult = ',';
  11532. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11533. || (v < 0)
  11534. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11535. && (mult != ','))) {
  11536. continue;
  11537. }
  11538. v *= (lowercase(&mult) == 'k')
  11539. ? 1024
  11540. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11541. if (vec.len == 1 && vec.ptr[0] == '*') {
  11542. throttle = (int)v;
  11543. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11544. if ((remote_ip & mask) == net) {
  11545. throttle = (int)v;
  11546. }
  11547. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11548. throttle = (int)v;
  11549. }
  11550. }
  11551. return throttle;
  11552. }
  11553. static uint32_t
  11554. get_remote_ip(const struct mg_connection *conn)
  11555. {
  11556. if (!conn) {
  11557. return 0;
  11558. }
  11559. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11560. }
  11561. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11562. #include "handle_form.inl"
  11563. #if defined(MG_LEGACY_INTERFACE)
  11564. /* Implement the deprecated mg_upload function by calling the new
  11565. * mg_handle_form_request function. While mg_upload could only handle
  11566. * HTML forms sent as POST request in multipart/form-data format
  11567. * containing only file input elements, mg_handle_form_request can
  11568. * handle all form input elements and all standard request methods. */
  11569. struct mg_upload_user_data {
  11570. struct mg_connection *conn;
  11571. const char *destination_dir;
  11572. int num_uploaded_files;
  11573. };
  11574. /* Helper function for deprecated mg_upload. */
  11575. static int
  11576. mg_upload_field_found(const char *key,
  11577. const char *filename,
  11578. char *path,
  11579. size_t pathlen,
  11580. void *user_data)
  11581. {
  11582. int truncated = 0;
  11583. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11584. (void)key;
  11585. if (!filename) {
  11586. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11587. return FORM_FIELD_STORAGE_ABORT;
  11588. }
  11589. mg_snprintf(fud->conn,
  11590. &truncated,
  11591. path,
  11592. pathlen - 1,
  11593. "%s/%s",
  11594. fud->destination_dir,
  11595. filename);
  11596. if (truncated) {
  11597. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11598. return FORM_FIELD_STORAGE_ABORT;
  11599. }
  11600. return FORM_FIELD_STORAGE_STORE;
  11601. }
  11602. /* Helper function for deprecated mg_upload. */
  11603. static int
  11604. mg_upload_field_get(const char *key,
  11605. const char *value,
  11606. size_t value_size,
  11607. void *user_data)
  11608. {
  11609. /* Function should never be called */
  11610. (void)key;
  11611. (void)value;
  11612. (void)value_size;
  11613. (void)user_data;
  11614. return 0;
  11615. }
  11616. /* Helper function for deprecated mg_upload. */
  11617. static int
  11618. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11619. {
  11620. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11621. (void)file_size;
  11622. fud->num_uploaded_files++;
  11623. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11624. return 0;
  11625. }
  11626. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11627. int
  11628. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11629. {
  11630. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11631. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11632. mg_upload_field_get,
  11633. mg_upload_field_stored,
  11634. 0};
  11635. int ret;
  11636. fdh.user_data = (void *)&fud;
  11637. ret = mg_handle_form_request(conn, &fdh);
  11638. if (ret < 0) {
  11639. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11640. }
  11641. return fud.num_uploaded_files;
  11642. }
  11643. #endif
  11644. static int
  11645. get_first_ssl_listener_index(const struct mg_context *ctx)
  11646. {
  11647. unsigned int i;
  11648. int idx = -1;
  11649. if (ctx) {
  11650. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11651. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11652. }
  11653. }
  11654. return idx;
  11655. }
  11656. /* Return host (without port) */
  11657. /* Use mg_free to free the result */
  11658. static const char *
  11659. alloc_get_host(struct mg_connection *conn)
  11660. {
  11661. char buf[1025];
  11662. size_t buflen = sizeof(buf);
  11663. const char *host_header = get_header(conn->request_info.http_headers,
  11664. conn->request_info.num_headers,
  11665. "Host");
  11666. char *host;
  11667. if (host_header != NULL) {
  11668. char *pos;
  11669. /* Create a local copy of the "Host" header, since it might be
  11670. * modified here. */
  11671. mg_strlcpy(buf, host_header, buflen);
  11672. buf[buflen - 1] = '\0';
  11673. host = buf;
  11674. while (isspace((unsigned char)*host)) {
  11675. host++;
  11676. }
  11677. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11678. * is found. */
  11679. if (*host == '[') {
  11680. pos = strchr(host, ']');
  11681. if (!pos) {
  11682. /* Malformed hostname starts with '[', but no ']' found */
  11683. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11684. return NULL;
  11685. }
  11686. /* terminate after ']' */
  11687. pos[1] = 0;
  11688. } else {
  11689. /* Otherwise, a ':' separates hostname and port number */
  11690. pos = strchr(host, ':');
  11691. if (pos != NULL) {
  11692. *pos = '\0';
  11693. }
  11694. }
  11695. if (conn->ssl) {
  11696. /* This is a HTTPS connection, maybe we have a hostname
  11697. * from SNI (set in ssl_servername_callback). */
  11698. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11699. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11700. /* We are not using the default domain */
  11701. if (mg_strcasecmp(host, sslhost)) {
  11702. /* Mismatch between SNI domain and HTTP domain */
  11703. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11704. sslhost,
  11705. host);
  11706. return NULL;
  11707. }
  11708. }
  11709. DEBUG_TRACE("HTTPS Host: %s", host);
  11710. } else {
  11711. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11712. while (dom) {
  11713. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11714. /* Found matching domain */
  11715. DEBUG_TRACE("HTTP domain %s found",
  11716. dom->config[AUTHENTICATION_DOMAIN]);
  11717. /* TODO: Check if this is a HTTP or HTTPS domain */
  11718. conn->dom_ctx = dom;
  11719. break;
  11720. }
  11721. mg_lock_context(conn->phys_ctx);
  11722. dom = dom->next;
  11723. mg_unlock_context(conn->phys_ctx);
  11724. }
  11725. DEBUG_TRACE("HTTP Host: %s", host);
  11726. }
  11727. } else {
  11728. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11729. host = buf;
  11730. DEBUG_TRACE("IP: %s", host);
  11731. }
  11732. return mg_strdup_ctx(host, conn->phys_ctx);
  11733. }
  11734. static void
  11735. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11736. {
  11737. char target_url[MG_BUF_LEN];
  11738. int truncated = 0;
  11739. conn->must_close = 1;
  11740. /* Send host, port, uri and (if it exists) ?query_string */
  11741. if (conn->host) {
  11742. /* Use "308 Permanent Redirect" */
  11743. int redirect_code = 308;
  11744. /* Create target URL */
  11745. mg_snprintf(
  11746. conn,
  11747. &truncated,
  11748. target_url,
  11749. sizeof(target_url),
  11750. "https://%s:%d%s%s%s",
  11751. conn->host,
  11752. #if defined(USE_IPV6)
  11753. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11754. == AF_INET6)
  11755. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11756. .lsa.sin6.sin6_port)
  11757. :
  11758. #endif
  11759. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11760. .lsa.sin.sin_port),
  11761. conn->request_info.local_uri,
  11762. (conn->request_info.query_string == NULL) ? "" : "?",
  11763. (conn->request_info.query_string == NULL)
  11764. ? ""
  11765. : conn->request_info.query_string);
  11766. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11767. * is used as buffer size) */
  11768. if (truncated) {
  11769. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11770. return;
  11771. }
  11772. /* Use redirect helper function */
  11773. mg_send_http_redirect(conn, target_url, redirect_code);
  11774. }
  11775. }
  11776. static void
  11777. mg_set_handler_type(struct mg_context *phys_ctx,
  11778. struct mg_domain_context *dom_ctx,
  11779. const char *uri,
  11780. int handler_type,
  11781. int is_delete_request,
  11782. mg_request_handler handler,
  11783. struct mg_websocket_subprotocols *subprotocols,
  11784. mg_websocket_connect_handler connect_handler,
  11785. mg_websocket_ready_handler ready_handler,
  11786. mg_websocket_data_handler data_handler,
  11787. mg_websocket_close_handler close_handler,
  11788. mg_authorization_handler auth_handler,
  11789. void *cbdata)
  11790. {
  11791. struct mg_handler_info *tmp_rh, **lastref;
  11792. size_t urilen = strlen(uri);
  11793. if (handler_type == WEBSOCKET_HANDLER) {
  11794. DEBUG_ASSERT(handler == NULL);
  11795. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11796. || ready_handler != NULL || data_handler != NULL
  11797. || close_handler != NULL);
  11798. DEBUG_ASSERT(auth_handler == NULL);
  11799. if (handler != NULL) {
  11800. return;
  11801. }
  11802. if (!is_delete_request && (connect_handler == NULL)
  11803. && (ready_handler == NULL) && (data_handler == NULL)
  11804. && (close_handler == NULL)) {
  11805. return;
  11806. }
  11807. if (auth_handler != NULL) {
  11808. return;
  11809. }
  11810. } else if (handler_type == REQUEST_HANDLER) {
  11811. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11812. && data_handler == NULL && close_handler == NULL);
  11813. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11814. DEBUG_ASSERT(auth_handler == NULL);
  11815. if ((connect_handler != NULL) || (ready_handler != NULL)
  11816. || (data_handler != NULL) || (close_handler != NULL)) {
  11817. return;
  11818. }
  11819. if (!is_delete_request && (handler == NULL)) {
  11820. return;
  11821. }
  11822. if (auth_handler != NULL) {
  11823. return;
  11824. }
  11825. } else { /* AUTH_HANDLER */
  11826. DEBUG_ASSERT(handler == NULL);
  11827. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11828. && data_handler == NULL && close_handler == NULL);
  11829. DEBUG_ASSERT(auth_handler != NULL);
  11830. if (handler != NULL) {
  11831. return;
  11832. }
  11833. if ((connect_handler != NULL) || (ready_handler != NULL)
  11834. || (data_handler != NULL) || (close_handler != NULL)) {
  11835. return;
  11836. }
  11837. if (!is_delete_request && (auth_handler == NULL)) {
  11838. return;
  11839. }
  11840. }
  11841. if (!phys_ctx || !dom_ctx) {
  11842. return;
  11843. }
  11844. mg_lock_context(phys_ctx);
  11845. /* first try to find an existing handler */
  11846. do {
  11847. lastref = &(dom_ctx->handlers);
  11848. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11849. tmp_rh = tmp_rh->next) {
  11850. if (tmp_rh->handler_type == handler_type
  11851. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11852. if (!is_delete_request) {
  11853. /* update existing handler */
  11854. if (handler_type == REQUEST_HANDLER) {
  11855. /* Wait for end of use before updating */
  11856. if (tmp_rh->refcount) {
  11857. mg_unlock_context(phys_ctx);
  11858. mg_sleep(1);
  11859. mg_lock_context(phys_ctx);
  11860. /* tmp_rh might have been freed, search again. */
  11861. break;
  11862. }
  11863. /* Ok, the handler is no more use -> Update it */
  11864. tmp_rh->handler = handler;
  11865. } else if (handler_type == WEBSOCKET_HANDLER) {
  11866. tmp_rh->subprotocols = subprotocols;
  11867. tmp_rh->connect_handler = connect_handler;
  11868. tmp_rh->ready_handler = ready_handler;
  11869. tmp_rh->data_handler = data_handler;
  11870. tmp_rh->close_handler = close_handler;
  11871. } else { /* AUTH_HANDLER */
  11872. tmp_rh->auth_handler = auth_handler;
  11873. }
  11874. tmp_rh->cbdata = cbdata;
  11875. } else {
  11876. /* remove existing handler */
  11877. if (handler_type == REQUEST_HANDLER) {
  11878. /* Wait for end of use before removing */
  11879. if (tmp_rh->refcount) {
  11880. tmp_rh->removing = 1;
  11881. mg_unlock_context(phys_ctx);
  11882. mg_sleep(1);
  11883. mg_lock_context(phys_ctx);
  11884. /* tmp_rh might have been freed, search again. */
  11885. break;
  11886. }
  11887. /* Ok, the handler is no more used */
  11888. }
  11889. *lastref = tmp_rh->next;
  11890. mg_free(tmp_rh->uri);
  11891. mg_free(tmp_rh);
  11892. }
  11893. mg_unlock_context(phys_ctx);
  11894. return;
  11895. }
  11896. lastref = &(tmp_rh->next);
  11897. }
  11898. } while (tmp_rh != NULL);
  11899. if (is_delete_request) {
  11900. /* no handler to set, this was a remove request to a non-existing
  11901. * handler */
  11902. mg_unlock_context(phys_ctx);
  11903. return;
  11904. }
  11905. tmp_rh =
  11906. (struct mg_handler_info *)mg_calloc_ctx(1,
  11907. sizeof(struct mg_handler_info),
  11908. phys_ctx);
  11909. if (tmp_rh == NULL) {
  11910. mg_unlock_context(phys_ctx);
  11911. mg_cry_ctx_internal(phys_ctx,
  11912. "%s",
  11913. "Cannot create new request handler struct, OOM");
  11914. return;
  11915. }
  11916. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11917. if (!tmp_rh->uri) {
  11918. mg_unlock_context(phys_ctx);
  11919. mg_free(tmp_rh);
  11920. mg_cry_ctx_internal(phys_ctx,
  11921. "%s",
  11922. "Cannot create new request handler struct, OOM");
  11923. return;
  11924. }
  11925. tmp_rh->uri_len = urilen;
  11926. if (handler_type == REQUEST_HANDLER) {
  11927. tmp_rh->refcount = 0;
  11928. tmp_rh->removing = 0;
  11929. tmp_rh->handler = handler;
  11930. } else if (handler_type == WEBSOCKET_HANDLER) {
  11931. tmp_rh->subprotocols = subprotocols;
  11932. tmp_rh->connect_handler = connect_handler;
  11933. tmp_rh->ready_handler = ready_handler;
  11934. tmp_rh->data_handler = data_handler;
  11935. tmp_rh->close_handler = close_handler;
  11936. } else { /* AUTH_HANDLER */
  11937. tmp_rh->auth_handler = auth_handler;
  11938. }
  11939. tmp_rh->cbdata = cbdata;
  11940. tmp_rh->handler_type = handler_type;
  11941. tmp_rh->next = NULL;
  11942. *lastref = tmp_rh;
  11943. mg_unlock_context(phys_ctx);
  11944. }
  11945. void
  11946. mg_set_request_handler(struct mg_context *ctx,
  11947. const char *uri,
  11948. mg_request_handler handler,
  11949. void *cbdata)
  11950. {
  11951. mg_set_handler_type(ctx,
  11952. &(ctx->dd),
  11953. uri,
  11954. REQUEST_HANDLER,
  11955. handler == NULL,
  11956. handler,
  11957. NULL,
  11958. NULL,
  11959. NULL,
  11960. NULL,
  11961. NULL,
  11962. NULL,
  11963. cbdata);
  11964. }
  11965. void
  11966. mg_set_websocket_handler(struct mg_context *ctx,
  11967. const char *uri,
  11968. mg_websocket_connect_handler connect_handler,
  11969. mg_websocket_ready_handler ready_handler,
  11970. mg_websocket_data_handler data_handler,
  11971. mg_websocket_close_handler close_handler,
  11972. void *cbdata)
  11973. {
  11974. mg_set_websocket_handler_with_subprotocols(ctx,
  11975. uri,
  11976. NULL,
  11977. connect_handler,
  11978. ready_handler,
  11979. data_handler,
  11980. close_handler,
  11981. cbdata);
  11982. }
  11983. void
  11984. mg_set_websocket_handler_with_subprotocols(
  11985. struct mg_context *ctx,
  11986. const char *uri,
  11987. struct mg_websocket_subprotocols *subprotocols,
  11988. mg_websocket_connect_handler connect_handler,
  11989. mg_websocket_ready_handler ready_handler,
  11990. mg_websocket_data_handler data_handler,
  11991. mg_websocket_close_handler close_handler,
  11992. void *cbdata)
  11993. {
  11994. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11995. && (data_handler == NULL)
  11996. && (close_handler == NULL);
  11997. mg_set_handler_type(ctx,
  11998. &(ctx->dd),
  11999. uri,
  12000. WEBSOCKET_HANDLER,
  12001. is_delete_request,
  12002. NULL,
  12003. subprotocols,
  12004. connect_handler,
  12005. ready_handler,
  12006. data_handler,
  12007. close_handler,
  12008. NULL,
  12009. cbdata);
  12010. }
  12011. void
  12012. mg_set_auth_handler(struct mg_context *ctx,
  12013. const char *uri,
  12014. mg_authorization_handler handler,
  12015. void *cbdata)
  12016. {
  12017. mg_set_handler_type(ctx,
  12018. &(ctx->dd),
  12019. uri,
  12020. AUTH_HANDLER,
  12021. handler == NULL,
  12022. NULL,
  12023. NULL,
  12024. NULL,
  12025. NULL,
  12026. NULL,
  12027. NULL,
  12028. handler,
  12029. cbdata);
  12030. }
  12031. static int
  12032. get_request_handler(struct mg_connection *conn,
  12033. int handler_type,
  12034. mg_request_handler *handler,
  12035. struct mg_websocket_subprotocols **subprotocols,
  12036. mg_websocket_connect_handler *connect_handler,
  12037. mg_websocket_ready_handler *ready_handler,
  12038. mg_websocket_data_handler *data_handler,
  12039. mg_websocket_close_handler *close_handler,
  12040. mg_authorization_handler *auth_handler,
  12041. void **cbdata,
  12042. struct mg_handler_info **handler_info)
  12043. {
  12044. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12045. if (request_info) {
  12046. const char *uri = request_info->local_uri;
  12047. size_t urilen = strlen(uri);
  12048. struct mg_handler_info *tmp_rh;
  12049. int step, matched;
  12050. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12051. return 0;
  12052. }
  12053. mg_lock_context(conn->phys_ctx);
  12054. for (step = 0; step < 3; step++) {
  12055. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12056. tmp_rh = tmp_rh->next) {
  12057. if (tmp_rh->handler_type != handler_type) {
  12058. continue;
  12059. }
  12060. if (step == 0) {
  12061. /* first try for an exact match */
  12062. matched = (tmp_rh->uri_len == urilen)
  12063. && (strcmp(tmp_rh->uri, uri) == 0);
  12064. } else if (step == 1) {
  12065. /* next try for a partial match, we will accept
  12066. uri/something */
  12067. matched =
  12068. (tmp_rh->uri_len < urilen)
  12069. && (uri[tmp_rh->uri_len] == '/')
  12070. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12071. } else {
  12072. /* finally try for pattern match */
  12073. matched =
  12074. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12075. }
  12076. if (matched) {
  12077. if (handler_type == WEBSOCKET_HANDLER) {
  12078. *subprotocols = tmp_rh->subprotocols;
  12079. *connect_handler = tmp_rh->connect_handler;
  12080. *ready_handler = tmp_rh->ready_handler;
  12081. *data_handler = tmp_rh->data_handler;
  12082. *close_handler = tmp_rh->close_handler;
  12083. } else if (handler_type == REQUEST_HANDLER) {
  12084. if (tmp_rh->removing) {
  12085. /* Treat as none found */
  12086. step = 2;
  12087. break;
  12088. }
  12089. *handler = tmp_rh->handler;
  12090. /* Acquire handler and give it back */
  12091. tmp_rh->refcount++;
  12092. *handler_info = tmp_rh;
  12093. } else { /* AUTH_HANDLER */
  12094. *auth_handler = tmp_rh->auth_handler;
  12095. }
  12096. *cbdata = tmp_rh->cbdata;
  12097. mg_unlock_context(conn->phys_ctx);
  12098. return 1;
  12099. }
  12100. }
  12101. }
  12102. mg_unlock_context(conn->phys_ctx);
  12103. }
  12104. return 0; /* none found */
  12105. }
  12106. /* Check if the script file is in a path, allowed for script files.
  12107. * This can be used if uploading files is possible not only for the server
  12108. * admin, and the upload mechanism does not check the file extension.
  12109. */
  12110. static int
  12111. is_in_script_path(const struct mg_connection *conn, const char *path)
  12112. {
  12113. /* TODO (Feature): Add config value for allowed script path.
  12114. * Default: All allowed. */
  12115. (void)conn;
  12116. (void)path;
  12117. return 1;
  12118. }
  12119. #if defined(USE_WEBSOCKET) \
  12120. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12121. static int
  12122. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12123. void *cbdata)
  12124. {
  12125. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12126. if (pcallbacks->websocket_connect) {
  12127. return pcallbacks->websocket_connect(conn);
  12128. }
  12129. /* No handler set - assume "OK" */
  12130. return 0;
  12131. }
  12132. static void
  12133. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12134. {
  12135. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12136. if (pcallbacks->websocket_ready) {
  12137. pcallbacks->websocket_ready(conn);
  12138. }
  12139. }
  12140. static int
  12141. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12142. int bits,
  12143. char *data,
  12144. size_t len,
  12145. void *cbdata)
  12146. {
  12147. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12148. if (pcallbacks->websocket_data) {
  12149. return pcallbacks->websocket_data(conn, bits, data, len);
  12150. }
  12151. /* No handler set - assume "OK" */
  12152. return 1;
  12153. }
  12154. static void
  12155. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12156. void *cbdata)
  12157. {
  12158. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12159. if (pcallbacks->connection_close) {
  12160. pcallbacks->connection_close(conn);
  12161. }
  12162. }
  12163. #endif
  12164. /* This is the heart of the Civetweb's logic.
  12165. * This function is called when the request is read, parsed and validated,
  12166. * and Civetweb must decide what action to take: serve a file, or
  12167. * a directory, or call embedded function, etcetera. */
  12168. static void
  12169. handle_request(struct mg_connection *conn)
  12170. {
  12171. struct mg_request_info *ri = &conn->request_info;
  12172. char path[PATH_MAX];
  12173. int uri_len, ssl_index;
  12174. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12175. is_put_or_delete_request = 0, is_callback_resource = 0;
  12176. int i;
  12177. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12178. mg_request_handler callback_handler = NULL;
  12179. struct mg_handler_info *handler_info = NULL;
  12180. struct mg_websocket_subprotocols *subprotocols;
  12181. mg_websocket_connect_handler ws_connect_handler = NULL;
  12182. mg_websocket_ready_handler ws_ready_handler = NULL;
  12183. mg_websocket_data_handler ws_data_handler = NULL;
  12184. mg_websocket_close_handler ws_close_handler = NULL;
  12185. void *callback_data = NULL;
  12186. mg_authorization_handler auth_handler = NULL;
  12187. void *auth_callback_data = NULL;
  12188. int handler_type;
  12189. time_t curtime = time(NULL);
  12190. char date[64];
  12191. path[0] = 0;
  12192. /* 1. get the request url */
  12193. /* 1.1. split into url and query string */
  12194. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12195. != NULL) {
  12196. *((char *)conn->request_info.query_string++) = '\0';
  12197. }
  12198. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12199. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12200. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12201. if (ssl_index >= 0) {
  12202. redirect_to_https_port(conn, ssl_index);
  12203. } else {
  12204. /* A http to https forward port has been specified,
  12205. * but no https port to forward to. */
  12206. mg_send_http_error(conn,
  12207. 503,
  12208. "%s",
  12209. "Error: SSL forward not configured properly");
  12210. mg_cry_internal(conn,
  12211. "%s",
  12212. "Can not redirect to SSL, no SSL port available");
  12213. }
  12214. return;
  12215. }
  12216. uri_len = (int)strlen(ri->local_uri);
  12217. /* 1.3. decode url (if config says so) */
  12218. if (should_decode_url(conn)) {
  12219. mg_url_decode(
  12220. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12221. }
  12222. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12223. * not possible */
  12224. remove_dot_segments((char *)ri->local_uri);
  12225. /* step 1. completed, the url is known now */
  12226. uri_len = (int)strlen(ri->local_uri);
  12227. DEBUG_TRACE("URL: %s", ri->local_uri);
  12228. /* 2. if this ip has limited speed, set it for this connection */
  12229. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12230. get_remote_ip(conn),
  12231. ri->local_uri);
  12232. /* 3. call a "handle everything" callback, if registered */
  12233. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12234. /* Note that since V1.7 the "begin_request" function is called
  12235. * before an authorization check. If an authorization check is
  12236. * required, use a request_handler instead. */
  12237. i = conn->phys_ctx->callbacks.begin_request(conn);
  12238. if (i > 0) {
  12239. /* callback already processed the request. Store the
  12240. return value as a status code for the access log. */
  12241. conn->status_code = i;
  12242. if (!conn->must_close) {
  12243. discard_unread_request_data(conn);
  12244. }
  12245. return;
  12246. } else if (i == 0) {
  12247. /* civetweb should process the request */
  12248. } else {
  12249. /* unspecified - may change with the next version */
  12250. return;
  12251. }
  12252. }
  12253. /* request not yet handled by a handler or redirect, so the request
  12254. * is processed here */
  12255. /* 4. Check for CORS preflight requests and handle them (if configured).
  12256. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12257. */
  12258. if (!strcmp(ri->request_method, "OPTIONS")) {
  12259. /* Send a response to CORS preflights only if
  12260. * access_control_allow_methods is not NULL and not an empty string.
  12261. * In this case, scripts can still handle CORS. */
  12262. const char *cors_meth_cfg =
  12263. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12264. const char *cors_orig_cfg =
  12265. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12266. const char *cors_origin =
  12267. get_header(ri->http_headers, ri->num_headers, "Origin");
  12268. const char *cors_acrm = get_header(ri->http_headers,
  12269. ri->num_headers,
  12270. "Access-Control-Request-Method");
  12271. /* Todo: check if cors_origin is in cors_orig_cfg.
  12272. * Or, let the client check this. */
  12273. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12274. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12275. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12276. /* This is a valid CORS preflight, and the server is configured
  12277. * to
  12278. * handle it automatically. */
  12279. const char *cors_acrh =
  12280. get_header(ri->http_headers,
  12281. ri->num_headers,
  12282. "Access-Control-Request-Headers");
  12283. gmt_time_string(date, sizeof(date), &curtime);
  12284. mg_printf(conn,
  12285. "HTTP/1.1 200 OK\r\n"
  12286. "Date: %s\r\n"
  12287. "Access-Control-Allow-Origin: %s\r\n"
  12288. "Access-Control-Allow-Methods: %s\r\n"
  12289. "Content-Length: 0\r\n"
  12290. "Connection: %s\r\n",
  12291. date,
  12292. cors_orig_cfg,
  12293. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12294. suggest_connection_header(conn));
  12295. if (cors_acrh != NULL) {
  12296. /* CORS request is asking for additional headers */
  12297. const char *cors_hdr_cfg =
  12298. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12299. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12300. /* Allow only if access_control_allow_headers is
  12301. * not NULL and not an empty string. If this
  12302. * configuration is set to *, allow everything.
  12303. * Otherwise this configuration must be a list
  12304. * of allowed HTTP header names. */
  12305. mg_printf(conn,
  12306. "Access-Control-Allow-Headers: %s\r\n",
  12307. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12308. : cors_hdr_cfg));
  12309. }
  12310. }
  12311. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12312. mg_printf(conn, "\r\n");
  12313. return;
  12314. }
  12315. }
  12316. /* 5. interpret the url to find out how the request must be handled
  12317. */
  12318. /* 5.1. first test, if the request targets the regular http(s)://
  12319. * protocol namespace or the websocket ws(s):// protocol namespace.
  12320. */
  12321. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12322. #if defined(USE_WEBSOCKET)
  12323. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12324. #else
  12325. handler_type = REQUEST_HANDLER;
  12326. #endif /* defined(USE_WEBSOCKET) */
  12327. /* 5.2. check if the request will be handled by a callback */
  12328. if (get_request_handler(conn,
  12329. handler_type,
  12330. &callback_handler,
  12331. &subprotocols,
  12332. &ws_connect_handler,
  12333. &ws_ready_handler,
  12334. &ws_data_handler,
  12335. &ws_close_handler,
  12336. NULL,
  12337. &callback_data,
  12338. &handler_info)) {
  12339. /* 5.2.1. A callback will handle this request. All requests
  12340. * handled
  12341. * by a callback have to be considered as requests to a script
  12342. * resource. */
  12343. is_callback_resource = 1;
  12344. is_script_resource = 1;
  12345. is_put_or_delete_request = is_put_or_delete_method(conn);
  12346. } else {
  12347. no_callback_resource:
  12348. /* 5.2.2. No callback is responsible for this request. The URI
  12349. * addresses a file based resource (static content or Lua/cgi
  12350. * scripts in the file system). */
  12351. is_callback_resource = 0;
  12352. interpret_uri(conn,
  12353. path,
  12354. sizeof(path),
  12355. &file.stat,
  12356. &is_found,
  12357. &is_script_resource,
  12358. &is_websocket_request,
  12359. &is_put_or_delete_request);
  12360. }
  12361. /* 6. authorization check */
  12362. /* 6.1. a custom authorization handler is installed */
  12363. if (get_request_handler(conn,
  12364. AUTH_HANDLER,
  12365. NULL,
  12366. NULL,
  12367. NULL,
  12368. NULL,
  12369. NULL,
  12370. NULL,
  12371. &auth_handler,
  12372. &auth_callback_data,
  12373. NULL)) {
  12374. if (!auth_handler(conn, auth_callback_data)) {
  12375. return;
  12376. }
  12377. } else if (is_put_or_delete_request && !is_script_resource
  12378. && !is_callback_resource) {
  12379. /* 6.2. this request is a PUT/DELETE to a real file */
  12380. /* 6.2.1. thus, the server must have real files */
  12381. #if defined(NO_FILES)
  12382. if (1) {
  12383. #else
  12384. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12385. #endif
  12386. /* This server does not have any real files, thus the
  12387. * PUT/DELETE methods are not valid. */
  12388. mg_send_http_error(conn,
  12389. 405,
  12390. "%s method not allowed",
  12391. conn->request_info.request_method);
  12392. return;
  12393. }
  12394. #if !defined(NO_FILES)
  12395. /* 6.2.2. Check if put authorization for static files is
  12396. * available.
  12397. */
  12398. if (!is_authorized_for_put(conn)) {
  12399. send_authorization_request(conn, NULL);
  12400. return;
  12401. }
  12402. #endif
  12403. } else {
  12404. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12405. * or it is a PUT or DELETE request to a resource that does not
  12406. * correspond to a file. Check authorization. */
  12407. if (!check_authorization(conn, path)) {
  12408. send_authorization_request(conn, NULL);
  12409. return;
  12410. }
  12411. }
  12412. /* request is authorized or does not need authorization */
  12413. /* 7. check if there are request handlers for this uri */
  12414. if (is_callback_resource) {
  12415. if (!is_websocket_request) {
  12416. i = callback_handler(conn, callback_data);
  12417. /* Callback handler will not be used anymore. Release it */
  12418. mg_lock_context(conn->phys_ctx);
  12419. handler_info->refcount--;
  12420. mg_unlock_context(conn->phys_ctx);
  12421. if (i > 0) {
  12422. /* Do nothing, callback has served the request. Store
  12423. * then return value as status code for the log and discard
  12424. * all data from the client not used by the callback. */
  12425. conn->status_code = i;
  12426. if (!conn->must_close) {
  12427. discard_unread_request_data(conn);
  12428. }
  12429. } else {
  12430. /* The handler did NOT handle the request. */
  12431. /* Some proper reactions would be:
  12432. * a) close the connections without sending anything
  12433. * b) send a 404 not found
  12434. * c) try if there is a file matching the URI
  12435. * It would be possible to do a, b or c in the callback
  12436. * implementation, and return 1 - we cannot do anything
  12437. * here, that is not possible in the callback.
  12438. *
  12439. * TODO: What would be the best reaction here?
  12440. * (Note: The reaction may change, if there is a better
  12441. *idea.)
  12442. */
  12443. /* For the moment, use option c: We look for a proper file,
  12444. * but since a file request is not always a script resource,
  12445. * the authorization check might be different. */
  12446. interpret_uri(conn,
  12447. path,
  12448. sizeof(path),
  12449. &file.stat,
  12450. &is_found,
  12451. &is_script_resource,
  12452. &is_websocket_request,
  12453. &is_put_or_delete_request);
  12454. callback_handler = NULL;
  12455. /* Here we are at a dead end:
  12456. * According to URI matching, a callback should be
  12457. * responsible for handling the request,
  12458. * we called it, but the callback declared itself
  12459. * not responsible.
  12460. * We use a goto here, to get out of this dead end,
  12461. * and continue with the default handling.
  12462. * A goto here is simpler and better to understand
  12463. * than some curious loop. */
  12464. goto no_callback_resource;
  12465. }
  12466. } else {
  12467. #if defined(USE_WEBSOCKET)
  12468. handle_websocket_request(conn,
  12469. path,
  12470. is_callback_resource,
  12471. subprotocols,
  12472. ws_connect_handler,
  12473. ws_ready_handler,
  12474. ws_data_handler,
  12475. ws_close_handler,
  12476. callback_data);
  12477. #endif
  12478. }
  12479. return;
  12480. }
  12481. /* 8. handle websocket requests */
  12482. #if defined(USE_WEBSOCKET)
  12483. if (is_websocket_request) {
  12484. if (is_script_resource) {
  12485. if (is_in_script_path(conn, path)) {
  12486. /* Websocket Lua script */
  12487. handle_websocket_request(conn,
  12488. path,
  12489. 0 /* Lua Script */,
  12490. NULL,
  12491. NULL,
  12492. NULL,
  12493. NULL,
  12494. NULL,
  12495. conn->phys_ctx->user_data);
  12496. } else {
  12497. /* Script was in an illegal path */
  12498. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12499. }
  12500. } else {
  12501. #if defined(MG_LEGACY_INTERFACE)
  12502. handle_websocket_request(
  12503. conn,
  12504. path,
  12505. !is_script_resource /* could be deprecated global callback
  12506. */
  12507. ,
  12508. NULL,
  12509. deprecated_websocket_connect_wrapper,
  12510. deprecated_websocket_ready_wrapper,
  12511. deprecated_websocket_data_wrapper,
  12512. NULL,
  12513. conn->phys_ctx->callbacks);
  12514. #else
  12515. mg_send_http_error(conn, 404, "%s", "Not found");
  12516. #endif
  12517. }
  12518. return;
  12519. } else
  12520. #endif
  12521. #if defined(NO_FILES)
  12522. /* 9a. In case the server uses only callbacks, this uri is
  12523. * unknown.
  12524. * Then, all request handling ends here. */
  12525. mg_send_http_error(conn, 404, "%s", "Not Found");
  12526. #else
  12527. /* 9b. This request is either for a static file or resource handled
  12528. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12529. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12530. mg_send_http_error(conn, 404, "%s", "Not Found");
  12531. return;
  12532. }
  12533. /* 10. Request is handled by a script */
  12534. if (is_script_resource) {
  12535. handle_file_based_request(conn, path, &file);
  12536. return;
  12537. }
  12538. /* 11. Handle put/delete/mkcol requests */
  12539. if (is_put_or_delete_request) {
  12540. /* 11.1. PUT method */
  12541. if (!strcmp(ri->request_method, "PUT")) {
  12542. put_file(conn, path);
  12543. return;
  12544. }
  12545. /* 11.2. DELETE method */
  12546. if (!strcmp(ri->request_method, "DELETE")) {
  12547. delete_file(conn, path);
  12548. return;
  12549. }
  12550. /* 11.3. MKCOL method */
  12551. if (!strcmp(ri->request_method, "MKCOL")) {
  12552. mkcol(conn, path);
  12553. return;
  12554. }
  12555. /* 11.4. PATCH method
  12556. * This method is not supported for static resources,
  12557. * only for scripts (Lua, CGI) and callbacks. */
  12558. mg_send_http_error(conn,
  12559. 405,
  12560. "%s method not allowed",
  12561. conn->request_info.request_method);
  12562. return;
  12563. }
  12564. /* 11. File does not exist, or it was configured that it should be
  12565. * hidden */
  12566. if (!is_found || (must_hide_file(conn, path))) {
  12567. mg_send_http_error(conn, 404, "%s", "Not found");
  12568. return;
  12569. }
  12570. /* 12. Directory uris should end with a slash */
  12571. if (file.stat.is_directory && (uri_len > 0)
  12572. && (ri->local_uri[uri_len - 1] != '/')) {
  12573. gmt_time_string(date, sizeof(date), &curtime);
  12574. mg_printf(conn,
  12575. "HTTP/1.1 301 Moved Permanently\r\n"
  12576. "Location: %s/\r\n"
  12577. "Date: %s\r\n"
  12578. /* "Cache-Control: private\r\n" (= default) */
  12579. "Content-Length: 0\r\n"
  12580. "Connection: %s\r\n",
  12581. ri->request_uri,
  12582. date,
  12583. suggest_connection_header(conn));
  12584. send_additional_header(conn);
  12585. mg_printf(conn, "\r\n");
  12586. return;
  12587. }
  12588. /* 13. Handle other methods than GET/HEAD */
  12589. /* 13.1. Handle PROPFIND */
  12590. if (!strcmp(ri->request_method, "PROPFIND")) {
  12591. handle_propfind(conn, path, &file.stat);
  12592. return;
  12593. }
  12594. /* 13.2. Handle OPTIONS for files */
  12595. if (!strcmp(ri->request_method, "OPTIONS")) {
  12596. /* This standard handler is only used for real files.
  12597. * Scripts should support the OPTIONS method themselves, to allow a
  12598. * maximum flexibility.
  12599. * Lua and CGI scripts may fully support CORS this way (including
  12600. * preflights). */
  12601. send_options(conn);
  12602. return;
  12603. }
  12604. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12605. if ((0 != strcmp(ri->request_method, "GET"))
  12606. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12607. mg_send_http_error(conn,
  12608. 405,
  12609. "%s method not allowed",
  12610. conn->request_info.request_method);
  12611. return;
  12612. }
  12613. /* 14. directories */
  12614. if (file.stat.is_directory) {
  12615. /* Substitute files have already been handled above. */
  12616. /* Here we can either generate and send a directory listing,
  12617. * or send an "access denied" error. */
  12618. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12619. "yes")) {
  12620. handle_directory_request(conn, path);
  12621. } else {
  12622. mg_send_http_error(conn,
  12623. 403,
  12624. "%s",
  12625. "Error: Directory listing denied");
  12626. }
  12627. return;
  12628. }
  12629. /* 15. read a normal file with GET or HEAD */
  12630. handle_file_based_request(conn, path, &file);
  12631. #endif /* !defined(NO_FILES) */
  12632. }
  12633. /* Include HTTP/2 modules */
  12634. #ifdef USE_HTTP2
  12635. #if defined(NO_SSL)
  12636. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12637. #endif
  12638. #include "mod_http2.inl"
  12639. #endif
  12640. #if !defined(NO_FILESYSTEMS)
  12641. static void
  12642. handle_file_based_request(struct mg_connection *conn,
  12643. const char *path,
  12644. struct mg_file *file)
  12645. {
  12646. if (!conn || !conn->dom_ctx) {
  12647. return;
  12648. }
  12649. if (0) {
  12650. #if defined(USE_LUA)
  12651. } else if (match_prefix(
  12652. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12653. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12654. path)
  12655. > 0) {
  12656. if (is_in_script_path(conn, path)) {
  12657. /* Lua server page: an SSI like page containing mostly plain
  12658. * html
  12659. * code
  12660. * plus some tags with server generated contents. */
  12661. handle_lsp_request(conn, path, file, NULL);
  12662. } else {
  12663. /* Script was in an illegal path */
  12664. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12665. }
  12666. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12667. strlen(
  12668. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12669. path)
  12670. > 0) {
  12671. if (is_in_script_path(conn, path)) {
  12672. /* Lua in-server module script: a CGI like script used to
  12673. * generate
  12674. * the
  12675. * entire reply. */
  12676. mg_exec_lua_script(conn, path, NULL);
  12677. } else {
  12678. /* Script was in an illegal path */
  12679. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12680. }
  12681. #endif
  12682. #if defined(USE_DUKTAPE)
  12683. } else if (match_prefix(
  12684. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12685. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12686. path)
  12687. > 0) {
  12688. if (is_in_script_path(conn, path)) {
  12689. /* Call duktape to generate the page */
  12690. mg_exec_duktape_script(conn, path);
  12691. } else {
  12692. /* Script was in an illegal path */
  12693. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12694. }
  12695. #endif
  12696. #if !defined(NO_CGI)
  12697. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12698. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12699. path)
  12700. > 0) {
  12701. if (is_in_script_path(conn, path)) {
  12702. /* CGI scripts may support all HTTP methods */
  12703. handle_cgi_request(conn, path);
  12704. } else {
  12705. /* Script was in an illegal path */
  12706. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12707. }
  12708. #endif /* !NO_CGI */
  12709. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12710. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12711. path)
  12712. > 0) {
  12713. if (is_in_script_path(conn, path)) {
  12714. handle_ssi_file_request(conn, path, file);
  12715. } else {
  12716. /* Script was in an illegal path */
  12717. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12718. }
  12719. #if !defined(NO_CACHING)
  12720. } else if ((!conn->in_error_handler)
  12721. && is_not_modified(conn, &file->stat)) {
  12722. /* Send 304 "Not Modified" - this must not send any body data */
  12723. handle_not_modified_static_file_request(conn, file);
  12724. #endif /* !NO_CACHING */
  12725. } else {
  12726. handle_static_file_request(conn, path, file, NULL, NULL);
  12727. }
  12728. }
  12729. #endif /* NO_FILESYSTEMS */
  12730. static void
  12731. close_all_listening_sockets(struct mg_context *ctx)
  12732. {
  12733. unsigned int i;
  12734. if (!ctx) {
  12735. return;
  12736. }
  12737. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12738. closesocket(ctx->listening_sockets[i].sock);
  12739. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12740. }
  12741. mg_free(ctx->listening_sockets);
  12742. ctx->listening_sockets = NULL;
  12743. mg_free(ctx->listening_socket_fds);
  12744. ctx->listening_socket_fds = NULL;
  12745. }
  12746. /* Valid listening port specification is: [ip_address:]port[s]
  12747. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12748. * Examples for IPv6: [::]:80, [::1]:80,
  12749. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12750. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12751. * In order to bind to both, IPv4 and IPv6, you can either add
  12752. * both ports using 8080,[::]:8080, or the short form +8080.
  12753. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12754. * one only accepting IPv4 the other only IPv6. +8080 creates
  12755. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12756. * environment, they might work differently, or might not work
  12757. * at all - it must be tested what options work best in the
  12758. * relevant network environment.
  12759. */
  12760. static int
  12761. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12762. {
  12763. unsigned int a, b, c, d;
  12764. unsigned port;
  12765. unsigned long portUL;
  12766. int ch, len;
  12767. const char *cb;
  12768. char *endptr;
  12769. #if defined(USE_IPV6)
  12770. char buf[100] = {0};
  12771. #endif
  12772. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12773. * Also, all-zeroes in the socket address means binding to all addresses
  12774. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12775. memset(so, 0, sizeof(*so));
  12776. so->lsa.sin.sin_family = AF_INET;
  12777. *ip_version = 0;
  12778. /* Initialize len as invalid. */
  12779. port = 0;
  12780. len = 0;
  12781. /* Test for different ways to format this string */
  12782. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12783. == 5) {
  12784. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12785. so->lsa.sin.sin_addr.s_addr =
  12786. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12787. so->lsa.sin.sin_port = htons((uint16_t)port);
  12788. *ip_version = 4;
  12789. #if defined(USE_IPV6)
  12790. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12791. && ((size_t)len <= vec->len)
  12792. && mg_inet_pton(
  12793. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12794. /* IPv6 address, examples: see above */
  12795. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12796. */
  12797. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12798. *ip_version = 6;
  12799. #endif
  12800. } else if ((vec->ptr[0] == '+')
  12801. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12802. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12803. /* Add 1 to len for the + character we skipped before */
  12804. len++;
  12805. #if defined(USE_IPV6)
  12806. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12807. so->lsa.sin6.sin6_family = AF_INET6;
  12808. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12809. *ip_version = 4 + 6;
  12810. #else
  12811. /* Bind to IPv4 only, since IPv6 is not built in. */
  12812. so->lsa.sin.sin_port = htons((uint16_t)port);
  12813. *ip_version = 4;
  12814. #endif
  12815. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12816. && (vec->ptr != endptr)) {
  12817. len = (int)(endptr - vec->ptr);
  12818. port = (uint16_t)portUL;
  12819. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12820. so->lsa.sin.sin_port = htons((uint16_t)port);
  12821. *ip_version = 4;
  12822. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12823. /* String could be a hostname. This check algotithm
  12824. * will only work for RFC 952 compliant hostnames,
  12825. * starting with a letter, containing only letters,
  12826. * digits and hyphen ('-'). Newer specs may allow
  12827. * more, but this is not guaranteed here, since it
  12828. * may interfere with rules for port option lists. */
  12829. /* According to RFC 1035, hostnames are restricted to 255 characters
  12830. * in total (63 between two dots). */
  12831. char hostname[256];
  12832. size_t hostnlen = (size_t)(cb - vec->ptr);
  12833. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12834. /* This would be invalid in any case */
  12835. *ip_version = 0;
  12836. return 0;
  12837. }
  12838. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12839. if (mg_inet_pton(
  12840. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12841. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12842. *ip_version = 4;
  12843. so->lsa.sin.sin_port = htons((uint16_t)port);
  12844. len += (int)(hostnlen + 1);
  12845. } else {
  12846. len = 0;
  12847. }
  12848. #if defined(USE_IPV6)
  12849. } else if (mg_inet_pton(AF_INET6,
  12850. hostname,
  12851. &so->lsa.sin6,
  12852. sizeof(so->lsa.sin6),
  12853. 1)) {
  12854. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12855. *ip_version = 6;
  12856. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12857. len += (int)(hostnlen + 1);
  12858. } else {
  12859. len = 0;
  12860. }
  12861. #endif
  12862. } else {
  12863. len = 0;
  12864. }
  12865. } else {
  12866. /* Parsing failure. */
  12867. len = 0;
  12868. }
  12869. /* sscanf and the option splitting code ensure the following condition
  12870. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12871. if ((len > 0) && is_valid_port(port)
  12872. && (((size_t)len == vec->len) || ((size_t)(len + 1) == vec->len))) {
  12873. /* Next character after the port number */
  12874. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12875. so->is_ssl = (ch == 's');
  12876. so->ssl_redir = (ch == 'r');
  12877. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12878. return 1;
  12879. }
  12880. }
  12881. /* Reset ip_version to 0 if there is an error */
  12882. *ip_version = 0;
  12883. return 0;
  12884. }
  12885. /* Is there any SSL port in use? */
  12886. static int
  12887. is_ssl_port_used(const char *ports)
  12888. {
  12889. if (ports) {
  12890. /* There are several different allowed syntax variants:
  12891. * - "80" for a single port using every network interface
  12892. * - "localhost:80" for a single port using only localhost
  12893. * - "80,localhost:8080" for two ports, one bound to localhost
  12894. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12895. * to IPv4 localhost, one to IPv6 localhost
  12896. * - "+80" use port 80 for IPv4 and IPv6
  12897. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12898. * for both: IPv4 and IPv4
  12899. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12900. * additionally port 8080 bound to localhost connections
  12901. *
  12902. * If we just look for 's' anywhere in the string, "localhost:80"
  12903. * will be detected as SSL (false positive).
  12904. * Looking for 's' after a digit may cause false positives in
  12905. * "my24service:8080".
  12906. * Looking from 's' backward if there are only ':' and numbers
  12907. * before will not work for "24service:8080" (non SSL, port 8080)
  12908. * or "24s" (SSL, port 24).
  12909. *
  12910. * Remark: Initially hostnames were not allowed to start with a
  12911. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12912. * Section 2.1).
  12913. *
  12914. * To get this correct, the entire string must be parsed as a whole,
  12915. * reading it as a list element for element and parsing with an
  12916. * algorithm equivalent to parse_port_string.
  12917. *
  12918. * In fact, we use local interface names here, not arbitrary
  12919. * hostnames, so in most cases the only name will be "localhost".
  12920. *
  12921. * So, for now, we use this simple algorithm, that may still return
  12922. * a false positive in bizarre cases.
  12923. */
  12924. int i;
  12925. int portslen = (int)strlen(ports);
  12926. char prevIsNumber = 0;
  12927. for (i = 0; i < portslen; i++) {
  12928. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12929. return 1;
  12930. }
  12931. if (ports[i] >= '0' && ports[i] <= '9') {
  12932. prevIsNumber = 1;
  12933. } else {
  12934. prevIsNumber = 0;
  12935. }
  12936. }
  12937. }
  12938. return 0;
  12939. }
  12940. static int
  12941. set_ports_option(struct mg_context *phys_ctx)
  12942. {
  12943. const char *list;
  12944. int on = 1;
  12945. #if defined(USE_IPV6)
  12946. int off = 0;
  12947. #endif
  12948. struct vec vec;
  12949. struct socket so, *ptr;
  12950. struct mg_pollfd *pfd;
  12951. union usa usa;
  12952. socklen_t len;
  12953. int ip_version;
  12954. int portsTotal = 0;
  12955. int portsOk = 0;
  12956. const char *opt_txt;
  12957. long opt_listen_backlog;
  12958. if (!phys_ctx) {
  12959. return 0;
  12960. }
  12961. memset(&so, 0, sizeof(so));
  12962. memset(&usa, 0, sizeof(usa));
  12963. len = sizeof(usa);
  12964. list = phys_ctx->dd.config[LISTENING_PORTS];
  12965. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12966. portsTotal++;
  12967. if (!parse_port_string(&vec, &so, &ip_version)) {
  12968. mg_cry_ctx_internal(
  12969. phys_ctx,
  12970. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12971. (int)vec.len,
  12972. vec.ptr,
  12973. portsTotal,
  12974. "[IP_ADDRESS:]PORT[s|r]");
  12975. continue;
  12976. }
  12977. #if !defined(NO_SSL)
  12978. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12979. mg_cry_ctx_internal(phys_ctx,
  12980. "Cannot add SSL socket (entry %i)",
  12981. portsTotal);
  12982. continue;
  12983. }
  12984. #endif
  12985. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12986. == INVALID_SOCKET) {
  12987. mg_cry_ctx_internal(phys_ctx,
  12988. "cannot create socket (entry %i)",
  12989. portsTotal);
  12990. continue;
  12991. }
  12992. #if defined(_WIN32)
  12993. /* Windows SO_REUSEADDR lets many procs binds to a
  12994. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12995. * if someone already has the socket -- DTL */
  12996. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12997. * Windows might need a few seconds before
  12998. * the same port can be used again in the
  12999. * same process, so a short Sleep may be
  13000. * required between mg_stop and mg_start.
  13001. */
  13002. if (setsockopt(so.sock,
  13003. SOL_SOCKET,
  13004. SO_EXCLUSIVEADDRUSE,
  13005. (SOCK_OPT_TYPE)&on,
  13006. sizeof(on))
  13007. != 0) {
  13008. /* Set reuse option, but don't abort on errors. */
  13009. mg_cry_ctx_internal(
  13010. phys_ctx,
  13011. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13012. portsTotal);
  13013. }
  13014. #else
  13015. if (setsockopt(so.sock,
  13016. SOL_SOCKET,
  13017. SO_REUSEADDR,
  13018. (SOCK_OPT_TYPE)&on,
  13019. sizeof(on))
  13020. != 0) {
  13021. /* Set reuse option, but don't abort on errors. */
  13022. mg_cry_ctx_internal(
  13023. phys_ctx,
  13024. "cannot set socket option SO_REUSEADDR (entry %i)",
  13025. portsTotal);
  13026. }
  13027. #endif
  13028. if (ip_version > 4) {
  13029. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13030. #if defined(USE_IPV6)
  13031. if (ip_version > 6) {
  13032. if (so.lsa.sa.sa_family == AF_INET6
  13033. && setsockopt(so.sock,
  13034. IPPROTO_IPV6,
  13035. IPV6_V6ONLY,
  13036. (void *)&off,
  13037. sizeof(off))
  13038. != 0) {
  13039. /* Set IPv6 only option, but don't abort on errors. */
  13040. mg_cry_ctx_internal(phys_ctx,
  13041. "cannot set socket option "
  13042. "IPV6_V6ONLY=off (entry %i)",
  13043. portsTotal);
  13044. }
  13045. } else {
  13046. if (so.lsa.sa.sa_family == AF_INET6
  13047. && setsockopt(so.sock,
  13048. IPPROTO_IPV6,
  13049. IPV6_V6ONLY,
  13050. (void *)&on,
  13051. sizeof(on))
  13052. != 0) {
  13053. /* Set IPv6 only option, but don't abort on errors. */
  13054. mg_cry_ctx_internal(phys_ctx,
  13055. "cannot set socket option "
  13056. "IPV6_V6ONLY=on (entry %i)",
  13057. portsTotal);
  13058. }
  13059. }
  13060. #else
  13061. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13062. closesocket(so.sock);
  13063. so.sock = INVALID_SOCKET;
  13064. continue;
  13065. #endif
  13066. }
  13067. if (so.lsa.sa.sa_family == AF_INET) {
  13068. len = sizeof(so.lsa.sin);
  13069. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13070. mg_cry_ctx_internal(phys_ctx,
  13071. "cannot bind to %.*s: %d (%s)",
  13072. (int)vec.len,
  13073. vec.ptr,
  13074. (int)ERRNO,
  13075. strerror(errno));
  13076. closesocket(so.sock);
  13077. so.sock = INVALID_SOCKET;
  13078. continue;
  13079. }
  13080. }
  13081. #if defined(USE_IPV6)
  13082. else if (so.lsa.sa.sa_family == AF_INET6) {
  13083. len = sizeof(so.lsa.sin6);
  13084. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13085. mg_cry_ctx_internal(phys_ctx,
  13086. "cannot bind to IPv6 %.*s: %d (%s)",
  13087. (int)vec.len,
  13088. vec.ptr,
  13089. (int)ERRNO,
  13090. strerror(errno));
  13091. closesocket(so.sock);
  13092. so.sock = INVALID_SOCKET;
  13093. continue;
  13094. }
  13095. }
  13096. #endif
  13097. else {
  13098. mg_cry_ctx_internal(
  13099. phys_ctx,
  13100. "cannot bind: address family not supported (entry %i)",
  13101. portsTotal);
  13102. closesocket(so.sock);
  13103. so.sock = INVALID_SOCKET;
  13104. continue;
  13105. }
  13106. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13107. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13108. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13109. mg_cry_ctx_internal(phys_ctx,
  13110. "%s value \"%s\" is invalid",
  13111. config_options[LISTEN_BACKLOG_SIZE].name,
  13112. opt_txt);
  13113. closesocket(so.sock);
  13114. so.sock = INVALID_SOCKET;
  13115. continue;
  13116. }
  13117. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13118. mg_cry_ctx_internal(phys_ctx,
  13119. "cannot listen to %.*s: %d (%s)",
  13120. (int)vec.len,
  13121. vec.ptr,
  13122. (int)ERRNO,
  13123. strerror(errno));
  13124. closesocket(so.sock);
  13125. so.sock = INVALID_SOCKET;
  13126. continue;
  13127. }
  13128. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13129. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13130. int err = (int)ERRNO;
  13131. mg_cry_ctx_internal(phys_ctx,
  13132. "call to getsockname failed %.*s: %d (%s)",
  13133. (int)vec.len,
  13134. vec.ptr,
  13135. err,
  13136. strerror(errno));
  13137. closesocket(so.sock);
  13138. so.sock = INVALID_SOCKET;
  13139. continue;
  13140. }
  13141. /* Update lsa port in case of random free ports */
  13142. #if defined(USE_IPV6)
  13143. if (so.lsa.sa.sa_family == AF_INET6) {
  13144. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13145. } else
  13146. #endif
  13147. {
  13148. so.lsa.sin.sin_port = usa.sin.sin_port;
  13149. }
  13150. if ((ptr = (struct socket *)
  13151. mg_realloc_ctx(phys_ctx->listening_sockets,
  13152. (phys_ctx->num_listening_sockets + 1)
  13153. * sizeof(phys_ctx->listening_sockets[0]),
  13154. phys_ctx))
  13155. == NULL) {
  13156. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13157. closesocket(so.sock);
  13158. so.sock = INVALID_SOCKET;
  13159. continue;
  13160. }
  13161. if ((pfd = (struct mg_pollfd *)
  13162. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13163. (phys_ctx->num_listening_sockets + 1)
  13164. * sizeof(phys_ctx->listening_socket_fds[0]),
  13165. phys_ctx))
  13166. == NULL) {
  13167. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13168. closesocket(so.sock);
  13169. so.sock = INVALID_SOCKET;
  13170. mg_free(ptr);
  13171. continue;
  13172. }
  13173. set_close_on_exec(so.sock, NULL, phys_ctx);
  13174. phys_ctx->listening_sockets = ptr;
  13175. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13176. phys_ctx->listening_socket_fds = pfd;
  13177. phys_ctx->num_listening_sockets++;
  13178. portsOk++;
  13179. }
  13180. if (portsOk != portsTotal) {
  13181. close_all_listening_sockets(phys_ctx);
  13182. portsOk = 0;
  13183. }
  13184. return portsOk;
  13185. }
  13186. static const char *
  13187. header_val(const struct mg_connection *conn, const char *header)
  13188. {
  13189. const char *header_value;
  13190. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13191. return "-";
  13192. } else {
  13193. return header_value;
  13194. }
  13195. }
  13196. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13197. static void log_access(const struct mg_connection *conn);
  13198. #include "external_log_access.inl"
  13199. #elif !defined(NO_FILESYSTEMS)
  13200. static void
  13201. log_access(const struct mg_connection *conn)
  13202. {
  13203. const struct mg_request_info *ri;
  13204. struct mg_file fi;
  13205. char date[64], src_addr[IP_ADDR_STR_LEN];
  13206. struct tm *tm;
  13207. const char *referer;
  13208. const char *user_agent;
  13209. char buf[4096];
  13210. if (!conn || !conn->dom_ctx) {
  13211. return;
  13212. }
  13213. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13214. if (mg_fopen(conn,
  13215. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13216. MG_FOPEN_MODE_APPEND,
  13217. &fi)
  13218. == 0) {
  13219. fi.access.fp = NULL;
  13220. }
  13221. } else {
  13222. fi.access.fp = NULL;
  13223. }
  13224. /* Log is written to a file and/or a callback. If both are not set,
  13225. * executing the rest of the function is pointless. */
  13226. if ((fi.access.fp == NULL)
  13227. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13228. return;
  13229. }
  13230. tm = localtime(&conn->conn_birth_time);
  13231. if (tm != NULL) {
  13232. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13233. } else {
  13234. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13235. date[sizeof(date) - 1] = '\0';
  13236. }
  13237. ri = &conn->request_info;
  13238. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13239. referer = header_val(conn, "Referer");
  13240. user_agent = header_val(conn, "User-Agent");
  13241. mg_snprintf(conn,
  13242. NULL, /* Ignore truncation in access log */
  13243. buf,
  13244. sizeof(buf),
  13245. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13246. src_addr,
  13247. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13248. date,
  13249. ri->request_method ? ri->request_method : "-",
  13250. ri->request_uri ? ri->request_uri : "-",
  13251. ri->query_string ? "?" : "",
  13252. ri->query_string ? ri->query_string : "",
  13253. ri->http_version,
  13254. conn->status_code,
  13255. conn->num_bytes_sent,
  13256. referer,
  13257. user_agent);
  13258. if (conn->phys_ctx->callbacks.log_access) {
  13259. conn->phys_ctx->callbacks.log_access(conn, buf);
  13260. }
  13261. if (fi.access.fp) {
  13262. int ok = 1;
  13263. flockfile(fi.access.fp);
  13264. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13265. ok = 0;
  13266. }
  13267. if (fflush(fi.access.fp) != 0) {
  13268. ok = 0;
  13269. }
  13270. funlockfile(fi.access.fp);
  13271. if (mg_fclose(&fi.access) != 0) {
  13272. ok = 0;
  13273. }
  13274. if (!ok) {
  13275. mg_cry_internal(conn,
  13276. "Error writing log file %s",
  13277. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13278. }
  13279. }
  13280. }
  13281. #else
  13282. #error Must either enable filesystems or provide a custom log_access implementation
  13283. #endif /* Externally provided function */
  13284. /* Verify given socket address against the ACL.
  13285. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13286. */
  13287. static int
  13288. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13289. {
  13290. int allowed, flag;
  13291. uint32_t net, mask;
  13292. struct vec vec;
  13293. if (phys_ctx) {
  13294. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13295. /* If any ACL is set, deny by default */
  13296. allowed = (list == NULL) ? '+' : '-';
  13297. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13298. flag = vec.ptr[0];
  13299. if ((flag != '+' && flag != '-')
  13300. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13301. mg_cry_ctx_internal(phys_ctx,
  13302. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13303. __func__);
  13304. return -1;
  13305. }
  13306. if (net == (remote_ip & mask)) {
  13307. allowed = flag;
  13308. }
  13309. }
  13310. return allowed == '+';
  13311. }
  13312. return -1;
  13313. }
  13314. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13315. static int
  13316. set_uid_option(struct mg_context *phys_ctx)
  13317. {
  13318. int success = 0;
  13319. if (phys_ctx) {
  13320. /* We are currently running as curr_uid. */
  13321. const uid_t curr_uid = getuid();
  13322. /* If set, we want to run as run_as_user. */
  13323. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13324. const struct passwd *to_pw = NULL;
  13325. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13326. /* run_as_user does not exist on the system. We can't proceed
  13327. * further. */
  13328. mg_cry_ctx_internal(phys_ctx,
  13329. "%s: unknown user [%s]",
  13330. __func__,
  13331. run_as_user);
  13332. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13333. /* There was either no request to change user, or we're already
  13334. * running as run_as_user. Nothing else to do.
  13335. */
  13336. success = 1;
  13337. } else {
  13338. /* Valid change request. */
  13339. if (setgid(to_pw->pw_gid) == -1) {
  13340. mg_cry_ctx_internal(phys_ctx,
  13341. "%s: setgid(%s): %s",
  13342. __func__,
  13343. run_as_user,
  13344. strerror(errno));
  13345. } else if (setgroups(0, NULL) == -1) {
  13346. mg_cry_ctx_internal(phys_ctx,
  13347. "%s: setgroups(): %s",
  13348. __func__,
  13349. strerror(errno));
  13350. } else if (setuid(to_pw->pw_uid) == -1) {
  13351. mg_cry_ctx_internal(phys_ctx,
  13352. "%s: setuid(%s): %s",
  13353. __func__,
  13354. run_as_user,
  13355. strerror(errno));
  13356. } else {
  13357. success = 1;
  13358. }
  13359. }
  13360. }
  13361. return success;
  13362. }
  13363. #endif /* !_WIN32 */
  13364. static void
  13365. tls_dtor(void *key)
  13366. {
  13367. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13368. /* key == pthread_getspecific(sTlsKey); */
  13369. if (tls) {
  13370. if (tls->is_master == 2) {
  13371. tls->is_master = -3; /* Mark memory as dead */
  13372. mg_free(tls);
  13373. }
  13374. }
  13375. pthread_setspecific(sTlsKey, NULL);
  13376. }
  13377. #if !defined(NO_SSL)
  13378. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13379. struct mg_domain_context *dom_ctx,
  13380. const char *pem,
  13381. const char *chain);
  13382. static const char *ssl_error(void);
  13383. static int
  13384. refresh_trust(struct mg_connection *conn)
  13385. {
  13386. struct stat cert_buf;
  13387. int64_t t = 0;
  13388. const char *pem;
  13389. const char *chain;
  13390. int should_verify_peer;
  13391. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13392. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13393. * refresh_trust still can not work. */
  13394. return 0;
  13395. }
  13396. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13397. if (chain == NULL) {
  13398. /* pem is not NULL here */
  13399. chain = pem;
  13400. }
  13401. if (*chain == 0) {
  13402. chain = NULL;
  13403. }
  13404. if (stat(pem, &cert_buf) != -1) {
  13405. t = (int64_t)cert_buf.st_mtime;
  13406. }
  13407. mg_lock_context(conn->phys_ctx);
  13408. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13409. conn->dom_ctx->ssl_cert_last_mtime = t;
  13410. should_verify_peer = 0;
  13411. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13412. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13413. == 0) {
  13414. should_verify_peer = 1;
  13415. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13416. "optional")
  13417. == 0) {
  13418. should_verify_peer = 1;
  13419. }
  13420. }
  13421. if (should_verify_peer) {
  13422. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13423. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13424. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13425. ca_file,
  13426. ca_path)
  13427. != 1) {
  13428. mg_unlock_context(conn->phys_ctx);
  13429. mg_cry_ctx_internal(
  13430. conn->phys_ctx,
  13431. "SSL_CTX_load_verify_locations error: %s "
  13432. "ssl_verify_peer requires setting "
  13433. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13434. "present in "
  13435. "the .conf file?",
  13436. ssl_error());
  13437. return 0;
  13438. }
  13439. }
  13440. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13441. mg_unlock_context(conn->phys_ctx);
  13442. return 0;
  13443. }
  13444. }
  13445. mg_unlock_context(conn->phys_ctx);
  13446. return 1;
  13447. }
  13448. #if defined(OPENSSL_API_1_1)
  13449. #else
  13450. static pthread_mutex_t *ssl_mutexes;
  13451. #endif /* OPENSSL_API_1_1 */
  13452. static int
  13453. sslize(struct mg_connection *conn,
  13454. int (*func)(SSL *),
  13455. const struct mg_client_options *client_options)
  13456. {
  13457. int ret, err;
  13458. int short_trust;
  13459. unsigned timeout = 1024;
  13460. unsigned i;
  13461. if (!conn) {
  13462. return 0;
  13463. }
  13464. short_trust =
  13465. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13466. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13467. if (short_trust) {
  13468. int trust_ret = refresh_trust(conn);
  13469. if (!trust_ret) {
  13470. return trust_ret;
  13471. }
  13472. }
  13473. mg_lock_context(conn->phys_ctx);
  13474. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13475. mg_unlock_context(conn->phys_ctx);
  13476. if (conn->ssl == NULL) {
  13477. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13478. OPENSSL_REMOVE_THREAD_STATE();
  13479. return 0;
  13480. }
  13481. SSL_set_app_data(conn->ssl, (char *)conn);
  13482. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13483. if (ret != 1) {
  13484. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13485. SSL_free(conn->ssl);
  13486. conn->ssl = NULL;
  13487. OPENSSL_REMOVE_THREAD_STATE();
  13488. return 0;
  13489. }
  13490. if (client_options) {
  13491. if (client_options->host_name) {
  13492. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13493. }
  13494. }
  13495. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13496. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13497. /* NOTE: The loop below acts as a back-off, so we can end
  13498. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13499. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13500. if (to >= 0) {
  13501. timeout = (unsigned)to;
  13502. }
  13503. }
  13504. /* SSL functions may fail and require to be called again:
  13505. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13506. * Here "func" could be SSL_connect or SSL_accept. */
  13507. for (i = 0; i <= timeout; i += 50) {
  13508. ERR_clear_error();
  13509. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13510. ret = func(conn->ssl);
  13511. if (ret != 1) {
  13512. err = SSL_get_error(conn->ssl, ret);
  13513. if ((err == SSL_ERROR_WANT_CONNECT)
  13514. || (err == SSL_ERROR_WANT_ACCEPT)
  13515. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13516. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13517. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13518. /* Don't wait if the server is going to be stopped. */
  13519. break;
  13520. }
  13521. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13522. /* Simply retry the function call. */
  13523. mg_sleep(50);
  13524. } else {
  13525. /* Need to retry the function call "later".
  13526. * See https://linux.die.net/man/3/ssl_get_error
  13527. * This is typical for non-blocking sockets. */
  13528. struct mg_pollfd pfd;
  13529. int pollres;
  13530. pfd.fd = conn->client.sock;
  13531. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13532. || (err == SSL_ERROR_WANT_WRITE))
  13533. ? POLLOUT
  13534. : POLLIN;
  13535. pollres =
  13536. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13537. if (pollres < 0) {
  13538. /* Break if error occured (-1)
  13539. * or server shutdown (-2) */
  13540. break;
  13541. }
  13542. }
  13543. } else if (err == SSL_ERROR_SYSCALL) {
  13544. /* This is an IO error. Look at errno. */
  13545. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13546. break;
  13547. } else {
  13548. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13549. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13550. break;
  13551. }
  13552. } else {
  13553. /* success */
  13554. break;
  13555. }
  13556. }
  13557. ERR_clear_error();
  13558. if (ret != 1) {
  13559. SSL_free(conn->ssl);
  13560. conn->ssl = NULL;
  13561. OPENSSL_REMOVE_THREAD_STATE();
  13562. return 0;
  13563. }
  13564. return 1;
  13565. }
  13566. /* Return OpenSSL error message (from CRYPTO lib) */
  13567. static const char *
  13568. ssl_error(void)
  13569. {
  13570. unsigned long err;
  13571. err = ERR_get_error();
  13572. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13573. }
  13574. static int
  13575. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13576. {
  13577. int i;
  13578. const char hexdigit[] = "0123456789abcdef";
  13579. if ((memlen <= 0) || (buflen <= 0)) {
  13580. return 0;
  13581. }
  13582. if (buflen < (3 * memlen)) {
  13583. return 0;
  13584. }
  13585. for (i = 0; i < memlen; i++) {
  13586. if (i > 0) {
  13587. buf[3 * i - 1] = ' ';
  13588. }
  13589. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13590. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13591. }
  13592. buf[3 * memlen - 1] = 0;
  13593. return 1;
  13594. }
  13595. static int
  13596. ssl_get_client_cert_info(const struct mg_connection *conn,
  13597. struct mg_client_cert *client_cert)
  13598. {
  13599. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13600. if (cert) {
  13601. char str_buf[1024];
  13602. unsigned char buf[256];
  13603. char *str_serial = NULL;
  13604. unsigned int ulen;
  13605. int ilen;
  13606. unsigned char *tmp_buf;
  13607. unsigned char *tmp_p;
  13608. /* Handle to algorithm used for fingerprint */
  13609. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13610. /* Get Subject and issuer */
  13611. X509_NAME *subj = X509_get_subject_name(cert);
  13612. X509_NAME *iss = X509_get_issuer_name(cert);
  13613. /* Get serial number */
  13614. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13615. /* Translate serial number to a hex string */
  13616. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13617. if (serial_bn) {
  13618. str_serial = BN_bn2hex(serial_bn);
  13619. BN_free(serial_bn);
  13620. }
  13621. client_cert->serial =
  13622. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13623. /* Translate subject and issuer to a string */
  13624. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13625. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13626. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13627. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13628. /* Calculate SHA1 fingerprint and store as a hex string */
  13629. ulen = 0;
  13630. /* ASN1_digest is deprecated. Do the calculation manually,
  13631. * using EVP_Digest. */
  13632. ilen = i2d_X509(cert, NULL);
  13633. tmp_buf = (ilen > 0)
  13634. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13635. conn->phys_ctx)
  13636. : NULL;
  13637. if (tmp_buf) {
  13638. tmp_p = tmp_buf;
  13639. (void)i2d_X509(cert, &tmp_p);
  13640. if (!EVP_Digest(
  13641. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13642. ulen = 0;
  13643. }
  13644. mg_free(tmp_buf);
  13645. }
  13646. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13647. *str_buf = 0;
  13648. }
  13649. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13650. client_cert->peer_cert = (void *)cert;
  13651. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13652. * see https://linux.die.net/man/3/bn_bn2hex */
  13653. OPENSSL_free(str_serial);
  13654. return 1;
  13655. }
  13656. return 0;
  13657. }
  13658. #if defined(OPENSSL_API_1_1)
  13659. #else
  13660. static void
  13661. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13662. {
  13663. (void)line;
  13664. (void)file;
  13665. if (mode & 1) {
  13666. /* 1 is CRYPTO_LOCK */
  13667. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13668. } else {
  13669. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13670. }
  13671. }
  13672. #endif /* OPENSSL_API_1_1 */
  13673. #if !defined(NO_SSL_DL)
  13674. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13675. static void *
  13676. load_tls_dll(char *ebuf,
  13677. size_t ebuf_len,
  13678. const char *dll_name,
  13679. struct ssl_func *sw)
  13680. {
  13681. union {
  13682. void *p;
  13683. void (*fp)(void);
  13684. } u;
  13685. void *dll_handle;
  13686. struct ssl_func *fp;
  13687. int ok;
  13688. int truncated = 0;
  13689. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13690. mg_snprintf(NULL,
  13691. NULL, /* No truncation check for ebuf */
  13692. ebuf,
  13693. ebuf_len,
  13694. "%s: cannot load %s",
  13695. __func__,
  13696. dll_name);
  13697. return NULL;
  13698. }
  13699. ok = 1;
  13700. for (fp = sw; fp->name != NULL; fp++) {
  13701. enum ssl_func_category req = fp->required;
  13702. #if defined(_WIN32)
  13703. /* GetProcAddress() returns pointer to function */
  13704. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13705. #else
  13706. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13707. * pointers to function pointers. We need to use a union to make a
  13708. * cast. */
  13709. u.p = dlsym(dll_handle, fp->name);
  13710. #endif /* _WIN32 */
  13711. /* Set pointer (might be NULL) */
  13712. fp->ptr = u.fp;
  13713. if (u.fp == NULL) {
  13714. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13715. tls_feature_missing[req]++;
  13716. if (req == TLS_Mandatory) {
  13717. /* Mandatory function is missing */
  13718. if (ok) {
  13719. /* This is the first missing function.
  13720. * Create a new error message. */
  13721. mg_snprintf(NULL,
  13722. &truncated,
  13723. ebuf,
  13724. ebuf_len,
  13725. "%s: %s: cannot find %s",
  13726. __func__,
  13727. dll_name,
  13728. fp->name);
  13729. ok = 0;
  13730. } else {
  13731. /* This is yet anothermissing function.
  13732. * Append existing error message. */
  13733. size_t cur_len = strlen(ebuf);
  13734. if (!truncated) {
  13735. mg_snprintf(NULL,
  13736. &truncated,
  13737. ebuf + cur_len,
  13738. ebuf_len - cur_len - 3,
  13739. ", %s",
  13740. fp->name);
  13741. if (truncated) {
  13742. /* If truncated, add "..." */
  13743. strcat(ebuf, "...");
  13744. }
  13745. }
  13746. }
  13747. }
  13748. }
  13749. }
  13750. if (!ok) {
  13751. (void)dlclose(dll_handle);
  13752. return NULL;
  13753. }
  13754. return dll_handle;
  13755. }
  13756. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13757. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13758. #endif /* NO_SSL_DL */
  13759. #if defined(SSL_ALREADY_INITIALIZED)
  13760. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13761. #else
  13762. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13763. #endif
  13764. static int
  13765. initialize_ssl(char *ebuf, size_t ebuf_len)
  13766. {
  13767. #if defined(OPENSSL_API_1_1)
  13768. if (ebuf_len > 0) {
  13769. ebuf[0] = 0;
  13770. }
  13771. #if !defined(NO_SSL_DL)
  13772. if (!cryptolib_dll_handle) {
  13773. cryptolib_dll_handle =
  13774. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13775. if (!cryptolib_dll_handle) {
  13776. mg_snprintf(NULL,
  13777. NULL, /* No truncation check for ebuf */
  13778. ebuf,
  13779. ebuf_len,
  13780. "%s: error loading library %s",
  13781. __func__,
  13782. CRYPTO_LIB);
  13783. DEBUG_TRACE("%s", ebuf);
  13784. return 0;
  13785. }
  13786. }
  13787. #endif /* NO_SSL_DL */
  13788. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13789. return 1;
  13790. }
  13791. #else /* not OPENSSL_API_1_1 */
  13792. int i, num_locks;
  13793. size_t size;
  13794. if (ebuf_len > 0) {
  13795. ebuf[0] = 0;
  13796. }
  13797. #if !defined(NO_SSL_DL)
  13798. if (!cryptolib_dll_handle) {
  13799. cryptolib_dll_handle =
  13800. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13801. if (!cryptolib_dll_handle) {
  13802. mg_snprintf(NULL,
  13803. NULL, /* No truncation check for ebuf */
  13804. ebuf,
  13805. ebuf_len,
  13806. "%s: error loading library %s",
  13807. __func__,
  13808. CRYPTO_LIB);
  13809. DEBUG_TRACE("%s", ebuf);
  13810. return 0;
  13811. }
  13812. }
  13813. #endif /* NO_SSL_DL */
  13814. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13815. return 1;
  13816. }
  13817. /* Initialize locking callbacks, needed for thread safety.
  13818. * http://www.openssl.org/support/faq.html#PROG1
  13819. */
  13820. num_locks = CRYPTO_num_locks();
  13821. if (num_locks < 0) {
  13822. num_locks = 0;
  13823. }
  13824. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13825. /* allocate mutex array, if required */
  13826. if (num_locks == 0) {
  13827. /* No mutex array required */
  13828. ssl_mutexes = NULL;
  13829. } else {
  13830. /* Mutex array required - allocate it */
  13831. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13832. /* Check OOM */
  13833. if (ssl_mutexes == NULL) {
  13834. mg_snprintf(NULL,
  13835. NULL, /* No truncation check for ebuf */
  13836. ebuf,
  13837. ebuf_len,
  13838. "%s: cannot allocate mutexes: %s",
  13839. __func__,
  13840. ssl_error());
  13841. DEBUG_TRACE("%s", ebuf);
  13842. return 0;
  13843. }
  13844. /* initialize mutex array */
  13845. for (i = 0; i < num_locks; i++) {
  13846. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13847. mg_snprintf(NULL,
  13848. NULL, /* No truncation check for ebuf */
  13849. ebuf,
  13850. ebuf_len,
  13851. "%s: error initializing mutex %i of %i",
  13852. __func__,
  13853. i,
  13854. num_locks);
  13855. DEBUG_TRACE("%s", ebuf);
  13856. mg_free(ssl_mutexes);
  13857. return 0;
  13858. }
  13859. }
  13860. }
  13861. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13862. CRYPTO_set_id_callback(&mg_current_thread_id);
  13863. #endif /* OPENSSL_API_1_1 */
  13864. #if !defined(NO_SSL_DL)
  13865. if (!ssllib_dll_handle) {
  13866. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13867. if (!ssllib_dll_handle) {
  13868. #if !defined(OPENSSL_API_1_1)
  13869. mg_free(ssl_mutexes);
  13870. #endif
  13871. DEBUG_TRACE("%s", ebuf);
  13872. return 0;
  13873. }
  13874. }
  13875. #endif /* NO_SSL_DL */
  13876. #if defined(OPENSSL_API_1_1)
  13877. /* Initialize SSL library */
  13878. OPENSSL_init_ssl(0, NULL);
  13879. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13880. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13881. NULL);
  13882. #else
  13883. /* Initialize SSL library */
  13884. SSL_library_init();
  13885. SSL_load_error_strings();
  13886. #endif
  13887. return 1;
  13888. }
  13889. static int
  13890. ssl_use_pem_file(struct mg_context *phys_ctx,
  13891. struct mg_domain_context *dom_ctx,
  13892. const char *pem,
  13893. const char *chain)
  13894. {
  13895. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13896. mg_cry_ctx_internal(phys_ctx,
  13897. "%s: cannot open certificate file %s: %s",
  13898. __func__,
  13899. pem,
  13900. ssl_error());
  13901. return 0;
  13902. }
  13903. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13904. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13905. mg_cry_ctx_internal(phys_ctx,
  13906. "%s: cannot open private key file %s: %s",
  13907. __func__,
  13908. pem,
  13909. ssl_error());
  13910. return 0;
  13911. }
  13912. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13913. mg_cry_ctx_internal(phys_ctx,
  13914. "%s: certificate and private key do not match: %s",
  13915. __func__,
  13916. pem);
  13917. return 0;
  13918. }
  13919. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13920. * chain files that contain private keys and certificates in
  13921. * SSL_CTX_use_certificate_chain_file.
  13922. * The CivetWeb-Server used pem-Files that contained both information.
  13923. * In order to make wolfSSL work, it is split in two files.
  13924. * One file that contains key and certificate used by the server and
  13925. * an optional chain file for the ssl stack.
  13926. */
  13927. if (chain) {
  13928. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13929. mg_cry_ctx_internal(phys_ctx,
  13930. "%s: cannot use certificate chain file %s: %s",
  13931. __func__,
  13932. chain,
  13933. ssl_error());
  13934. return 0;
  13935. }
  13936. }
  13937. return 1;
  13938. }
  13939. #if defined(OPENSSL_API_1_1)
  13940. static unsigned long
  13941. ssl_get_protocol(int version_id)
  13942. {
  13943. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13944. if (version_id > 0)
  13945. ret |= SSL_OP_NO_SSLv2;
  13946. if (version_id > 1)
  13947. ret |= SSL_OP_NO_SSLv3;
  13948. if (version_id > 2)
  13949. ret |= SSL_OP_NO_TLSv1;
  13950. if (version_id > 3)
  13951. ret |= SSL_OP_NO_TLSv1_1;
  13952. if (version_id > 4)
  13953. ret |= SSL_OP_NO_TLSv1_2;
  13954. #if defined(SSL_OP_NO_TLSv1_3)
  13955. if (version_id > 5)
  13956. ret |= SSL_OP_NO_TLSv1_3;
  13957. #endif
  13958. return ret;
  13959. }
  13960. #else
  13961. static long
  13962. ssl_get_protocol(int version_id)
  13963. {
  13964. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13965. if (version_id > 0)
  13966. ret |= SSL_OP_NO_SSLv2;
  13967. if (version_id > 1)
  13968. ret |= SSL_OP_NO_SSLv3;
  13969. if (version_id > 2)
  13970. ret |= SSL_OP_NO_TLSv1;
  13971. if (version_id > 3)
  13972. ret |= SSL_OP_NO_TLSv1_1;
  13973. if (version_id > 4)
  13974. ret |= SSL_OP_NO_TLSv1_2;
  13975. #if defined(SSL_OP_NO_TLSv1_3)
  13976. if (version_id > 5)
  13977. ret |= SSL_OP_NO_TLSv1_3;
  13978. #endif
  13979. return (long)ret;
  13980. }
  13981. #endif /* OPENSSL_API_1_1 */
  13982. /* SSL callback documentation:
  13983. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13984. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13985. * https://linux.die.net/man/3/ssl_set_info_callback */
  13986. /* Note: There is no "const" for the first argument in the documentation
  13987. * examples, however some (maybe most, but not all) headers of OpenSSL
  13988. * versions / OpenSSL compatibility layers have it. Having a different
  13989. * definition will cause a warning in C and an error in C++. Use "const SSL
  13990. * *", while automatical conversion from "SSL *" works for all compilers,
  13991. * but not other way around */
  13992. static void
  13993. ssl_info_callback(const SSL *ssl, int what, int ret)
  13994. {
  13995. (void)ret;
  13996. if (what & SSL_CB_HANDSHAKE_START) {
  13997. SSL_get_app_data(ssl);
  13998. }
  13999. if (what & SSL_CB_HANDSHAKE_DONE) {
  14000. /* TODO: check for openSSL 1.1 */
  14001. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14002. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14003. }
  14004. }
  14005. static int
  14006. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14007. {
  14008. #if defined(GCC_DIAGNOSTIC)
  14009. #pragma GCC diagnostic push
  14010. #pragma GCC diagnostic ignored "-Wcast-align"
  14011. #endif /* defined(GCC_DIAGNOSTIC) */
  14012. /* We used an aligned pointer in SSL_set_app_data */
  14013. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14014. #if defined(GCC_DIAGNOSTIC)
  14015. #pragma GCC diagnostic pop
  14016. #endif /* defined(GCC_DIAGNOSTIC) */
  14017. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14018. (void)ad;
  14019. (void)arg;
  14020. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14021. DEBUG_ASSERT(0);
  14022. return SSL_TLSEXT_ERR_NOACK;
  14023. }
  14024. conn->dom_ctx = &(conn->phys_ctx->dd);
  14025. /* Old clients (Win XP) will not support SNI. Then, there
  14026. * is no server name available in the request - we can
  14027. * only work with the default certificate.
  14028. * Multiple HTTPS hosts on one IP+port are only possible
  14029. * with a certificate containing all alternative names.
  14030. */
  14031. if ((servername == NULL) || (*servername == 0)) {
  14032. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14033. mg_lock_context(conn->phys_ctx);
  14034. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14035. mg_unlock_context(conn->phys_ctx);
  14036. return SSL_TLSEXT_ERR_NOACK;
  14037. }
  14038. DEBUG_TRACE("TLS connection to host %s", servername);
  14039. while (conn->dom_ctx) {
  14040. if (!mg_strcasecmp(servername,
  14041. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14042. /* Found matching domain */
  14043. DEBUG_TRACE("TLS domain %s found",
  14044. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14045. break;
  14046. }
  14047. mg_lock_context(conn->phys_ctx);
  14048. conn->dom_ctx = conn->dom_ctx->next;
  14049. mg_unlock_context(conn->phys_ctx);
  14050. }
  14051. if (conn->dom_ctx == NULL) {
  14052. /* Default domain */
  14053. DEBUG_TRACE("TLS default domain %s used",
  14054. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14055. conn->dom_ctx = &(conn->phys_ctx->dd);
  14056. }
  14057. mg_lock_context(conn->phys_ctx);
  14058. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14059. mg_unlock_context(conn->phys_ctx);
  14060. return SSL_TLSEXT_ERR_OK;
  14061. }
  14062. #if defined(USE_HTTP2)
  14063. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14064. static const char *alpn_proto_order[] = {alpn_proto_list,
  14065. alpn_proto_list + 3,
  14066. alpn_proto_list + 3 + 8,
  14067. NULL};
  14068. #else
  14069. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14070. static const char *alpn_proto_order[] = {alpn_proto_list,
  14071. alpn_proto_list + 8,
  14072. NULL};
  14073. #endif
  14074. static int
  14075. alpn_select_cb(SSL *ssl,
  14076. const unsigned char **out,
  14077. unsigned char *outlen,
  14078. const unsigned char *in,
  14079. unsigned int inlen,
  14080. void *arg)
  14081. {
  14082. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14083. unsigned int i, j;
  14084. struct mg_workerTLS *tls =
  14085. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14086. (void)ssl;
  14087. (void)dom_ctx;
  14088. if (tls == NULL) {
  14089. /* Need to store protocol in Thread Local Storage */
  14090. /* If there is no Thread Local Storage, don't use ALPN */
  14091. return SSL_TLSEXT_ERR_NOACK;
  14092. }
  14093. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14094. /* check all accepted protocols in this order */
  14095. const char *alpn_proto = alpn_proto_order[j];
  14096. /* search input for matching protocol */
  14097. for (i = 0; i < inlen; i++) {
  14098. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14099. *out = in + i + 1;
  14100. *outlen = in[i];
  14101. tls->alpn_proto = alpn_proto;
  14102. return SSL_TLSEXT_ERR_OK;
  14103. }
  14104. }
  14105. }
  14106. /* Nothing found */
  14107. return SSL_TLSEXT_ERR_NOACK;
  14108. }
  14109. static int
  14110. next_protos_advertised_cb(SSL *ssl,
  14111. const unsigned char **data,
  14112. unsigned int *len,
  14113. void *arg)
  14114. {
  14115. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14116. *data = (const unsigned char *)alpn_proto_list;
  14117. *len = (unsigned int)strlen((const char *)data);
  14118. (void)ssl;
  14119. (void)dom_ctx;
  14120. return SSL_TLSEXT_ERR_OK;
  14121. }
  14122. static int
  14123. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14124. {
  14125. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14126. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14127. (const unsigned char *)alpn_proto_list,
  14128. alpn_len);
  14129. if (ret != 0) {
  14130. mg_cry_ctx_internal(phys_ctx,
  14131. "SSL_CTX_set_alpn_protos error: %s",
  14132. ssl_error());
  14133. }
  14134. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14135. alpn_select_cb,
  14136. (void *)dom_ctx);
  14137. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14138. next_protos_advertised_cb,
  14139. (void *)dom_ctx);
  14140. return ret;
  14141. }
  14142. /* Setup SSL CTX as required by CivetWeb */
  14143. static int
  14144. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14145. struct mg_domain_context *dom_ctx,
  14146. const char *pem,
  14147. const char *chain)
  14148. {
  14149. int callback_ret;
  14150. int should_verify_peer;
  14151. int peer_certificate_optional;
  14152. const char *ca_path;
  14153. const char *ca_file;
  14154. int use_default_verify_paths;
  14155. int verify_depth;
  14156. struct timespec now_mt;
  14157. md5_byte_t ssl_context_id[16];
  14158. md5_state_t md5state;
  14159. int protocol_ver;
  14160. #if defined(OPENSSL_API_1_1)
  14161. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14162. mg_cry_ctx_internal(phys_ctx,
  14163. "SSL_CTX_new (server) error: %s",
  14164. ssl_error());
  14165. return 0;
  14166. }
  14167. #else
  14168. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14169. mg_cry_ctx_internal(phys_ctx,
  14170. "SSL_CTX_new (server) error: %s",
  14171. ssl_error());
  14172. return 0;
  14173. }
  14174. #endif /* OPENSSL_API_1_1 */
  14175. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14176. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14177. | SSL_OP_NO_TLSv1_1);
  14178. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14179. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14180. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14181. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14182. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14183. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14184. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14185. #if defined(SSL_OP_NO_RENEGOTIATION)
  14186. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14187. #endif
  14188. #if !defined(NO_SSL_DL)
  14189. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14190. #endif /* NO_SSL_DL */
  14191. /* In SSL documentation examples callback defined without const
  14192. * specifier 'void (*)(SSL *, int, int)' See:
  14193. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14194. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14195. * But in the source code const SSL is used:
  14196. * 'void (*)(const SSL *, int, int)' See:
  14197. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14198. * Problem about wrong documentation described, but not resolved:
  14199. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14200. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14201. * But when compiled with modern C++ compiler, correct const should be
  14202. * provided
  14203. */
  14204. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14205. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14206. ssl_servername_callback);
  14207. /* If a callback has been specified, call it. */
  14208. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14209. ? 0
  14210. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14211. phys_ctx->user_data));
  14212. /* If callback returns 0, civetweb sets up the SSL certificate.
  14213. * If it returns 1, civetweb assumes the calback already did this.
  14214. * If it returns -1, initializing ssl fails. */
  14215. if (callback_ret < 0) {
  14216. mg_cry_ctx_internal(phys_ctx,
  14217. "SSL callback returned error: %i",
  14218. callback_ret);
  14219. return 0;
  14220. }
  14221. if (callback_ret > 0) {
  14222. /* Callback did everything. */
  14223. return 1;
  14224. }
  14225. /* If a domain callback has been specified, call it. */
  14226. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14227. ? 0
  14228. : (phys_ctx->callbacks.init_ssl_domain(
  14229. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14230. dom_ctx->ssl_ctx,
  14231. phys_ctx->user_data));
  14232. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14233. * If it returns 1, civetweb assumes the calback already did this.
  14234. * If it returns -1, initializing ssl fails. */
  14235. if (callback_ret < 0) {
  14236. mg_cry_ctx_internal(phys_ctx,
  14237. "Domain SSL callback returned error: %i",
  14238. callback_ret);
  14239. return 0;
  14240. }
  14241. if (callback_ret > 0) {
  14242. /* Domain callback did everything. */
  14243. return 1;
  14244. }
  14245. /* Use some combination of start time, domain and port as a SSL
  14246. * context ID. This should be unique on the current machine. */
  14247. md5_init(&md5state);
  14248. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14249. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14250. md5_append(&md5state,
  14251. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14252. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14253. md5_append(&md5state,
  14254. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14255. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14256. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14257. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14258. md5_finish(&md5state, ssl_context_id);
  14259. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14260. (unsigned char *)ssl_context_id,
  14261. sizeof(ssl_context_id));
  14262. if (pem != NULL) {
  14263. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14264. return 0;
  14265. }
  14266. }
  14267. /* Should we support client certificates? */
  14268. /* Default is "no". */
  14269. should_verify_peer = 0;
  14270. peer_certificate_optional = 0;
  14271. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14272. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14273. /* Yes, they are mandatory */
  14274. should_verify_peer = 1;
  14275. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14276. "optional")
  14277. == 0) {
  14278. /* Yes, they are optional */
  14279. should_verify_peer = 1;
  14280. peer_certificate_optional = 1;
  14281. }
  14282. }
  14283. use_default_verify_paths =
  14284. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14285. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14286. == 0);
  14287. if (should_verify_peer) {
  14288. ca_path = dom_ctx->config[SSL_CA_PATH];
  14289. ca_file = dom_ctx->config[SSL_CA_FILE];
  14290. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14291. != 1) {
  14292. mg_cry_ctx_internal(phys_ctx,
  14293. "SSL_CTX_load_verify_locations error: %s "
  14294. "ssl_verify_peer requires setting "
  14295. "either ssl_ca_path or ssl_ca_file. "
  14296. "Is any of them present in the "
  14297. ".conf file?",
  14298. ssl_error());
  14299. return 0;
  14300. }
  14301. if (peer_certificate_optional) {
  14302. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14303. } else {
  14304. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14305. SSL_VERIFY_PEER
  14306. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14307. NULL);
  14308. }
  14309. if (use_default_verify_paths
  14310. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14311. mg_cry_ctx_internal(phys_ctx,
  14312. "SSL_CTX_set_default_verify_paths error: %s",
  14313. ssl_error());
  14314. return 0;
  14315. }
  14316. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14317. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14318. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14319. }
  14320. }
  14321. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14322. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14323. dom_ctx->config[SSL_CIPHER_LIST])
  14324. != 1) {
  14325. mg_cry_ctx_internal(phys_ctx,
  14326. "SSL_CTX_set_cipher_list error: %s",
  14327. ssl_error());
  14328. }
  14329. }
  14330. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14331. #if !defined(NO_SSL_DL)
  14332. if (!tls_feature_missing[TLS_ALPN])
  14333. #endif
  14334. {
  14335. init_alpn(phys_ctx, dom_ctx);
  14336. }
  14337. return 1;
  14338. }
  14339. /* Check if SSL is required.
  14340. * If so, dynamically load SSL library
  14341. * and set up ctx->ssl_ctx pointer. */
  14342. static int
  14343. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14344. {
  14345. void *ssl_ctx = 0;
  14346. int callback_ret;
  14347. const char *pem;
  14348. const char *chain;
  14349. char ebuf[128];
  14350. if (!phys_ctx) {
  14351. return 0;
  14352. }
  14353. if (!dom_ctx) {
  14354. dom_ctx = &(phys_ctx->dd);
  14355. }
  14356. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14357. /* No SSL port is set. No need to setup SSL. */
  14358. return 1;
  14359. }
  14360. /* Check for external SSL_CTX */
  14361. callback_ret =
  14362. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14363. ? 0
  14364. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14365. phys_ctx->user_data));
  14366. if (callback_ret < 0) {
  14367. mg_cry_ctx_internal(phys_ctx,
  14368. "external_ssl_ctx callback returned error: %i",
  14369. callback_ret);
  14370. return 0;
  14371. } else if (callback_ret > 0) {
  14372. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14373. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14374. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14375. return 0;
  14376. }
  14377. return 1;
  14378. }
  14379. /* Check for external domain SSL_CTX */
  14380. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14381. ? 0
  14382. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14383. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14384. &ssl_ctx,
  14385. phys_ctx->user_data));
  14386. if (callback_ret < 0) {
  14387. mg_cry_ctx_internal(
  14388. phys_ctx,
  14389. "external_ssl_ctx_domain callback returned error: %i",
  14390. callback_ret);
  14391. return 0;
  14392. } else if (callback_ret > 0) {
  14393. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14394. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14395. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14396. return 0;
  14397. }
  14398. return 1;
  14399. }
  14400. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14401. * 0, CivetWeb should continue initializing SSL */
  14402. /* If PEM file is not specified and the init_ssl callbacks
  14403. * are not specified, setup will fail. */
  14404. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14405. && (phys_ctx->callbacks.init_ssl == NULL)
  14406. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14407. /* No certificate and no init_ssl callbacks:
  14408. * Essential data to set up TLS is missing.
  14409. */
  14410. mg_cry_ctx_internal(phys_ctx,
  14411. "Initializing SSL failed: -%s is not set",
  14412. config_options[SSL_CERTIFICATE].name);
  14413. return 0;
  14414. }
  14415. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14416. if (chain == NULL) {
  14417. chain = pem;
  14418. }
  14419. if ((chain != NULL) && (*chain == 0)) {
  14420. chain = NULL;
  14421. }
  14422. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14423. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14424. return 0;
  14425. }
  14426. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14427. }
  14428. static void
  14429. uninitialize_ssl(void)
  14430. {
  14431. #if defined(OPENSSL_API_1_1)
  14432. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14433. /* Shutdown according to
  14434. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14435. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14436. */
  14437. CONF_modules_unload(1);
  14438. #else
  14439. int i;
  14440. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14441. /* Shutdown according to
  14442. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14443. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14444. */
  14445. CRYPTO_set_locking_callback(NULL);
  14446. CRYPTO_set_id_callback(NULL);
  14447. ENGINE_cleanup();
  14448. CONF_modules_unload(1);
  14449. ERR_free_strings();
  14450. EVP_cleanup();
  14451. CRYPTO_cleanup_all_ex_data();
  14452. OPENSSL_REMOVE_THREAD_STATE();
  14453. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14454. pthread_mutex_destroy(&ssl_mutexes[i]);
  14455. }
  14456. mg_free(ssl_mutexes);
  14457. ssl_mutexes = NULL;
  14458. #endif /* OPENSSL_API_1_1 */
  14459. }
  14460. }
  14461. #endif /* !NO_SSL */
  14462. #if !defined(NO_FILESYSTEMS)
  14463. static int
  14464. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14465. {
  14466. if (phys_ctx) {
  14467. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14468. const char *path;
  14469. struct mg_connection fc;
  14470. if (!dom_ctx) {
  14471. dom_ctx = &(phys_ctx->dd);
  14472. }
  14473. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14474. if ((path != NULL)
  14475. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14476. mg_cry_ctx_internal(phys_ctx,
  14477. "Cannot open %s: %s",
  14478. path,
  14479. strerror(ERRNO));
  14480. return 0;
  14481. }
  14482. return 1;
  14483. }
  14484. return 0;
  14485. }
  14486. #endif /* NO_FILESYSTEMS */
  14487. static int
  14488. set_acl_option(struct mg_context *phys_ctx)
  14489. {
  14490. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14491. }
  14492. static void
  14493. reset_per_request_attributes(struct mg_connection *conn)
  14494. {
  14495. if (!conn) {
  14496. return;
  14497. }
  14498. conn->connection_type =
  14499. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14500. conn->num_bytes_sent = conn->consumed_content = 0;
  14501. conn->path_info = NULL;
  14502. conn->status_code = -1;
  14503. conn->content_len = -1;
  14504. conn->is_chunked = 0;
  14505. conn->must_close = 0;
  14506. conn->request_len = 0;
  14507. conn->throttle = 0;
  14508. conn->accept_gzip = 0;
  14509. conn->response_info.content_length = conn->request_info.content_length = -1;
  14510. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14511. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14512. conn->response_info.status_text = NULL;
  14513. conn->response_info.status_code = 0;
  14514. conn->request_info.remote_user = NULL;
  14515. conn->request_info.request_method = NULL;
  14516. conn->request_info.request_uri = NULL;
  14517. conn->request_info.local_uri = NULL;
  14518. #if defined(MG_LEGACY_INTERFACE)
  14519. /* Legacy before split into local_uri and request_uri */
  14520. conn->request_info.uri = NULL;
  14521. #endif
  14522. }
  14523. static int
  14524. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14525. {
  14526. if (setsockopt(sock,
  14527. IPPROTO_TCP,
  14528. TCP_NODELAY,
  14529. (SOCK_OPT_TYPE)&nodelay_on,
  14530. sizeof(nodelay_on))
  14531. != 0) {
  14532. /* Error */
  14533. return 1;
  14534. }
  14535. /* OK */
  14536. return 0;
  14537. }
  14538. #if !defined(__ZEPHYR__)
  14539. static void
  14540. close_socket_gracefully(struct mg_connection *conn)
  14541. {
  14542. #if defined(_WIN32)
  14543. char buf[MG_BUF_LEN];
  14544. int n;
  14545. #endif
  14546. struct linger linger;
  14547. int error_code = 0;
  14548. int linger_timeout = -2;
  14549. socklen_t opt_len = sizeof(error_code);
  14550. if (!conn) {
  14551. return;
  14552. }
  14553. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14554. * "Note that enabling a nonzero timeout on a nonblocking socket
  14555. * is not recommended.", so set it to blocking now */
  14556. set_blocking_mode(conn->client.sock);
  14557. /* Send FIN to the client */
  14558. shutdown(conn->client.sock, SHUTDOWN_WR);
  14559. #if defined(_WIN32)
  14560. /* Read and discard pending incoming data. If we do not do that and
  14561. * close
  14562. * the socket, the data in the send buffer may be discarded. This
  14563. * behaviour is seen on Windows, when client keeps sending data
  14564. * when server decides to close the connection; then when client
  14565. * does recv() it gets no data back. */
  14566. do {
  14567. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14568. } while (n > 0);
  14569. #endif
  14570. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14571. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14572. }
  14573. /* Set linger option according to configuration */
  14574. if (linger_timeout >= 0) {
  14575. /* Set linger option to avoid socket hanging out after close. This
  14576. * prevent ephemeral port exhaust problem under high QPS. */
  14577. linger.l_onoff = 1;
  14578. #if defined(_MSC_VER)
  14579. #pragma warning(push)
  14580. #pragma warning(disable : 4244)
  14581. #endif
  14582. #if defined(GCC_DIAGNOSTIC)
  14583. #pragma GCC diagnostic push
  14584. #pragma GCC diagnostic ignored "-Wconversion"
  14585. #endif
  14586. /* Data type of linger structure elements may differ,
  14587. * so we don't know what cast we need here.
  14588. * Disable type conversion warnings. */
  14589. linger.l_linger = (linger_timeout + 999) / 1000;
  14590. #if defined(GCC_DIAGNOSTIC)
  14591. #pragma GCC diagnostic pop
  14592. #endif
  14593. #if defined(_MSC_VER)
  14594. #pragma warning(pop)
  14595. #endif
  14596. } else {
  14597. linger.l_onoff = 0;
  14598. linger.l_linger = 0;
  14599. }
  14600. if (linger_timeout < -1) {
  14601. /* Default: don't configure any linger */
  14602. } else if (getsockopt(conn->client.sock,
  14603. SOL_SOCKET,
  14604. SO_ERROR,
  14605. #if defined(_WIN32) /* WinSock uses different data type here */
  14606. (char *)&error_code,
  14607. #else
  14608. &error_code,
  14609. #endif
  14610. &opt_len)
  14611. != 0) {
  14612. /* Cannot determine if socket is already closed. This should
  14613. * not occur and never did in a test. Log an error message
  14614. * and continue. */
  14615. mg_cry_internal(conn,
  14616. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14617. __func__,
  14618. strerror(ERRNO));
  14619. #if defined(_WIN32)
  14620. } else if (error_code == WSAECONNRESET) {
  14621. #else
  14622. } else if (error_code == ECONNRESET) {
  14623. #endif
  14624. /* Socket already closed by client/peer, close socket without linger
  14625. */
  14626. } else {
  14627. /* Set linger timeout */
  14628. if (setsockopt(conn->client.sock,
  14629. SOL_SOCKET,
  14630. SO_LINGER,
  14631. (char *)&linger,
  14632. sizeof(linger))
  14633. != 0) {
  14634. mg_cry_internal(
  14635. conn,
  14636. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14637. __func__,
  14638. linger.l_onoff,
  14639. linger.l_linger,
  14640. strerror(ERRNO));
  14641. }
  14642. }
  14643. /* Now we know that our FIN is ACK-ed, safe to close */
  14644. closesocket(conn->client.sock);
  14645. conn->client.sock = INVALID_SOCKET;
  14646. }
  14647. #endif
  14648. static void
  14649. close_connection(struct mg_connection *conn)
  14650. {
  14651. #if defined(USE_SERVER_STATS)
  14652. conn->conn_state = 6; /* to close */
  14653. #endif
  14654. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14655. if (conn->lua_websocket_state) {
  14656. lua_websocket_close(conn, conn->lua_websocket_state);
  14657. conn->lua_websocket_state = NULL;
  14658. }
  14659. #endif
  14660. mg_lock_connection(conn);
  14661. /* Set close flag, so keep-alive loops will stop */
  14662. conn->must_close = 1;
  14663. /* call the connection_close callback if assigned */
  14664. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14665. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14666. conn->phys_ctx->callbacks.connection_close(conn);
  14667. }
  14668. }
  14669. /* Reset user data, after close callback is called.
  14670. * Do not reuse it. If the user needs a destructor,
  14671. * it must be done in the connection_close callback. */
  14672. mg_set_user_connection_data(conn, NULL);
  14673. #if defined(USE_SERVER_STATS)
  14674. conn->conn_state = 7; /* closing */
  14675. #endif
  14676. #if !defined(NO_SSL)
  14677. if (conn->ssl != NULL) {
  14678. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14679. */
  14680. SSL_shutdown(conn->ssl);
  14681. SSL_free(conn->ssl);
  14682. OPENSSL_REMOVE_THREAD_STATE();
  14683. conn->ssl = NULL;
  14684. }
  14685. #endif
  14686. if (conn->client.sock != INVALID_SOCKET) {
  14687. #if defined(__ZEPHYR__)
  14688. closesocket(conn->client.sock);
  14689. #else
  14690. close_socket_gracefully(conn);
  14691. #endif
  14692. conn->client.sock = INVALID_SOCKET;
  14693. }
  14694. if (conn->host) {
  14695. mg_free((void *)conn->host);
  14696. conn->host = NULL;
  14697. }
  14698. mg_unlock_connection(conn);
  14699. #if defined(USE_SERVER_STATS)
  14700. conn->conn_state = 8; /* closed */
  14701. #endif
  14702. }
  14703. void
  14704. mg_close_connection(struct mg_connection *conn)
  14705. {
  14706. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14707. return;
  14708. }
  14709. #if defined(USE_WEBSOCKET)
  14710. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14711. if (conn->in_websocket_handling) {
  14712. /* Set close flag, so the server thread can exit. */
  14713. conn->must_close = 1;
  14714. return;
  14715. }
  14716. }
  14717. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14718. unsigned int i;
  14719. /* client context: loops must end */
  14720. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14721. conn->must_close = 1;
  14722. /* We need to get the client thread out of the select/recv call
  14723. * here. */
  14724. /* Since we use a sleep quantum of some seconds to check for recv
  14725. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14726. /* join worker thread */
  14727. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14728. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14729. }
  14730. }
  14731. #endif /* defined(USE_WEBSOCKET) */
  14732. close_connection(conn);
  14733. #if !defined(NO_SSL)
  14734. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14735. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14736. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14737. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14738. }
  14739. #endif
  14740. #if defined(USE_WEBSOCKET)
  14741. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14742. mg_free(conn->phys_ctx->worker_threadids);
  14743. (void)pthread_mutex_destroy(&conn->mutex);
  14744. mg_free(conn);
  14745. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14746. (void)pthread_mutex_destroy(&conn->mutex);
  14747. mg_free(conn);
  14748. }
  14749. #else
  14750. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14751. (void)pthread_mutex_destroy(&conn->mutex);
  14752. mg_free(conn);
  14753. }
  14754. #endif /* defined(USE_WEBSOCKET) */
  14755. }
  14756. static struct mg_connection *
  14757. mg_connect_client_impl(const struct mg_client_options *client_options,
  14758. int use_ssl,
  14759. char *ebuf,
  14760. size_t ebuf_len)
  14761. {
  14762. struct mg_connection *conn = NULL;
  14763. SOCKET sock;
  14764. union usa sa;
  14765. struct sockaddr *psa;
  14766. socklen_t len;
  14767. unsigned max_req_size =
  14768. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14769. /* Size of structures, aligned to 8 bytes */
  14770. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14771. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14772. conn =
  14773. (struct mg_connection *)mg_calloc(1,
  14774. conn_size + ctx_size + max_req_size);
  14775. if (conn == NULL) {
  14776. mg_snprintf(NULL,
  14777. NULL, /* No truncation check for ebuf */
  14778. ebuf,
  14779. ebuf_len,
  14780. "calloc(): %s",
  14781. strerror(ERRNO));
  14782. return NULL;
  14783. }
  14784. #if defined(GCC_DIAGNOSTIC)
  14785. #pragma GCC diagnostic push
  14786. #pragma GCC diagnostic ignored "-Wcast-align"
  14787. #endif /* defined(GCC_DIAGNOSTIC) */
  14788. /* conn_size is aligned to 8 bytes */
  14789. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14790. #if defined(GCC_DIAGNOSTIC)
  14791. #pragma GCC diagnostic pop
  14792. #endif /* defined(GCC_DIAGNOSTIC) */
  14793. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14794. conn->buf_size = (int)max_req_size;
  14795. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14796. conn->dom_ctx = &(conn->phys_ctx->dd);
  14797. if (!connect_socket(conn->phys_ctx,
  14798. client_options->host,
  14799. client_options->port,
  14800. use_ssl,
  14801. ebuf,
  14802. ebuf_len,
  14803. &sock,
  14804. &sa)) {
  14805. /* ebuf is set by connect_socket,
  14806. * free all memory and return NULL; */
  14807. mg_free(conn);
  14808. return NULL;
  14809. }
  14810. #if !defined(NO_SSL)
  14811. #if defined(OPENSSL_API_1_1)
  14812. if (use_ssl
  14813. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14814. == NULL) {
  14815. mg_snprintf(NULL,
  14816. NULL, /* No truncation check for ebuf */
  14817. ebuf,
  14818. ebuf_len,
  14819. "SSL_CTX_new error: %s",
  14820. ssl_error());
  14821. closesocket(sock);
  14822. mg_free(conn);
  14823. return NULL;
  14824. }
  14825. #else
  14826. if (use_ssl
  14827. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14828. == NULL) {
  14829. mg_snprintf(NULL,
  14830. NULL, /* No truncation check for ebuf */
  14831. ebuf,
  14832. ebuf_len,
  14833. "SSL_CTX_new error: %s",
  14834. ssl_error());
  14835. closesocket(sock);
  14836. mg_free(conn);
  14837. return NULL;
  14838. }
  14839. #endif /* OPENSSL_API_1_1 */
  14840. #endif /* NO_SSL */
  14841. #if defined(USE_IPV6)
  14842. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14843. : sizeof(conn->client.rsa.sin6);
  14844. psa = (sa.sa.sa_family == AF_INET)
  14845. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14846. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14847. #else
  14848. len = sizeof(conn->client.rsa.sin);
  14849. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14850. #endif
  14851. conn->client.sock = sock;
  14852. conn->client.lsa = sa;
  14853. if (getsockname(sock, psa, &len) != 0) {
  14854. mg_cry_internal(conn,
  14855. "%s: getsockname() failed: %s",
  14856. __func__,
  14857. strerror(ERRNO));
  14858. }
  14859. conn->client.is_ssl = use_ssl ? 1 : 0;
  14860. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14861. mg_snprintf(NULL,
  14862. NULL, /* No truncation check for ebuf */
  14863. ebuf,
  14864. ebuf_len,
  14865. "Can not create mutex");
  14866. #if !defined(NO_SSL)
  14867. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14868. #endif
  14869. closesocket(sock);
  14870. mg_free(conn);
  14871. return NULL;
  14872. }
  14873. #if !defined(NO_SSL)
  14874. if (use_ssl) {
  14875. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14876. * SSL_CTX_set_verify call is needed to switch off server
  14877. * certificate checking, which is off by default in OpenSSL and
  14878. * on in yaSSL. */
  14879. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14880. * SSL_VERIFY_PEER, verify_ssl_server); */
  14881. if (client_options->client_cert) {
  14882. if (!ssl_use_pem_file(conn->phys_ctx,
  14883. conn->dom_ctx,
  14884. client_options->client_cert,
  14885. NULL)) {
  14886. mg_snprintf(NULL,
  14887. NULL, /* No truncation check for ebuf */
  14888. ebuf,
  14889. ebuf_len,
  14890. "Can not use SSL client certificate");
  14891. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14892. closesocket(sock);
  14893. mg_free(conn);
  14894. return NULL;
  14895. }
  14896. }
  14897. if (client_options->server_cert) {
  14898. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14899. client_options->server_cert,
  14900. NULL)
  14901. != 1) {
  14902. mg_cry_internal(conn,
  14903. "SSL_CTX_load_verify_locations error: %s ",
  14904. ssl_error());
  14905. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14906. closesocket(sock);
  14907. mg_free(conn);
  14908. return NULL;
  14909. }
  14910. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14911. } else {
  14912. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14913. }
  14914. if (!sslize(conn, SSL_connect, client_options)) {
  14915. mg_snprintf(NULL,
  14916. NULL, /* No truncation check for ebuf */
  14917. ebuf,
  14918. ebuf_len,
  14919. "SSL connection error");
  14920. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14921. closesocket(sock);
  14922. mg_free(conn);
  14923. return NULL;
  14924. }
  14925. }
  14926. #endif
  14927. return conn;
  14928. }
  14929. CIVETWEB_API struct mg_connection *
  14930. mg_connect_client_secure(const struct mg_client_options *client_options,
  14931. char *error_buffer,
  14932. size_t error_buffer_size)
  14933. {
  14934. return mg_connect_client_impl(client_options,
  14935. 1,
  14936. error_buffer,
  14937. error_buffer_size);
  14938. }
  14939. struct mg_connection *
  14940. mg_connect_client(const char *host,
  14941. int port,
  14942. int use_ssl,
  14943. char *error_buffer,
  14944. size_t error_buffer_size)
  14945. {
  14946. struct mg_client_options opts;
  14947. memset(&opts, 0, sizeof(opts));
  14948. opts.host = host;
  14949. opts.port = port;
  14950. return mg_connect_client_impl(&opts,
  14951. use_ssl,
  14952. error_buffer,
  14953. error_buffer_size);
  14954. }
  14955. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14956. struct mg_connection *
  14957. mg_connect_client2(const char *host,
  14958. const char *protocol,
  14959. int port,
  14960. const char *path,
  14961. struct mg_init_data *init,
  14962. struct mg_error_data *error)
  14963. {
  14964. int is_ssl, is_ws;
  14965. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14966. if (error != NULL) {
  14967. error->code = 0;
  14968. if (error->text_buffer_size > 0) {
  14969. *error->text = 0;
  14970. }
  14971. }
  14972. if ((host == NULL) || (protocol == NULL)) {
  14973. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14974. mg_snprintf(NULL,
  14975. NULL, /* No truncation check for error buffers */
  14976. error->text,
  14977. error->text_buffer_size,
  14978. "%s",
  14979. "Invalid parameters");
  14980. }
  14981. return NULL;
  14982. }
  14983. /* check all known protocolls */
  14984. if (!mg_strcasecmp(protocol, "http")) {
  14985. is_ssl = 0;
  14986. is_ws = 0;
  14987. } else if (!mg_strcasecmp(protocol, "https")) {
  14988. is_ssl = 1;
  14989. is_ws = 0;
  14990. #if defined(USE_WEBSOCKET)
  14991. } else if (!mg_strcasecmp(protocol, "ws")) {
  14992. is_ssl = 0;
  14993. is_ws = 1;
  14994. } else if (!mg_strcasecmp(protocol, "wss")) {
  14995. is_ssl = 1;
  14996. is_ws = 1;
  14997. #endif
  14998. } else {
  14999. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15000. mg_snprintf(NULL,
  15001. NULL, /* No truncation check for error buffers */
  15002. error->text,
  15003. error->text_buffer_size,
  15004. "Protocol %s not supported",
  15005. protocol);
  15006. }
  15007. return NULL;
  15008. }
  15009. /* TODO: The current implementation here just calls the old
  15010. * implementations, without using any new options. This is just a first
  15011. * step to test the new interfaces. */
  15012. #if defined(USE_WEBSOCKET)
  15013. if (is_ws) {
  15014. /* TODO: implement all options */
  15015. return mg_connect_websocket_client(
  15016. host,
  15017. port,
  15018. is_ssl,
  15019. ((error != NULL) ? error->text : NULL),
  15020. ((error != NULL) ? error->text_buffer_size : 0),
  15021. (path ? path : ""),
  15022. NULL /* TODO: origin */,
  15023. deprecated_websocket_data_wrapper,
  15024. deprecated_websocket_close_wrapper,
  15025. (void *)init->callbacks);
  15026. }
  15027. #endif
  15028. /* TODO: all additional options */
  15029. struct mg_client_options opts;
  15030. memset(&opts, 0, sizeof(opts));
  15031. opts.host = host;
  15032. opts.port = port;
  15033. return mg_connect_client_impl(&opts,
  15034. is_ssl,
  15035. ((error != NULL) ? error->text : NULL),
  15036. ((error != NULL) ? error->text_buffer_size
  15037. : 0));
  15038. }
  15039. #endif
  15040. static const struct {
  15041. const char *proto;
  15042. size_t proto_len;
  15043. unsigned default_port;
  15044. } abs_uri_protocols[] = {{"http://", 7, 80},
  15045. {"https://", 8, 443},
  15046. {"ws://", 5, 80},
  15047. {"wss://", 6, 443},
  15048. {NULL, 0, 0}};
  15049. /* Check if the uri is valid.
  15050. * return 0 for invalid uri,
  15051. * return 1 for *,
  15052. * return 2 for relative uri,
  15053. * return 3 for absolute uri without port,
  15054. * return 4 for absolute uri with port */
  15055. static int
  15056. get_uri_type(const char *uri)
  15057. {
  15058. int i;
  15059. const char *hostend, *portbegin;
  15060. char *portend;
  15061. unsigned long port;
  15062. /* According to the HTTP standard
  15063. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15064. * URI can be an asterisk (*) or should start with slash (relative uri),
  15065. * or it should start with the protocol (absolute uri). */
  15066. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15067. /* asterisk */
  15068. return 1;
  15069. }
  15070. /* Valid URIs according to RFC 3986
  15071. * (https://www.ietf.org/rfc/rfc3986.txt)
  15072. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15073. * and unreserved characters A-Z a-z 0-9 and -._~
  15074. * and % encoded symbols.
  15075. */
  15076. for (i = 0; uri[i] != 0; i++) {
  15077. if (uri[i] < 33) {
  15078. /* control characters and spaces are invalid */
  15079. return 0;
  15080. }
  15081. if (uri[i] > 126) {
  15082. /* non-ascii characters must be % encoded */
  15083. return 0;
  15084. } else {
  15085. switch (uri[i]) {
  15086. case '"': /* 34 */
  15087. case '<': /* 60 */
  15088. case '>': /* 62 */
  15089. case '\\': /* 92 */
  15090. case '^': /* 94 */
  15091. case '`': /* 96 */
  15092. case '{': /* 123 */
  15093. case '|': /* 124 */
  15094. case '}': /* 125 */
  15095. return 0;
  15096. default:
  15097. /* character is ok */
  15098. break;
  15099. }
  15100. }
  15101. }
  15102. /* A relative uri starts with a / character */
  15103. if (uri[0] == '/') {
  15104. /* relative uri */
  15105. return 2;
  15106. }
  15107. /* It could be an absolute uri: */
  15108. /* This function only checks if the uri is valid, not if it is
  15109. * addressing the current server. So civetweb can also be used
  15110. * as a proxy server. */
  15111. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15112. if (mg_strncasecmp(uri,
  15113. abs_uri_protocols[i].proto,
  15114. abs_uri_protocols[i].proto_len)
  15115. == 0) {
  15116. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15117. if (!hostend) {
  15118. return 0;
  15119. }
  15120. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15121. if (!portbegin) {
  15122. return 3;
  15123. }
  15124. port = strtoul(portbegin + 1, &portend, 10);
  15125. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15126. return 0;
  15127. }
  15128. return 4;
  15129. }
  15130. }
  15131. return 0;
  15132. }
  15133. /* Return NULL or the relative uri at the current server */
  15134. static const char *
  15135. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15136. {
  15137. const char *server_domain;
  15138. size_t server_domain_len;
  15139. size_t request_domain_len = 0;
  15140. unsigned long port = 0;
  15141. int i, auth_domain_check_enabled;
  15142. const char *hostbegin = NULL;
  15143. const char *hostend = NULL;
  15144. const char *portbegin;
  15145. char *portend;
  15146. auth_domain_check_enabled =
  15147. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15148. /* DNS is case insensitive, so use case insensitive string compare here
  15149. */
  15150. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15151. if (mg_strncasecmp(uri,
  15152. abs_uri_protocols[i].proto,
  15153. abs_uri_protocols[i].proto_len)
  15154. == 0) {
  15155. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15156. hostend = strchr(hostbegin, '/');
  15157. if (!hostend) {
  15158. return 0;
  15159. }
  15160. portbegin = strchr(hostbegin, ':');
  15161. if ((!portbegin) || (portbegin > hostend)) {
  15162. port = abs_uri_protocols[i].default_port;
  15163. request_domain_len = (size_t)(hostend - hostbegin);
  15164. } else {
  15165. port = strtoul(portbegin + 1, &portend, 10);
  15166. if ((portend != hostend) || (port <= 0)
  15167. || !is_valid_port(port)) {
  15168. return 0;
  15169. }
  15170. request_domain_len = (size_t)(portbegin - hostbegin);
  15171. }
  15172. /* protocol found, port set */
  15173. break;
  15174. }
  15175. }
  15176. if (!port) {
  15177. /* port remains 0 if the protocol is not found */
  15178. return 0;
  15179. }
  15180. /* Check if the request is directed to a different server. */
  15181. /* First check if the port is the same (IPv4 and IPv6). */
  15182. #if defined(USE_IPV6)
  15183. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15184. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15185. /* Request is directed to a different port */
  15186. return 0;
  15187. }
  15188. } else
  15189. #endif
  15190. {
  15191. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15192. /* Request is directed to a different port */
  15193. return 0;
  15194. }
  15195. }
  15196. /* Finally check if the server corresponds to the authentication
  15197. * domain of the server (the server domain).
  15198. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15199. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15200. * but do not allow substrings (like
  15201. * http://notmydomain.com/path/file.ext
  15202. * or http://mydomain.com.fake/path/file.ext).
  15203. */
  15204. if (auth_domain_check_enabled) {
  15205. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15206. server_domain_len = strlen(server_domain);
  15207. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15208. return 0;
  15209. }
  15210. if ((request_domain_len == server_domain_len)
  15211. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15212. /* Request is directed to this server - full name match. */
  15213. } else {
  15214. if (request_domain_len < (server_domain_len + 2)) {
  15215. /* Request is directed to another server: The server name
  15216. * is longer than the request name.
  15217. * Drop this case here to avoid overflows in the
  15218. * following checks. */
  15219. return 0;
  15220. }
  15221. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15222. /* Request is directed to another server: It could be a
  15223. * substring
  15224. * like notmyserver.com */
  15225. return 0;
  15226. }
  15227. if (0
  15228. != memcmp(server_domain,
  15229. hostbegin + request_domain_len - server_domain_len,
  15230. server_domain_len)) {
  15231. /* Request is directed to another server:
  15232. * The server name is different. */
  15233. return 0;
  15234. }
  15235. }
  15236. }
  15237. return hostend;
  15238. }
  15239. static int
  15240. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15241. {
  15242. if (ebuf_len > 0) {
  15243. ebuf[0] = '\0';
  15244. }
  15245. *err = 0;
  15246. reset_per_request_attributes(conn);
  15247. if (!conn) {
  15248. mg_snprintf(conn,
  15249. NULL, /* No truncation check for ebuf */
  15250. ebuf,
  15251. ebuf_len,
  15252. "%s",
  15253. "Internal error");
  15254. *err = 500;
  15255. return 0;
  15256. }
  15257. /* Set the time the request was received. This value should be used for
  15258. * timeouts. */
  15259. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15260. conn->request_len =
  15261. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15262. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15263. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15264. mg_snprintf(conn,
  15265. NULL, /* No truncation check for ebuf */
  15266. ebuf,
  15267. ebuf_len,
  15268. "%s",
  15269. "Invalid message size");
  15270. *err = 500;
  15271. return 0;
  15272. }
  15273. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15274. mg_snprintf(conn,
  15275. NULL, /* No truncation check for ebuf */
  15276. ebuf,
  15277. ebuf_len,
  15278. "%s",
  15279. "Message too large");
  15280. *err = 413;
  15281. return 0;
  15282. }
  15283. if (conn->request_len <= 0) {
  15284. if (conn->data_len > 0) {
  15285. mg_snprintf(conn,
  15286. NULL, /* No truncation check for ebuf */
  15287. ebuf,
  15288. ebuf_len,
  15289. "%s",
  15290. "Malformed message");
  15291. *err = 400;
  15292. } else {
  15293. /* Server did not recv anything -> just close the connection */
  15294. conn->must_close = 1;
  15295. mg_snprintf(conn,
  15296. NULL, /* No truncation check for ebuf */
  15297. ebuf,
  15298. ebuf_len,
  15299. "%s",
  15300. "No data received");
  15301. *err = 0;
  15302. }
  15303. return 0;
  15304. }
  15305. return 1;
  15306. }
  15307. static int
  15308. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15309. {
  15310. const char *cl;
  15311. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15312. return 0;
  15313. }
  15314. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15315. <= 0) {
  15316. mg_snprintf(conn,
  15317. NULL, /* No truncation check for ebuf */
  15318. ebuf,
  15319. ebuf_len,
  15320. "%s",
  15321. "Bad request");
  15322. *err = 400;
  15323. return 0;
  15324. }
  15325. /* Message is a valid request */
  15326. /* Is there a "host" ? */
  15327. if (conn->host != NULL) {
  15328. mg_free((void *)conn->host);
  15329. }
  15330. conn->host = alloc_get_host(conn);
  15331. if (!conn->host) {
  15332. mg_snprintf(conn,
  15333. NULL, /* No truncation check for ebuf */
  15334. ebuf,
  15335. ebuf_len,
  15336. "%s",
  15337. "Bad request: Host mismatch");
  15338. *err = 400;
  15339. return 0;
  15340. }
  15341. if (((cl = get_header(conn->request_info.http_headers,
  15342. conn->request_info.num_headers,
  15343. "Transfer-Encoding"))
  15344. != NULL)
  15345. && mg_strcasecmp(cl, "identity")) {
  15346. if (mg_strcasecmp(cl, "chunked")) {
  15347. mg_snprintf(conn,
  15348. NULL, /* No truncation check for ebuf */
  15349. ebuf,
  15350. ebuf_len,
  15351. "%s",
  15352. "Bad request");
  15353. *err = 400;
  15354. return 0;
  15355. }
  15356. conn->is_chunked = 1;
  15357. conn->content_len = 0; /* not yet read */
  15358. } else if ((cl = get_header(conn->request_info.http_headers,
  15359. conn->request_info.num_headers,
  15360. "Content-Length"))
  15361. != NULL) {
  15362. /* Request has content length set */
  15363. char *endptr = NULL;
  15364. conn->content_len = strtoll(cl, &endptr, 10);
  15365. if ((endptr == cl) || (conn->content_len < 0)) {
  15366. mg_snprintf(conn,
  15367. NULL, /* No truncation check for ebuf */
  15368. ebuf,
  15369. ebuf_len,
  15370. "%s",
  15371. "Bad request");
  15372. *err = 411;
  15373. return 0;
  15374. }
  15375. /* Publish the content length back to the request info. */
  15376. conn->request_info.content_length = conn->content_len;
  15377. } else {
  15378. /* There is no exception, see RFC7230. */
  15379. conn->content_len = 0;
  15380. }
  15381. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15382. return 1;
  15383. }
  15384. /* conn is assumed to be valid in this internal function */
  15385. static int
  15386. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15387. {
  15388. const char *cl;
  15389. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15390. return 0;
  15391. }
  15392. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15393. <= 0) {
  15394. mg_snprintf(conn,
  15395. NULL, /* No truncation check for ebuf */
  15396. ebuf,
  15397. ebuf_len,
  15398. "%s",
  15399. "Bad response");
  15400. *err = 400;
  15401. return 0;
  15402. }
  15403. /* Message is a valid response */
  15404. if (((cl = get_header(conn->response_info.http_headers,
  15405. conn->response_info.num_headers,
  15406. "Transfer-Encoding"))
  15407. != NULL)
  15408. && mg_strcasecmp(cl, "identity")) {
  15409. if (mg_strcasecmp(cl, "chunked")) {
  15410. mg_snprintf(conn,
  15411. NULL, /* No truncation check for ebuf */
  15412. ebuf,
  15413. ebuf_len,
  15414. "%s",
  15415. "Bad request");
  15416. *err = 400;
  15417. return 0;
  15418. }
  15419. conn->is_chunked = 1;
  15420. conn->content_len = 0; /* not yet read */
  15421. } else if ((cl = get_header(conn->response_info.http_headers,
  15422. conn->response_info.num_headers,
  15423. "Content-Length"))
  15424. != NULL) {
  15425. char *endptr = NULL;
  15426. conn->content_len = strtoll(cl, &endptr, 10);
  15427. if ((endptr == cl) || (conn->content_len < 0)) {
  15428. mg_snprintf(conn,
  15429. NULL, /* No truncation check for ebuf */
  15430. ebuf,
  15431. ebuf_len,
  15432. "%s",
  15433. "Bad request");
  15434. *err = 411;
  15435. return 0;
  15436. }
  15437. /* Publish the content length back to the response info. */
  15438. conn->response_info.content_length = conn->content_len;
  15439. /* TODO: check if it is still used in response_info */
  15440. conn->request_info.content_length = conn->content_len;
  15441. /* TODO: we should also consider HEAD method */
  15442. if (conn->response_info.status_code == 304) {
  15443. conn->content_len = 0;
  15444. }
  15445. } else {
  15446. /* TODO: we should also consider HEAD method */
  15447. if (((conn->response_info.status_code >= 100)
  15448. && (conn->response_info.status_code <= 199))
  15449. || (conn->response_info.status_code == 204)
  15450. || (conn->response_info.status_code == 304)) {
  15451. conn->content_len = 0;
  15452. } else {
  15453. conn->content_len = -1; /* unknown content length */
  15454. }
  15455. }
  15456. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15457. return 1;
  15458. }
  15459. int
  15460. mg_get_response(struct mg_connection *conn,
  15461. char *ebuf,
  15462. size_t ebuf_len,
  15463. int timeout)
  15464. {
  15465. int err, ret;
  15466. char txt[32]; /* will not overflow */
  15467. char *save_timeout;
  15468. char *new_timeout;
  15469. if (ebuf_len > 0) {
  15470. ebuf[0] = '\0';
  15471. }
  15472. if (!conn) {
  15473. mg_snprintf(conn,
  15474. NULL, /* No truncation check for ebuf */
  15475. ebuf,
  15476. ebuf_len,
  15477. "%s",
  15478. "Parameter error");
  15479. return -1;
  15480. }
  15481. /* Reset the previous responses */
  15482. conn->data_len = 0;
  15483. /* Implementation of API function for HTTP clients */
  15484. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15485. if (timeout >= 0) {
  15486. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15487. new_timeout = txt;
  15488. } else {
  15489. new_timeout = NULL;
  15490. }
  15491. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15492. ret = get_response(conn, ebuf, ebuf_len, &err);
  15493. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15494. #if defined(MG_LEGACY_INTERFACE)
  15495. /* TODO: 1) uri is deprecated;
  15496. * 2) here, ri.uri is the http response code */
  15497. conn->request_info.uri = conn->request_info.request_uri;
  15498. #endif
  15499. conn->request_info.local_uri = conn->request_info.request_uri;
  15500. /* TODO (mid): Define proper return values - maybe return length?
  15501. * For the first test use <0 for error and >0 for OK */
  15502. return (ret == 0) ? -1 : +1;
  15503. }
  15504. struct mg_connection *
  15505. mg_download(const char *host,
  15506. int port,
  15507. int use_ssl,
  15508. char *ebuf,
  15509. size_t ebuf_len,
  15510. const char *fmt,
  15511. ...)
  15512. {
  15513. struct mg_connection *conn;
  15514. va_list ap;
  15515. int i;
  15516. int reqerr;
  15517. if (ebuf_len > 0) {
  15518. ebuf[0] = '\0';
  15519. }
  15520. va_start(ap, fmt);
  15521. /* open a connection */
  15522. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15523. if (conn != NULL) {
  15524. i = mg_vprintf(conn, fmt, ap);
  15525. if (i <= 0) {
  15526. mg_snprintf(conn,
  15527. NULL, /* No truncation check for ebuf */
  15528. ebuf,
  15529. ebuf_len,
  15530. "%s",
  15531. "Error sending request");
  15532. } else {
  15533. /* make sure the buffer is clear */
  15534. conn->data_len = 0;
  15535. get_response(conn, ebuf, ebuf_len, &reqerr);
  15536. #if defined(MG_LEGACY_INTERFACE)
  15537. /* TODO: 1) uri is deprecated;
  15538. * 2) here, ri.uri is the http response code */
  15539. conn->request_info.uri = conn->request_info.request_uri;
  15540. #endif
  15541. conn->request_info.local_uri = conn->request_info.request_uri;
  15542. }
  15543. }
  15544. /* if an error occurred, close the connection */
  15545. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15546. mg_close_connection(conn);
  15547. conn = NULL;
  15548. }
  15549. va_end(ap);
  15550. return conn;
  15551. }
  15552. struct websocket_client_thread_data {
  15553. struct mg_connection *conn;
  15554. mg_websocket_data_handler data_handler;
  15555. mg_websocket_close_handler close_handler;
  15556. void *callback_data;
  15557. };
  15558. #if defined(USE_WEBSOCKET)
  15559. #if defined(_WIN32)
  15560. static unsigned __stdcall websocket_client_thread(void *data)
  15561. #else
  15562. static void *
  15563. websocket_client_thread(void *data)
  15564. #endif
  15565. {
  15566. struct websocket_client_thread_data *cdata =
  15567. (struct websocket_client_thread_data *)data;
  15568. void *user_thread_ptr = NULL;
  15569. #if !defined(_WIN32)
  15570. struct sigaction sa;
  15571. /* Ignore SIGPIPE */
  15572. memset(&sa, 0, sizeof(sa));
  15573. sa.sa_handler = SIG_IGN;
  15574. sigaction(SIGPIPE, &sa, NULL);
  15575. #endif
  15576. mg_set_thread_name("ws-clnt");
  15577. if (cdata->conn->phys_ctx) {
  15578. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15579. /* 3 indicates a websocket client thread */
  15580. /* TODO: check if conn->phys_ctx can be set */
  15581. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15582. cdata->conn->phys_ctx, 3);
  15583. }
  15584. }
  15585. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15586. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15587. if (cdata->close_handler != NULL) {
  15588. cdata->close_handler(cdata->conn, cdata->callback_data);
  15589. }
  15590. /* The websocket_client context has only this thread. If it runs out,
  15591. set the stop_flag to 2 (= "stopped"). */
  15592. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15593. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15594. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15595. 3,
  15596. user_thread_ptr);
  15597. }
  15598. mg_free((void *)cdata);
  15599. #if defined(_WIN32)
  15600. return 0;
  15601. #else
  15602. return NULL;
  15603. #endif
  15604. }
  15605. #endif
  15606. static struct mg_connection *
  15607. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15608. int use_ssl,
  15609. char *error_buffer,
  15610. size_t error_buffer_size,
  15611. const char *path,
  15612. const char *origin,
  15613. mg_websocket_data_handler data_func,
  15614. mg_websocket_close_handler close_func,
  15615. void *user_data)
  15616. {
  15617. struct mg_connection *conn = NULL;
  15618. #if defined(USE_WEBSOCKET)
  15619. struct websocket_client_thread_data *thread_data;
  15620. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15621. const char *handshake_req;
  15622. int port = client_options->port;
  15623. const char *host = client_options->host;
  15624. int i;
  15625. if (origin != NULL) {
  15626. handshake_req = "GET %s HTTP/1.1\r\n"
  15627. "Host: %s\r\n"
  15628. "Upgrade: websocket\r\n"
  15629. "Connection: Upgrade\r\n"
  15630. "Sec-WebSocket-Key: %s\r\n"
  15631. "Sec-WebSocket-Version: 13\r\n"
  15632. "Origin: %s\r\n"
  15633. "\r\n";
  15634. } else {
  15635. handshake_req = "GET %s HTTP/1.1\r\n"
  15636. "Host: %s\r\n"
  15637. "Upgrade: websocket\r\n"
  15638. "Connection: Upgrade\r\n"
  15639. "Sec-WebSocket-Key: %s\r\n"
  15640. "Sec-WebSocket-Version: 13\r\n"
  15641. "\r\n";
  15642. }
  15643. #if defined(__clang__)
  15644. #pragma clang diagnostic push
  15645. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15646. #endif
  15647. /* Establish the client connection and request upgrade */
  15648. conn =
  15649. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15650. if (conn == NULL) {
  15651. /* error_buffer already filled */
  15652. return NULL;
  15653. }
  15654. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15655. if (i <= 0) {
  15656. mg_snprintf(conn,
  15657. NULL, /* No truncation check for ebuf */
  15658. error_buffer,
  15659. error_buffer_size,
  15660. "%s",
  15661. "Error sending request");
  15662. mg_close_connection(conn);
  15663. return NULL;
  15664. }
  15665. conn->data_len = 0;
  15666. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15667. mg_close_connection(conn);
  15668. return NULL;
  15669. }
  15670. conn->request_info.local_uri = conn->request_info.request_uri;
  15671. #if defined(__clang__)
  15672. #pragma clang diagnostic pop
  15673. #endif
  15674. /* Connection object will be null if something goes wrong */
  15675. if (conn == NULL) {
  15676. if (!*error_buffer) {
  15677. /* There should be already an error message */
  15678. mg_snprintf(conn,
  15679. NULL, /* No truncation check for ebuf */
  15680. error_buffer,
  15681. error_buffer_size,
  15682. "Unexpected error");
  15683. }
  15684. return NULL;
  15685. }
  15686. if (conn->response_info.status_code != 101) {
  15687. /* We sent an "upgrade" request. For a correct websocket
  15688. * protocol handshake, we expect a "101 Continue" response.
  15689. * Otherwise it is a protocol violation. Maybe the HTTP
  15690. * Server does not know websockets. */
  15691. if (!*error_buffer) {
  15692. /* set an error, if not yet set */
  15693. mg_snprintf(conn,
  15694. NULL, /* No truncation check for ebuf */
  15695. error_buffer,
  15696. error_buffer_size,
  15697. "Unexpected server reply");
  15698. }
  15699. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15700. mg_close_connection(conn);
  15701. return NULL;
  15702. }
  15703. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15704. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15705. if (!thread_data) {
  15706. DEBUG_TRACE("%s\r\n", "Out of memory");
  15707. mg_close_connection(conn);
  15708. return NULL;
  15709. }
  15710. thread_data->conn = conn;
  15711. thread_data->data_handler = data_func;
  15712. thread_data->close_handler = close_func;
  15713. thread_data->callback_data = user_data;
  15714. conn->phys_ctx->worker_threadids =
  15715. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15716. if (!conn->phys_ctx->worker_threadids) {
  15717. DEBUG_TRACE("%s\r\n", "Out of memory");
  15718. mg_free(thread_data);
  15719. mg_close_connection(conn);
  15720. return NULL;
  15721. }
  15722. /* Now upgrade to ws/wss client context */
  15723. conn->phys_ctx->user_data = user_data;
  15724. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15725. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15726. /* Start a thread to read the websocket client connection
  15727. * This thread will automatically stop when mg_disconnect is
  15728. * called on the client connection */
  15729. if (mg_start_thread_with_id(websocket_client_thread,
  15730. thread_data,
  15731. conn->phys_ctx->worker_threadids)
  15732. != 0) {
  15733. conn->phys_ctx->cfg_worker_threads = 0;
  15734. mg_free(thread_data);
  15735. mg_close_connection(conn);
  15736. conn = NULL;
  15737. DEBUG_TRACE("%s",
  15738. "Websocket client connect thread could not be started\r\n");
  15739. }
  15740. #else
  15741. /* Appease "unused parameter" warnings */
  15742. (void)client_options;
  15743. (void)use_ssl;
  15744. (void)error_buffer;
  15745. (void)error_buffer_size;
  15746. (void)path;
  15747. (void)origin;
  15748. (void)user_data;
  15749. (void)data_func;
  15750. (void)close_func;
  15751. #endif
  15752. return conn;
  15753. }
  15754. struct mg_connection *
  15755. mg_connect_websocket_client(const char *host,
  15756. int port,
  15757. int use_ssl,
  15758. char *error_buffer,
  15759. size_t error_buffer_size,
  15760. const char *path,
  15761. const char *origin,
  15762. mg_websocket_data_handler data_func,
  15763. mg_websocket_close_handler close_func,
  15764. void *user_data)
  15765. {
  15766. struct mg_client_options client_options;
  15767. memset(&client_options, 0, sizeof(client_options));
  15768. client_options.host = host;
  15769. client_options.port = port;
  15770. return mg_connect_websocket_client_impl(&client_options,
  15771. use_ssl,
  15772. error_buffer,
  15773. error_buffer_size,
  15774. path,
  15775. origin,
  15776. data_func,
  15777. close_func,
  15778. user_data);
  15779. }
  15780. struct mg_connection *
  15781. mg_connect_websocket_client_secure(
  15782. const struct mg_client_options *client_options,
  15783. char *error_buffer,
  15784. size_t error_buffer_size,
  15785. const char *path,
  15786. const char *origin,
  15787. mg_websocket_data_handler data_func,
  15788. mg_websocket_close_handler close_func,
  15789. void *user_data)
  15790. {
  15791. if (!client_options) {
  15792. return NULL;
  15793. }
  15794. return mg_connect_websocket_client_impl(client_options,
  15795. 1,
  15796. error_buffer,
  15797. error_buffer_size,
  15798. path,
  15799. origin,
  15800. data_func,
  15801. close_func,
  15802. user_data);
  15803. }
  15804. /* Prepare connection data structure */
  15805. static void
  15806. init_connection(struct mg_connection *conn)
  15807. {
  15808. /* Is keep alive allowed by the server */
  15809. int keep_alive_enabled =
  15810. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15811. if (!keep_alive_enabled) {
  15812. conn->must_close = 1;
  15813. }
  15814. /* Important: on new connection, reset the receiving buffer. Credit
  15815. * goes to crule42. */
  15816. conn->data_len = 0;
  15817. conn->handled_requests = 0;
  15818. mg_set_user_connection_data(conn, NULL);
  15819. #if defined(USE_SERVER_STATS)
  15820. conn->conn_state = 2; /* init */
  15821. #endif
  15822. /* call the init_connection callback if assigned */
  15823. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15824. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15825. void *conn_data = NULL;
  15826. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15827. mg_set_user_connection_data(conn, conn_data);
  15828. }
  15829. }
  15830. }
  15831. /* Process a connection - may handle multiple requests
  15832. * using the same connection.
  15833. * Must be called with a valid connection (conn and
  15834. * conn->phys_ctx must be valid).
  15835. */
  15836. static void
  15837. process_new_connection(struct mg_connection *conn)
  15838. {
  15839. struct mg_request_info *ri = &conn->request_info;
  15840. int keep_alive, discard_len;
  15841. char ebuf[100];
  15842. const char *hostend;
  15843. int reqerr, uri_type;
  15844. #if defined(USE_SERVER_STATS)
  15845. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15846. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15847. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15848. /* could use atomic compare exchange, but this
  15849. * seems overkill for statistics data */
  15850. conn->phys_ctx->max_active_connections = mcon;
  15851. }
  15852. #endif
  15853. init_connection(conn);
  15854. DEBUG_TRACE("Start processing connection from %s",
  15855. conn->request_info.remote_addr);
  15856. /* Loop over multiple requests sent using the same connection
  15857. * (while "keep alive"). */
  15858. do {
  15859. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15860. conn->handled_requests + 1);
  15861. #if defined(USE_SERVER_STATS)
  15862. conn->conn_state = 3; /* ready */
  15863. #endif
  15864. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15865. /* The request sent by the client could not be understood by
  15866. * the server, or it was incomplete or a timeout. Send an
  15867. * error message and close the connection. */
  15868. if (reqerr > 0) {
  15869. DEBUG_ASSERT(ebuf[0] != '\0');
  15870. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15871. }
  15872. } else if (strcmp(ri->http_version, "1.0")
  15873. && strcmp(ri->http_version, "1.1")) {
  15874. /* HTTP/2 is not allowed here */
  15875. mg_snprintf(conn,
  15876. NULL, /* No truncation check for ebuf */
  15877. ebuf,
  15878. sizeof(ebuf),
  15879. "Bad HTTP version: [%s]",
  15880. ri->http_version);
  15881. mg_send_http_error(conn, 505, "%s", ebuf);
  15882. }
  15883. if (ebuf[0] == '\0') {
  15884. uri_type = get_uri_type(conn->request_info.request_uri);
  15885. switch (uri_type) {
  15886. case 1:
  15887. /* Asterisk */
  15888. conn->request_info.local_uri = 0;
  15889. /* TODO: Deal with '*'. */
  15890. break;
  15891. case 2:
  15892. /* relative uri */
  15893. conn->request_info.local_uri = conn->request_info.request_uri;
  15894. break;
  15895. case 3:
  15896. case 4:
  15897. /* absolute uri (with/without port) */
  15898. hostend = get_rel_url_at_current_server(
  15899. conn->request_info.request_uri, conn);
  15900. if (hostend) {
  15901. conn->request_info.local_uri = hostend;
  15902. } else {
  15903. conn->request_info.local_uri = NULL;
  15904. }
  15905. break;
  15906. default:
  15907. mg_snprintf(conn,
  15908. NULL, /* No truncation check for ebuf */
  15909. ebuf,
  15910. sizeof(ebuf),
  15911. "Invalid URI");
  15912. mg_send_http_error(conn, 400, "%s", ebuf);
  15913. conn->request_info.local_uri = NULL;
  15914. break;
  15915. }
  15916. #if defined(MG_LEGACY_INTERFACE)
  15917. /* Legacy before split into local_uri and request_uri */
  15918. conn->request_info.uri = conn->request_info.local_uri;
  15919. #endif
  15920. }
  15921. if (ebuf[0] != '\0') {
  15922. conn->protocol_type = -1;
  15923. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15924. /* HTTP/1 allows protocol upgrade */
  15925. conn->protocol_type = should_switch_to_protocol(conn);
  15926. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15927. /* This will occur, if a HTTP/1.1 request should be upgraded
  15928. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15929. * Since most (all?) major browsers only support HTTP/2 using
  15930. * ALPN, this is hard to test and very low priority.
  15931. * Deactivate it (at least for now).
  15932. */
  15933. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15934. }
  15935. }
  15936. DEBUG_TRACE("http: %s, error: %s",
  15937. (ri->http_version ? ri->http_version : "none"),
  15938. (ebuf[0] ? ebuf : "none"));
  15939. if (ebuf[0] == '\0') {
  15940. if (conn->request_info.local_uri) {
  15941. /* handle request to local server */
  15942. #if defined(USE_SERVER_STATS)
  15943. conn->conn_state = 4; /* processing */
  15944. #endif
  15945. handle_request(conn);
  15946. #if defined(USE_SERVER_STATS)
  15947. conn->conn_state = 5; /* processed */
  15948. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15949. conn->consumed_content);
  15950. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15951. conn->num_bytes_sent);
  15952. #endif
  15953. DEBUG_TRACE("%s", "handle_request done");
  15954. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15955. conn->phys_ctx->callbacks.end_request(conn,
  15956. conn->status_code);
  15957. DEBUG_TRACE("%s", "end_request callback done");
  15958. }
  15959. log_access(conn);
  15960. } else {
  15961. /* TODO: handle non-local request (PROXY) */
  15962. conn->must_close = 1;
  15963. }
  15964. } else {
  15965. conn->must_close = 1;
  15966. }
  15967. if (ri->remote_user != NULL) {
  15968. mg_free((void *)ri->remote_user);
  15969. /* Important! When having connections with and without auth
  15970. * would cause double free and then crash */
  15971. ri->remote_user = NULL;
  15972. }
  15973. /* NOTE(lsm): order is important here. should_keep_alive() call
  15974. * is using parsed request, which will be invalid after
  15975. * memmove's below.
  15976. * Therefore, memorize should_keep_alive() result now for later
  15977. * use in loop exit condition. */
  15978. /* Enable it only if this request is completely discardable. */
  15979. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  15980. && should_keep_alive(conn) && (conn->content_len >= 0)
  15981. && (conn->request_len > 0)
  15982. && ((conn->is_chunked == 4)
  15983. || (!conn->is_chunked
  15984. && ((conn->consumed_content == conn->content_len)
  15985. || ((conn->request_len + conn->content_len)
  15986. <= conn->data_len))))
  15987. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  15988. if (keep_alive) {
  15989. /* Discard all buffered data for this request */
  15990. discard_len =
  15991. ((conn->request_len + conn->content_len) < conn->data_len)
  15992. ? (int)(conn->request_len + conn->content_len)
  15993. : conn->data_len;
  15994. conn->data_len -= discard_len;
  15995. if (conn->data_len > 0) {
  15996. DEBUG_TRACE("discard_len = %d", discard_len);
  15997. memmove(conn->buf,
  15998. conn->buf + discard_len,
  15999. (size_t)conn->data_len);
  16000. }
  16001. }
  16002. DEBUG_ASSERT(conn->data_len >= 0);
  16003. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16004. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16005. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16006. (long int)conn->data_len,
  16007. (long int)conn->buf_size);
  16008. break;
  16009. }
  16010. conn->handled_requests++;
  16011. } while (keep_alive);
  16012. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16013. conn->request_info.remote_addr,
  16014. difftime(time(NULL), conn->conn_birth_time));
  16015. close_connection(conn);
  16016. #if defined(USE_SERVER_STATS)
  16017. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16018. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16019. #endif
  16020. }
  16021. #if defined(ALTERNATIVE_QUEUE)
  16022. static void
  16023. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16024. {
  16025. unsigned int i;
  16026. while (!ctx->stop_flag) {
  16027. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16028. /* find a free worker slot and signal it */
  16029. if (ctx->client_socks[i].in_use == 2) {
  16030. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16031. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16032. ctx->client_socks[i] = *sp;
  16033. ctx->client_socks[i].in_use = 1;
  16034. /* socket has been moved to the consumer */
  16035. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16036. (void)event_signal(ctx->client_wait_events[i]);
  16037. return;
  16038. }
  16039. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16040. }
  16041. }
  16042. /* queue is full */
  16043. mg_sleep(1);
  16044. }
  16045. /* must consume */
  16046. set_blocking_mode(sp->sock);
  16047. closesocket(sp->sock);
  16048. }
  16049. static int
  16050. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16051. {
  16052. DEBUG_TRACE("%s", "going idle");
  16053. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16054. ctx->client_socks[thread_index].in_use = 2;
  16055. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16056. event_wait(ctx->client_wait_events[thread_index]);
  16057. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16058. *sp = ctx->client_socks[thread_index];
  16059. if (ctx->stop_flag) {
  16060. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16061. if (sp->in_use == 1) {
  16062. /* must consume */
  16063. set_blocking_mode(sp->sock);
  16064. closesocket(sp->sock);
  16065. }
  16066. return 0;
  16067. }
  16068. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16069. if (sp->in_use == 1) {
  16070. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16071. return 1;
  16072. }
  16073. /* must not reach here */
  16074. DEBUG_ASSERT(0);
  16075. return 0;
  16076. }
  16077. #else /* ALTERNATIVE_QUEUE */
  16078. /* Worker threads take accepted socket from the queue */
  16079. static int
  16080. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16081. {
  16082. (void)thread_index;
  16083. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16084. DEBUG_TRACE("%s", "going idle");
  16085. /* If the queue is empty, wait. We're idle at this point. */
  16086. while ((ctx->sq_head == ctx->sq_tail)
  16087. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16088. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16089. }
  16090. /* If we're stopping, sq_head may be equal to sq_tail. */
  16091. if (ctx->sq_head > ctx->sq_tail) {
  16092. /* Copy socket from the queue and increment tail */
  16093. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16094. ctx->sq_tail++;
  16095. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16096. /* Wrap pointers if needed */
  16097. while (ctx->sq_tail > ctx->sq_size) {
  16098. ctx->sq_tail -= ctx->sq_size;
  16099. ctx->sq_head -= ctx->sq_size;
  16100. }
  16101. }
  16102. (void)pthread_cond_signal(&ctx->sq_empty);
  16103. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16104. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16105. }
  16106. /* Master thread adds accepted socket to a queue */
  16107. static void
  16108. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16109. {
  16110. int queue_filled;
  16111. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16112. queue_filled = ctx->sq_head - ctx->sq_tail;
  16113. /* If the queue is full, wait */
  16114. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16115. && (queue_filled >= ctx->sq_size)) {
  16116. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16117. #if defined(USE_SERVER_STATS)
  16118. if (queue_filled > ctx->sq_max_fill) {
  16119. ctx->sq_max_fill = queue_filled;
  16120. }
  16121. #endif
  16122. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16123. ctx->sq_blocked = 0; /* Not blocked now */
  16124. queue_filled = ctx->sq_head - ctx->sq_tail;
  16125. }
  16126. if (queue_filled < ctx->sq_size) {
  16127. /* Copy socket to the queue and increment head */
  16128. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16129. ctx->sq_head++;
  16130. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16131. }
  16132. queue_filled = ctx->sq_head - ctx->sq_tail;
  16133. #if defined(USE_SERVER_STATS)
  16134. if (queue_filled > ctx->sq_max_fill) {
  16135. ctx->sq_max_fill = queue_filled;
  16136. }
  16137. #endif
  16138. (void)pthread_cond_signal(&ctx->sq_full);
  16139. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16140. }
  16141. #endif /* ALTERNATIVE_QUEUE */
  16142. static void
  16143. worker_thread_run(struct mg_connection *conn)
  16144. {
  16145. struct mg_context *ctx = conn->phys_ctx;
  16146. int thread_index;
  16147. struct mg_workerTLS tls;
  16148. #if defined(MG_LEGACY_INTERFACE)
  16149. uint32_t addr;
  16150. #endif
  16151. mg_set_thread_name("worker");
  16152. tls.is_master = 0;
  16153. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16154. #if defined(_WIN32)
  16155. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16156. #endif
  16157. /* Initialize thread local storage before calling any callback */
  16158. pthread_setspecific(sTlsKey, &tls);
  16159. /* Check if there is a user callback */
  16160. if (ctx->callbacks.init_thread) {
  16161. /* call init_thread for a worker thread (type 1), and store the
  16162. * return value */
  16163. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16164. } else {
  16165. /* No callback: set user pointer to NULL */
  16166. tls.user_ptr = NULL;
  16167. }
  16168. /* Connection structure has been pre-allocated */
  16169. thread_index = (int)(conn - ctx->worker_connections);
  16170. if ((thread_index < 0)
  16171. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16172. mg_cry_ctx_internal(ctx,
  16173. "Internal error: Invalid worker index %i",
  16174. thread_index);
  16175. return;
  16176. }
  16177. /* Request buffers are not pre-allocated. They are private to the
  16178. * request and do not contain any state information that might be
  16179. * of interest to anyone observing a server status. */
  16180. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16181. if (conn->buf == NULL) {
  16182. mg_cry_ctx_internal(
  16183. ctx,
  16184. "Out of memory: Cannot allocate buffer for worker %i",
  16185. thread_index);
  16186. return;
  16187. }
  16188. conn->buf_size = (int)ctx->max_request_size;
  16189. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16190. conn->host = NULL; /* until we have more information. */
  16191. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16192. conn->request_info.user_data = ctx->user_data;
  16193. /* Allocate a mutex for this connection to allow communication both
  16194. * within the request handler and from elsewhere in the application
  16195. */
  16196. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16197. mg_free(conn->buf);
  16198. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16199. return;
  16200. }
  16201. #if defined(USE_SERVER_STATS)
  16202. conn->conn_state = 1; /* not consumed */
  16203. #endif
  16204. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16205. * signal sq_empty condvar to wake up the master waiting in
  16206. * produce_socket() */
  16207. while (consume_socket(ctx, &conn->client, thread_index)) {
  16208. /* New connections must start with new protocol negotiation */
  16209. tls.alpn_proto = NULL;
  16210. #if defined(USE_SERVER_STATS)
  16211. conn->conn_close_time = 0;
  16212. #endif
  16213. conn->conn_birth_time = time(NULL);
  16214. /* Fill in IP, port info early so even if SSL setup below fails,
  16215. * error handler would have the corresponding info.
  16216. * Thanks to Johannes Winkelmann for the patch.
  16217. */
  16218. #if defined(USE_IPV6)
  16219. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16220. conn->request_info.remote_port =
  16221. ntohs(conn->client.rsa.sin6.sin6_port);
  16222. } else
  16223. #endif
  16224. {
  16225. conn->request_info.remote_port =
  16226. ntohs(conn->client.rsa.sin.sin_port);
  16227. }
  16228. sockaddr_to_string(conn->request_info.remote_addr,
  16229. sizeof(conn->request_info.remote_addr),
  16230. &conn->client.rsa);
  16231. DEBUG_TRACE("Start processing connection from %s",
  16232. conn->request_info.remote_addr);
  16233. conn->request_info.is_ssl = conn->client.is_ssl;
  16234. if (conn->client.is_ssl) {
  16235. #if !defined(NO_SSL)
  16236. /* HTTPS connection */
  16237. if (sslize(conn, SSL_accept, NULL)) {
  16238. /* conn->dom_ctx is set in get_request */
  16239. /* Get SSL client certificate information (if set) */
  16240. struct mg_client_cert client_cert;
  16241. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16242. conn->request_info.client_cert = &client_cert;
  16243. }
  16244. /* process HTTPS connection */
  16245. #if defined(USE_HTTP2)
  16246. if ((tls.alpn_proto != NULL)
  16247. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16248. /* process HTTPS/2 connection */
  16249. init_connection(conn);
  16250. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16251. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16252. conn->content_len = -1;
  16253. conn->is_chunked = 0;
  16254. process_new_http2_connection(conn);
  16255. } else
  16256. #endif
  16257. {
  16258. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16259. process_new_connection(conn);
  16260. }
  16261. /* Free client certificate info */
  16262. if (conn->request_info.client_cert) {
  16263. mg_free((void *)(conn->request_info.client_cert->subject));
  16264. mg_free((void *)(conn->request_info.client_cert->issuer));
  16265. mg_free((void *)(conn->request_info.client_cert->serial));
  16266. mg_free((void *)(conn->request_info.client_cert->finger));
  16267. /* Free certificate memory */
  16268. X509_free(
  16269. (X509 *)conn->request_info.client_cert->peer_cert);
  16270. conn->request_info.client_cert->peer_cert = 0;
  16271. conn->request_info.client_cert->subject = 0;
  16272. conn->request_info.client_cert->issuer = 0;
  16273. conn->request_info.client_cert->serial = 0;
  16274. conn->request_info.client_cert->finger = 0;
  16275. conn->request_info.client_cert = 0;
  16276. }
  16277. } else {
  16278. /* make sure the connection is cleaned up on SSL failure */
  16279. close_connection(conn);
  16280. }
  16281. #endif
  16282. } else {
  16283. /* process HTTP connection */
  16284. process_new_connection(conn);
  16285. }
  16286. DEBUG_TRACE("%s", "Connection closed");
  16287. #if defined(USE_SERVER_STATS)
  16288. conn->conn_close_time = time(NULL);
  16289. #endif
  16290. }
  16291. /* Call exit thread user callback */
  16292. if (ctx->callbacks.exit_thread) {
  16293. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16294. }
  16295. /* delete thread local storage objects */
  16296. pthread_setspecific(sTlsKey, NULL);
  16297. #if defined(_WIN32)
  16298. CloseHandle(tls.pthread_cond_helper_mutex);
  16299. #endif
  16300. pthread_mutex_destroy(&conn->mutex);
  16301. /* Free the request buffer. */
  16302. conn->buf_size = 0;
  16303. mg_free(conn->buf);
  16304. conn->buf = NULL;
  16305. #if defined(USE_SERVER_STATS)
  16306. conn->conn_state = 9; /* done */
  16307. #endif
  16308. DEBUG_TRACE("%s", "exiting");
  16309. }
  16310. /* Threads have different return types on Windows and Unix. */
  16311. #if defined(_WIN32)
  16312. static unsigned __stdcall worker_thread(void *thread_func_param)
  16313. {
  16314. worker_thread_run((struct mg_connection *)thread_func_param);
  16315. return 0;
  16316. }
  16317. #else
  16318. static void *
  16319. worker_thread(void *thread_func_param)
  16320. {
  16321. #if !defined(__ZEPHYR__)
  16322. struct sigaction sa;
  16323. /* Ignore SIGPIPE */
  16324. memset(&sa, 0, sizeof(sa));
  16325. sa.sa_handler = SIG_IGN;
  16326. sigaction(SIGPIPE, &sa, NULL);
  16327. #endif
  16328. worker_thread_run((struct mg_connection *)thread_func_param);
  16329. return NULL;
  16330. }
  16331. #endif /* _WIN32 */
  16332. /* This is an internal function, thus all arguments are expected to be
  16333. * valid - a NULL check is not required. */
  16334. static void
  16335. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16336. {
  16337. struct socket so;
  16338. char src_addr[IP_ADDR_STR_LEN];
  16339. socklen_t len = sizeof(so.rsa);
  16340. #if !defined(__ZEPHYR__)
  16341. int on = 1;
  16342. #endif
  16343. memset(&so, 0, sizeof(so));
  16344. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16345. == INVALID_SOCKET) {
  16346. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16347. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16348. mg_cry_ctx_internal(ctx,
  16349. "%s: %s is not allowed to connect",
  16350. __func__,
  16351. src_addr);
  16352. closesocket(so.sock);
  16353. } else {
  16354. /* Put so socket structure into the queue */
  16355. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16356. set_close_on_exec(so.sock, NULL, ctx);
  16357. so.is_ssl = listener->is_ssl;
  16358. so.ssl_redir = listener->ssl_redir;
  16359. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16360. mg_cry_ctx_internal(ctx,
  16361. "%s: getsockname() failed: %s",
  16362. __func__,
  16363. strerror(ERRNO));
  16364. }
  16365. #if !defined(__ZEPHYR__)
  16366. /* Set TCP keep-alive. This is needed because if HTTP-level
  16367. * keep-alive
  16368. * is enabled, and client resets the connection, server won't get
  16369. * TCP FIN or RST and will keep the connection open forever. With
  16370. * TCP keep-alive, next keep-alive handshake will figure out that
  16371. * the client is down and will close the server end.
  16372. * Thanks to Igor Klopov who suggested the patch. */
  16373. if (setsockopt(so.sock,
  16374. SOL_SOCKET,
  16375. SO_KEEPALIVE,
  16376. (SOCK_OPT_TYPE)&on,
  16377. sizeof(on))
  16378. != 0) {
  16379. mg_cry_ctx_internal(
  16380. ctx,
  16381. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16382. __func__,
  16383. strerror(ERRNO));
  16384. }
  16385. #endif
  16386. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16387. * to effectively fill up the underlying IP packet payload and
  16388. * reduce the overhead of sending lots of small buffers. However
  16389. * this hurts the server's throughput (ie. operations per second)
  16390. * when HTTP 1.1 persistent connections are used and the responses
  16391. * are relatively small (eg. less than 1400 bytes).
  16392. */
  16393. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16394. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16395. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16396. mg_cry_ctx_internal(
  16397. ctx,
  16398. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16399. __func__,
  16400. strerror(ERRNO));
  16401. }
  16402. }
  16403. /* The "non blocking" property should already be
  16404. * inherited from the parent socket. Set it for
  16405. * non-compliant socket implementations. */
  16406. set_non_blocking_mode(so.sock);
  16407. so.in_use = 0;
  16408. produce_socket(ctx, &so);
  16409. }
  16410. }
  16411. static void
  16412. master_thread_run(struct mg_context *ctx)
  16413. {
  16414. struct mg_workerTLS tls;
  16415. struct mg_pollfd *pfd;
  16416. unsigned int i;
  16417. unsigned int workerthreadcount;
  16418. if (!ctx) {
  16419. return;
  16420. }
  16421. mg_set_thread_name("master");
  16422. /* Increase priority of the master thread */
  16423. #if defined(_WIN32)
  16424. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16425. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16426. int min_prio = sched_get_priority_min(SCHED_RR);
  16427. int max_prio = sched_get_priority_max(SCHED_RR);
  16428. if ((min_prio >= 0) && (max_prio >= 0)
  16429. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16430. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16431. struct sched_param sched_param = {0};
  16432. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16433. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16434. }
  16435. #endif
  16436. /* Initialize thread local storage */
  16437. #if defined(_WIN32)
  16438. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16439. #endif
  16440. tls.is_master = 1;
  16441. pthread_setspecific(sTlsKey, &tls);
  16442. if (ctx->callbacks.init_thread) {
  16443. /* Callback for the master thread (type 0) */
  16444. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16445. } else {
  16446. tls.user_ptr = NULL;
  16447. }
  16448. /* Server starts *now* */
  16449. ctx->start_time = time(NULL);
  16450. /* Start the server */
  16451. pfd = ctx->listening_socket_fds;
  16452. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16453. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16454. pfd[i].fd = ctx->listening_sockets[i].sock;
  16455. pfd[i].events = POLLIN;
  16456. }
  16457. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16458. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16459. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16460. * successful poll, and POLLIN is defined as
  16461. * (POLLRDNORM | POLLRDBAND)
  16462. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16463. * pfd[i].revents == POLLIN. */
  16464. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16465. && (pfd[i].revents & POLLIN)) {
  16466. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16467. }
  16468. }
  16469. }
  16470. }
  16471. /* Here stop_flag is 1 - Initiate shutdown. */
  16472. DEBUG_TRACE("%s", "stopping workers");
  16473. /* Stop signal received: somebody called mg_stop. Quit. */
  16474. close_all_listening_sockets(ctx);
  16475. /* Wakeup workers that are waiting for connections to handle. */
  16476. #if defined(ALTERNATIVE_QUEUE)
  16477. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16478. event_signal(ctx->client_wait_events[i]);
  16479. }
  16480. #else
  16481. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16482. pthread_cond_broadcast(&ctx->sq_full);
  16483. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16484. #endif
  16485. /* Join all worker threads to avoid leaking threads. */
  16486. workerthreadcount = ctx->cfg_worker_threads;
  16487. for (i = 0; i < workerthreadcount; i++) {
  16488. if (ctx->worker_threadids[i] != 0) {
  16489. mg_join_thread(ctx->worker_threadids[i]);
  16490. }
  16491. }
  16492. #if defined(USE_LUA)
  16493. /* Free Lua state of lua background task */
  16494. if (ctx->lua_background_state) {
  16495. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16496. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16497. if (lua_istable(lstate, -1)) {
  16498. reg_boolean(lstate, "shutdown", 1);
  16499. lua_pop(lstate, 1);
  16500. mg_sleep(2);
  16501. }
  16502. lua_close(lstate);
  16503. ctx->lua_background_state = 0;
  16504. }
  16505. #endif
  16506. DEBUG_TRACE("%s", "exiting");
  16507. /* call exit thread callback */
  16508. if (ctx->callbacks.exit_thread) {
  16509. /* Callback for the master thread (type 0) */
  16510. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16511. }
  16512. #if defined(_WIN32)
  16513. CloseHandle(tls.pthread_cond_helper_mutex);
  16514. #endif
  16515. pthread_setspecific(sTlsKey, NULL);
  16516. /* Signal mg_stop() that we're done.
  16517. * WARNING: This must be the very last thing this
  16518. * thread does, as ctx becomes invalid after this line. */
  16519. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16520. }
  16521. /* Threads have different return types on Windows and Unix. */
  16522. #if defined(_WIN32)
  16523. static unsigned __stdcall master_thread(void *thread_func_param)
  16524. {
  16525. master_thread_run((struct mg_context *)thread_func_param);
  16526. return 0;
  16527. }
  16528. #else
  16529. static void *
  16530. master_thread(void *thread_func_param)
  16531. {
  16532. #if !defined(__ZEPHYR__)
  16533. struct sigaction sa;
  16534. /* Ignore SIGPIPE */
  16535. memset(&sa, 0, sizeof(sa));
  16536. sa.sa_handler = SIG_IGN;
  16537. sigaction(SIGPIPE, &sa, NULL);
  16538. #endif
  16539. master_thread_run((struct mg_context *)thread_func_param);
  16540. return NULL;
  16541. }
  16542. #endif /* _WIN32 */
  16543. static void
  16544. free_context(struct mg_context *ctx)
  16545. {
  16546. int i;
  16547. struct mg_handler_info *tmp_rh;
  16548. if (ctx == NULL) {
  16549. return;
  16550. }
  16551. if (ctx->callbacks.exit_context) {
  16552. ctx->callbacks.exit_context(ctx);
  16553. }
  16554. /* All threads exited, no sync is needed. Destroy thread mutex and
  16555. * condvars
  16556. */
  16557. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16558. #if defined(ALTERNATIVE_QUEUE)
  16559. mg_free(ctx->client_socks);
  16560. if (ctx->client_wait_events != NULL) {
  16561. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16562. event_destroy(ctx->client_wait_events[i]);
  16563. }
  16564. mg_free(ctx->client_wait_events);
  16565. }
  16566. #else
  16567. (void)pthread_cond_destroy(&ctx->sq_empty);
  16568. (void)pthread_cond_destroy(&ctx->sq_full);
  16569. mg_free(ctx->squeue);
  16570. #endif
  16571. /* Destroy other context global data structures mutex */
  16572. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16573. #if defined(USE_TIMERS)
  16574. timers_exit(ctx);
  16575. #endif
  16576. /* Deallocate config parameters */
  16577. for (i = 0; i < NUM_OPTIONS; i++) {
  16578. if (ctx->dd.config[i] != NULL) {
  16579. #if defined(_MSC_VER)
  16580. #pragma warning(suppress : 6001)
  16581. #endif
  16582. mg_free(ctx->dd.config[i]);
  16583. }
  16584. }
  16585. /* Deallocate request handlers */
  16586. while (ctx->dd.handlers) {
  16587. tmp_rh = ctx->dd.handlers;
  16588. ctx->dd.handlers = tmp_rh->next;
  16589. mg_free(tmp_rh->uri);
  16590. mg_free(tmp_rh);
  16591. }
  16592. #if !defined(NO_SSL)
  16593. /* Deallocate SSL context */
  16594. if (ctx->dd.ssl_ctx != NULL) {
  16595. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16596. int callback_ret =
  16597. (ctx->callbacks.external_ssl_ctx == NULL)
  16598. ? 0
  16599. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16600. if (callback_ret == 0) {
  16601. SSL_CTX_free(ctx->dd.ssl_ctx);
  16602. }
  16603. /* else: ignore error and ommit SSL_CTX_free in case
  16604. * callback_ret is 1 */
  16605. }
  16606. #endif /* !NO_SSL */
  16607. /* Deallocate worker thread ID array */
  16608. mg_free(ctx->worker_threadids);
  16609. /* Deallocate worker thread ID array */
  16610. mg_free(ctx->worker_connections);
  16611. /* deallocate system name string */
  16612. mg_free(ctx->systemName);
  16613. /* Deallocate context itself */
  16614. mg_free(ctx);
  16615. }
  16616. void
  16617. mg_stop(struct mg_context *ctx)
  16618. {
  16619. pthread_t mt;
  16620. if (!ctx) {
  16621. return;
  16622. }
  16623. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16624. * two threads is not allowed. */
  16625. mt = ctx->masterthreadid;
  16626. if (mt == 0) {
  16627. return;
  16628. }
  16629. ctx->masterthreadid = 0;
  16630. /* Set stop flag, so all threads know they have to exit. */
  16631. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16632. /* Wait until everything has stopped. */
  16633. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16634. (void)mg_sleep(10);
  16635. }
  16636. mg_join_thread(mt);
  16637. free_context(ctx);
  16638. }
  16639. static void
  16640. get_system_name(char **sysName)
  16641. {
  16642. #if defined(_WIN32)
  16643. #if defined(_WIN32_WCE)
  16644. *sysName = mg_strdup("WinCE");
  16645. #else
  16646. char name[128];
  16647. DWORD dwVersion = 0;
  16648. DWORD dwMajorVersion = 0;
  16649. DWORD dwMinorVersion = 0;
  16650. DWORD dwBuild = 0;
  16651. BOOL wowRet, isWoW = FALSE;
  16652. #if defined(_MSC_VER)
  16653. #pragma warning(push)
  16654. /* GetVersion was declared deprecated */
  16655. #pragma warning(disable : 4996)
  16656. #endif
  16657. dwVersion = GetVersion();
  16658. #if defined(_MSC_VER)
  16659. #pragma warning(pop)
  16660. #endif
  16661. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16662. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16663. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16664. (void)dwBuild;
  16665. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16666. sprintf(name,
  16667. "Windows %u.%u%s",
  16668. (unsigned)dwMajorVersion,
  16669. (unsigned)dwMinorVersion,
  16670. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16671. *sysName = mg_strdup(name);
  16672. #endif
  16673. #elif defined(__ZEPHYR__)
  16674. *sysName = mg_strdup("Zephyr OS");
  16675. #else
  16676. struct utsname name;
  16677. memset(&name, 0, sizeof(name));
  16678. uname(&name);
  16679. *sysName = mg_strdup(name.sysname);
  16680. #endif
  16681. }
  16682. static void
  16683. legacy_init(const char **options)
  16684. {
  16685. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16686. if (options) {
  16687. const char **run_options = options;
  16688. const char *optname = config_options[LISTENING_PORTS].name;
  16689. /* Try to find the "listening_ports" option */
  16690. while (*run_options) {
  16691. if (!strcmp(*run_options, optname)) {
  16692. ports_option = run_options[1];
  16693. }
  16694. run_options += 2;
  16695. }
  16696. }
  16697. if (is_ssl_port_used(ports_option)) {
  16698. /* Initialize with SSL support */
  16699. mg_init_library(MG_FEATURES_TLS);
  16700. } else {
  16701. /* Initialize without SSL support */
  16702. mg_init_library(MG_FEATURES_DEFAULT);
  16703. }
  16704. }
  16705. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16706. static
  16707. #endif
  16708. struct mg_context *
  16709. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16710. {
  16711. struct mg_context *ctx;
  16712. const char *name, *value, *default_value;
  16713. int idx, ok, workerthreadcount;
  16714. unsigned int i;
  16715. int itmp;
  16716. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16717. const char **options =
  16718. ((init != NULL) ? (init->configuration_options) : (NULL));
  16719. struct mg_workerTLS tls;
  16720. if (error != NULL) {
  16721. error->code = 0;
  16722. if (error->text_buffer_size > 0) {
  16723. *error->text = 0;
  16724. }
  16725. }
  16726. if (mg_init_library_called == 0) {
  16727. /* Legacy INIT, if mg_start is called without mg_init_library.
  16728. * Note: This will cause a memory leak when unloading the library.
  16729. */
  16730. legacy_init(options);
  16731. }
  16732. if (mg_init_library_called == 0) {
  16733. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16734. mg_snprintf(NULL,
  16735. NULL, /* No truncation check for error buffers */
  16736. error->text,
  16737. error->text_buffer_size,
  16738. "%s",
  16739. "Library uninitialized");
  16740. }
  16741. return NULL;
  16742. }
  16743. /* Allocate context and initialize reasonable general case defaults. */
  16744. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16745. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16746. mg_snprintf(NULL,
  16747. NULL, /* No truncation check for error buffers */
  16748. error->text,
  16749. error->text_buffer_size,
  16750. "%s",
  16751. "Out of memory");
  16752. }
  16753. return NULL;
  16754. }
  16755. /* Random number generator will initialize at the first call */
  16756. ctx->dd.auth_nonce_mask =
  16757. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16758. /* Save started thread index to reuse in other external API calls
  16759. * For the sake of thread synchronization all non-civetweb threads
  16760. * can be considered as single external thread */
  16761. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16762. tls.is_master = -1; /* Thread calling mg_start */
  16763. tls.thread_idx = ctx->starter_thread_idx;
  16764. #if defined(_WIN32)
  16765. tls.pthread_cond_helper_mutex = NULL;
  16766. #endif
  16767. pthread_setspecific(sTlsKey, &tls);
  16768. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16769. #if !defined(ALTERNATIVE_QUEUE)
  16770. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16771. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16772. ctx->sq_blocked = 0;
  16773. #endif
  16774. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16775. if (!ok) {
  16776. const char *err_msg =
  16777. "Cannot initialize thread synchronization objects";
  16778. /* Fatal error - abort start. However, this situation should never
  16779. * occur in practice. */
  16780. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16781. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16782. mg_snprintf(NULL,
  16783. NULL, /* No truncation check for error buffers */
  16784. error->text,
  16785. error->text_buffer_size,
  16786. "%s",
  16787. err_msg);
  16788. }
  16789. mg_free(ctx);
  16790. pthread_setspecific(sTlsKey, NULL);
  16791. return NULL;
  16792. }
  16793. if ((init != NULL) && (init->callbacks != NULL)) {
  16794. /* Set all callbacks except exit_context. */
  16795. ctx->callbacks = *init->callbacks;
  16796. exit_callback = init->callbacks->exit_context;
  16797. /* The exit callback is activated once the context is successfully
  16798. * created. It should not be called, if an incomplete context object
  16799. * is deleted during a failed initialization. */
  16800. ctx->callbacks.exit_context = 0;
  16801. }
  16802. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16803. ctx->dd.handlers = NULL;
  16804. ctx->dd.next = NULL;
  16805. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16806. ctx->dd.shared_lua_websockets = NULL;
  16807. #endif
  16808. /* Store options */
  16809. while (options && (name = *options++) != NULL) {
  16810. if ((idx = get_option_index(name)) == -1) {
  16811. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16812. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16813. mg_snprintf(NULL,
  16814. NULL, /* No truncation check for error buffers */
  16815. error->text,
  16816. error->text_buffer_size,
  16817. "Invalid configuration option: %s",
  16818. name);
  16819. }
  16820. free_context(ctx);
  16821. pthread_setspecific(sTlsKey, NULL);
  16822. return NULL;
  16823. } else if ((value = *options++) == NULL) {
  16824. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16825. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16826. mg_snprintf(NULL,
  16827. NULL, /* No truncation check for error buffers */
  16828. error->text,
  16829. error->text_buffer_size,
  16830. "Invalid configuration option value: %s",
  16831. name);
  16832. }
  16833. free_context(ctx);
  16834. pthread_setspecific(sTlsKey, NULL);
  16835. return NULL;
  16836. }
  16837. if (ctx->dd.config[idx] != NULL) {
  16838. /* A duplicate configuration option is not an error - the last
  16839. * option value will be used. */
  16840. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16841. mg_free(ctx->dd.config[idx]);
  16842. }
  16843. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16844. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16845. }
  16846. /* Set default value if needed */
  16847. for (i = 0; config_options[i].name != NULL; i++) {
  16848. default_value = config_options[i].default_value;
  16849. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16850. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16851. }
  16852. }
  16853. /* Request size option */
  16854. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16855. if (itmp < 1024) {
  16856. mg_cry_ctx_internal(ctx,
  16857. "%s too small",
  16858. config_options[MAX_REQUEST_SIZE].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 value: %s",
  16865. config_options[MAX_REQUEST_SIZE].name);
  16866. }
  16867. free_context(ctx);
  16868. pthread_setspecific(sTlsKey, NULL);
  16869. return NULL;
  16870. }
  16871. ctx->max_request_size = (unsigned)itmp;
  16872. /* Queue length */
  16873. #if !defined(ALTERNATIVE_QUEUE)
  16874. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16875. if (itmp < 1) {
  16876. mg_cry_ctx_internal(ctx,
  16877. "%s too small",
  16878. config_options[CONNECTION_QUEUE_SIZE].name);
  16879. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16880. mg_snprintf(NULL,
  16881. NULL, /* No truncation check for error buffers */
  16882. error->text,
  16883. error->text_buffer_size,
  16884. "Invalid configuration option value: %s",
  16885. config_options[CONNECTION_QUEUE_SIZE].name);
  16886. }
  16887. free_context(ctx);
  16888. pthread_setspecific(sTlsKey, NULL);
  16889. return NULL;
  16890. }
  16891. ctx->squeue =
  16892. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16893. if (ctx->squeue == NULL) {
  16894. mg_cry_ctx_internal(ctx,
  16895. "Out of memory: Cannot allocate %s",
  16896. config_options[CONNECTION_QUEUE_SIZE].name);
  16897. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16898. mg_snprintf(NULL,
  16899. NULL, /* No truncation check for error buffers */
  16900. error->text,
  16901. error->text_buffer_size,
  16902. "Out of memory: Cannot allocate %s",
  16903. config_options[CONNECTION_QUEUE_SIZE].name);
  16904. }
  16905. free_context(ctx);
  16906. pthread_setspecific(sTlsKey, NULL);
  16907. return NULL;
  16908. }
  16909. ctx->sq_size = itmp;
  16910. #endif
  16911. /* Worker thread count option */
  16912. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16913. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16914. if (workerthreadcount <= 0) {
  16915. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16916. } else {
  16917. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16918. }
  16919. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16920. mg_snprintf(NULL,
  16921. NULL, /* No truncation check for error buffers */
  16922. error->text,
  16923. error->text_buffer_size,
  16924. "Invalid configuration option value: %s",
  16925. config_options[NUM_THREADS].name);
  16926. }
  16927. free_context(ctx);
  16928. pthread_setspecific(sTlsKey, NULL);
  16929. return NULL;
  16930. }
  16931. /* Document root */
  16932. #if defined(NO_FILES)
  16933. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16934. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16935. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16936. mg_snprintf(NULL,
  16937. NULL, /* No truncation check for error buffers */
  16938. error->text,
  16939. error->text_buffer_size,
  16940. "Invalid configuration option value: %s",
  16941. config_options[DOCUMENT_ROOT].name);
  16942. }
  16943. free_context(ctx);
  16944. pthread_setspecific(sTlsKey, NULL);
  16945. return NULL;
  16946. }
  16947. #endif
  16948. get_system_name(&ctx->systemName);
  16949. #if defined(USE_LUA)
  16950. /* If a Lua background script has been configured, start it. */
  16951. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16952. char ebuf[256];
  16953. struct vec opt_vec;
  16954. struct vec eq_vec;
  16955. const char *sparams;
  16956. lua_State *state = mg_prepare_lua_context_script(
  16957. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16958. if (!state) {
  16959. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16960. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16961. mg_snprintf(NULL,
  16962. NULL, /* No truncation check for error buffers */
  16963. error->text,
  16964. error->text_buffer_size,
  16965. "Error in script %s: %s",
  16966. config_options[DOCUMENT_ROOT].name,
  16967. ebuf);
  16968. }
  16969. free_context(ctx);
  16970. pthread_setspecific(sTlsKey, NULL);
  16971. return NULL;
  16972. }
  16973. ctx->lua_background_state = (void *)state;
  16974. lua_newtable(state);
  16975. reg_boolean(state, "shutdown", 0);
  16976. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16977. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16978. reg_llstring(
  16979. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16980. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16981. break;
  16982. }
  16983. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16984. } else {
  16985. ctx->lua_background_state = 0;
  16986. }
  16987. #endif
  16988. /* Step by step initialization of ctx - depending on build options */
  16989. #if !defined(NO_FILESYSTEMS)
  16990. if (!set_gpass_option(ctx, NULL)) {
  16991. const char *err_msg = "Invalid global password file";
  16992. /* Fatal error - abort start. */
  16993. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16994. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16995. mg_snprintf(NULL,
  16996. NULL, /* No truncation check for error buffers */
  16997. error->text,
  16998. error->text_buffer_size,
  16999. "%s",
  17000. err_msg);
  17001. }
  17002. free_context(ctx);
  17003. pthread_setspecific(sTlsKey, NULL);
  17004. return NULL;
  17005. }
  17006. #endif
  17007. #if !defined(NO_SSL)
  17008. if (!init_ssl_ctx(ctx, NULL)) {
  17009. const char *err_msg = "Error initializing SSL context";
  17010. /* Fatal error - abort start. */
  17011. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17012. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17013. mg_snprintf(NULL,
  17014. NULL, /* No truncation check for error buffers */
  17015. error->text,
  17016. error->text_buffer_size,
  17017. "%s",
  17018. err_msg);
  17019. }
  17020. free_context(ctx);
  17021. pthread_setspecific(sTlsKey, NULL);
  17022. return NULL;
  17023. }
  17024. #endif
  17025. if (!set_ports_option(ctx)) {
  17026. const char *err_msg = "Failed to setup server ports";
  17027. /* Fatal error - abort start. */
  17028. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17029. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17030. mg_snprintf(NULL,
  17031. NULL, /* No truncation check for error buffers */
  17032. error->text,
  17033. error->text_buffer_size,
  17034. "%s",
  17035. err_msg);
  17036. }
  17037. free_context(ctx);
  17038. pthread_setspecific(sTlsKey, NULL);
  17039. return NULL;
  17040. }
  17041. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17042. if (!set_uid_option(ctx)) {
  17043. const char *err_msg = "Failed to run as configured user";
  17044. /* Fatal error - abort start. */
  17045. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17046. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17047. mg_snprintf(NULL,
  17048. NULL, /* No truncation check for error buffers */
  17049. error->text,
  17050. error->text_buffer_size,
  17051. "%s",
  17052. err_msg);
  17053. }
  17054. free_context(ctx);
  17055. pthread_setspecific(sTlsKey, NULL);
  17056. return NULL;
  17057. }
  17058. #endif
  17059. if (!set_acl_option(ctx)) {
  17060. const char *err_msg = "Failed to setup access control list";
  17061. /* Fatal error - abort start. */
  17062. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17063. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17064. mg_snprintf(NULL,
  17065. NULL, /* No truncation check for error buffers */
  17066. error->text,
  17067. error->text_buffer_size,
  17068. "%s",
  17069. err_msg);
  17070. }
  17071. free_context(ctx);
  17072. pthread_setspecific(sTlsKey, NULL);
  17073. return NULL;
  17074. }
  17075. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17076. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17077. sizeof(pthread_t),
  17078. ctx);
  17079. if (ctx->worker_threadids == NULL) {
  17080. const char *err_msg = "Not enough memory for worker thread ID array";
  17081. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17082. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17083. mg_snprintf(NULL,
  17084. NULL, /* No truncation check for error buffers */
  17085. error->text,
  17086. error->text_buffer_size,
  17087. "%s",
  17088. err_msg);
  17089. }
  17090. free_context(ctx);
  17091. pthread_setspecific(sTlsKey, NULL);
  17092. return NULL;
  17093. }
  17094. ctx->worker_connections =
  17095. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17096. sizeof(struct mg_connection),
  17097. ctx);
  17098. if (ctx->worker_connections == NULL) {
  17099. const char *err_msg =
  17100. "Not enough memory for worker thread connection array";
  17101. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17102. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17103. mg_snprintf(NULL,
  17104. NULL, /* No truncation check for error buffers */
  17105. error->text,
  17106. error->text_buffer_size,
  17107. "%s",
  17108. err_msg);
  17109. }
  17110. free_context(ctx);
  17111. pthread_setspecific(sTlsKey, NULL);
  17112. return NULL;
  17113. }
  17114. #if defined(ALTERNATIVE_QUEUE)
  17115. ctx->client_wait_events =
  17116. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17117. sizeof(ctx->client_wait_events[0]),
  17118. ctx);
  17119. if (ctx->client_wait_events == NULL) {
  17120. const char *err_msg = "Not enough memory for worker event array";
  17121. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17122. mg_free(ctx->worker_threadids);
  17123. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17124. mg_snprintf(NULL,
  17125. NULL, /* No truncation check for error buffers */
  17126. error->text,
  17127. error->text_buffer_size,
  17128. "%s",
  17129. err_msg);
  17130. }
  17131. free_context(ctx);
  17132. pthread_setspecific(sTlsKey, NULL);
  17133. return NULL;
  17134. }
  17135. ctx->client_socks =
  17136. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17137. sizeof(ctx->client_socks[0]),
  17138. ctx);
  17139. if (ctx->client_socks == NULL) {
  17140. const char *err_msg = "Not enough memory for worker socket array";
  17141. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17142. mg_free(ctx->client_wait_events);
  17143. mg_free(ctx->worker_threadids);
  17144. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17145. mg_snprintf(NULL,
  17146. NULL, /* No truncation check for error buffers */
  17147. error->text,
  17148. error->text_buffer_size,
  17149. "%s",
  17150. err_msg);
  17151. }
  17152. free_context(ctx);
  17153. pthread_setspecific(sTlsKey, NULL);
  17154. return NULL;
  17155. }
  17156. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17157. ctx->client_wait_events[i] = event_create();
  17158. if (ctx->client_wait_events[i] == 0) {
  17159. const char *err_msg = "Error creating worker event %i";
  17160. mg_cry_ctx_internal(ctx, err_msg, i);
  17161. while (i > 0) {
  17162. i--;
  17163. event_destroy(ctx->client_wait_events[i]);
  17164. }
  17165. mg_free(ctx->client_socks);
  17166. mg_free(ctx->client_wait_events);
  17167. mg_free(ctx->worker_threadids);
  17168. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17169. mg_snprintf(NULL,
  17170. NULL, /* No truncation check for error buffers */
  17171. error->text,
  17172. error->text_buffer_size,
  17173. err_msg,
  17174. i);
  17175. }
  17176. free_context(ctx);
  17177. pthread_setspecific(sTlsKey, NULL);
  17178. return NULL;
  17179. }
  17180. }
  17181. #endif
  17182. #if defined(USE_TIMERS)
  17183. if (timers_init(ctx) != 0) {
  17184. const char *err_msg = "Error creating timers";
  17185. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17186. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17187. mg_snprintf(NULL,
  17188. NULL, /* No truncation check for error buffers */
  17189. error->text,
  17190. error->text_buffer_size,
  17191. "%s",
  17192. err_msg);
  17193. }
  17194. free_context(ctx);
  17195. pthread_setspecific(sTlsKey, NULL);
  17196. return NULL;
  17197. }
  17198. #endif
  17199. /* Context has been created - init user libraries */
  17200. if (ctx->callbacks.init_context) {
  17201. ctx->callbacks.init_context(ctx);
  17202. }
  17203. /* From now, the context is successfully created.
  17204. * When it is destroyed, the exit callback should be called. */
  17205. ctx->callbacks.exit_context = exit_callback;
  17206. ctx->context_type = CONTEXT_SERVER; /* server context */
  17207. /* Start worker threads */
  17208. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17209. /* worker_thread sets up the other fields */
  17210. ctx->worker_connections[i].phys_ctx = ctx;
  17211. if (mg_start_thread_with_id(worker_thread,
  17212. &ctx->worker_connections[i],
  17213. &ctx->worker_threadids[i])
  17214. != 0) {
  17215. long error_no = (long)ERRNO;
  17216. /* thread was not created */
  17217. if (i > 0) {
  17218. /* If the second, third, ... thread cannot be created, set a
  17219. * warning, but keep running. */
  17220. mg_cry_ctx_internal(ctx,
  17221. "Cannot start worker thread %i: error %ld",
  17222. i + 1,
  17223. error_no);
  17224. /* If the server initialization should stop here, all
  17225. * threads that have already been created must be stopped
  17226. * first, before any free_context(ctx) call.
  17227. */
  17228. } else {
  17229. /* If the first worker thread cannot be created, stop
  17230. * initialization and free the entire server context. */
  17231. mg_cry_ctx_internal(ctx,
  17232. "Cannot create threads: error %ld",
  17233. error_no);
  17234. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17235. mg_snprintf(
  17236. NULL,
  17237. NULL, /* No truncation check for error buffers */
  17238. error->text,
  17239. error->text_buffer_size,
  17240. "Cannot create first worker thread: error %ld",
  17241. error_no);
  17242. }
  17243. free_context(ctx);
  17244. pthread_setspecific(sTlsKey, NULL);
  17245. return NULL;
  17246. }
  17247. break;
  17248. }
  17249. }
  17250. /* Start master (listening) thread */
  17251. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17252. pthread_setspecific(sTlsKey, NULL);
  17253. return ctx;
  17254. }
  17255. struct mg_context *
  17256. mg_start(const struct mg_callbacks *callbacks,
  17257. void *user_data,
  17258. const char **options)
  17259. {
  17260. struct mg_init_data init = {0};
  17261. init.callbacks = callbacks;
  17262. init.user_data = user_data;
  17263. init.configuration_options = options;
  17264. return mg_start2(&init, NULL);
  17265. }
  17266. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17267. /* Add an additional domain to an already running web server. */
  17268. int
  17269. mg_start_domain2(struct mg_context *ctx,
  17270. const char **options,
  17271. struct mg_error_data *error)
  17272. {
  17273. const char *name;
  17274. const char *value;
  17275. const char *default_value;
  17276. struct mg_domain_context *new_dom;
  17277. struct mg_domain_context *dom;
  17278. int idx, i;
  17279. if (error != NULL) {
  17280. error->code = 0;
  17281. if (error->text_buffer_size > 0) {
  17282. *error->text = 0;
  17283. }
  17284. }
  17285. if ((ctx == NULL) || (options == NULL)) {
  17286. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17287. mg_snprintf(NULL,
  17288. NULL, /* No truncation check for error buffers */
  17289. error->text,
  17290. error->text_buffer_size,
  17291. "%s",
  17292. "Invalid parameters");
  17293. }
  17294. return -1;
  17295. }
  17296. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17297. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17298. mg_snprintf(NULL,
  17299. NULL, /* No truncation check for error buffers */
  17300. error->text,
  17301. error->text_buffer_size,
  17302. "%s",
  17303. "Server already stopped");
  17304. }
  17305. return -1;
  17306. }
  17307. new_dom = (struct mg_domain_context *)
  17308. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17309. if (!new_dom) {
  17310. /* Out of memory */
  17311. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17312. mg_snprintf(NULL,
  17313. NULL, /* No truncation check for error buffers */
  17314. error->text,
  17315. error->text_buffer_size,
  17316. "%s",
  17317. "Out or memory");
  17318. }
  17319. return -6;
  17320. }
  17321. /* Store options - TODO: unite duplicate code */
  17322. while (options && (name = *options++) != NULL) {
  17323. if ((idx = get_option_index(name)) == -1) {
  17324. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17325. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17326. mg_snprintf(NULL,
  17327. NULL, /* No truncation check for error buffers */
  17328. error->text,
  17329. error->text_buffer_size,
  17330. "Invalid option: %s",
  17331. name);
  17332. }
  17333. mg_free(new_dom);
  17334. return -2;
  17335. } else if ((value = *options++) == NULL) {
  17336. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17337. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17338. mg_snprintf(NULL,
  17339. NULL, /* No truncation check for error buffers */
  17340. error->text,
  17341. error->text_buffer_size,
  17342. "Invalid option value: %s",
  17343. name);
  17344. }
  17345. mg_free(new_dom);
  17346. return -2;
  17347. }
  17348. if (new_dom->config[idx] != NULL) {
  17349. /* Duplicate option: Later values overwrite earlier ones. */
  17350. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17351. mg_free(new_dom->config[idx]);
  17352. }
  17353. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17354. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17355. }
  17356. /* Authentication domain is mandatory */
  17357. /* TODO: Maybe use a new option hostname? */
  17358. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17359. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17360. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17361. mg_snprintf(NULL,
  17362. NULL, /* No truncation check for error buffers */
  17363. error->text,
  17364. error->text_buffer_size,
  17365. "Mandatory option %s missing",
  17366. config_options[AUTHENTICATION_DOMAIN].name);
  17367. }
  17368. mg_free(new_dom);
  17369. return -4;
  17370. }
  17371. /* Set default value if needed. Take the config value from
  17372. * ctx as a default value. */
  17373. for (i = 0; config_options[i].name != NULL; i++) {
  17374. default_value = ctx->dd.config[i];
  17375. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17376. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17377. }
  17378. }
  17379. new_dom->handlers = NULL;
  17380. new_dom->next = NULL;
  17381. new_dom->nonce_count = 0;
  17382. new_dom->auth_nonce_mask =
  17383. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17384. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17385. new_dom->shared_lua_websockets = NULL;
  17386. #endif
  17387. #if !defined(NO_SSL)
  17388. if (!init_ssl_ctx(ctx, new_dom)) {
  17389. /* Init SSL failed */
  17390. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17391. mg_snprintf(NULL,
  17392. NULL, /* No truncation check for error buffers */
  17393. error->text,
  17394. error->text_buffer_size,
  17395. "%s",
  17396. "Initializing SSL context failed");
  17397. }
  17398. mg_free(new_dom);
  17399. return -3;
  17400. }
  17401. #endif
  17402. /* Add element to linked list. */
  17403. mg_lock_context(ctx);
  17404. idx = 0;
  17405. dom = &(ctx->dd);
  17406. for (;;) {
  17407. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17408. dom->config[AUTHENTICATION_DOMAIN])) {
  17409. /* Domain collision */
  17410. mg_cry_ctx_internal(ctx,
  17411. "domain %s already in use",
  17412. new_dom->config[AUTHENTICATION_DOMAIN]);
  17413. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17414. mg_snprintf(NULL,
  17415. NULL, /* No truncation check for error buffers */
  17416. error->text,
  17417. error->text_buffer_size,
  17418. "Domain %s specified by %s is already in use",
  17419. new_dom->config[AUTHENTICATION_DOMAIN],
  17420. config_options[AUTHENTICATION_DOMAIN].name);
  17421. }
  17422. mg_free(new_dom);
  17423. mg_unlock_context(ctx);
  17424. return -5;
  17425. }
  17426. /* Count number of domains */
  17427. idx++;
  17428. if (dom->next == NULL) {
  17429. dom->next = new_dom;
  17430. break;
  17431. }
  17432. dom = dom->next;
  17433. }
  17434. mg_unlock_context(ctx);
  17435. /* Return domain number */
  17436. return idx;
  17437. }
  17438. int
  17439. mg_start_domain(struct mg_context *ctx, const char **options)
  17440. {
  17441. return mg_start_domain2(ctx, options, NULL);
  17442. }
  17443. #endif
  17444. /* Feature check API function */
  17445. unsigned
  17446. mg_check_feature(unsigned feature)
  17447. {
  17448. static const unsigned feature_set = 0
  17449. /* Set bits for available features according to API documentation.
  17450. * This bit mask is created at compile time, according to the active
  17451. * preprocessor defines. It is a single const value at runtime. */
  17452. #if !defined(NO_FILES)
  17453. | MG_FEATURES_FILES
  17454. #endif
  17455. #if !defined(NO_SSL)
  17456. | MG_FEATURES_SSL
  17457. #endif
  17458. #if !defined(NO_CGI)
  17459. | MG_FEATURES_CGI
  17460. #endif
  17461. #if defined(USE_IPV6)
  17462. | MG_FEATURES_IPV6
  17463. #endif
  17464. #if defined(USE_WEBSOCKET)
  17465. | MG_FEATURES_WEBSOCKET
  17466. #endif
  17467. #if defined(USE_LUA)
  17468. | MG_FEATURES_LUA
  17469. #endif
  17470. #if defined(USE_DUKTAPE)
  17471. | MG_FEATURES_SSJS
  17472. #endif
  17473. #if !defined(NO_CACHING)
  17474. | MG_FEATURES_CACHE
  17475. #endif
  17476. #if defined(USE_SERVER_STATS)
  17477. | MG_FEATURES_STATS
  17478. #endif
  17479. #if defined(USE_ZLIB)
  17480. | MG_FEATURES_COMPRESSION
  17481. #endif
  17482. /* Set some extra bits not defined in the API documentation.
  17483. * These bits may change without further notice. */
  17484. #if defined(MG_LEGACY_INTERFACE)
  17485. | 0x00008000u
  17486. #endif
  17487. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17488. | 0x00004000u
  17489. #endif
  17490. #if defined(MEMORY_DEBUGGING)
  17491. | 0x00001000u
  17492. #endif
  17493. #if defined(USE_TIMERS)
  17494. | 0x00020000u
  17495. #endif
  17496. #if !defined(NO_NONCE_CHECK)
  17497. | 0x00040000u
  17498. #endif
  17499. #if !defined(NO_POPEN)
  17500. | 0x00080000u
  17501. #endif
  17502. ;
  17503. return (feature & feature_set);
  17504. }
  17505. static size_t
  17506. mg_str_append(char **dst, char *end, const char *src)
  17507. {
  17508. size_t len = strlen(src);
  17509. if (*dst != end) {
  17510. /* Append src if enough space, or close dst. */
  17511. if ((size_t)(end - *dst) > len) {
  17512. strcpy(*dst, src);
  17513. *dst += len;
  17514. } else {
  17515. *dst = end;
  17516. }
  17517. }
  17518. return len;
  17519. }
  17520. /* Get system information. It can be printed or stored by the caller.
  17521. * Return the size of available information. */
  17522. int
  17523. mg_get_system_info(char *buffer, int buflen)
  17524. {
  17525. char *end, *append_eoobj = NULL, block[256];
  17526. size_t system_info_length = 0;
  17527. #if defined(_WIN32)
  17528. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17529. #else
  17530. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17531. #endif
  17532. if ((buffer == NULL) || (buflen < 1)) {
  17533. buflen = 0;
  17534. end = buffer;
  17535. } else {
  17536. *buffer = 0;
  17537. end = buffer + buflen;
  17538. }
  17539. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17540. /* has enough space to append eoobj */
  17541. append_eoobj = buffer;
  17542. if (end) {
  17543. end -= sizeof(eoobj) - 1;
  17544. }
  17545. }
  17546. system_info_length += mg_str_append(&buffer, end, "{");
  17547. /* Server version */
  17548. {
  17549. const char *version = mg_version();
  17550. mg_snprintf(NULL,
  17551. NULL,
  17552. block,
  17553. sizeof(block),
  17554. "%s\"version\" : \"%s\"",
  17555. eol,
  17556. version);
  17557. system_info_length += mg_str_append(&buffer, end, block);
  17558. }
  17559. /* System info */
  17560. {
  17561. #if defined(_WIN32)
  17562. DWORD dwVersion = 0;
  17563. DWORD dwMajorVersion = 0;
  17564. DWORD dwMinorVersion = 0;
  17565. SYSTEM_INFO si;
  17566. GetSystemInfo(&si);
  17567. #if defined(_MSC_VER)
  17568. #pragma warning(push)
  17569. /* GetVersion was declared deprecated */
  17570. #pragma warning(disable : 4996)
  17571. #endif
  17572. dwVersion = GetVersion();
  17573. #if defined(_MSC_VER)
  17574. #pragma warning(pop)
  17575. #endif
  17576. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17577. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17578. mg_snprintf(NULL,
  17579. NULL,
  17580. block,
  17581. sizeof(block),
  17582. ",%s\"os\" : \"Windows %u.%u\"",
  17583. eol,
  17584. (unsigned)dwMajorVersion,
  17585. (unsigned)dwMinorVersion);
  17586. system_info_length += mg_str_append(&buffer, end, block);
  17587. mg_snprintf(NULL,
  17588. NULL,
  17589. block,
  17590. sizeof(block),
  17591. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17592. eol,
  17593. (unsigned)si.wProcessorArchitecture,
  17594. (unsigned)si.dwNumberOfProcessors,
  17595. (unsigned)si.dwActiveProcessorMask);
  17596. system_info_length += mg_str_append(&buffer, end, block);
  17597. #elif defined(__ZEPHYR__)
  17598. mg_snprintf(NULL,
  17599. NULL,
  17600. block,
  17601. sizeof(block),
  17602. ",%s\"os\" : \"%s %s\"",
  17603. eol,
  17604. "Zephyr OS",
  17605. ZEPHYR_VERSION);
  17606. system_info_length += mg_str_append(&buffer, end, block);
  17607. #else
  17608. struct utsname name;
  17609. memset(&name, 0, sizeof(name));
  17610. uname(&name);
  17611. mg_snprintf(NULL,
  17612. NULL,
  17613. block,
  17614. sizeof(block),
  17615. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17616. eol,
  17617. name.sysname,
  17618. name.version,
  17619. name.release,
  17620. name.machine);
  17621. system_info_length += mg_str_append(&buffer, end, block);
  17622. #endif
  17623. }
  17624. /* Features */
  17625. {
  17626. mg_snprintf(NULL,
  17627. NULL,
  17628. block,
  17629. sizeof(block),
  17630. ",%s\"features\" : %lu"
  17631. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17632. eol,
  17633. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17634. eol,
  17635. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17636. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17637. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17638. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17639. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17640. : "",
  17641. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17642. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17643. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17644. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17645. system_info_length += mg_str_append(&buffer, end, block);
  17646. #if defined(USE_LUA)
  17647. mg_snprintf(NULL,
  17648. NULL,
  17649. block,
  17650. sizeof(block),
  17651. ",%s\"lua_version\" : \"%u (%s)\"",
  17652. eol,
  17653. (unsigned)LUA_VERSION_NUM,
  17654. LUA_RELEASE);
  17655. system_info_length += mg_str_append(&buffer, end, block);
  17656. #endif
  17657. #if defined(USE_DUKTAPE)
  17658. mg_snprintf(NULL,
  17659. NULL,
  17660. block,
  17661. sizeof(block),
  17662. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17663. eol,
  17664. (unsigned)DUK_VERSION / 10000,
  17665. ((unsigned)DUK_VERSION / 100) % 100,
  17666. (unsigned)DUK_VERSION % 100);
  17667. system_info_length += mg_str_append(&buffer, end, block);
  17668. #endif
  17669. }
  17670. /* Build date */
  17671. {
  17672. #if defined(GCC_DIAGNOSTIC)
  17673. #if GCC_VERSION >= 40900
  17674. #pragma GCC diagnostic push
  17675. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17676. #pragma GCC diagnostic ignored "-Wdate-time"
  17677. #endif
  17678. #endif
  17679. mg_snprintf(NULL,
  17680. NULL,
  17681. block,
  17682. sizeof(block),
  17683. ",%s\"build\" : \"%s\"",
  17684. eol,
  17685. __DATE__);
  17686. #if defined(GCC_DIAGNOSTIC)
  17687. #if GCC_VERSION >= 40900
  17688. #pragma GCC diagnostic pop
  17689. #endif
  17690. #endif
  17691. system_info_length += mg_str_append(&buffer, end, block);
  17692. }
  17693. /* Compiler information */
  17694. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17695. {
  17696. #if defined(_MSC_VER)
  17697. mg_snprintf(NULL,
  17698. NULL,
  17699. block,
  17700. sizeof(block),
  17701. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17702. eol,
  17703. (unsigned)_MSC_VER,
  17704. (unsigned)_MSC_FULL_VER);
  17705. system_info_length += mg_str_append(&buffer, end, block);
  17706. #elif defined(__MINGW64__)
  17707. mg_snprintf(NULL,
  17708. NULL,
  17709. block,
  17710. sizeof(block),
  17711. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17712. eol,
  17713. (unsigned)__MINGW64_VERSION_MAJOR,
  17714. (unsigned)__MINGW64_VERSION_MINOR);
  17715. system_info_length += mg_str_append(&buffer, end, block);
  17716. mg_snprintf(NULL,
  17717. NULL,
  17718. block,
  17719. sizeof(block),
  17720. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17721. eol,
  17722. (unsigned)__MINGW32_MAJOR_VERSION,
  17723. (unsigned)__MINGW32_MINOR_VERSION);
  17724. system_info_length += mg_str_append(&buffer, end, block);
  17725. #elif defined(__MINGW32__)
  17726. mg_snprintf(NULL,
  17727. NULL,
  17728. block,
  17729. sizeof(block),
  17730. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17731. eol,
  17732. (unsigned)__MINGW32_MAJOR_VERSION,
  17733. (unsigned)__MINGW32_MINOR_VERSION);
  17734. system_info_length += mg_str_append(&buffer, end, block);
  17735. #elif defined(__clang__)
  17736. mg_snprintf(NULL,
  17737. NULL,
  17738. block,
  17739. sizeof(block),
  17740. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17741. eol,
  17742. __clang_major__,
  17743. __clang_minor__,
  17744. __clang_patchlevel__,
  17745. __clang_version__);
  17746. system_info_length += mg_str_append(&buffer, end, block);
  17747. #elif defined(__GNUC__)
  17748. mg_snprintf(NULL,
  17749. NULL,
  17750. block,
  17751. sizeof(block),
  17752. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17753. eol,
  17754. (unsigned)__GNUC__,
  17755. (unsigned)__GNUC_MINOR__,
  17756. (unsigned)__GNUC_PATCHLEVEL__);
  17757. system_info_length += mg_str_append(&buffer, end, block);
  17758. #elif defined(__INTEL_COMPILER)
  17759. mg_snprintf(NULL,
  17760. NULL,
  17761. block,
  17762. sizeof(block),
  17763. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17764. eol,
  17765. (unsigned)__INTEL_COMPILER);
  17766. system_info_length += mg_str_append(&buffer, end, block);
  17767. #elif defined(__BORLANDC__)
  17768. mg_snprintf(NULL,
  17769. NULL,
  17770. block,
  17771. sizeof(block),
  17772. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17773. eol,
  17774. (unsigned)__BORLANDC__);
  17775. system_info_length += mg_str_append(&buffer, end, block);
  17776. #elif defined(__SUNPRO_C)
  17777. mg_snprintf(NULL,
  17778. NULL,
  17779. block,
  17780. sizeof(block),
  17781. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17782. eol,
  17783. (unsigned)__SUNPRO_C);
  17784. system_info_length += mg_str_append(&buffer, end, block);
  17785. #else
  17786. mg_snprintf(NULL,
  17787. NULL,
  17788. block,
  17789. sizeof(block),
  17790. ",%s\"compiler\" : \"other\"",
  17791. eol);
  17792. system_info_length += mg_str_append(&buffer, end, block);
  17793. #endif
  17794. }
  17795. /* Determine 32/64 bit data mode.
  17796. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17797. {
  17798. mg_snprintf(NULL,
  17799. NULL,
  17800. block,
  17801. sizeof(block),
  17802. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17803. "char:%u/%u, "
  17804. "ptr:%u, size:%u, time:%u\"",
  17805. eol,
  17806. (unsigned)sizeof(short),
  17807. (unsigned)sizeof(int),
  17808. (unsigned)sizeof(long),
  17809. (unsigned)sizeof(long long),
  17810. (unsigned)sizeof(float),
  17811. (unsigned)sizeof(double),
  17812. (unsigned)sizeof(long double),
  17813. (unsigned)sizeof(char),
  17814. (unsigned)sizeof(wchar_t),
  17815. (unsigned)sizeof(void *),
  17816. (unsigned)sizeof(size_t),
  17817. (unsigned)sizeof(time_t));
  17818. system_info_length += mg_str_append(&buffer, end, block);
  17819. }
  17820. /* Terminate string */
  17821. if (append_eoobj) {
  17822. strcat(append_eoobj, eoobj);
  17823. }
  17824. system_info_length += sizeof(eoobj) - 1;
  17825. return (int)system_info_length;
  17826. }
  17827. /* Get context information. It can be printed or stored by the caller.
  17828. * Return the size of available information. */
  17829. int
  17830. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17831. {
  17832. #if defined(USE_SERVER_STATS)
  17833. char *end, *append_eoobj = NULL, block[256];
  17834. size_t context_info_length = 0;
  17835. #if defined(_WIN32)
  17836. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17837. #else
  17838. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17839. #endif
  17840. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17841. if ((buffer == NULL) || (buflen < 1)) {
  17842. buflen = 0;
  17843. end = buffer;
  17844. } else {
  17845. *buffer = 0;
  17846. end = buffer + buflen;
  17847. }
  17848. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17849. /* has enough space to append eoobj */
  17850. append_eoobj = buffer;
  17851. end -= sizeof(eoobj) - 1;
  17852. }
  17853. context_info_length += mg_str_append(&buffer, end, "{");
  17854. if (ms) { /* <-- should be always true */
  17855. /* Memory information */
  17856. mg_snprintf(NULL,
  17857. NULL,
  17858. block,
  17859. sizeof(block),
  17860. "%s\"memory\" : {%s"
  17861. "\"blocks\" : %i,%s"
  17862. "\"used\" : %" INT64_FMT ",%s"
  17863. "\"maxUsed\" : %" INT64_FMT "%s"
  17864. "}",
  17865. eol,
  17866. eol,
  17867. ms->blockCount,
  17868. eol,
  17869. ms->totalMemUsed,
  17870. eol,
  17871. ms->maxMemUsed,
  17872. eol);
  17873. context_info_length += mg_str_append(&buffer, end, block);
  17874. }
  17875. if (ctx) {
  17876. /* Declare all variables at begin of the block, to comply
  17877. * with old C standards. */
  17878. char start_time_str[64] = {0};
  17879. char now_str[64] = {0};
  17880. time_t start_time = ctx->start_time;
  17881. time_t now = time(NULL);
  17882. /* Connections information */
  17883. mg_snprintf(NULL,
  17884. NULL,
  17885. block,
  17886. sizeof(block),
  17887. ",%s\"connections\" : {%s"
  17888. "\"active\" : %i,%s"
  17889. "\"maxActive\" : %i,%s"
  17890. "\"total\" : %" INT64_FMT "%s"
  17891. "}",
  17892. eol,
  17893. eol,
  17894. ctx->active_connections,
  17895. eol,
  17896. ctx->max_active_connections,
  17897. eol,
  17898. ctx->total_connections,
  17899. eol);
  17900. context_info_length += mg_str_append(&buffer, end, block);
  17901. /* Queue information */
  17902. #if !defined(ALTERNATIVE_QUEUE)
  17903. mg_snprintf(NULL,
  17904. NULL,
  17905. block,
  17906. sizeof(block),
  17907. ",%s\"queue\" : {%s"
  17908. "\"length\" : %i,%s"
  17909. "\"filled\" : %i,%s"
  17910. "\"maxFilled\" : %i,%s"
  17911. "\"full\" : %s%s"
  17912. "}",
  17913. eol,
  17914. eol,
  17915. ctx->sq_size,
  17916. eol,
  17917. ctx->sq_head - ctx->sq_tail,
  17918. eol,
  17919. ctx->sq_max_fill,
  17920. eol,
  17921. (ctx->sq_blocked ? "true" : "false"),
  17922. eol);
  17923. context_info_length += mg_str_append(&buffer, end, block);
  17924. #endif
  17925. /* Requests information */
  17926. mg_snprintf(NULL,
  17927. NULL,
  17928. block,
  17929. sizeof(block),
  17930. ",%s\"requests\" : {%s"
  17931. "\"total\" : %" INT64_FMT "%s"
  17932. "}",
  17933. eol,
  17934. eol,
  17935. ctx->total_requests,
  17936. eol);
  17937. context_info_length += mg_str_append(&buffer, end, block);
  17938. /* Data information */
  17939. mg_snprintf(NULL,
  17940. NULL,
  17941. block,
  17942. sizeof(block),
  17943. ",%s\"data\" : {%s"
  17944. "\"read\" : %" INT64_FMT ",%s"
  17945. "\"written\" : %" INT64_FMT "%s"
  17946. "}",
  17947. eol,
  17948. eol,
  17949. ctx->total_data_read,
  17950. eol,
  17951. ctx->total_data_written,
  17952. eol);
  17953. context_info_length += mg_str_append(&buffer, end, block);
  17954. /* Execution time information */
  17955. gmt_time_string(start_time_str,
  17956. sizeof(start_time_str) - 1,
  17957. &start_time);
  17958. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17959. mg_snprintf(NULL,
  17960. NULL,
  17961. block,
  17962. sizeof(block),
  17963. ",%s\"time\" : {%s"
  17964. "\"uptime\" : %.0f,%s"
  17965. "\"start\" : \"%s\",%s"
  17966. "\"now\" : \"%s\"%s"
  17967. "}",
  17968. eol,
  17969. eol,
  17970. difftime(now, start_time),
  17971. eol,
  17972. start_time_str,
  17973. eol,
  17974. now_str,
  17975. eol);
  17976. context_info_length += mg_str_append(&buffer, end, block);
  17977. }
  17978. /* Terminate string */
  17979. if (append_eoobj) {
  17980. strcat(append_eoobj, eoobj);
  17981. }
  17982. context_info_length += sizeof(eoobj) - 1;
  17983. return (int)context_info_length;
  17984. #else
  17985. (void)ctx;
  17986. if ((buffer != NULL) && (buflen > 0)) {
  17987. *buffer = 0;
  17988. }
  17989. return 0;
  17990. #endif
  17991. }
  17992. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17993. /* Get connection information. It can be printed or stored by the caller.
  17994. * Return the size of available information. */
  17995. int
  17996. mg_get_connection_info(const struct mg_context *ctx,
  17997. int idx,
  17998. char *buffer,
  17999. int buflen)
  18000. {
  18001. const struct mg_connection *conn;
  18002. const struct mg_request_info *ri;
  18003. char *end, *append_eoobj = NULL, block[256];
  18004. size_t connection_info_length = 0;
  18005. int state = 0;
  18006. const char *state_str = "unknown";
  18007. #if defined(_WIN32)
  18008. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18009. #else
  18010. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18011. #endif
  18012. if ((buffer == NULL) || (buflen < 1)) {
  18013. buflen = 0;
  18014. end = buffer;
  18015. } else {
  18016. *buffer = 0;
  18017. end = buffer + buflen;
  18018. }
  18019. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18020. /* has enough space to append eoobj */
  18021. append_eoobj = buffer;
  18022. end -= sizeof(eoobj) - 1;
  18023. }
  18024. if ((ctx == NULL) || (idx < 0)) {
  18025. /* Parameter error */
  18026. return 0;
  18027. }
  18028. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18029. /* Out of range */
  18030. return 0;
  18031. }
  18032. /* Take connection [idx]. This connection is not locked in
  18033. * any way, so some other thread might use it. */
  18034. conn = (ctx->worker_connections) + idx;
  18035. /* Initialize output string */
  18036. connection_info_length += mg_str_append(&buffer, end, "{");
  18037. /* Init variables */
  18038. ri = &(conn->request_info);
  18039. #if defined(USE_SERVER_STATS)
  18040. state = conn->conn_state;
  18041. /* State as string */
  18042. switch (state) {
  18043. case 0:
  18044. state_str = "undefined";
  18045. break;
  18046. case 1:
  18047. state_str = "not used";
  18048. break;
  18049. case 2:
  18050. state_str = "init";
  18051. break;
  18052. case 3:
  18053. state_str = "ready";
  18054. break;
  18055. case 4:
  18056. state_str = "processing";
  18057. break;
  18058. case 5:
  18059. state_str = "processed";
  18060. break;
  18061. case 6:
  18062. state_str = "to close";
  18063. break;
  18064. case 7:
  18065. state_str = "closing";
  18066. break;
  18067. case 8:
  18068. state_str = "closed";
  18069. break;
  18070. case 9:
  18071. state_str = "done";
  18072. break;
  18073. }
  18074. #endif
  18075. /* Connection info */
  18076. if ((state >= 3) && (state < 9)) {
  18077. mg_snprintf(NULL,
  18078. NULL,
  18079. block,
  18080. sizeof(block),
  18081. "%s\"connection\" : {%s"
  18082. "\"remote\" : {%s"
  18083. "\"protocol\" : \"%s\",%s"
  18084. "\"addr\" : \"%s\",%s"
  18085. "\"port\" : %u%s"
  18086. "},%s"
  18087. "\"handled_requests\" : %u%s"
  18088. "}",
  18089. eol,
  18090. eol,
  18091. eol,
  18092. get_proto_name(conn),
  18093. eol,
  18094. ri->remote_addr,
  18095. eol,
  18096. ri->remote_port,
  18097. eol,
  18098. eol,
  18099. conn->handled_requests,
  18100. eol);
  18101. connection_info_length += mg_str_append(&buffer, end, block);
  18102. }
  18103. /* Request info */
  18104. if ((state >= 4) && (state < 6)) {
  18105. mg_snprintf(NULL,
  18106. NULL,
  18107. block,
  18108. sizeof(block),
  18109. "%s%s\"request_info\" : {%s"
  18110. "\"method\" : \"%s\",%s"
  18111. "\"uri\" : \"%s\",%s"
  18112. "\"query\" : %s%s%s%s"
  18113. "}",
  18114. (connection_info_length > 1 ? "," : ""),
  18115. eol,
  18116. eol,
  18117. ri->request_method,
  18118. eol,
  18119. ri->request_uri,
  18120. eol,
  18121. ri->query_string ? "\"" : "",
  18122. ri->query_string ? ri->query_string : "null",
  18123. ri->query_string ? "\"" : "",
  18124. eol);
  18125. connection_info_length += mg_str_append(&buffer, end, block);
  18126. }
  18127. /* Execution time information */
  18128. if ((state >= 2) && (state < 9)) {
  18129. char start_time_str[64] = {0};
  18130. char close_time_str[64] = {0};
  18131. time_t start_time = conn->conn_birth_time;
  18132. time_t close_time = 0;
  18133. double time_diff;
  18134. gmt_time_string(start_time_str,
  18135. sizeof(start_time_str) - 1,
  18136. &start_time);
  18137. #if defined(USE_SERVER_STATS)
  18138. close_time = conn->conn_close_time;
  18139. #endif
  18140. if (close_time != 0) {
  18141. time_diff = difftime(close_time, start_time);
  18142. gmt_time_string(close_time_str,
  18143. sizeof(close_time_str) - 1,
  18144. &close_time);
  18145. } else {
  18146. time_t now = time(NULL);
  18147. time_diff = difftime(now, start_time);
  18148. close_time_str[0] = 0; /* or use "now" ? */
  18149. }
  18150. mg_snprintf(NULL,
  18151. NULL,
  18152. block,
  18153. sizeof(block),
  18154. "%s%s\"time\" : {%s"
  18155. "\"uptime\" : %.0f,%s"
  18156. "\"start\" : \"%s\",%s"
  18157. "\"closed\" : \"%s\"%s"
  18158. "}",
  18159. (connection_info_length > 1 ? "," : ""),
  18160. eol,
  18161. eol,
  18162. time_diff,
  18163. eol,
  18164. start_time_str,
  18165. eol,
  18166. close_time_str,
  18167. eol);
  18168. connection_info_length += mg_str_append(&buffer, end, block);
  18169. }
  18170. /* Remote user name */
  18171. if ((ri->remote_user) && (state < 9)) {
  18172. mg_snprintf(NULL,
  18173. NULL,
  18174. block,
  18175. sizeof(block),
  18176. "%s%s\"user\" : {%s"
  18177. "\"name\" : \"%s\",%s"
  18178. "}",
  18179. (connection_info_length > 1 ? "," : ""),
  18180. eol,
  18181. eol,
  18182. ri->remote_user,
  18183. eol);
  18184. connection_info_length += mg_str_append(&buffer, end, block);
  18185. }
  18186. /* Data block */
  18187. if (state >= 3) {
  18188. mg_snprintf(NULL,
  18189. NULL,
  18190. block,
  18191. sizeof(block),
  18192. "%s%s\"data\" : {%s"
  18193. "\"read\" : %" INT64_FMT ",%s"
  18194. "\"written\" : %" INT64_FMT "%s"
  18195. "}",
  18196. (connection_info_length > 1 ? "," : ""),
  18197. eol,
  18198. eol,
  18199. conn->consumed_content,
  18200. eol,
  18201. conn->num_bytes_sent,
  18202. eol);
  18203. connection_info_length += mg_str_append(&buffer, end, block);
  18204. }
  18205. /* State */
  18206. mg_snprintf(NULL,
  18207. NULL,
  18208. block,
  18209. sizeof(block),
  18210. "%s%s\"state\" : \"%s\"",
  18211. (connection_info_length > 1 ? "," : ""),
  18212. eol,
  18213. state_str);
  18214. connection_info_length += mg_str_append(&buffer, end, block);
  18215. /* Terminate string */
  18216. if (append_eoobj) {
  18217. strcat(append_eoobj, eoobj);
  18218. }
  18219. connection_info_length += sizeof(eoobj) - 1;
  18220. return (int)connection_info_length;
  18221. }
  18222. #endif
  18223. /* Initialize this library. This function does not need to be thread safe.
  18224. */
  18225. unsigned
  18226. mg_init_library(unsigned features)
  18227. {
  18228. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18229. unsigned features_inited = features_to_init;
  18230. if (mg_init_library_called <= 0) {
  18231. /* Not initialized yet */
  18232. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18233. return 0;
  18234. }
  18235. }
  18236. mg_global_lock();
  18237. if (mg_init_library_called <= 0) {
  18238. #if defined(_WIN32)
  18239. int file_mutex_init = 1;
  18240. int wsa = 1;
  18241. #else
  18242. int mutexattr_init = 1;
  18243. #endif
  18244. int failed = 1;
  18245. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18246. if (key_create == 0) {
  18247. #if defined(_WIN32)
  18248. file_mutex_init =
  18249. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18250. if (file_mutex_init == 0) {
  18251. /* Start WinSock */
  18252. WSADATA data;
  18253. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18254. }
  18255. #else
  18256. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18257. if (mutexattr_init == 0) {
  18258. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18259. PTHREAD_MUTEX_RECURSIVE);
  18260. }
  18261. #endif
  18262. }
  18263. if (failed) {
  18264. #if defined(_WIN32)
  18265. if (wsa == 0) {
  18266. (void)WSACleanup();
  18267. }
  18268. if (file_mutex_init == 0) {
  18269. (void)pthread_mutex_destroy(&global_log_file_lock);
  18270. }
  18271. #else
  18272. if (mutexattr_init == 0) {
  18273. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18274. }
  18275. #endif
  18276. if (key_create == 0) {
  18277. (void)pthread_key_delete(sTlsKey);
  18278. }
  18279. mg_global_unlock();
  18280. (void)pthread_mutex_destroy(&global_lock_mutex);
  18281. return 0;
  18282. }
  18283. #if defined(USE_LUA)
  18284. lua_init_optional_libraries();
  18285. #endif
  18286. }
  18287. mg_global_unlock();
  18288. #if !defined(NO_SSL)
  18289. if (features_to_init & MG_FEATURES_SSL) {
  18290. if (!mg_ssl_initialized) {
  18291. char ebuf[128];
  18292. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18293. mg_ssl_initialized = 1;
  18294. } else {
  18295. (void)ebuf;
  18296. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18297. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18298. }
  18299. } else {
  18300. /* ssl already initialized */
  18301. }
  18302. }
  18303. #endif
  18304. mg_global_lock();
  18305. if (mg_init_library_called <= 0) {
  18306. mg_init_library_called = 1;
  18307. } else {
  18308. mg_init_library_called++;
  18309. }
  18310. mg_global_unlock();
  18311. return features_inited;
  18312. }
  18313. /* Un-initialize this library. */
  18314. unsigned
  18315. mg_exit_library(void)
  18316. {
  18317. if (mg_init_library_called <= 0) {
  18318. return 0;
  18319. }
  18320. mg_global_lock();
  18321. mg_init_library_called--;
  18322. if (mg_init_library_called == 0) {
  18323. #if !defined(NO_SSL)
  18324. if (mg_ssl_initialized) {
  18325. uninitialize_ssl();
  18326. mg_ssl_initialized = 0;
  18327. }
  18328. #endif
  18329. #if defined(_WIN32)
  18330. (void)WSACleanup();
  18331. (void)pthread_mutex_destroy(&global_log_file_lock);
  18332. #else
  18333. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18334. #endif
  18335. (void)pthread_key_delete(sTlsKey);
  18336. #if defined(USE_LUA)
  18337. lua_exit_optional_libraries();
  18338. #endif
  18339. mg_global_unlock();
  18340. (void)pthread_mutex_destroy(&global_lock_mutex);
  18341. return 1;
  18342. }
  18343. mg_global_unlock();
  18344. return 1;
  18345. }
  18346. /* End of civetweb.c */