civetweb.c 567 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143
  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. enum ssl_func_category required; /* Mandatory or optional */
  1599. void (*ptr)(void); /* Function pointer */
  1600. };
  1601. #if defined(OPENSSL_API_1_1)
  1602. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1603. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1604. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1605. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1606. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1607. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1608. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1609. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1610. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1611. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1612. #define OPENSSL_init_ssl \
  1613. (*(int (*)(uint64_t opts, \
  1614. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1615. .ptr)
  1616. #define SSL_CTX_use_PrivateKey_file \
  1617. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1618. #define SSL_CTX_use_certificate_file \
  1619. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1620. #define SSL_CTX_set_default_passwd_cb \
  1621. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1622. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1623. #define SSL_CTX_use_certificate_chain_file \
  1624. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1625. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1626. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1627. #define SSL_CTX_set_verify \
  1628. (*(void (*)(SSL_CTX *, \
  1629. int, \
  1630. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1631. .ptr)
  1632. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1633. #define SSL_CTX_load_verify_locations \
  1634. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1635. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1636. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1637. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1638. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1639. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1640. #define SSL_CIPHER_get_name \
  1641. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1642. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1643. #define SSL_CTX_set_session_id_context \
  1644. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1645. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1646. #define SSL_CTX_set_cipher_list \
  1647. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1648. #define SSL_CTX_set_options \
  1649. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1650. #define SSL_CTX_set_info_callback \
  1651. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1652. ssl_sw[32] \
  1653. .ptr)
  1654. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1655. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1656. #define SSL_CTX_callback_ctrl \
  1657. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1658. #define SSL_get_servername \
  1659. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1660. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1661. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1662. #define SSL_CTX_set_alpn_protos \
  1663. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1664. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1665. const unsigned char **out,
  1666. unsigned char *outlen,
  1667. const unsigned char *in,
  1668. unsigned int inlen,
  1669. void *arg);
  1670. #define SSL_CTX_set_alpn_select_cb \
  1671. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1672. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1673. const unsigned char **out,
  1674. unsigned int *outlen,
  1675. void *arg);
  1676. #define SSL_CTX_set_next_protos_advertised_cb \
  1677. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1678. .ptr)
  1679. #define SSL_CTX_clear_options(ctx, op) \
  1680. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1681. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1682. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1683. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1684. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1685. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1686. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1687. SSL_CTX_callback_ctrl(ctx, \
  1688. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1689. (void (*)(void))cb)
  1690. #define SSL_set_tlsext_host_name(ctx, arg) \
  1691. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1692. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1693. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1694. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1695. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1696. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1697. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1698. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1699. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1700. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1701. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1702. #define X509_NAME_oneline \
  1703. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1704. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1705. #define EVP_get_digestbyname \
  1706. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1707. #define EVP_Digest \
  1708. (*(int (*)( \
  1709. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1710. crypto_sw[9] \
  1711. .ptr)
  1712. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1713. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1714. #define ASN1_INTEGER_to_BN \
  1715. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1716. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1717. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1718. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1719. #define OPENSSL_free(a) CRYPTO_free(a)
  1720. #define OPENSSL_REMOVE_THREAD_STATE()
  1721. /* init_ssl_ctx() function updates this array.
  1722. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1723. * of respective functions. The macros above (like SSL_connect()) are really
  1724. * just calling these functions indirectly via the pointer. */
  1725. static struct ssl_func ssl_sw[] = {
  1726. {"SSL_free", TLS_Mandatory, NULL},
  1727. {"SSL_accept", TLS_Mandatory, NULL},
  1728. {"SSL_connect", TLS_Mandatory, NULL},
  1729. {"SSL_read", TLS_Mandatory, NULL},
  1730. {"SSL_write", TLS_Mandatory, NULL},
  1731. {"SSL_get_error", TLS_Mandatory, NULL},
  1732. {"SSL_set_fd", TLS_Mandatory, NULL},
  1733. {"SSL_new", TLS_Mandatory, NULL},
  1734. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1735. {"TLS_server_method", TLS_Mandatory, NULL},
  1736. {"OPENSSL_init_ssl", TLS_Mandatory, NULL},
  1737. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1738. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1739. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1740. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1741. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1742. {"TLS_client_method", TLS_Mandatory, NULL},
  1743. {"SSL_pending", TLS_Mandatory, NULL},
  1744. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1745. {"SSL_shutdown", TLS_Mandatory, NULL},
  1746. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1747. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1748. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1749. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1750. {"SSL_get_version", TLS_Mandatory, NULL},
  1751. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1752. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1753. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1754. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1755. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1756. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1757. {"SSL_CTX_set_options", TLS_Mandatory, NULL},
  1758. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1759. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1760. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1761. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1762. {"SSL_get_servername", TLS_Mandatory, NULL},
  1763. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1764. {"SSL_ctrl", TLS_Mandatory, NULL},
  1765. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1766. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1767. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1768. {NULL, TLS_END_OF_LIST, NULL}};
  1769. /* Similar array as ssl_sw. These functions could be located in different
  1770. * lib. */
  1771. static struct ssl_func crypto_sw[] = {
  1772. {"ERR_get_error", TLS_Mandatory, NULL},
  1773. {"ERR_error_string", TLS_Mandatory, NULL},
  1774. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1775. {"X509_free", TLS_Mandatory, NULL},
  1776. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1777. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1778. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1779. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1780. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1781. {"EVP_Digest", TLS_Mandatory, NULL},
  1782. {"i2d_X509", TLS_Mandatory, NULL},
  1783. {"BN_bn2hex", TLS_Mandatory, NULL},
  1784. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1785. {"BN_free", TLS_Mandatory, NULL},
  1786. {"CRYPTO_free", TLS_Mandatory, NULL},
  1787. {"ERR_clear_error", TLS_Mandatory, NULL},
  1788. {NULL, TLS_END_OF_LIST, NULL}};
  1789. #else
  1790. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1791. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1792. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1793. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1794. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1795. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1796. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1797. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1798. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1799. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1800. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1801. #define SSL_CTX_use_PrivateKey_file \
  1802. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1803. #define SSL_CTX_use_certificate_file \
  1804. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1805. #define SSL_CTX_set_default_passwd_cb \
  1806. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1807. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1808. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1809. #define SSL_CTX_use_certificate_chain_file \
  1810. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1811. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1812. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1813. #define SSL_CTX_set_verify \
  1814. (*(void (*)(SSL_CTX *, \
  1815. int, \
  1816. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1817. .ptr)
  1818. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1819. #define SSL_CTX_load_verify_locations \
  1820. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1821. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1822. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1823. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1824. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1825. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1826. #define SSL_CIPHER_get_name \
  1827. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1828. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1829. #define SSL_CTX_set_session_id_context \
  1830. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1831. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1832. #define SSL_CTX_set_cipher_list \
  1833. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1834. #define SSL_CTX_set_info_callback \
  1835. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1836. .ptr)
  1837. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1838. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1839. #define SSL_CTX_callback_ctrl \
  1840. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1841. #define SSL_get_servername \
  1842. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1843. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1844. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1845. #define SSL_CTX_set_alpn_protos \
  1846. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1847. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1848. const unsigned char **out,
  1849. unsigned char *outlen,
  1850. const unsigned char *in,
  1851. unsigned int inlen,
  1852. void *arg);
  1853. #define SSL_CTX_set_alpn_select_cb \
  1854. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1855. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1856. const unsigned char **out,
  1857. unsigned int *outlen,
  1858. void *arg);
  1859. #define SSL_CTX_set_next_protos_advertised_cb \
  1860. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1861. .ptr)
  1862. #define SSL_CTX_set_options(ctx, op) \
  1863. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1864. #define SSL_CTX_clear_options(ctx, op) \
  1865. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1866. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1867. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1868. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1869. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1870. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1871. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1872. SSL_CTX_callback_ctrl(ctx, \
  1873. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1874. (void (*)(void))cb)
  1875. #define SSL_set_tlsext_host_name(ctx, arg) \
  1876. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1877. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1878. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1879. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1880. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1881. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1882. #define CRYPTO_set_locking_callback \
  1883. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1884. #define CRYPTO_set_id_callback \
  1885. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1886. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1887. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1888. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1889. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1890. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1891. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1892. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1893. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1894. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1895. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1896. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1897. #define X509_NAME_oneline \
  1898. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1899. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1900. #define i2c_ASN1_INTEGER \
  1901. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1902. #define EVP_get_digestbyname \
  1903. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1904. #define EVP_Digest \
  1905. (*(int (*)( \
  1906. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1907. crypto_sw[18] \
  1908. .ptr)
  1909. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1910. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1911. #define ASN1_INTEGER_to_BN \
  1912. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1913. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1914. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1915. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1916. #define OPENSSL_free(a) CRYPTO_free(a)
  1917. /* use here ERR_remove_state,
  1918. * while on some platforms function is not included into library due to
  1919. * deprication */
  1920. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1921. /* init_ssl_ctx() function updates this array.
  1922. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1923. * of respective functions. The macros above (like SSL_connect()) are really
  1924. * just calling these functions indirectly via the pointer. */
  1925. static struct ssl_func ssl_sw[] = {
  1926. {"SSL_free", TLS_Mandatory, NULL},
  1927. {"SSL_accept", TLS_Mandatory, NULL},
  1928. {"SSL_connect", TLS_Mandatory, NULL},
  1929. {"SSL_read", TLS_Mandatory, NULL},
  1930. {"SSL_write", TLS_Mandatory, NULL},
  1931. {"SSL_get_error", TLS_Mandatory, NULL},
  1932. {"SSL_set_fd", TLS_Mandatory, NULL},
  1933. {"SSL_new", TLS_Mandatory, NULL},
  1934. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1935. {"SSLv23_server_method", TLS_Mandatory, NULL},
  1936. {"SSL_library_init", TLS_Mandatory, NULL},
  1937. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1938. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1939. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1940. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1941. {"SSL_load_error_strings", TLS_Mandatory, NULL},
  1942. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1943. {"SSLv23_client_method", TLS_Mandatory, NULL},
  1944. {"SSL_pending", TLS_Mandatory, NULL},
  1945. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1946. {"SSL_shutdown", TLS_Mandatory, NULL},
  1947. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1948. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1949. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1950. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1951. {"SSL_get_version", TLS_Mandatory, NULL},
  1952. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1953. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1954. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1955. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1956. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1957. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1958. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1959. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1960. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1961. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1962. {"SSL_get_servername", TLS_Mandatory, NULL},
  1963. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1964. {"SSL_ctrl", TLS_Mandatory, NULL},
  1965. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1966. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1967. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1968. {NULL, TLS_END_OF_LIST, NULL}};
  1969. /* Similar array as ssl_sw. These functions could be located in different
  1970. * lib. */
  1971. static struct ssl_func crypto_sw[] = {
  1972. {"CRYPTO_num_locks", TLS_Mandatory, NULL},
  1973. {"CRYPTO_set_locking_callback", TLS_Mandatory, NULL},
  1974. {"CRYPTO_set_id_callback", TLS_Mandatory, NULL},
  1975. {"ERR_get_error", TLS_Mandatory, NULL},
  1976. {"ERR_error_string", TLS_Mandatory, NULL},
  1977. {"ERR_remove_state", TLS_Mandatory, NULL},
  1978. {"ERR_free_strings", TLS_Mandatory, NULL},
  1979. {"ENGINE_cleanup", TLS_Mandatory, NULL},
  1980. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1981. {"CRYPTO_cleanup_all_ex_data", TLS_Mandatory, NULL},
  1982. {"EVP_cleanup", TLS_Mandatory, NULL},
  1983. {"X509_free", TLS_Mandatory, NULL},
  1984. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1985. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1986. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1987. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1988. {"i2c_ASN1_INTEGER", TLS_Mandatory, NULL},
  1989. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1990. {"EVP_Digest", TLS_Mandatory, NULL},
  1991. {"i2d_X509", TLS_Mandatory, NULL},
  1992. {"BN_bn2hex", TLS_Mandatory, NULL},
  1993. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1994. {"BN_free", TLS_Mandatory, NULL},
  1995. {"CRYPTO_free", TLS_Mandatory, NULL},
  1996. {"ERR_clear_error", TLS_Mandatory, NULL},
  1997. {NULL, TLS_END_OF_LIST, NULL}};
  1998. #endif /* OPENSSL_API_1_1 */
  1999. #endif /* NO_SSL_DL */
  2000. #endif /* NO_SSL */
  2001. #if !defined(NO_CACHING)
  2002. static const char month_names[][4] = {"Jan",
  2003. "Feb",
  2004. "Mar",
  2005. "Apr",
  2006. "May",
  2007. "Jun",
  2008. "Jul",
  2009. "Aug",
  2010. "Sep",
  2011. "Oct",
  2012. "Nov",
  2013. "Dec"};
  2014. #endif /* !NO_CACHING */
  2015. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2016. * the union u. */
  2017. union usa {
  2018. struct sockaddr sa;
  2019. struct sockaddr_in sin;
  2020. #if defined(USE_IPV6)
  2021. struct sockaddr_in6 sin6;
  2022. #endif
  2023. };
  2024. #if defined(USE_IPV6)
  2025. #define USA_IN_PORT_UNSAFE(s) \
  2026. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2027. #else
  2028. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2029. #endif
  2030. /* Describes a string (chunk of memory). */
  2031. struct vec {
  2032. const char *ptr;
  2033. size_t len;
  2034. };
  2035. struct mg_file_stat {
  2036. /* File properties filled by mg_stat: */
  2037. uint64_t size;
  2038. time_t last_modified;
  2039. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2040. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2041. * case we need a "Content-Eencoding: gzip" header */
  2042. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2043. };
  2044. struct mg_file_in_memory {
  2045. char *p;
  2046. uint32_t pos;
  2047. char mode;
  2048. };
  2049. struct mg_file_access {
  2050. /* File properties filled by mg_fopen: */
  2051. FILE *fp;
  2052. #if defined(MG_USE_OPEN_FILE)
  2053. /* TODO (low): Remove obsolete "file in memory" implementation.
  2054. * In an "early 2017" discussion at Google groups
  2055. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2056. * we decided to get rid of this feature (after some fade-out
  2057. * phase). */
  2058. const char *membuf;
  2059. #endif
  2060. };
  2061. struct mg_file {
  2062. struct mg_file_stat stat;
  2063. struct mg_file_access access;
  2064. };
  2065. #if defined(MG_USE_OPEN_FILE)
  2066. #define STRUCT_FILE_INITIALIZER \
  2067. { \
  2068. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2069. { \
  2070. (FILE *)NULL, (const char *)NULL \
  2071. } \
  2072. }
  2073. #else
  2074. #define STRUCT_FILE_INITIALIZER \
  2075. { \
  2076. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2077. { \
  2078. (FILE *)NULL \
  2079. } \
  2080. }
  2081. #endif
  2082. /* Describes listening socket, or socket which was accept()-ed by the master
  2083. * thread and queued for future handling by the worker thread. */
  2084. struct socket {
  2085. SOCKET sock; /* Listening socket */
  2086. union usa lsa; /* Local socket address */
  2087. union usa rsa; /* Remote socket address */
  2088. unsigned char is_ssl; /* Is port SSL-ed */
  2089. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2090. * port */
  2091. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2092. };
  2093. /* Enum const for all options must be in sync with
  2094. * static struct mg_option config_options[]
  2095. * This is tested in the unit test (test/private.c)
  2096. * "Private Config Options"
  2097. */
  2098. enum {
  2099. /* Once for each server */
  2100. LISTENING_PORTS,
  2101. NUM_THREADS,
  2102. RUN_AS_USER,
  2103. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2104. * socket option typedef TCP_NODELAY. */
  2105. MAX_REQUEST_SIZE,
  2106. LINGER_TIMEOUT,
  2107. CONNECTION_QUEUE_SIZE,
  2108. LISTEN_BACKLOG_SIZE,
  2109. #if defined(__linux__)
  2110. ALLOW_SENDFILE_CALL,
  2111. #endif
  2112. #if defined(_WIN32)
  2113. CASE_SENSITIVE_FILES,
  2114. #endif
  2115. THROTTLE,
  2116. ACCESS_LOG_FILE,
  2117. ERROR_LOG_FILE,
  2118. ENABLE_KEEP_ALIVE,
  2119. REQUEST_TIMEOUT,
  2120. KEEP_ALIVE_TIMEOUT,
  2121. #if defined(USE_WEBSOCKET)
  2122. WEBSOCKET_TIMEOUT,
  2123. ENABLE_WEBSOCKET_PING_PONG,
  2124. #endif
  2125. DECODE_URL,
  2126. #if defined(USE_LUA)
  2127. LUA_BACKGROUND_SCRIPT,
  2128. LUA_BACKGROUND_SCRIPT_PARAMS,
  2129. #endif
  2130. #if defined(USE_TIMERS)
  2131. CGI_TIMEOUT,
  2132. #endif
  2133. /* Once for each domain */
  2134. DOCUMENT_ROOT,
  2135. CGI_EXTENSIONS,
  2136. CGI_ENVIRONMENT,
  2137. PUT_DELETE_PASSWORDS_FILE,
  2138. CGI_INTERPRETER,
  2139. CGI_INTERPRETER_ARGS,
  2140. PROTECT_URI,
  2141. AUTHENTICATION_DOMAIN,
  2142. ENABLE_AUTH_DOMAIN_CHECK,
  2143. SSI_EXTENSIONS,
  2144. ENABLE_DIRECTORY_LISTING,
  2145. GLOBAL_PASSWORDS_FILE,
  2146. INDEX_FILES,
  2147. ACCESS_CONTROL_LIST,
  2148. EXTRA_MIME_TYPES,
  2149. SSL_CERTIFICATE,
  2150. SSL_CERTIFICATE_CHAIN,
  2151. URL_REWRITE_PATTERN,
  2152. HIDE_FILES,
  2153. SSL_DO_VERIFY_PEER,
  2154. SSL_CA_PATH,
  2155. SSL_CA_FILE,
  2156. SSL_VERIFY_DEPTH,
  2157. SSL_DEFAULT_VERIFY_PATHS,
  2158. SSL_CIPHER_LIST,
  2159. SSL_PROTOCOL_VERSION,
  2160. SSL_SHORT_TRUST,
  2161. #if defined(USE_LUA)
  2162. LUA_PRELOAD_FILE,
  2163. LUA_SCRIPT_EXTENSIONS,
  2164. LUA_SERVER_PAGE_EXTENSIONS,
  2165. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2166. LUA_DEBUG_PARAMS,
  2167. #endif
  2168. #endif
  2169. #if defined(USE_DUKTAPE)
  2170. DUKTAPE_SCRIPT_EXTENSIONS,
  2171. #endif
  2172. #if defined(USE_WEBSOCKET)
  2173. WEBSOCKET_ROOT,
  2174. #endif
  2175. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2176. LUA_WEBSOCKET_EXTENSIONS,
  2177. #endif
  2178. ACCESS_CONTROL_ALLOW_ORIGIN,
  2179. ACCESS_CONTROL_ALLOW_METHODS,
  2180. ACCESS_CONTROL_ALLOW_HEADERS,
  2181. ERROR_PAGES,
  2182. #if !defined(NO_CACHING)
  2183. STATIC_FILE_MAX_AGE,
  2184. STATIC_FILE_CACHE_CONTROL,
  2185. #endif
  2186. #if !defined(NO_SSL)
  2187. STRICT_HTTPS_MAX_AGE,
  2188. #endif
  2189. ADDITIONAL_HEADER,
  2190. ALLOW_INDEX_SCRIPT_SUB_RES,
  2191. #if defined(DAEMONIZE)
  2192. ENABLE_DAEMONIZE,
  2193. #endif
  2194. NUM_OPTIONS
  2195. };
  2196. /* Config option name, config types, default value.
  2197. * Must be in the same order as the enum const above.
  2198. */
  2199. static const struct mg_option config_options[] = {
  2200. /* Once for each server */
  2201. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2202. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2203. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2204. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2205. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2206. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2207. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2208. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2209. #if defined(__linux__)
  2210. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2211. #endif
  2212. #if defined(_WIN32)
  2213. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2214. #endif
  2215. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2216. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2217. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2218. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2219. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2220. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2221. #if defined(USE_WEBSOCKET)
  2222. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2223. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2224. #endif
  2225. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2226. #if defined(USE_LUA)
  2227. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2228. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2229. #endif
  2230. #if defined(USE_TIMERS)
  2231. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2232. #endif
  2233. /* Once for each domain */
  2234. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2235. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2236. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2237. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2238. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2239. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2240. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2241. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2242. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2243. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2244. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2245. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2246. {"index_files",
  2247. MG_CONFIG_TYPE_STRING_LIST,
  2248. #if defined(USE_LUA)
  2249. "index.xhtml,index.html,index.htm,"
  2250. "index.lp,index.lsp,index.lua,index.cgi,"
  2251. "index.shtml,index.php"},
  2252. #else
  2253. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2254. #endif
  2255. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2256. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2257. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2258. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2259. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2260. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2261. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2262. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2263. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2264. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2265. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2266. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2267. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2268. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2269. #if defined(USE_LUA)
  2270. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2271. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2272. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2273. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2274. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2275. #endif
  2276. #endif
  2277. #if defined(USE_DUKTAPE)
  2278. /* The support for duktape is still in alpha version state.
  2279. * The name of this config option might change. */
  2280. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2281. #endif
  2282. #if defined(USE_WEBSOCKET)
  2283. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2284. #endif
  2285. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2286. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2287. #endif
  2288. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2289. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2290. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2291. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2292. #if !defined(NO_CACHING)
  2293. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2294. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2295. #endif
  2296. #if !defined(NO_SSL)
  2297. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2298. #endif
  2299. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2300. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2301. #if defined(DAEMONIZE)
  2302. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2303. #endif
  2304. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2305. /* Check if the config_options and the corresponding enum have compatible
  2306. * sizes. */
  2307. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2308. == (NUM_OPTIONS + 1),
  2309. "config_options and enum not sync");
  2310. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2311. struct mg_handler_info {
  2312. /* Name/Pattern of the URI. */
  2313. char *uri;
  2314. size_t uri_len;
  2315. /* handler type */
  2316. int handler_type;
  2317. /* Handler for http/https or authorization requests. */
  2318. mg_request_handler handler;
  2319. unsigned int refcount;
  2320. int removing;
  2321. /* Handler for ws/wss (websocket) requests. */
  2322. mg_websocket_connect_handler connect_handler;
  2323. mg_websocket_ready_handler ready_handler;
  2324. mg_websocket_data_handler data_handler;
  2325. mg_websocket_close_handler close_handler;
  2326. /* accepted subprotocols for ws/wss requests. */
  2327. struct mg_websocket_subprotocols *subprotocols;
  2328. /* Handler for authorization requests */
  2329. mg_authorization_handler auth_handler;
  2330. /* User supplied argument for the handler function. */
  2331. void *cbdata;
  2332. /* next handler in a linked list */
  2333. struct mg_handler_info *next;
  2334. };
  2335. enum {
  2336. CONTEXT_INVALID,
  2337. CONTEXT_SERVER,
  2338. CONTEXT_HTTP_CLIENT,
  2339. CONTEXT_WS_CLIENT
  2340. };
  2341. struct mg_domain_context {
  2342. SSL_CTX *ssl_ctx; /* SSL context */
  2343. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2344. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2345. int64_t ssl_cert_last_mtime;
  2346. /* Server nonce */
  2347. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2348. unsigned long nonce_count; /* Used nonces, used for authentication */
  2349. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2350. /* linked list of shared lua websockets */
  2351. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2352. #endif
  2353. /* Linked list of domains */
  2354. struct mg_domain_context *next;
  2355. };
  2356. /* Stop flag can be "volatile" or require a lock */
  2357. typedef int volatile stop_flag_t;
  2358. #ifdef STOP_FLAG_NEEDS_LOCK
  2359. static int
  2360. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2361. {
  2362. int r;
  2363. mg_global_lock();
  2364. r = ((*f) == 0);
  2365. mg_global_unlock();
  2366. return r;
  2367. }
  2368. static int
  2369. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2370. {
  2371. int r;
  2372. mg_global_lock();
  2373. r = ((*f) == 2);
  2374. mg_global_unlock();
  2375. return r;
  2376. }
  2377. static void
  2378. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2379. {
  2380. mg_global_lock();
  2381. (*f) = v;
  2382. mg_global_unlock();
  2383. }
  2384. #else /* STOP_FLAG_NEEDS_LOCK */
  2385. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2386. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2387. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2388. #endif /* STOP_FLAG_NEEDS_LOCK */
  2389. struct mg_context {
  2390. /* Part 1 - Physical context:
  2391. * This holds threads, ports, timeouts, ...
  2392. * set for the entire server, independent from the
  2393. * addressed hostname.
  2394. */
  2395. /* Connection related */
  2396. int context_type; /* See CONTEXT_* above */
  2397. struct socket *listening_sockets;
  2398. struct mg_pollfd *listening_socket_fds;
  2399. unsigned int num_listening_sockets;
  2400. struct mg_connection *worker_connections; /* The connection struct, pre-
  2401. * allocated for each worker */
  2402. #if defined(USE_SERVER_STATS)
  2403. int active_connections;
  2404. int max_active_connections;
  2405. int64_t total_connections;
  2406. int64_t total_requests;
  2407. int64_t total_data_read;
  2408. int64_t total_data_written;
  2409. #endif
  2410. /* Thread related */
  2411. stop_flag_t stop_flag; /* Should we stop event loop */
  2412. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2413. pthread_t masterthreadid; /* The master thread ID */
  2414. unsigned int
  2415. cfg_worker_threads; /* The number of configured worker threads. */
  2416. pthread_t *worker_threadids; /* The worker thread IDs */
  2417. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2418. /* Connection to thread dispatching */
  2419. #if defined(ALTERNATIVE_QUEUE)
  2420. struct socket *client_socks;
  2421. void **client_wait_events;
  2422. #else
  2423. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2424. worker thread */
  2425. volatile int sq_head; /* Head of the socket queue */
  2426. volatile int sq_tail; /* Tail of the socket queue */
  2427. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2428. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2429. volatile int sq_blocked; /* Status information: sq is full */
  2430. int sq_size; /* No of elements in socket queue */
  2431. #if defined(USE_SERVER_STATS)
  2432. int sq_max_fill;
  2433. #endif /* USE_SERVER_STATS */
  2434. #endif /* ALTERNATIVE_QUEUE */
  2435. /* Memory related */
  2436. unsigned int max_request_size; /* The max request size */
  2437. #if defined(USE_SERVER_STATS)
  2438. struct mg_memory_stat ctx_memory;
  2439. #endif
  2440. /* Operating system related */
  2441. char *systemName; /* What operating system is running */
  2442. time_t start_time; /* Server start time, used for authentication
  2443. * and for diagnstics. */
  2444. #if defined(USE_TIMERS)
  2445. struct ttimers *timers;
  2446. #endif
  2447. /* Lua specific: Background operations and shared websockets */
  2448. #if defined(USE_LUA)
  2449. void *lua_background_state;
  2450. #endif
  2451. /* Server nonce */
  2452. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2453. * ssl_cert_last_mtime, nonce_count, and
  2454. * next (linked list) */
  2455. /* Server callbacks */
  2456. struct mg_callbacks callbacks; /* User-defined callback function */
  2457. void *user_data; /* User-defined data */
  2458. /* Part 2 - Logical domain:
  2459. * This holds hostname, TLS certificate, document root, ...
  2460. * set for a domain hosted at the server.
  2461. * There may be multiple domains hosted at one physical server.
  2462. * The default domain "dd" is the first element of a list of
  2463. * domains.
  2464. */
  2465. struct mg_domain_context dd; /* default domain */
  2466. };
  2467. #if defined(USE_SERVER_STATS)
  2468. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2469. static struct mg_memory_stat *
  2470. get_memory_stat(struct mg_context *ctx)
  2471. {
  2472. if (ctx) {
  2473. return &(ctx->ctx_memory);
  2474. }
  2475. return &mg_common_memory;
  2476. }
  2477. #endif
  2478. enum {
  2479. CONNECTION_TYPE_INVALID,
  2480. CONNECTION_TYPE_REQUEST,
  2481. CONNECTION_TYPE_RESPONSE
  2482. };
  2483. enum {
  2484. PROTOCOL_TYPE_HTTP1 = 0,
  2485. PROTOCOL_TYPE_WEBSOCKET = 1,
  2486. PROTOCOL_TYPE_HTTP2 = 2
  2487. };
  2488. struct mg_connection {
  2489. int connection_type; /* see CONNECTION_TYPE_* above */
  2490. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2491. struct mg_request_info request_info;
  2492. struct mg_response_info response_info;
  2493. struct mg_context *phys_ctx;
  2494. struct mg_domain_context *dom_ctx;
  2495. #if defined(USE_SERVER_STATS)
  2496. int conn_state; /* 0 = undef, numerical value may change in different
  2497. * versions. For the current definition, see
  2498. * mg_get_connection_info_impl */
  2499. #endif
  2500. SSL *ssl; /* SSL descriptor */
  2501. struct socket client; /* Connected client */
  2502. time_t conn_birth_time; /* Time (wall clock) when connection was
  2503. * established */
  2504. #if defined(USE_SERVER_STATS)
  2505. time_t conn_close_time; /* Time (wall clock) when connection was
  2506. * closed (or 0 if still open) */
  2507. #endif
  2508. struct timespec req_time; /* Time (since system start) when the request
  2509. * was received */
  2510. int64_t num_bytes_sent; /* Total bytes sent to client */
  2511. int64_t content_len; /* How many bytes of content can be read
  2512. * !is_chunked: Content-Length header value
  2513. * or -1 (until connection closed,
  2514. * not allowed for a request)
  2515. * is_chunked: >= 0, appended gradually
  2516. */
  2517. int64_t consumed_content; /* How many bytes of content have been read */
  2518. int is_chunked; /* Transfer-Encoding is chunked:
  2519. * 0 = not chunked,
  2520. * 1 = chunked, not yet, or some data read,
  2521. * 2 = chunked, has error,
  2522. * 3 = chunked, all data read except trailer,
  2523. * 4 = chunked, all data read
  2524. */
  2525. char *buf; /* Buffer for received data */
  2526. char *path_info; /* PATH_INFO part of the URL */
  2527. int must_close; /* 1 if connection must be closed */
  2528. int accept_gzip; /* 1 if gzip encoding is accepted */
  2529. int in_error_handler; /* 1 if in handler for user defined error
  2530. * pages */
  2531. #if defined(USE_WEBSOCKET)
  2532. int in_websocket_handling; /* 1 if in read_websocket */
  2533. #endif
  2534. int handled_requests; /* Number of requests handled by this connection
  2535. */
  2536. int buf_size; /* Buffer size */
  2537. int request_len; /* Size of the request + headers in a buffer */
  2538. int data_len; /* Total size of data in a buffer */
  2539. int status_code; /* HTTP reply status code, e.g. 200 */
  2540. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2541. * throttle */
  2542. time_t last_throttle_time; /* Last time throttled data was sent */
  2543. int last_throttle_bytes; /* Bytes sent this second */
  2544. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2545. * atomic transmissions for websockets */
  2546. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2547. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2548. #endif
  2549. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2550. * for quick access */
  2551. };
  2552. /* Directory entry */
  2553. struct de {
  2554. struct mg_connection *conn;
  2555. char *file_name;
  2556. struct mg_file_stat file;
  2557. };
  2558. #define mg_cry_internal(conn, fmt, ...) \
  2559. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2560. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2561. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2562. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2563. struct mg_context *ctx,
  2564. const char *func,
  2565. unsigned line,
  2566. const char *fmt,
  2567. ...) PRINTF_ARGS(5, 6);
  2568. #if !defined(NO_THREAD_NAME)
  2569. #if defined(_WIN32) && defined(_MSC_VER)
  2570. /* Set the thread name for debugging purposes in Visual Studio
  2571. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2572. */
  2573. #pragma pack(push, 8)
  2574. typedef struct tagTHREADNAME_INFO {
  2575. DWORD dwType; /* Must be 0x1000. */
  2576. LPCSTR szName; /* Pointer to name (in user addr space). */
  2577. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2578. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2579. } THREADNAME_INFO;
  2580. #pragma pack(pop)
  2581. #elif defined(__linux__)
  2582. #include <sys/prctl.h>
  2583. #include <sys/sendfile.h>
  2584. #if defined(ALTERNATIVE_QUEUE)
  2585. #include <sys/eventfd.h>
  2586. #endif /* ALTERNATIVE_QUEUE */
  2587. #if defined(ALTERNATIVE_QUEUE)
  2588. static void *
  2589. event_create(void)
  2590. {
  2591. int evhdl = eventfd(0, EFD_CLOEXEC);
  2592. int *ret;
  2593. if (evhdl == -1) {
  2594. /* Linux uses -1 on error, Windows NULL. */
  2595. /* However, Linux does not return 0 on success either. */
  2596. return 0;
  2597. }
  2598. ret = (int *)mg_malloc(sizeof(int));
  2599. if (ret) {
  2600. *ret = evhdl;
  2601. } else {
  2602. (void)close(evhdl);
  2603. }
  2604. return (void *)ret;
  2605. }
  2606. static int
  2607. event_wait(void *eventhdl)
  2608. {
  2609. uint64_t u;
  2610. int evhdl, s;
  2611. if (!eventhdl) {
  2612. /* error */
  2613. return 0;
  2614. }
  2615. evhdl = *(int *)eventhdl;
  2616. s = (int)read(evhdl, &u, sizeof(u));
  2617. if (s != sizeof(u)) {
  2618. /* error */
  2619. return 0;
  2620. }
  2621. (void)u; /* the value is not required */
  2622. return 1;
  2623. }
  2624. static int
  2625. event_signal(void *eventhdl)
  2626. {
  2627. uint64_t u = 1;
  2628. int evhdl, s;
  2629. if (!eventhdl) {
  2630. /* error */
  2631. return 0;
  2632. }
  2633. evhdl = *(int *)eventhdl;
  2634. s = (int)write(evhdl, &u, sizeof(u));
  2635. if (s != sizeof(u)) {
  2636. /* error */
  2637. return 0;
  2638. }
  2639. return 1;
  2640. }
  2641. static void
  2642. event_destroy(void *eventhdl)
  2643. {
  2644. int evhdl;
  2645. if (!eventhdl) {
  2646. /* error */
  2647. return;
  2648. }
  2649. evhdl = *(int *)eventhdl;
  2650. close(evhdl);
  2651. mg_free(eventhdl);
  2652. }
  2653. #endif
  2654. #endif
  2655. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2656. struct posix_event {
  2657. pthread_mutex_t mutex;
  2658. pthread_cond_t cond;
  2659. int signaled;
  2660. };
  2661. static void *
  2662. event_create(void)
  2663. {
  2664. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2665. if (ret == 0) {
  2666. /* out of memory */
  2667. return 0;
  2668. }
  2669. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2670. /* pthread mutex not available */
  2671. mg_free(ret);
  2672. return 0;
  2673. }
  2674. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2675. /* pthread cond not available */
  2676. pthread_mutex_destroy(&(ret->mutex));
  2677. mg_free(ret);
  2678. return 0;
  2679. }
  2680. ret->signaled = 0;
  2681. return (void *)ret;
  2682. }
  2683. static int
  2684. event_wait(void *eventhdl)
  2685. {
  2686. struct posix_event *ev = (struct posix_event *)eventhdl;
  2687. pthread_mutex_lock(&(ev->mutex));
  2688. while (!ev->signaled) {
  2689. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2690. }
  2691. ev->signaled = 0;
  2692. pthread_mutex_unlock(&(ev->mutex));
  2693. return 1;
  2694. }
  2695. static int
  2696. event_signal(void *eventhdl)
  2697. {
  2698. struct posix_event *ev = (struct posix_event *)eventhdl;
  2699. pthread_mutex_lock(&(ev->mutex));
  2700. pthread_cond_signal(&(ev->cond));
  2701. ev->signaled = 1;
  2702. pthread_mutex_unlock(&(ev->mutex));
  2703. return 1;
  2704. }
  2705. static void
  2706. event_destroy(void *eventhdl)
  2707. {
  2708. struct posix_event *ev = (struct posix_event *)eventhdl;
  2709. pthread_cond_destroy(&(ev->cond));
  2710. pthread_mutex_destroy(&(ev->mutex));
  2711. mg_free(ev);
  2712. }
  2713. #endif
  2714. static void
  2715. mg_set_thread_name(const char *name)
  2716. {
  2717. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2718. mg_snprintf(
  2719. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2720. #if defined(_WIN32)
  2721. #if defined(_MSC_VER)
  2722. /* Windows and Visual Studio Compiler */
  2723. __try {
  2724. THREADNAME_INFO info;
  2725. info.dwType = 0x1000;
  2726. info.szName = threadName;
  2727. info.dwThreadID = ~0U;
  2728. info.dwFlags = 0;
  2729. RaiseException(0x406D1388,
  2730. 0,
  2731. sizeof(info) / sizeof(ULONG_PTR),
  2732. (ULONG_PTR *)&info);
  2733. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2734. }
  2735. #elif defined(__MINGW32__)
  2736. /* No option known to set thread name for MinGW known */
  2737. #endif
  2738. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2739. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2740. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2741. #if defined(__MACH__)
  2742. /* OS X only current thread name can be changed */
  2743. (void)pthread_setname_np(threadName);
  2744. #else
  2745. (void)pthread_setname_np(pthread_self(), threadName);
  2746. #endif
  2747. #elif defined(__linux__)
  2748. /* On Linux we can use the prctl function.
  2749. * When building for Linux Standard Base (LSB) use
  2750. * NO_THREAD_NAME. However, thread names are a big
  2751. * help for debugging, so the stadard is to set them.
  2752. */
  2753. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2754. #endif
  2755. }
  2756. #else /* !defined(NO_THREAD_NAME) */
  2757. void
  2758. mg_set_thread_name(const char *threadName)
  2759. {
  2760. }
  2761. #endif
  2762. #if defined(MG_LEGACY_INTERFACE)
  2763. const char **
  2764. mg_get_valid_option_names(void)
  2765. {
  2766. /* This function is deprecated. Use mg_get_valid_options instead. */
  2767. static const char
  2768. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2769. int i;
  2770. for (i = 0; config_options[i].name != NULL; i++) {
  2771. data[i * 2] = config_options[i].name;
  2772. data[i * 2 + 1] = config_options[i].default_value;
  2773. }
  2774. return data;
  2775. }
  2776. #endif
  2777. const struct mg_option *
  2778. mg_get_valid_options(void)
  2779. {
  2780. return config_options;
  2781. }
  2782. /* Do not open file (used in is_file_in_memory) */
  2783. #define MG_FOPEN_MODE_NONE (0)
  2784. /* Open file for read only access */
  2785. #define MG_FOPEN_MODE_READ (1)
  2786. /* Open file for writing, create and overwrite */
  2787. #define MG_FOPEN_MODE_WRITE (2)
  2788. /* Open file for writing, create and append */
  2789. #define MG_FOPEN_MODE_APPEND (4)
  2790. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2791. * output filep and return 1, otherwise return 0 and don't modify anything.
  2792. */
  2793. static int
  2794. open_file_in_memory(const struct mg_connection *conn,
  2795. const char *path,
  2796. struct mg_file *filep,
  2797. int mode)
  2798. {
  2799. #if defined(MG_USE_OPEN_FILE)
  2800. size_t size = 0;
  2801. const char *buf = NULL;
  2802. if (!conn) {
  2803. return 0;
  2804. }
  2805. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2806. return 0;
  2807. }
  2808. if (conn->phys_ctx->callbacks.open_file) {
  2809. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2810. if (buf != NULL) {
  2811. if (filep == NULL) {
  2812. /* This is a file in memory, but we cannot store the
  2813. * properties
  2814. * now.
  2815. * Called from "is_file_in_memory" function. */
  2816. return 1;
  2817. }
  2818. /* NOTE: override filep->size only on success. Otherwise, it
  2819. * might
  2820. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2821. filep->access.membuf = buf;
  2822. filep->access.fp = NULL;
  2823. /* Size was set by the callback */
  2824. filep->stat.size = size;
  2825. /* Assume the data may change during runtime by setting
  2826. * last_modified = now */
  2827. filep->stat.last_modified = time(NULL);
  2828. filep->stat.is_directory = 0;
  2829. filep->stat.is_gzipped = 0;
  2830. }
  2831. }
  2832. return (buf != NULL);
  2833. #else
  2834. (void)conn;
  2835. (void)path;
  2836. (void)filep;
  2837. (void)mode;
  2838. return 0;
  2839. #endif
  2840. }
  2841. static int
  2842. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2843. {
  2844. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2845. }
  2846. static int
  2847. is_file_opened(const struct mg_file_access *fileacc)
  2848. {
  2849. if (!fileacc) {
  2850. return 0;
  2851. }
  2852. #if defined(MG_USE_OPEN_FILE)
  2853. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2854. #else
  2855. return (fileacc->fp != NULL);
  2856. #endif
  2857. }
  2858. #if !defined(NO_FILESYSTEMS)
  2859. static int mg_stat(const struct mg_connection *conn,
  2860. const char *path,
  2861. struct mg_file_stat *filep);
  2862. /* mg_fopen will open a file either in memory or on the disk.
  2863. * The input parameter path is a string in UTF-8 encoding.
  2864. * The input parameter mode is MG_FOPEN_MODE_*
  2865. * On success, either fp or membuf will be set in the output
  2866. * struct file. All status members will also be set.
  2867. * The function returns 1 on success, 0 on error. */
  2868. static int
  2869. mg_fopen(const struct mg_connection *conn,
  2870. const char *path,
  2871. int mode,
  2872. struct mg_file *filep)
  2873. {
  2874. int found;
  2875. if (!filep) {
  2876. return 0;
  2877. }
  2878. filep->access.fp = NULL;
  2879. #if defined(MG_USE_OPEN_FILE)
  2880. filep->access.membuf = NULL;
  2881. #endif
  2882. if (!is_file_in_memory(conn, path)) {
  2883. /* filep is initialized in mg_stat: all fields with memset to,
  2884. * some fields like size and modification date with values */
  2885. found = mg_stat(conn, path, &(filep->stat));
  2886. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2887. /* file does not exist and will not be created */
  2888. return 0;
  2889. }
  2890. #if defined(_WIN32)
  2891. {
  2892. wchar_t wbuf[W_PATH_MAX];
  2893. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2894. switch (mode) {
  2895. case MG_FOPEN_MODE_READ:
  2896. filep->access.fp = _wfopen(wbuf, L"rb");
  2897. break;
  2898. case MG_FOPEN_MODE_WRITE:
  2899. filep->access.fp = _wfopen(wbuf, L"wb");
  2900. break;
  2901. case MG_FOPEN_MODE_APPEND:
  2902. filep->access.fp = _wfopen(wbuf, L"ab");
  2903. break;
  2904. }
  2905. }
  2906. #else
  2907. /* Linux et al already use unicode. No need to convert. */
  2908. switch (mode) {
  2909. case MG_FOPEN_MODE_READ:
  2910. filep->access.fp = fopen(path, "r");
  2911. break;
  2912. case MG_FOPEN_MODE_WRITE:
  2913. filep->access.fp = fopen(path, "w");
  2914. break;
  2915. case MG_FOPEN_MODE_APPEND:
  2916. filep->access.fp = fopen(path, "a");
  2917. break;
  2918. }
  2919. #endif
  2920. if (!found) {
  2921. /* File did not exist before fopen was called.
  2922. * Maybe it has been created now. Get stat info
  2923. * like creation time now. */
  2924. found = mg_stat(conn, path, &(filep->stat));
  2925. (void)found;
  2926. }
  2927. /* file is on disk */
  2928. return (filep->access.fp != NULL);
  2929. } else {
  2930. #if defined(MG_USE_OPEN_FILE)
  2931. /* is_file_in_memory returned true */
  2932. if (open_file_in_memory(conn, path, filep, mode)) {
  2933. /* file is in memory */
  2934. return (filep->access.membuf != NULL);
  2935. }
  2936. #endif
  2937. }
  2938. /* Open failed */
  2939. return 0;
  2940. }
  2941. /* return 0 on success, just like fclose */
  2942. static int
  2943. mg_fclose(struct mg_file_access *fileacc)
  2944. {
  2945. int ret = -1;
  2946. if (fileacc != NULL) {
  2947. if (fileacc->fp != NULL) {
  2948. ret = fclose(fileacc->fp);
  2949. #if defined(MG_USE_OPEN_FILE)
  2950. } else if (fileacc->membuf != NULL) {
  2951. ret = 0;
  2952. #endif
  2953. }
  2954. /* reset all members of fileacc */
  2955. memset(fileacc, 0, sizeof(*fileacc));
  2956. }
  2957. return ret;
  2958. }
  2959. #endif /* NO_FILESYSTEMS */
  2960. static void
  2961. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2962. {
  2963. for (; *src != '\0' && n > 1; n--) {
  2964. *dst++ = *src++;
  2965. }
  2966. *dst = '\0';
  2967. }
  2968. static int
  2969. lowercase(const char *s)
  2970. {
  2971. return tolower((unsigned char)*s);
  2972. }
  2973. int
  2974. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2975. {
  2976. int diff = 0;
  2977. if (len > 0) {
  2978. do {
  2979. diff = lowercase(s1++) - lowercase(s2++);
  2980. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2981. }
  2982. return diff;
  2983. }
  2984. int
  2985. mg_strcasecmp(const char *s1, const char *s2)
  2986. {
  2987. int diff;
  2988. do {
  2989. diff = lowercase(s1++) - lowercase(s2++);
  2990. } while (diff == 0 && s1[-1] != '\0');
  2991. return diff;
  2992. }
  2993. static char *
  2994. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2995. {
  2996. char *p;
  2997. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2998. * defined */
  2999. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3000. mg_strlcpy(p, ptr, len + 1);
  3001. }
  3002. return p;
  3003. }
  3004. static char *
  3005. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3006. {
  3007. return mg_strndup_ctx(str, strlen(str), ctx);
  3008. }
  3009. static char *
  3010. mg_strdup(const char *str)
  3011. {
  3012. return mg_strndup_ctx(str, strlen(str), NULL);
  3013. }
  3014. static const char *
  3015. mg_strcasestr(const char *big_str, const char *small_str)
  3016. {
  3017. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3018. if (big_len >= small_len) {
  3019. for (i = 0; i <= (big_len - small_len); i++) {
  3020. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3021. return big_str + i;
  3022. }
  3023. }
  3024. }
  3025. return NULL;
  3026. }
  3027. /* Return null terminated string of given maximum length.
  3028. * Report errors if length is exceeded. */
  3029. static void
  3030. mg_vsnprintf(const struct mg_connection *conn,
  3031. int *truncated,
  3032. char *buf,
  3033. size_t buflen,
  3034. const char *fmt,
  3035. va_list ap)
  3036. {
  3037. int n, ok;
  3038. if (buflen == 0) {
  3039. if (truncated) {
  3040. *truncated = 1;
  3041. }
  3042. return;
  3043. }
  3044. #if defined(__clang__)
  3045. #pragma clang diagnostic push
  3046. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3047. /* Using fmt as a non-literal is intended here, since it is mostly called
  3048. * indirectly by mg_snprintf */
  3049. #endif
  3050. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3051. ok = (n >= 0) && ((size_t)n < buflen);
  3052. #if defined(__clang__)
  3053. #pragma clang diagnostic pop
  3054. #endif
  3055. if (ok) {
  3056. if (truncated) {
  3057. *truncated = 0;
  3058. }
  3059. } else {
  3060. if (truncated) {
  3061. *truncated = 1;
  3062. }
  3063. mg_cry_internal(conn,
  3064. "truncating vsnprintf buffer: [%.*s]",
  3065. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3066. buf);
  3067. n = (int)buflen - 1;
  3068. }
  3069. buf[n] = '\0';
  3070. }
  3071. static void
  3072. mg_snprintf(const struct mg_connection *conn,
  3073. int *truncated,
  3074. char *buf,
  3075. size_t buflen,
  3076. const char *fmt,
  3077. ...)
  3078. {
  3079. va_list ap;
  3080. va_start(ap, fmt);
  3081. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3082. va_end(ap);
  3083. }
  3084. static int
  3085. get_option_index(const char *name)
  3086. {
  3087. int i;
  3088. for (i = 0; config_options[i].name != NULL; i++) {
  3089. if (strcmp(config_options[i].name, name) == 0) {
  3090. return i;
  3091. }
  3092. }
  3093. return -1;
  3094. }
  3095. const char *
  3096. mg_get_option(const struct mg_context *ctx, const char *name)
  3097. {
  3098. int i;
  3099. if ((i = get_option_index(name)) == -1) {
  3100. return NULL;
  3101. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3102. return "";
  3103. } else {
  3104. return ctx->dd.config[i];
  3105. }
  3106. }
  3107. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3108. struct mg_context *
  3109. mg_get_context(const struct mg_connection *conn)
  3110. {
  3111. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3112. }
  3113. void *
  3114. mg_get_user_data(const struct mg_context *ctx)
  3115. {
  3116. return (ctx == NULL) ? NULL : ctx->user_data;
  3117. }
  3118. void *
  3119. mg_get_user_context_data(const struct mg_connection *conn)
  3120. {
  3121. return mg_get_user_data(mg_get_context(conn));
  3122. }
  3123. void *
  3124. mg_get_thread_pointer(const struct mg_connection *conn)
  3125. {
  3126. /* both methods should return the same pointer */
  3127. if (conn) {
  3128. /* quick access, in case conn is known */
  3129. return conn->tls_user_ptr;
  3130. } else {
  3131. /* otherwise get pointer from thread local storage (TLS) */
  3132. struct mg_workerTLS *tls =
  3133. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3134. return tls->user_ptr;
  3135. }
  3136. }
  3137. void
  3138. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3139. {
  3140. if (conn != NULL) {
  3141. conn->request_info.conn_data = data;
  3142. }
  3143. }
  3144. void *
  3145. mg_get_user_connection_data(const struct mg_connection *conn)
  3146. {
  3147. if (conn != NULL) {
  3148. return conn->request_info.conn_data;
  3149. }
  3150. return NULL;
  3151. }
  3152. #if defined(MG_LEGACY_INTERFACE)
  3153. /* Deprecated: Use mg_get_server_ports instead. */
  3154. size_t
  3155. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3156. {
  3157. size_t i;
  3158. if (!ctx) {
  3159. return 0;
  3160. }
  3161. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3162. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3163. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3164. }
  3165. return i;
  3166. }
  3167. #endif
  3168. int
  3169. mg_get_server_ports(const struct mg_context *ctx,
  3170. int size,
  3171. struct mg_server_port *ports)
  3172. {
  3173. int i, cnt = 0;
  3174. if (size <= 0) {
  3175. return -1;
  3176. }
  3177. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3178. if (!ctx) {
  3179. return -1;
  3180. }
  3181. if (!ctx->listening_sockets) {
  3182. return -1;
  3183. }
  3184. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3185. ports[cnt].port =
  3186. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3187. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3188. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3189. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3190. /* IPv4 */
  3191. ports[cnt].protocol = 1;
  3192. cnt++;
  3193. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3194. /* IPv6 */
  3195. ports[cnt].protocol = 3;
  3196. cnt++;
  3197. }
  3198. }
  3199. return cnt;
  3200. }
  3201. static void
  3202. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3203. {
  3204. buf[0] = '\0';
  3205. if (!usa) {
  3206. return;
  3207. }
  3208. if (usa->sa.sa_family == AF_INET) {
  3209. getnameinfo(&usa->sa,
  3210. sizeof(usa->sin),
  3211. buf,
  3212. (unsigned)len,
  3213. NULL,
  3214. 0,
  3215. NI_NUMERICHOST);
  3216. }
  3217. #if defined(USE_IPV6)
  3218. else if (usa->sa.sa_family == AF_INET6) {
  3219. getnameinfo(&usa->sa,
  3220. sizeof(usa->sin6),
  3221. buf,
  3222. (unsigned)len,
  3223. NULL,
  3224. 0,
  3225. NI_NUMERICHOST);
  3226. }
  3227. #endif
  3228. }
  3229. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3230. * included in all responses other than 100, 101, 5xx. */
  3231. static void
  3232. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3233. {
  3234. #if !defined(REENTRANT_TIME)
  3235. struct tm *tm;
  3236. tm = ((t != NULL) ? gmtime(t) : NULL);
  3237. if (tm != NULL) {
  3238. #else
  3239. struct tm _tm;
  3240. struct tm *tm = &_tm;
  3241. if (t != NULL) {
  3242. gmtime_r(t, tm);
  3243. #endif
  3244. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3245. } else {
  3246. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3247. buf[buf_len - 1] = '\0';
  3248. }
  3249. }
  3250. /* difftime for struct timespec. Return value is in seconds. */
  3251. static double
  3252. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3253. {
  3254. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3255. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3256. }
  3257. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3258. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3259. const char *func,
  3260. unsigned line,
  3261. const char *fmt,
  3262. va_list ap);
  3263. #include "external_mg_cry_internal_impl.inl"
  3264. #elif !defined(NO_FILESYSTEMS)
  3265. /* Print error message to the opened error log stream. */
  3266. static void
  3267. 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. {
  3273. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3274. struct mg_file fi;
  3275. time_t timestamp;
  3276. /* Unused, in the RELEASE build */
  3277. (void)func;
  3278. (void)line;
  3279. #if defined(GCC_DIAGNOSTIC)
  3280. #pragma GCC diagnostic push
  3281. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3282. #endif
  3283. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3284. #if defined(GCC_DIAGNOSTIC)
  3285. #pragma GCC diagnostic pop
  3286. #endif
  3287. buf[sizeof(buf) - 1] = 0;
  3288. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3289. if (!conn) {
  3290. puts(buf);
  3291. return;
  3292. }
  3293. /* Do not lock when getting the callback value, here and below.
  3294. * I suppose this is fine, since function cannot disappear in the
  3295. * same way string option can. */
  3296. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3297. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3298. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3299. if (mg_fopen(conn,
  3300. conn->dom_ctx->config[ERROR_LOG_FILE],
  3301. MG_FOPEN_MODE_APPEND,
  3302. &fi)
  3303. == 0) {
  3304. fi.access.fp = NULL;
  3305. }
  3306. } else {
  3307. fi.access.fp = NULL;
  3308. }
  3309. if (fi.access.fp != NULL) {
  3310. flockfile(fi.access.fp);
  3311. timestamp = time(NULL);
  3312. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3313. fprintf(fi.access.fp,
  3314. "[%010lu] [error] [client %s] ",
  3315. (unsigned long)timestamp,
  3316. src_addr);
  3317. if (conn->request_info.request_method != NULL) {
  3318. fprintf(fi.access.fp,
  3319. "%s %s: ",
  3320. conn->request_info.request_method,
  3321. conn->request_info.request_uri
  3322. ? conn->request_info.request_uri
  3323. : "");
  3324. }
  3325. fprintf(fi.access.fp, "%s", buf);
  3326. fputc('\n', fi.access.fp);
  3327. fflush(fi.access.fp);
  3328. funlockfile(fi.access.fp);
  3329. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3330. * mg_cry here anyway ;-) */
  3331. }
  3332. }
  3333. }
  3334. #else
  3335. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3336. #endif /* Externally provided function */
  3337. /* Construct fake connection structure. Used for logging, if connection
  3338. * is not applicable at the moment of logging. */
  3339. static struct mg_connection *
  3340. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3341. {
  3342. static const struct mg_connection conn_zero = {0};
  3343. *fc = conn_zero;
  3344. fc->phys_ctx = ctx;
  3345. fc->dom_ctx = &(ctx->dd);
  3346. return fc;
  3347. }
  3348. static void
  3349. mg_cry_internal_wrap(const struct mg_connection *conn,
  3350. struct mg_context *ctx,
  3351. const char *func,
  3352. unsigned line,
  3353. const char *fmt,
  3354. ...)
  3355. {
  3356. va_list ap;
  3357. va_start(ap, fmt);
  3358. if (!conn && ctx) {
  3359. struct mg_connection fc;
  3360. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3361. } else {
  3362. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3363. }
  3364. va_end(ap);
  3365. }
  3366. void
  3367. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3368. {
  3369. va_list ap;
  3370. va_start(ap, fmt);
  3371. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3372. va_end(ap);
  3373. }
  3374. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3375. const char *
  3376. mg_version(void)
  3377. {
  3378. return CIVETWEB_VERSION;
  3379. }
  3380. const struct mg_request_info *
  3381. mg_get_request_info(const struct mg_connection *conn)
  3382. {
  3383. if (!conn) {
  3384. return NULL;
  3385. }
  3386. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3387. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3388. char txt[16];
  3389. struct mg_workerTLS *tls =
  3390. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3391. sprintf(txt, "%03i", conn->response_info.status_code);
  3392. if (strlen(txt) == 3) {
  3393. memcpy(tls->txtbuf, txt, 4);
  3394. } else {
  3395. strcpy(tls->txtbuf, "ERR");
  3396. }
  3397. ((struct mg_connection *)conn)->request_info.local_uri =
  3398. ((struct mg_connection *)conn)->request_info.request_uri =
  3399. tls->txtbuf; /* use thread safe buffer */
  3400. ((struct mg_connection *)conn)->request_info.num_headers =
  3401. conn->response_info.num_headers;
  3402. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3403. conn->response_info.http_headers,
  3404. sizeof(conn->response_info.http_headers));
  3405. } else
  3406. #endif
  3407. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3408. return NULL;
  3409. }
  3410. return &conn->request_info;
  3411. }
  3412. const struct mg_response_info *
  3413. mg_get_response_info(const struct mg_connection *conn)
  3414. {
  3415. if (!conn) {
  3416. return NULL;
  3417. }
  3418. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3419. return NULL;
  3420. }
  3421. return &conn->response_info;
  3422. }
  3423. static const char *
  3424. get_proto_name(const struct mg_connection *conn)
  3425. {
  3426. #if defined(__clang__)
  3427. #pragma clang diagnostic push
  3428. #pragma clang diagnostic ignored "-Wunreachable-code"
  3429. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3430. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3431. * unreachable, but splitting into four different #ifdef clauses here is more
  3432. * complicated.
  3433. */
  3434. #endif
  3435. const struct mg_request_info *ri = &conn->request_info;
  3436. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3437. ? (ri->is_ssl ? "wss" : "ws")
  3438. : (ri->is_ssl ? "https" : "http"));
  3439. return proto;
  3440. #if defined(__clang__)
  3441. #pragma clang diagnostic pop
  3442. #endif
  3443. }
  3444. int
  3445. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3446. {
  3447. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3448. return -1;
  3449. } else {
  3450. int truncated = 0;
  3451. const struct mg_request_info *ri = &conn->request_info;
  3452. const char *proto = get_proto_name(conn);
  3453. if (ri->local_uri == NULL) {
  3454. return -1;
  3455. }
  3456. if ((ri->request_uri != NULL)
  3457. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3458. /* The request uri is different from the local uri.
  3459. * This is usually if an absolute URI, including server
  3460. * name has been provided. */
  3461. mg_snprintf(conn,
  3462. &truncated,
  3463. buf,
  3464. buflen,
  3465. "%s://%s",
  3466. proto,
  3467. ri->request_uri);
  3468. if (truncated) {
  3469. return -1;
  3470. }
  3471. return 0;
  3472. } else {
  3473. /* The common case is a relative URI, so we have to
  3474. * construct an absolute URI from server name and port */
  3475. #if defined(USE_IPV6)
  3476. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3477. #endif
  3478. int port = htons(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  3479. int def_port = ri->is_ssl ? 443 : 80;
  3480. int auth_domain_check_enabled =
  3481. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3482. && (!mg_strcasecmp(
  3483. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3484. const char *server_domain =
  3485. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3486. char portstr[16];
  3487. char server_ip[48];
  3488. if (port != def_port) {
  3489. sprintf(portstr, ":%u", (unsigned)port);
  3490. } else {
  3491. portstr[0] = 0;
  3492. }
  3493. if (!auth_domain_check_enabled || !server_domain) {
  3494. sockaddr_to_string(server_ip,
  3495. sizeof(server_ip),
  3496. &conn->client.lsa);
  3497. server_domain = server_ip;
  3498. }
  3499. mg_snprintf(conn,
  3500. &truncated,
  3501. buf,
  3502. buflen,
  3503. #if defined(USE_IPV6)
  3504. "%s://%s%s%s%s%s",
  3505. proto,
  3506. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3507. server_domain,
  3508. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3509. #else
  3510. "%s://%s%s%s",
  3511. proto,
  3512. server_domain,
  3513. #endif
  3514. portstr,
  3515. ri->local_uri);
  3516. if (truncated) {
  3517. return -1;
  3518. }
  3519. return 0;
  3520. }
  3521. }
  3522. }
  3523. /* Skip the characters until one of the delimiters characters found.
  3524. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3525. * Advance pointer to buffer to the next word. Return found 0-terminated
  3526. * word.
  3527. * Delimiters can be quoted with quotechar. */
  3528. static char *
  3529. skip_quoted(char **buf,
  3530. const char *delimiters,
  3531. const char *whitespace,
  3532. char quotechar)
  3533. {
  3534. char *p, *begin_word, *end_word, *end_whitespace;
  3535. begin_word = *buf;
  3536. end_word = begin_word + strcspn(begin_word, delimiters);
  3537. /* Check for quotechar */
  3538. if (end_word > begin_word) {
  3539. p = end_word - 1;
  3540. while (*p == quotechar) {
  3541. /* While the delimiter is quoted, look for the next delimiter.
  3542. */
  3543. /* This happens, e.g., in calls from parse_auth_header,
  3544. * if the user name contains a " character. */
  3545. /* If there is anything beyond end_word, copy it. */
  3546. if (*end_word != '\0') {
  3547. size_t end_off = strcspn(end_word + 1, delimiters);
  3548. memmove(p, end_word, end_off + 1);
  3549. p += end_off; /* p must correspond to end_word - 1 */
  3550. end_word += end_off + 1;
  3551. } else {
  3552. *p = '\0';
  3553. break;
  3554. }
  3555. }
  3556. for (p++; p < end_word; p++) {
  3557. *p = '\0';
  3558. }
  3559. }
  3560. if (*end_word == '\0') {
  3561. *buf = end_word;
  3562. } else {
  3563. #if defined(GCC_DIAGNOSTIC)
  3564. /* Disable spurious conversion warning for GCC */
  3565. #pragma GCC diagnostic push
  3566. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3567. #endif /* defined(GCC_DIAGNOSTIC) */
  3568. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3569. #if defined(GCC_DIAGNOSTIC)
  3570. #pragma GCC diagnostic pop
  3571. #endif /* defined(GCC_DIAGNOSTIC) */
  3572. for (p = end_word; p < end_whitespace; p++) {
  3573. *p = '\0';
  3574. }
  3575. *buf = end_whitespace;
  3576. }
  3577. return begin_word;
  3578. }
  3579. /* Return HTTP header value, or NULL if not found. */
  3580. static const char *
  3581. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3582. {
  3583. int i;
  3584. for (i = 0; i < num_hdr; i++) {
  3585. if (!mg_strcasecmp(name, hdr[i].name)) {
  3586. return hdr[i].value;
  3587. }
  3588. }
  3589. return NULL;
  3590. }
  3591. #if defined(USE_WEBSOCKET)
  3592. /* Retrieve requested HTTP header multiple values, and return the number of
  3593. * found occurrences */
  3594. static int
  3595. get_req_headers(const struct mg_request_info *ri,
  3596. const char *name,
  3597. const char **output,
  3598. int output_max_size)
  3599. {
  3600. int i;
  3601. int cnt = 0;
  3602. if (ri) {
  3603. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3604. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3605. output[cnt++] = ri->http_headers[i].value;
  3606. }
  3607. }
  3608. }
  3609. return cnt;
  3610. }
  3611. #endif
  3612. const char *
  3613. mg_get_header(const struct mg_connection *conn, const char *name)
  3614. {
  3615. if (!conn) {
  3616. return NULL;
  3617. }
  3618. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3619. return get_header(conn->request_info.http_headers,
  3620. conn->request_info.num_headers,
  3621. name);
  3622. }
  3623. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3624. return get_header(conn->response_info.http_headers,
  3625. conn->response_info.num_headers,
  3626. name);
  3627. }
  3628. return NULL;
  3629. }
  3630. static const char *
  3631. get_http_version(const struct mg_connection *conn)
  3632. {
  3633. if (!conn) {
  3634. return NULL;
  3635. }
  3636. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3637. return conn->request_info.http_version;
  3638. }
  3639. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3640. return conn->response_info.http_version;
  3641. }
  3642. return NULL;
  3643. }
  3644. /* A helper function for traversing a comma separated list of values.
  3645. * It returns a list pointer shifted to the next value, or NULL if the end
  3646. * of the list found.
  3647. * Value is stored in val vector. If value has form "x=y", then eq_val
  3648. * vector is initialized to point to the "y" part, and val vector length
  3649. * is adjusted to point only to "x". */
  3650. static const char *
  3651. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3652. {
  3653. int end;
  3654. reparse:
  3655. if (val == NULL || list == NULL || *list == '\0') {
  3656. /* End of the list */
  3657. return NULL;
  3658. }
  3659. /* Skip over leading LWS */
  3660. while (*list == ' ' || *list == '\t')
  3661. list++;
  3662. val->ptr = list;
  3663. if ((list = strchr(val->ptr, ',')) != NULL) {
  3664. /* Comma found. Store length and shift the list ptr */
  3665. val->len = ((size_t)(list - val->ptr));
  3666. list++;
  3667. } else {
  3668. /* This value is the last one */
  3669. list = val->ptr + strlen(val->ptr);
  3670. val->len = ((size_t)(list - val->ptr));
  3671. }
  3672. /* Adjust length for trailing LWS */
  3673. end = (int)val->len - 1;
  3674. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3675. end--;
  3676. val->len = (size_t)(end) + (size_t)(1);
  3677. if (val->len == 0) {
  3678. /* Ignore any empty entries. */
  3679. goto reparse;
  3680. }
  3681. if (eq_val != NULL) {
  3682. /* Value has form "x=y", adjust pointers and lengths
  3683. * so that val points to "x", and eq_val points to "y". */
  3684. eq_val->len = 0;
  3685. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3686. if (eq_val->ptr != NULL) {
  3687. eq_val->ptr++; /* Skip over '=' character */
  3688. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3689. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3690. }
  3691. }
  3692. return list;
  3693. }
  3694. /* A helper function for checking if a comma separated list of values
  3695. * contains
  3696. * the given option (case insensitvely).
  3697. * 'header' can be NULL, in which case false is returned. */
  3698. static int
  3699. header_has_option(const char *header, const char *option)
  3700. {
  3701. struct vec opt_vec;
  3702. struct vec eq_vec;
  3703. DEBUG_ASSERT(option != NULL);
  3704. DEBUG_ASSERT(option[0] != '\0');
  3705. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3706. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3707. return 1;
  3708. }
  3709. return 0;
  3710. }
  3711. /* Perform case-insensitive match of string against pattern */
  3712. static ptrdiff_t
  3713. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3714. {
  3715. const char *or_str;
  3716. ptrdiff_t i, j, len, res;
  3717. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3718. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3719. return (res > 0) ? res
  3720. : match_prefix(or_str + 1,
  3721. (size_t)((pattern + pattern_len)
  3722. - (or_str + 1)),
  3723. str);
  3724. }
  3725. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3726. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3727. continue;
  3728. } else if (pattern[i] == '$') {
  3729. return (str[j] == '\0') ? j : -1;
  3730. } else if (pattern[i] == '*') {
  3731. i++;
  3732. if (pattern[i] == '*') {
  3733. i++;
  3734. len = (ptrdiff_t)strlen(str + j);
  3735. } else {
  3736. len = (ptrdiff_t)strcspn(str + j, "/");
  3737. }
  3738. if (i == (ptrdiff_t)pattern_len) {
  3739. return j + len;
  3740. }
  3741. do {
  3742. res = match_prefix(pattern + i,
  3743. (pattern_len - (size_t)i),
  3744. str + j + len);
  3745. } while (res == -1 && len-- > 0);
  3746. return (res == -1) ? -1 : j + res + len;
  3747. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3748. return -1;
  3749. }
  3750. }
  3751. return (ptrdiff_t)j;
  3752. }
  3753. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3754. * This function must tolerate situations when connection info is not
  3755. * set up, for example if request parsing failed. */
  3756. static int
  3757. should_keep_alive(const struct mg_connection *conn)
  3758. {
  3759. const char *http_version;
  3760. const char *header;
  3761. /* First satisfy needs of the server */
  3762. if ((conn == NULL) || conn->must_close) {
  3763. /* Close, if civetweb framework needs to close */
  3764. return 0;
  3765. }
  3766. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3767. /* Close, if keep alive is not enabled */
  3768. return 0;
  3769. }
  3770. /* Check explicit wish of the client */
  3771. header = mg_get_header(conn, "Connection");
  3772. if (header) {
  3773. /* If there is a connection header from the client, obey */
  3774. if (header_has_option(header, "keep-alive")) {
  3775. return 1;
  3776. }
  3777. return 0;
  3778. }
  3779. /* Use default of the standard */
  3780. http_version = get_http_version(conn);
  3781. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3782. /* HTTP 1.1 default is keep alive */
  3783. return 1;
  3784. }
  3785. /* HTTP 1.0 (and earlier) default is to close the connection */
  3786. return 0;
  3787. }
  3788. static int
  3789. should_decode_url(const struct mg_connection *conn)
  3790. {
  3791. if (!conn || !conn->dom_ctx) {
  3792. return 0;
  3793. }
  3794. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3795. }
  3796. static const char *
  3797. suggest_connection_header(const struct mg_connection *conn)
  3798. {
  3799. return should_keep_alive(conn) ? "keep-alive" : "close";
  3800. }
  3801. static int
  3802. send_no_cache_header(struct mg_connection *conn)
  3803. {
  3804. /* Send all current and obsolete cache opt-out directives. */
  3805. return mg_printf(conn,
  3806. "Cache-Control: no-cache, no-store, "
  3807. "must-revalidate, private, max-age=0\r\n"
  3808. "Pragma: no-cache\r\n"
  3809. "Expires: 0\r\n");
  3810. }
  3811. static int
  3812. send_static_cache_header(struct mg_connection *conn)
  3813. {
  3814. #if !defined(NO_CACHING)
  3815. int max_age;
  3816. const char *cache_control =
  3817. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3818. if (cache_control != NULL) {
  3819. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3820. }
  3821. /* Read the server config to check how long a file may be cached.
  3822. * The configuration is in seconds. */
  3823. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3824. if (max_age <= 0) {
  3825. /* 0 means "do not cache". All values <0 are reserved
  3826. * and may be used differently in the future. */
  3827. /* If a file should not be cached, do not only send
  3828. * max-age=0, but also pragmas and Expires headers. */
  3829. return send_no_cache_header(conn);
  3830. }
  3831. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3832. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3833. /* See also https://www.mnot.net/cache_docs/ */
  3834. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3835. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3836. * leap
  3837. * year to 31622400 seconds. For the moment, we just send whatever has
  3838. * been configured, still the behavior for >1 year should be considered
  3839. * as undefined. */
  3840. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3841. #else /* NO_CACHING */
  3842. return send_no_cache_header(conn);
  3843. #endif /* !NO_CACHING */
  3844. }
  3845. static int
  3846. send_additional_header(struct mg_connection *conn)
  3847. {
  3848. int i = 0;
  3849. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3850. #if !defined(NO_SSL)
  3851. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3852. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3853. if (max_age >= 0) {
  3854. i += mg_printf(conn,
  3855. "Strict-Transport-Security: max-age=%u\r\n",
  3856. (unsigned)max_age);
  3857. }
  3858. }
  3859. #endif
  3860. if (header && header[0]) {
  3861. i += mg_printf(conn, "%s\r\n", header);
  3862. }
  3863. return i;
  3864. }
  3865. #if !defined(NO_FILESYSTEMS)
  3866. static void handle_file_based_request(struct mg_connection *conn,
  3867. const char *path,
  3868. struct mg_file *filep);
  3869. #endif /* NO_FILESYSTEMS */
  3870. const char *
  3871. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3872. {
  3873. /* See IANA HTTP status code assignment:
  3874. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3875. */
  3876. switch (response_code) {
  3877. /* RFC2616 Section 10.1 - Informational 1xx */
  3878. case 100:
  3879. return "Continue"; /* RFC2616 Section 10.1.1 */
  3880. case 101:
  3881. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3882. case 102:
  3883. return "Processing"; /* RFC2518 Section 10.1 */
  3884. /* RFC2616 Section 10.2 - Successful 2xx */
  3885. case 200:
  3886. return "OK"; /* RFC2616 Section 10.2.1 */
  3887. case 201:
  3888. return "Created"; /* RFC2616 Section 10.2.2 */
  3889. case 202:
  3890. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3891. case 203:
  3892. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3893. case 204:
  3894. return "No Content"; /* RFC2616 Section 10.2.5 */
  3895. case 205:
  3896. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3897. case 206:
  3898. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3899. case 207:
  3900. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3901. */
  3902. case 208:
  3903. return "Already Reported"; /* RFC5842 Section 7.1 */
  3904. case 226:
  3905. return "IM used"; /* RFC3229 Section 10.4.1 */
  3906. /* RFC2616 Section 10.3 - Redirection 3xx */
  3907. case 300:
  3908. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3909. case 301:
  3910. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3911. case 302:
  3912. return "Found"; /* RFC2616 Section 10.3.3 */
  3913. case 303:
  3914. return "See Other"; /* RFC2616 Section 10.3.4 */
  3915. case 304:
  3916. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3917. case 305:
  3918. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3919. case 307:
  3920. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3921. case 308:
  3922. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3923. /* RFC2616 Section 10.4 - Client Error 4xx */
  3924. case 400:
  3925. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3926. case 401:
  3927. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3928. case 402:
  3929. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3930. case 403:
  3931. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3932. case 404:
  3933. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3934. case 405:
  3935. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3936. case 406:
  3937. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3938. case 407:
  3939. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3940. case 408:
  3941. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3942. case 409:
  3943. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3944. case 410:
  3945. return "Gone"; /* RFC2616 Section 10.4.11 */
  3946. case 411:
  3947. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3948. case 412:
  3949. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3950. case 413:
  3951. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3952. case 414:
  3953. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3954. case 415:
  3955. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3956. case 416:
  3957. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3958. */
  3959. case 417:
  3960. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3961. case 421:
  3962. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3963. case 422:
  3964. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3965. * Section 11.2 */
  3966. case 423:
  3967. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3968. case 424:
  3969. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3970. * Section 11.4 */
  3971. case 426:
  3972. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3973. case 428:
  3974. return "Precondition Required"; /* RFC 6585, Section 3 */
  3975. case 429:
  3976. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3977. case 431:
  3978. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3979. case 451:
  3980. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3981. * Section 3 */
  3982. /* RFC2616 Section 10.5 - Server Error 5xx */
  3983. case 500:
  3984. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3985. case 501:
  3986. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3987. case 502:
  3988. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3989. case 503:
  3990. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3991. case 504:
  3992. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3993. case 505:
  3994. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3995. case 506:
  3996. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3997. case 507:
  3998. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3999. * Section 11.5 */
  4000. case 508:
  4001. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4002. case 510:
  4003. return "Not Extended"; /* RFC 2774, Section 7 */
  4004. case 511:
  4005. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4006. /* Other status codes, not shown in the IANA HTTP status code
  4007. * assignment.
  4008. * E.g., "de facto" standards due to common use, ... */
  4009. case 418:
  4010. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4011. case 419:
  4012. return "Authentication Timeout"; /* common use */
  4013. case 420:
  4014. return "Enhance Your Calm"; /* common use */
  4015. case 440:
  4016. return "Login Timeout"; /* common use */
  4017. case 509:
  4018. return "Bandwidth Limit Exceeded"; /* common use */
  4019. default:
  4020. /* This error code is unknown. This should not happen. */
  4021. if (conn) {
  4022. mg_cry_internal(conn,
  4023. "Unknown HTTP response code: %u",
  4024. response_code);
  4025. }
  4026. /* Return at least a category according to RFC 2616 Section 10. */
  4027. if (response_code >= 100 && response_code < 200) {
  4028. /* Unknown informational status code */
  4029. return "Information";
  4030. }
  4031. if (response_code >= 200 && response_code < 300) {
  4032. /* Unknown success code */
  4033. return "Success";
  4034. }
  4035. if (response_code >= 300 && response_code < 400) {
  4036. /* Unknown redirection code */
  4037. return "Redirection";
  4038. }
  4039. if (response_code >= 400 && response_code < 500) {
  4040. /* Unknown request error code */
  4041. return "Client Error";
  4042. }
  4043. if (response_code >= 500 && response_code < 600) {
  4044. /* Unknown server error code */
  4045. return "Server Error";
  4046. }
  4047. /* Response code not even within reasonable range */
  4048. return "";
  4049. }
  4050. }
  4051. static int
  4052. mg_send_http_error_impl(struct mg_connection *conn,
  4053. int status,
  4054. const char *fmt,
  4055. va_list args)
  4056. {
  4057. char errmsg_buf[MG_BUF_LEN];
  4058. va_list ap;
  4059. int has_body;
  4060. char date[64];
  4061. time_t curtime = time(NULL);
  4062. #if !defined(NO_FILESYSTEMS)
  4063. char path_buf[PATH_MAX];
  4064. int len, i, page_handler_found, scope, truncated;
  4065. const char *error_handler = NULL;
  4066. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4067. const char *error_page_file_ext, *tstr;
  4068. #endif /* NO_FILESYSTEMS */
  4069. int handled_by_callback = 0;
  4070. const char *status_text = mg_get_response_code_text(conn, status);
  4071. if ((conn == NULL) || (fmt == NULL)) {
  4072. return -2;
  4073. }
  4074. /* Set status (for log) */
  4075. conn->status_code = status;
  4076. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4077. has_body = ((status > 199) && (status != 204) && (status != 304));
  4078. /* Prepare message in buf, if required */
  4079. if (has_body
  4080. || (!conn->in_error_handler
  4081. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4082. /* Store error message in errmsg_buf */
  4083. va_copy(ap, args);
  4084. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4085. va_end(ap);
  4086. /* In a debug build, print all html errors */
  4087. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4088. }
  4089. /* If there is a http_error callback, call it.
  4090. * But don't do it recursively, if callback calls mg_send_http_error again.
  4091. */
  4092. if (!conn->in_error_handler
  4093. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4094. /* Mark in_error_handler to avoid recursion and call user callback. */
  4095. conn->in_error_handler = 1;
  4096. handled_by_callback =
  4097. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4098. == 0);
  4099. conn->in_error_handler = 0;
  4100. }
  4101. if (!handled_by_callback) {
  4102. /* Check for recursion */
  4103. if (conn->in_error_handler) {
  4104. DEBUG_TRACE(
  4105. "Recursion when handling error %u - fall back to default",
  4106. status);
  4107. #if !defined(NO_FILESYSTEMS)
  4108. } else {
  4109. /* Send user defined error pages, if defined */
  4110. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4111. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4112. page_handler_found = 0;
  4113. if (error_handler != NULL) {
  4114. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4115. switch (scope) {
  4116. case 1: /* Handler for specific error, e.g. 404 error */
  4117. mg_snprintf(conn,
  4118. &truncated,
  4119. path_buf,
  4120. sizeof(path_buf) - 32,
  4121. "%serror%03u.",
  4122. error_handler,
  4123. status);
  4124. break;
  4125. case 2: /* Handler for error group, e.g., 5xx error
  4126. * handler
  4127. * for all server errors (500-599) */
  4128. mg_snprintf(conn,
  4129. &truncated,
  4130. path_buf,
  4131. sizeof(path_buf) - 32,
  4132. "%serror%01uxx.",
  4133. error_handler,
  4134. status / 100);
  4135. break;
  4136. default: /* Handler for all errors */
  4137. mg_snprintf(conn,
  4138. &truncated,
  4139. path_buf,
  4140. sizeof(path_buf) - 32,
  4141. "%serror.",
  4142. error_handler);
  4143. break;
  4144. }
  4145. /* String truncation in buf may only occur if
  4146. * error_handler is too long. This string is
  4147. * from the config, not from a client. */
  4148. (void)truncated;
  4149. /* The following code is redundant, but it should avoid
  4150. * false positives in static source code analyzers and
  4151. * vulnerability scanners.
  4152. */
  4153. path_buf[sizeof(path_buf) - 32] = 0;
  4154. len = (int)strlen(path_buf);
  4155. if (len > (int)sizeof(path_buf) - 32) {
  4156. len = (int)sizeof(path_buf) - 32;
  4157. }
  4158. /* Start with the file extenstion from the configuration. */
  4159. tstr = strchr(error_page_file_ext, '.');
  4160. while (tstr) {
  4161. for (i = 1;
  4162. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4163. i++) {
  4164. /* buffer overrun is not possible here, since
  4165. * (i < 32) && (len < sizeof(path_buf) - 32)
  4166. * ==> (i + len) < sizeof(path_buf) */
  4167. path_buf[len + i - 1] = tstr[i];
  4168. }
  4169. /* buffer overrun is not possible here, since
  4170. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4171. * ==> (i + len) <= sizeof(path_buf) */
  4172. path_buf[len + i - 1] = 0;
  4173. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4174. DEBUG_TRACE("Check error page %s - found",
  4175. path_buf);
  4176. page_handler_found = 1;
  4177. break;
  4178. }
  4179. DEBUG_TRACE("Check error page %s - not found",
  4180. path_buf);
  4181. /* Continue with the next file extenstion from the
  4182. * configuration (if there is a next one). */
  4183. tstr = strchr(tstr + i, '.');
  4184. }
  4185. }
  4186. }
  4187. if (page_handler_found) {
  4188. conn->in_error_handler = 1;
  4189. handle_file_based_request(conn, path_buf, &error_page_file);
  4190. conn->in_error_handler = 0;
  4191. return 0;
  4192. }
  4193. #endif /* NO_FILESYSTEMS */
  4194. }
  4195. /* No custom error page. Send default error page. */
  4196. gmt_time_string(date, sizeof(date), &curtime);
  4197. conn->must_close = 1;
  4198. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4199. send_no_cache_header(conn);
  4200. send_additional_header(conn);
  4201. if (has_body) {
  4202. mg_printf(conn,
  4203. "%s",
  4204. "Content-Type: text/plain; charset=utf-8\r\n");
  4205. }
  4206. mg_printf(conn,
  4207. "Date: %s\r\n"
  4208. "Connection: close\r\n\r\n",
  4209. date);
  4210. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4211. if (has_body) {
  4212. /* For other errors, send a generic error message. */
  4213. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4214. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4215. } else {
  4216. /* No body allowed. Close the connection. */
  4217. DEBUG_TRACE("Error %i", status);
  4218. }
  4219. }
  4220. return 0;
  4221. }
  4222. int
  4223. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4224. {
  4225. va_list ap;
  4226. int ret;
  4227. va_start(ap, fmt);
  4228. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4229. va_end(ap);
  4230. return ret;
  4231. }
  4232. int
  4233. mg_send_http_ok(struct mg_connection *conn,
  4234. const char *mime_type,
  4235. long long content_length)
  4236. {
  4237. char date[64];
  4238. time_t curtime = time(NULL);
  4239. if ((mime_type == NULL) || (*mime_type == 0)) {
  4240. /* No content type defined: default to text/html */
  4241. mime_type = "text/html";
  4242. }
  4243. gmt_time_string(date, sizeof(date), &curtime);
  4244. mg_printf(conn,
  4245. "HTTP/1.1 200 OK\r\n"
  4246. "Content-Type: %s\r\n"
  4247. "Date: %s\r\n"
  4248. "Connection: %s\r\n",
  4249. mime_type,
  4250. date,
  4251. suggest_connection_header(conn));
  4252. send_no_cache_header(conn);
  4253. send_additional_header(conn);
  4254. if (content_length < 0) {
  4255. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4256. } else {
  4257. mg_printf(conn,
  4258. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4259. (uint64_t)content_length);
  4260. }
  4261. return 0;
  4262. }
  4263. int
  4264. mg_send_http_redirect(struct mg_connection *conn,
  4265. const char *target_url,
  4266. int redirect_code)
  4267. {
  4268. /* Send a 30x redirect response.
  4269. *
  4270. * Redirect types (status codes):
  4271. *
  4272. * Status | Perm/Temp | Method | Version
  4273. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4274. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4275. * 303 | temporary | always use GET | HTTP/1.1
  4276. * 307 | temporary | always keep method | HTTP/1.1
  4277. * 308 | permanent | always keep method | HTTP/1.1
  4278. */
  4279. const char *redirect_text;
  4280. int ret;
  4281. size_t content_len = 0;
  4282. #if defined(MG_SEND_REDIRECT_BODY)
  4283. char reply[MG_BUF_LEN];
  4284. #endif
  4285. /* In case redirect_code=0, use 307. */
  4286. if (redirect_code == 0) {
  4287. redirect_code = 307;
  4288. }
  4289. /* In case redirect_code is none of the above, return error. */
  4290. if ((redirect_code != 301) && (redirect_code != 302)
  4291. && (redirect_code != 303) && (redirect_code != 307)
  4292. && (redirect_code != 308)) {
  4293. /* Parameter error */
  4294. return -2;
  4295. }
  4296. /* Get proper text for response code */
  4297. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4298. /* If target_url is not defined, redirect to "/". */
  4299. if ((target_url == NULL) || (*target_url == 0)) {
  4300. target_url = "/";
  4301. }
  4302. #if defined(MG_SEND_REDIRECT_BODY)
  4303. /* TODO: condition name? */
  4304. /* Prepare a response body with a hyperlink.
  4305. *
  4306. * According to RFC2616 (and RFC1945 before):
  4307. * Unless the request method was HEAD, the entity of the
  4308. * response SHOULD contain a short hypertext note with a hyperlink to
  4309. * the new URI(s).
  4310. *
  4311. * However, this response body is not useful in M2M communication.
  4312. * Probably the original reason in the RFC was, clients not supporting
  4313. * a 30x HTTP redirect could still show the HTML page and let the user
  4314. * press the link. Since current browsers support 30x HTTP, the additional
  4315. * HTML body does not seem to make sense anymore.
  4316. *
  4317. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4318. * but it only notes:
  4319. * The server's response payload usually contains a short
  4320. * hypertext note with a hyperlink to the new URI(s).
  4321. *
  4322. * Deactivated by default. If you need the 30x body, set the define.
  4323. */
  4324. mg_snprintf(
  4325. conn,
  4326. NULL /* ignore truncation */,
  4327. reply,
  4328. sizeof(reply),
  4329. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4330. redirect_text,
  4331. target_url,
  4332. target_url);
  4333. content_len = strlen(reply);
  4334. #endif
  4335. /* Do not send any additional header. For all other options,
  4336. * including caching, there are suitable defaults. */
  4337. ret = mg_printf(conn,
  4338. "HTTP/1.1 %i %s\r\n"
  4339. "Location: %s\r\n"
  4340. "Content-Length: %u\r\n"
  4341. "Connection: %s\r\n\r\n",
  4342. redirect_code,
  4343. redirect_text,
  4344. target_url,
  4345. (unsigned int)content_len,
  4346. suggest_connection_header(conn));
  4347. #if defined(MG_SEND_REDIRECT_BODY)
  4348. /* Send response body */
  4349. if (ret > 0) {
  4350. /* ... unless it is a HEAD request */
  4351. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4352. ret = mg_write(conn, reply, content_len);
  4353. }
  4354. }
  4355. #endif
  4356. return (ret > 0) ? ret : -1;
  4357. }
  4358. #if defined(_WIN32)
  4359. /* Create substitutes for POSIX functions in Win32. */
  4360. #if defined(GCC_DIAGNOSTIC)
  4361. /* Show no warning in case system functions are not used. */
  4362. #pragma GCC diagnostic push
  4363. #pragma GCC diagnostic ignored "-Wunused-function"
  4364. #endif
  4365. static int
  4366. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4367. {
  4368. (void)unused;
  4369. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4370. InitializeCriticalSection(&mutex->sec);
  4371. return 0;
  4372. }
  4373. static int
  4374. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4375. {
  4376. DeleteCriticalSection(&mutex->sec);
  4377. return 0;
  4378. }
  4379. static int
  4380. pthread_mutex_lock(pthread_mutex_t *mutex)
  4381. {
  4382. EnterCriticalSection(&mutex->sec);
  4383. return 0;
  4384. }
  4385. static int
  4386. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4387. {
  4388. LeaveCriticalSection(&mutex->sec);
  4389. return 0;
  4390. }
  4391. FUNCTION_MAY_BE_UNUSED
  4392. static int
  4393. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4394. {
  4395. (void)unused;
  4396. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4397. cv->waiting_thread = NULL;
  4398. return 0;
  4399. }
  4400. FUNCTION_MAY_BE_UNUSED
  4401. static int
  4402. pthread_cond_timedwait(pthread_cond_t *cv,
  4403. pthread_mutex_t *mutex,
  4404. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4405. {
  4406. struct mg_workerTLS **ptls,
  4407. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4408. int ok;
  4409. int64_t nsnow, nswaitabs, nswaitrel;
  4410. DWORD mswaitrel;
  4411. pthread_mutex_lock(&cv->threadIdSec);
  4412. /* Add this thread to cv's waiting list */
  4413. ptls = &cv->waiting_thread;
  4414. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4415. ;
  4416. tls->next_waiting_thread = NULL;
  4417. *ptls = tls;
  4418. pthread_mutex_unlock(&cv->threadIdSec);
  4419. if (abstime) {
  4420. nsnow = mg_get_current_time_ns();
  4421. nswaitabs =
  4422. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4423. nswaitrel = nswaitabs - nsnow;
  4424. if (nswaitrel < 0) {
  4425. nswaitrel = 0;
  4426. }
  4427. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4428. } else {
  4429. mswaitrel = (DWORD)INFINITE;
  4430. }
  4431. pthread_mutex_unlock(mutex);
  4432. ok = (WAIT_OBJECT_0
  4433. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4434. if (!ok) {
  4435. ok = 1;
  4436. pthread_mutex_lock(&cv->threadIdSec);
  4437. ptls = &cv->waiting_thread;
  4438. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4439. if (*ptls == tls) {
  4440. *ptls = tls->next_waiting_thread;
  4441. ok = 0;
  4442. break;
  4443. }
  4444. }
  4445. pthread_mutex_unlock(&cv->threadIdSec);
  4446. if (ok) {
  4447. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4448. (DWORD)INFINITE);
  4449. }
  4450. }
  4451. /* This thread has been removed from cv's waiting list */
  4452. pthread_mutex_lock(mutex);
  4453. return ok ? 0 : -1;
  4454. }
  4455. FUNCTION_MAY_BE_UNUSED
  4456. static int
  4457. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4458. {
  4459. return pthread_cond_timedwait(cv, mutex, NULL);
  4460. }
  4461. FUNCTION_MAY_BE_UNUSED
  4462. static int
  4463. pthread_cond_signal(pthread_cond_t *cv)
  4464. {
  4465. HANDLE wkup = NULL;
  4466. BOOL ok = FALSE;
  4467. pthread_mutex_lock(&cv->threadIdSec);
  4468. if (cv->waiting_thread) {
  4469. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4470. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4471. ok = SetEvent(wkup);
  4472. DEBUG_ASSERT(ok);
  4473. }
  4474. pthread_mutex_unlock(&cv->threadIdSec);
  4475. return ok ? 0 : 1;
  4476. }
  4477. FUNCTION_MAY_BE_UNUSED
  4478. static int
  4479. pthread_cond_broadcast(pthread_cond_t *cv)
  4480. {
  4481. pthread_mutex_lock(&cv->threadIdSec);
  4482. while (cv->waiting_thread) {
  4483. pthread_cond_signal(cv);
  4484. }
  4485. pthread_mutex_unlock(&cv->threadIdSec);
  4486. return 0;
  4487. }
  4488. FUNCTION_MAY_BE_UNUSED
  4489. static int
  4490. pthread_cond_destroy(pthread_cond_t *cv)
  4491. {
  4492. pthread_mutex_lock(&cv->threadIdSec);
  4493. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4494. pthread_mutex_unlock(&cv->threadIdSec);
  4495. pthread_mutex_destroy(&cv->threadIdSec);
  4496. return 0;
  4497. }
  4498. #if defined(ALTERNATIVE_QUEUE)
  4499. FUNCTION_MAY_BE_UNUSED
  4500. static void *
  4501. event_create(void)
  4502. {
  4503. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4504. }
  4505. FUNCTION_MAY_BE_UNUSED
  4506. static int
  4507. event_wait(void *eventhdl)
  4508. {
  4509. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4510. return (res == WAIT_OBJECT_0);
  4511. }
  4512. FUNCTION_MAY_BE_UNUSED
  4513. static int
  4514. event_signal(void *eventhdl)
  4515. {
  4516. return (int)SetEvent((HANDLE)eventhdl);
  4517. }
  4518. FUNCTION_MAY_BE_UNUSED
  4519. static void
  4520. event_destroy(void *eventhdl)
  4521. {
  4522. CloseHandle((HANDLE)eventhdl);
  4523. }
  4524. #endif
  4525. #if defined(GCC_DIAGNOSTIC)
  4526. /* Enable unused function warning again */
  4527. #pragma GCC diagnostic pop
  4528. #endif
  4529. /* For Windows, change all slashes to backslashes in path names. */
  4530. static void
  4531. change_slashes_to_backslashes(char *path)
  4532. {
  4533. int i;
  4534. for (i = 0; path[i] != '\0'; i++) {
  4535. if (path[i] == '/') {
  4536. path[i] = '\\';
  4537. }
  4538. /* remove double backslash (check i > 0 to preserve UNC paths,
  4539. * like \\server\file.txt) */
  4540. if ((i > 0) && (path[i] == '\\')) {
  4541. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4542. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4543. }
  4544. }
  4545. }
  4546. }
  4547. static int
  4548. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4549. {
  4550. int diff;
  4551. do {
  4552. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4553. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4554. s1++;
  4555. s2++;
  4556. } while ((diff == 0) && (s1[-1] != L'\0'));
  4557. return diff;
  4558. }
  4559. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4560. * wbuf and wbuf_len is a target buffer and its length. */
  4561. static void
  4562. path_to_unicode(const struct mg_connection *conn,
  4563. const char *path,
  4564. wchar_t *wbuf,
  4565. size_t wbuf_len)
  4566. {
  4567. char buf[PATH_MAX], buf2[PATH_MAX];
  4568. wchar_t wbuf2[W_PATH_MAX + 1];
  4569. DWORD long_len, err;
  4570. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4571. mg_strlcpy(buf, path, sizeof(buf));
  4572. change_slashes_to_backslashes(buf);
  4573. /* Convert to Unicode and back. If doubly-converted string does not
  4574. * match the original, something is fishy, reject. */
  4575. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4576. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4577. WideCharToMultiByte(
  4578. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4579. if (strcmp(buf, buf2) != 0) {
  4580. wbuf[0] = L'\0';
  4581. }
  4582. /* Windows file systems are not case sensitive, but you can still use
  4583. * uppercase and lowercase letters (on all modern file systems).
  4584. * The server can check if the URI uses the same upper/lowercase
  4585. * letters an the file system, effectively making Windows servers
  4586. * case sensitive (like Linux servers are). It is still not possible
  4587. * to use two files with the same name in different cases on Windows
  4588. * (like /a and /A) - this would be possible in Linux.
  4589. * As a default, Windows is not case sensitive, but the case sensitive
  4590. * file name check can be activated by an additional configuration. */
  4591. if (conn) {
  4592. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4593. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4594. "yes")) {
  4595. /* Use case sensitive compare function */
  4596. fcompare = wcscmp;
  4597. }
  4598. }
  4599. (void)conn; /* conn is currently unused */
  4600. #if !defined(_WIN32_WCE)
  4601. /* Only accept a full file path, not a Windows short (8.3) path. */
  4602. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4603. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4604. if (long_len == 0) {
  4605. err = GetLastError();
  4606. if (err == ERROR_FILE_NOT_FOUND) {
  4607. /* File does not exist. This is not always a problem here. */
  4608. return;
  4609. }
  4610. }
  4611. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4612. /* Short name is used. */
  4613. wbuf[0] = L'\0';
  4614. }
  4615. #else
  4616. (void)long_len;
  4617. (void)wbuf2;
  4618. (void)err;
  4619. if (strchr(path, '~')) {
  4620. wbuf[0] = L'\0';
  4621. }
  4622. #endif
  4623. }
  4624. #if !defined(NO_FILESYSTEMS)
  4625. static int
  4626. mg_stat(const struct mg_connection *conn,
  4627. const char *path,
  4628. struct mg_file_stat *filep)
  4629. {
  4630. wchar_t wbuf[W_PATH_MAX];
  4631. WIN32_FILE_ATTRIBUTE_DATA info;
  4632. time_t creation_time;
  4633. size_t len;
  4634. if (!filep) {
  4635. return 0;
  4636. }
  4637. memset(filep, 0, sizeof(*filep));
  4638. if (conn && is_file_in_memory(conn, path)) {
  4639. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4640. * memset */
  4641. /* Quick fix (for 1.9.x): */
  4642. /* mg_stat must fill all fields, also for files in memory */
  4643. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4644. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4645. filep->size = tmp_file.stat.size;
  4646. filep->location = 2;
  4647. /* TODO: for 1.10: restructure how files in memory are handled */
  4648. /* The "file in memory" feature is a candidate for deletion.
  4649. * Please join the discussion at
  4650. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4651. */
  4652. filep->last_modified = time(NULL); /* TODO */
  4653. /* last_modified = now ... assumes the file may change during
  4654. * runtime,
  4655. * so every mg_fopen call may return different data */
  4656. /* last_modified = conn->phys_ctx.start_time;
  4657. * May be used it the data does not change during runtime. This
  4658. * allows
  4659. * browser caching. Since we do not know, we have to assume the file
  4660. * in memory may change. */
  4661. return 1;
  4662. }
  4663. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4664. /* Windows happily opens files with some garbage at the end of file name.
  4665. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4666. * "a.cgi", despite one would expect an error back. */
  4667. len = strlen(path);
  4668. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4669. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4670. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4671. filep->last_modified =
  4672. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4673. info.ftLastWriteTime.dwHighDateTime);
  4674. /* On Windows, the file creation time can be higher than the
  4675. * modification time, e.g. when a file is copied.
  4676. * Since the Last-Modified timestamp is used for caching
  4677. * it should be based on the most recent timestamp. */
  4678. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4679. info.ftCreationTime.dwHighDateTime);
  4680. if (creation_time > filep->last_modified) {
  4681. filep->last_modified = creation_time;
  4682. }
  4683. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4684. return 1;
  4685. }
  4686. return 0;
  4687. }
  4688. #endif
  4689. static int
  4690. mg_remove(const struct mg_connection *conn, const char *path)
  4691. {
  4692. wchar_t wbuf[W_PATH_MAX];
  4693. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4694. return DeleteFileW(wbuf) ? 0 : -1;
  4695. }
  4696. static int
  4697. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4698. {
  4699. wchar_t wbuf[W_PATH_MAX];
  4700. (void)mode;
  4701. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4702. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4703. }
  4704. /* Create substitutes for POSIX functions in Win32. */
  4705. #if defined(GCC_DIAGNOSTIC)
  4706. /* Show no warning in case system functions are not used. */
  4707. #pragma GCC diagnostic push
  4708. #pragma GCC diagnostic ignored "-Wunused-function"
  4709. #endif
  4710. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4711. FUNCTION_MAY_BE_UNUSED
  4712. static DIR *
  4713. mg_opendir(const struct mg_connection *conn, const char *name)
  4714. {
  4715. DIR *dir = NULL;
  4716. wchar_t wpath[W_PATH_MAX];
  4717. DWORD attrs;
  4718. if (name == NULL) {
  4719. SetLastError(ERROR_BAD_ARGUMENTS);
  4720. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4721. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4722. } else {
  4723. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4724. attrs = GetFileAttributesW(wpath);
  4725. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4726. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4727. (void)wcscat(wpath, L"\\*");
  4728. dir->handle = FindFirstFileW(wpath, &dir->info);
  4729. dir->result.d_name[0] = '\0';
  4730. } else {
  4731. mg_free(dir);
  4732. dir = NULL;
  4733. }
  4734. }
  4735. return dir;
  4736. }
  4737. FUNCTION_MAY_BE_UNUSED
  4738. static int
  4739. mg_closedir(DIR *dir)
  4740. {
  4741. int result = 0;
  4742. if (dir != NULL) {
  4743. if (dir->handle != INVALID_HANDLE_VALUE)
  4744. result = FindClose(dir->handle) ? 0 : -1;
  4745. mg_free(dir);
  4746. } else {
  4747. result = -1;
  4748. SetLastError(ERROR_BAD_ARGUMENTS);
  4749. }
  4750. return result;
  4751. }
  4752. FUNCTION_MAY_BE_UNUSED
  4753. static struct dirent *
  4754. mg_readdir(DIR *dir)
  4755. {
  4756. struct dirent *result = 0;
  4757. if (dir) {
  4758. if (dir->handle != INVALID_HANDLE_VALUE) {
  4759. result = &dir->result;
  4760. (void)WideCharToMultiByte(CP_UTF8,
  4761. 0,
  4762. dir->info.cFileName,
  4763. -1,
  4764. result->d_name,
  4765. sizeof(result->d_name),
  4766. NULL,
  4767. NULL);
  4768. if (!FindNextFileW(dir->handle, &dir->info)) {
  4769. (void)FindClose(dir->handle);
  4770. dir->handle = INVALID_HANDLE_VALUE;
  4771. }
  4772. } else {
  4773. SetLastError(ERROR_FILE_NOT_FOUND);
  4774. }
  4775. } else {
  4776. SetLastError(ERROR_BAD_ARGUMENTS);
  4777. }
  4778. return result;
  4779. }
  4780. #if !defined(HAVE_POLL)
  4781. #undef POLLIN
  4782. #undef POLLPRI
  4783. #undef POLLOUT
  4784. #define POLLIN (1) /* Data ready - read will not block. */
  4785. #define POLLPRI (2) /* Priority data ready. */
  4786. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4787. FUNCTION_MAY_BE_UNUSED
  4788. static int
  4789. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4790. {
  4791. struct timeval tv;
  4792. fd_set rset;
  4793. fd_set wset;
  4794. unsigned int i;
  4795. int result;
  4796. SOCKET maxfd = 0;
  4797. memset(&tv, 0, sizeof(tv));
  4798. tv.tv_sec = milliseconds / 1000;
  4799. tv.tv_usec = (milliseconds % 1000) * 1000;
  4800. FD_ZERO(&rset);
  4801. FD_ZERO(&wset);
  4802. for (i = 0; i < n; i++) {
  4803. if (pfd[i].events & POLLIN) {
  4804. FD_SET(pfd[i].fd, &rset);
  4805. }
  4806. if (pfd[i].events & POLLOUT) {
  4807. FD_SET(pfd[i].fd, &wset);
  4808. }
  4809. pfd[i].revents = 0;
  4810. if (pfd[i].fd > maxfd) {
  4811. maxfd = pfd[i].fd;
  4812. }
  4813. }
  4814. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4815. for (i = 0; i < n; i++) {
  4816. if (FD_ISSET(pfd[i].fd, &rset)) {
  4817. pfd[i].revents |= POLLIN;
  4818. }
  4819. if (FD_ISSET(pfd[i].fd, &wset)) {
  4820. pfd[i].revents |= POLLOUT;
  4821. }
  4822. }
  4823. }
  4824. /* We should subtract the time used in select from remaining
  4825. * "milliseconds", in particular if called from mg_poll with a
  4826. * timeout quantum.
  4827. * Unfortunately, the remaining time is not stored in "tv" in all
  4828. * implementations, so the result in "tv" must be considered undefined.
  4829. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4830. return result;
  4831. }
  4832. #endif /* HAVE_POLL */
  4833. #if defined(GCC_DIAGNOSTIC)
  4834. /* Enable unused function warning again */
  4835. #pragma GCC diagnostic pop
  4836. #endif
  4837. static void
  4838. set_close_on_exec(SOCKET sock,
  4839. const struct mg_connection *conn /* may be null */,
  4840. struct mg_context *ctx /* may be null */)
  4841. {
  4842. (void)conn; /* Unused. */
  4843. (void)ctx;
  4844. #if defined(_WIN32_WCE)
  4845. (void)sock;
  4846. #else
  4847. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4848. #endif
  4849. }
  4850. int
  4851. mg_start_thread(mg_thread_func_t f, void *p)
  4852. {
  4853. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4854. /* Compile-time option to control stack size, e.g.
  4855. * -DUSE_STACK_SIZE=16384
  4856. */
  4857. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4858. == ((uintptr_t)(-1L)))
  4859. ? -1
  4860. : 0);
  4861. #else
  4862. return (
  4863. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4864. ? -1
  4865. : 0);
  4866. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4867. }
  4868. /* Start a thread storing the thread context. */
  4869. static int
  4870. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4871. void *p,
  4872. pthread_t *threadidptr)
  4873. {
  4874. uintptr_t uip;
  4875. HANDLE threadhandle;
  4876. int result = -1;
  4877. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4878. threadhandle = (HANDLE)uip;
  4879. if ((uip != 0) && (threadidptr != NULL)) {
  4880. *threadidptr = threadhandle;
  4881. result = 0;
  4882. }
  4883. return result;
  4884. }
  4885. /* Wait for a thread to finish. */
  4886. static int
  4887. mg_join_thread(pthread_t threadid)
  4888. {
  4889. int result;
  4890. DWORD dwevent;
  4891. result = -1;
  4892. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4893. if (dwevent == WAIT_FAILED) {
  4894. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4895. } else {
  4896. if (dwevent == WAIT_OBJECT_0) {
  4897. CloseHandle(threadid);
  4898. result = 0;
  4899. }
  4900. }
  4901. return result;
  4902. }
  4903. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4904. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4905. /* Create substitutes for POSIX functions in Win32. */
  4906. #if defined(GCC_DIAGNOSTIC)
  4907. /* Show no warning in case system functions are not used. */
  4908. #pragma GCC diagnostic push
  4909. #pragma GCC diagnostic ignored "-Wunused-function"
  4910. #endif
  4911. FUNCTION_MAY_BE_UNUSED
  4912. static HANDLE
  4913. dlopen(const char *dll_name, int flags)
  4914. {
  4915. wchar_t wbuf[W_PATH_MAX];
  4916. (void)flags;
  4917. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4918. return LoadLibraryW(wbuf);
  4919. }
  4920. FUNCTION_MAY_BE_UNUSED
  4921. static int
  4922. dlclose(void *handle)
  4923. {
  4924. int result;
  4925. if (FreeLibrary((HMODULE)handle) != 0) {
  4926. result = 0;
  4927. } else {
  4928. result = -1;
  4929. }
  4930. return result;
  4931. }
  4932. #if defined(GCC_DIAGNOSTIC)
  4933. /* Enable unused function warning again */
  4934. #pragma GCC diagnostic pop
  4935. #endif
  4936. #endif
  4937. #if !defined(NO_CGI)
  4938. #define SIGKILL (0)
  4939. static int
  4940. kill(pid_t pid, int sig_num)
  4941. {
  4942. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4943. (void)CloseHandle((HANDLE)pid);
  4944. return 0;
  4945. }
  4946. #if !defined(WNOHANG)
  4947. #define WNOHANG (1)
  4948. #endif
  4949. static pid_t
  4950. waitpid(pid_t pid, int *status, int flags)
  4951. {
  4952. DWORD timeout = INFINITE;
  4953. DWORD waitres;
  4954. (void)status; /* Currently not used by any client here */
  4955. if ((flags | WNOHANG) == WNOHANG) {
  4956. timeout = 0;
  4957. }
  4958. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4959. if (waitres == WAIT_OBJECT_0) {
  4960. return pid;
  4961. }
  4962. if (waitres == WAIT_TIMEOUT) {
  4963. return 0;
  4964. }
  4965. return (pid_t)-1;
  4966. }
  4967. static void
  4968. trim_trailing_whitespaces(char *s)
  4969. {
  4970. char *e = s + strlen(s);
  4971. while ((e > s) && isspace((unsigned char)e[-1])) {
  4972. *(--e) = '\0';
  4973. }
  4974. }
  4975. static pid_t
  4976. spawn_process(struct mg_connection *conn,
  4977. const char *prog,
  4978. char *envblk,
  4979. char *envp[],
  4980. int fdin[2],
  4981. int fdout[2],
  4982. int fderr[2],
  4983. const char *dir)
  4984. {
  4985. HANDLE me;
  4986. char *p, *interp;
  4987. char *interp_arg = 0;
  4988. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4989. buf[PATH_MAX];
  4990. int truncated;
  4991. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4992. STARTUPINFOA si;
  4993. PROCESS_INFORMATION pi = {0};
  4994. (void)envp;
  4995. memset(&si, 0, sizeof(si));
  4996. si.cb = sizeof(si);
  4997. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4998. si.wShowWindow = SW_HIDE;
  4999. me = GetCurrentProcess();
  5000. DuplicateHandle(me,
  5001. (HANDLE)_get_osfhandle(fdin[0]),
  5002. me,
  5003. &si.hStdInput,
  5004. 0,
  5005. TRUE,
  5006. DUPLICATE_SAME_ACCESS);
  5007. DuplicateHandle(me,
  5008. (HANDLE)_get_osfhandle(fdout[1]),
  5009. me,
  5010. &si.hStdOutput,
  5011. 0,
  5012. TRUE,
  5013. DUPLICATE_SAME_ACCESS);
  5014. DuplicateHandle(me,
  5015. (HANDLE)_get_osfhandle(fderr[1]),
  5016. me,
  5017. &si.hStdError,
  5018. 0,
  5019. TRUE,
  5020. DUPLICATE_SAME_ACCESS);
  5021. /* Mark handles that should not be inherited. See
  5022. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5023. */
  5024. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5025. HANDLE_FLAG_INHERIT,
  5026. 0);
  5027. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5028. HANDLE_FLAG_INHERIT,
  5029. 0);
  5030. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5031. HANDLE_FLAG_INHERIT,
  5032. 0);
  5033. /* First check, if there is a CGI interpreter configured for all CGI
  5034. * scripts. */
  5035. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5036. if (interp != NULL) {
  5037. /* If there is a configured interpreter, check for additional arguments
  5038. */
  5039. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5040. } else {
  5041. /* Otherwise, the interpreter must be stated in the first line of the
  5042. * CGI script file, after a #! (shebang) mark. */
  5043. buf[0] = buf[1] = '\0';
  5044. /* Get the full script path */
  5045. mg_snprintf(
  5046. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5047. if (truncated) {
  5048. pi.hProcess = (pid_t)-1;
  5049. goto spawn_cleanup;
  5050. }
  5051. /* Open the script file, to read the first line */
  5052. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5053. #if defined(MG_USE_OPEN_FILE)
  5054. p = (char *)file.access.membuf;
  5055. #else
  5056. p = (char *)NULL;
  5057. #endif
  5058. /* Read the first line of the script into the buffer */
  5059. mg_fgets(buf, sizeof(buf), &file, &p);
  5060. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5061. buf[sizeof(buf) - 1] = '\0';
  5062. }
  5063. if ((buf[0] == '#') && (buf[1] == '!')) {
  5064. trim_trailing_whitespaces(buf + 2);
  5065. } else {
  5066. buf[2] = '\0';
  5067. }
  5068. interp = buf + 2;
  5069. }
  5070. if (interp[0] != '\0') {
  5071. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5072. interp = full_interp;
  5073. }
  5074. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5075. if (interp[0] != '\0') {
  5076. /* This is an interpreted script file. We must call the interpreter. */
  5077. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5078. mg_snprintf(conn,
  5079. &truncated,
  5080. cmdline,
  5081. sizeof(cmdline),
  5082. "\"%s\" %s \"%s\\%s\"",
  5083. interp,
  5084. interp_arg,
  5085. full_dir,
  5086. prog);
  5087. } else {
  5088. mg_snprintf(conn,
  5089. &truncated,
  5090. cmdline,
  5091. sizeof(cmdline),
  5092. "\"%s\" \"%s\\%s\"",
  5093. interp,
  5094. full_dir,
  5095. prog);
  5096. }
  5097. } else {
  5098. /* This is (probably) a compiled program. We call it directly. */
  5099. mg_snprintf(conn,
  5100. &truncated,
  5101. cmdline,
  5102. sizeof(cmdline),
  5103. "\"%s\\%s\"",
  5104. full_dir,
  5105. prog);
  5106. }
  5107. if (truncated) {
  5108. pi.hProcess = (pid_t)-1;
  5109. goto spawn_cleanup;
  5110. }
  5111. DEBUG_TRACE("Running [%s]", cmdline);
  5112. if (CreateProcessA(NULL,
  5113. cmdline,
  5114. NULL,
  5115. NULL,
  5116. TRUE,
  5117. CREATE_NEW_PROCESS_GROUP,
  5118. envblk,
  5119. NULL,
  5120. &si,
  5121. &pi)
  5122. == 0) {
  5123. mg_cry_internal(
  5124. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5125. pi.hProcess = (pid_t)-1;
  5126. /* goto spawn_cleanup; */
  5127. }
  5128. spawn_cleanup:
  5129. (void)CloseHandle(si.hStdOutput);
  5130. (void)CloseHandle(si.hStdError);
  5131. (void)CloseHandle(si.hStdInput);
  5132. if (pi.hThread != NULL) {
  5133. (void)CloseHandle(pi.hThread);
  5134. }
  5135. return (pid_t)pi.hProcess;
  5136. }
  5137. #endif /* !NO_CGI */
  5138. static int
  5139. set_blocking_mode(SOCKET sock)
  5140. {
  5141. unsigned long non_blocking = 0;
  5142. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5143. }
  5144. static int
  5145. set_non_blocking_mode(SOCKET sock)
  5146. {
  5147. unsigned long non_blocking = 1;
  5148. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5149. }
  5150. #else
  5151. #if !defined(NO_FILESYSTEMS)
  5152. static int
  5153. mg_stat(const struct mg_connection *conn,
  5154. const char *path,
  5155. struct mg_file_stat *filep)
  5156. {
  5157. struct stat st;
  5158. if (!filep) {
  5159. return 0;
  5160. }
  5161. memset(filep, 0, sizeof(*filep));
  5162. if (conn && is_file_in_memory(conn, path)) {
  5163. /* Quick fix (for 1.9.x): */
  5164. /* mg_stat must fill all fields, also for files in memory */
  5165. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5166. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5167. filep->size = tmp_file.stat.size;
  5168. filep->last_modified = time(NULL);
  5169. filep->location = 2;
  5170. /* TODO: remove legacy "files in memory" feature */
  5171. return 1;
  5172. }
  5173. if (0 == stat(path, &st)) {
  5174. filep->size = (uint64_t)(st.st_size);
  5175. filep->last_modified = st.st_mtime;
  5176. filep->is_directory = S_ISDIR(st.st_mode);
  5177. return 1;
  5178. }
  5179. return 0;
  5180. }
  5181. #endif /* NO_FILESYSTEMS */
  5182. static void
  5183. set_close_on_exec(int fd,
  5184. const struct mg_connection *conn /* may be null */,
  5185. struct mg_context *ctx /* may be null */)
  5186. {
  5187. #if defined(__ZEPHYR__)
  5188. (void)fd;
  5189. (void)conn;
  5190. (void)ctx;
  5191. #else
  5192. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5193. if (conn || ctx) {
  5194. struct mg_connection fc;
  5195. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5196. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5197. __func__,
  5198. strerror(ERRNO));
  5199. }
  5200. }
  5201. #endif
  5202. }
  5203. int
  5204. mg_start_thread(mg_thread_func_t func, void *param)
  5205. {
  5206. pthread_t thread_id;
  5207. pthread_attr_t attr;
  5208. int result;
  5209. (void)pthread_attr_init(&attr);
  5210. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5211. #if defined(__ZEPHYR__)
  5212. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5213. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5214. /* Compile-time option to control stack size,
  5215. * e.g. -DUSE_STACK_SIZE=16384 */
  5216. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5217. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5218. result = pthread_create(&thread_id, &attr, func, param);
  5219. pthread_attr_destroy(&attr);
  5220. return result;
  5221. }
  5222. /* Start a thread storing the thread context. */
  5223. static int
  5224. mg_start_thread_with_id(mg_thread_func_t func,
  5225. void *param,
  5226. pthread_t *threadidptr)
  5227. {
  5228. pthread_t thread_id;
  5229. pthread_attr_t attr;
  5230. int result;
  5231. (void)pthread_attr_init(&attr);
  5232. #if defined(__ZEPHYR__)
  5233. pthread_attr_setstack(&attr,
  5234. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5235. ZEPHYR_STACK_SIZE);
  5236. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5237. /* Compile-time option to control stack size,
  5238. * e.g. -DUSE_STACK_SIZE=16384 */
  5239. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5240. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5241. result = pthread_create(&thread_id, &attr, func, param);
  5242. pthread_attr_destroy(&attr);
  5243. if ((result == 0) && (threadidptr != NULL)) {
  5244. *threadidptr = thread_id;
  5245. }
  5246. return result;
  5247. }
  5248. /* Wait for a thread to finish. */
  5249. static int
  5250. mg_join_thread(pthread_t threadid)
  5251. {
  5252. int result;
  5253. result = pthread_join(threadid, NULL);
  5254. return result;
  5255. }
  5256. #if !defined(NO_CGI)
  5257. static pid_t
  5258. spawn_process(struct mg_connection *conn,
  5259. const char *prog,
  5260. char *envblk,
  5261. char *envp[],
  5262. int fdin[2],
  5263. int fdout[2],
  5264. int fderr[2],
  5265. const char *dir)
  5266. {
  5267. pid_t pid;
  5268. const char *interp;
  5269. (void)envblk;
  5270. if ((pid = fork()) == -1) {
  5271. /* Parent */
  5272. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5273. } else if (pid != 0) {
  5274. /* Make sure children close parent-side descriptors.
  5275. * The caller will close the child-side immediately. */
  5276. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5277. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5278. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5279. } else {
  5280. /* Child */
  5281. if (chdir(dir) != 0) {
  5282. mg_cry_internal(
  5283. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5284. } else if (dup2(fdin[0], 0) == -1) {
  5285. mg_cry_internal(conn,
  5286. "%s: dup2(%d, 0): %s",
  5287. __func__,
  5288. fdin[0],
  5289. strerror(ERRNO));
  5290. } else if (dup2(fdout[1], 1) == -1) {
  5291. mg_cry_internal(conn,
  5292. "%s: dup2(%d, 1): %s",
  5293. __func__,
  5294. fdout[1],
  5295. strerror(ERRNO));
  5296. } else if (dup2(fderr[1], 2) == -1) {
  5297. mg_cry_internal(conn,
  5298. "%s: dup2(%d, 2): %s",
  5299. __func__,
  5300. fderr[1],
  5301. strerror(ERRNO));
  5302. } else {
  5303. struct sigaction sa;
  5304. /* Keep stderr and stdout in two different pipes.
  5305. * Stdout will be sent back to the client,
  5306. * stderr should go into a server error log. */
  5307. (void)close(fdin[0]);
  5308. (void)close(fdout[1]);
  5309. (void)close(fderr[1]);
  5310. /* Close write end fdin and read end fdout and fderr */
  5311. (void)close(fdin[1]);
  5312. (void)close(fdout[0]);
  5313. (void)close(fderr[0]);
  5314. /* After exec, all signal handlers are restored to their default
  5315. * values, with one exception of SIGCHLD. According to
  5316. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5317. * will leave unchanged after exec if it was set to be ignored.
  5318. * Restore it to default action. */
  5319. memset(&sa, 0, sizeof(sa));
  5320. sa.sa_handler = SIG_DFL;
  5321. sigaction(SIGCHLD, &sa, NULL);
  5322. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5323. if (interp == NULL) {
  5324. /* no interpreter configured, call the programm directly */
  5325. (void)execle(prog, prog, NULL, envp);
  5326. mg_cry_internal(conn,
  5327. "%s: execle(%s): %s",
  5328. __func__,
  5329. prog,
  5330. strerror(ERRNO));
  5331. } else {
  5332. /* call the configured interpreter */
  5333. const char *interp_args =
  5334. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5335. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5336. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5337. } else {
  5338. (void)execle(interp, interp, prog, NULL, envp);
  5339. }
  5340. mg_cry_internal(conn,
  5341. "%s: execle(%s %s): %s",
  5342. __func__,
  5343. interp,
  5344. prog,
  5345. strerror(ERRNO));
  5346. }
  5347. }
  5348. exit(EXIT_FAILURE);
  5349. }
  5350. return pid;
  5351. }
  5352. #endif /* !NO_CGI */
  5353. static int
  5354. set_non_blocking_mode(SOCKET sock)
  5355. {
  5356. int flags = fcntl(sock, F_GETFL, 0);
  5357. if (flags < 0) {
  5358. return -1;
  5359. }
  5360. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5361. return -1;
  5362. }
  5363. return 0;
  5364. }
  5365. static int
  5366. set_blocking_mode(SOCKET sock)
  5367. {
  5368. int flags = fcntl(sock, F_GETFL, 0);
  5369. if (flags < 0) {
  5370. return -1;
  5371. }
  5372. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5373. return -1;
  5374. }
  5375. return 0;
  5376. }
  5377. #endif /* _WIN32 / else */
  5378. /* End of initial operating system specific define block. */
  5379. /* Get a random number (independent of C rand function) */
  5380. static uint64_t
  5381. get_random(void)
  5382. {
  5383. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5384. static uint64_t lcg = 0; /* Linear congruential generator */
  5385. uint64_t now = mg_get_current_time_ns();
  5386. if (lfsr == 0) {
  5387. /* lfsr will be only 0 if has not been initialized,
  5388. * so this code is called only once. */
  5389. lfsr = mg_get_current_time_ns();
  5390. lcg = mg_get_current_time_ns();
  5391. } else {
  5392. /* Get the next step of both random number generators. */
  5393. lfsr = (lfsr >> 1)
  5394. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5395. << 63);
  5396. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5397. }
  5398. /* Combining two pseudo-random number generators and a high resolution
  5399. * part
  5400. * of the current server time will make it hard (impossible?) to guess
  5401. * the
  5402. * next number. */
  5403. return (lfsr ^ lcg ^ now);
  5404. }
  5405. static int
  5406. mg_poll(struct mg_pollfd *pfd,
  5407. unsigned int n,
  5408. int milliseconds,
  5409. stop_flag_t *stop_flag)
  5410. {
  5411. /* Call poll, but only for a maximum time of a few seconds.
  5412. * This will allow to stop the server after some seconds, instead
  5413. * of having to wait for a long socket timeout. */
  5414. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5415. do {
  5416. int result;
  5417. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5418. /* Shut down signal */
  5419. return -2;
  5420. }
  5421. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5422. ms_now = milliseconds;
  5423. }
  5424. result = poll(pfd, n, ms_now);
  5425. if (result != 0) {
  5426. /* Poll returned either success (1) or error (-1).
  5427. * Forward both to the caller. */
  5428. return result;
  5429. }
  5430. /* Poll returned timeout (0). */
  5431. if (milliseconds > 0) {
  5432. milliseconds -= ms_now;
  5433. }
  5434. } while (milliseconds != 0);
  5435. /* timeout: return 0 */
  5436. return 0;
  5437. }
  5438. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5439. * descriptor.
  5440. * Return value:
  5441. * >=0 .. number of bytes successfully written
  5442. * -1 .. timeout
  5443. * -2 .. error
  5444. */
  5445. static int
  5446. push_inner(struct mg_context *ctx,
  5447. FILE *fp,
  5448. SOCKET sock,
  5449. SSL *ssl,
  5450. const char *buf,
  5451. int len,
  5452. double timeout)
  5453. {
  5454. uint64_t start = 0, now = 0, timeout_ns = 0;
  5455. int n, err;
  5456. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5457. #if defined(_WIN32)
  5458. typedef int len_t;
  5459. #else
  5460. typedef size_t len_t;
  5461. #endif
  5462. if (timeout > 0) {
  5463. now = mg_get_current_time_ns();
  5464. start = now;
  5465. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5466. }
  5467. if (ctx == NULL) {
  5468. return -2;
  5469. }
  5470. #if defined(NO_SSL)
  5471. if (ssl) {
  5472. return -2;
  5473. }
  5474. #endif
  5475. /* Try to read until it succeeds, fails, times out, or the server
  5476. * shuts down. */
  5477. for (;;) {
  5478. #if !defined(NO_SSL)
  5479. if (ssl != NULL) {
  5480. ERR_clear_error();
  5481. n = SSL_write(ssl, buf, len);
  5482. if (n <= 0) {
  5483. err = SSL_get_error(ssl, n);
  5484. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5485. err = ERRNO;
  5486. } else if ((err == SSL_ERROR_WANT_READ)
  5487. || (err == SSL_ERROR_WANT_WRITE)) {
  5488. n = 0;
  5489. } else {
  5490. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5491. ERR_clear_error();
  5492. return -2;
  5493. }
  5494. ERR_clear_error();
  5495. } else {
  5496. err = 0;
  5497. }
  5498. } else
  5499. #endif
  5500. if (fp != NULL) {
  5501. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5502. if (ferror(fp)) {
  5503. n = -1;
  5504. err = ERRNO;
  5505. } else {
  5506. err = 0;
  5507. }
  5508. } else {
  5509. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5510. err = (n < 0) ? ERRNO : 0;
  5511. #if defined(_WIN32)
  5512. if (err == WSAEWOULDBLOCK) {
  5513. err = 0;
  5514. n = 0;
  5515. }
  5516. #else
  5517. if (err == EWOULDBLOCK) {
  5518. err = 0;
  5519. n = 0;
  5520. }
  5521. #endif
  5522. if (n < 0) {
  5523. /* shutdown of the socket at client side */
  5524. return -2;
  5525. }
  5526. }
  5527. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5528. return -2;
  5529. }
  5530. if ((n > 0) || ((n == 0) && (len == 0))) {
  5531. /* some data has been read, or no data was requested */
  5532. return n;
  5533. }
  5534. if (n < 0) {
  5535. /* socket error - check errno */
  5536. DEBUG_TRACE("send() failed, error %d", err);
  5537. /* TODO (mid): error handling depending on the error code.
  5538. * These codes are different between Windows and Linux.
  5539. * Currently there is no problem with failing send calls,
  5540. * if there is a reproducible situation, it should be
  5541. * investigated in detail.
  5542. */
  5543. return -2;
  5544. }
  5545. /* Only in case n=0 (timeout), repeat calling the write function */
  5546. /* If send failed, wait before retry */
  5547. if (fp != NULL) {
  5548. /* For files, just wait a fixed time.
  5549. * Maybe it helps, maybe not. */
  5550. mg_sleep(5);
  5551. } else {
  5552. /* For sockets, wait for the socket using poll */
  5553. struct mg_pollfd pfd[1];
  5554. int pollres;
  5555. pfd[0].fd = sock;
  5556. pfd[0].events = POLLOUT;
  5557. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5558. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5559. return -2;
  5560. }
  5561. if (pollres > 0) {
  5562. continue;
  5563. }
  5564. }
  5565. if (timeout > 0) {
  5566. now = mg_get_current_time_ns();
  5567. if ((now - start) > timeout_ns) {
  5568. /* Timeout */
  5569. break;
  5570. }
  5571. }
  5572. }
  5573. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5574. used */
  5575. return -1;
  5576. }
  5577. static int
  5578. push_all(struct mg_context *ctx,
  5579. FILE *fp,
  5580. SOCKET sock,
  5581. SSL *ssl,
  5582. const char *buf,
  5583. int len)
  5584. {
  5585. double timeout = -1.0;
  5586. int n, nwritten = 0;
  5587. if (ctx == NULL) {
  5588. return -1;
  5589. }
  5590. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5591. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5592. }
  5593. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5594. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5595. if (n < 0) {
  5596. if (nwritten == 0) {
  5597. nwritten = -1; /* Propagate the error */
  5598. }
  5599. break;
  5600. } else if (n == 0) {
  5601. break; /* No more data to write */
  5602. } else {
  5603. nwritten += n;
  5604. len -= n;
  5605. }
  5606. }
  5607. return nwritten;
  5608. }
  5609. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5610. * Return value:
  5611. * >=0 .. number of bytes successfully read
  5612. * -1 .. timeout
  5613. * -2 .. error
  5614. */
  5615. static int
  5616. pull_inner(FILE *fp,
  5617. struct mg_connection *conn,
  5618. char *buf,
  5619. int len,
  5620. double timeout)
  5621. {
  5622. int nread, err = 0;
  5623. #if defined(_WIN32)
  5624. typedef int len_t;
  5625. #else
  5626. typedef size_t len_t;
  5627. #endif
  5628. /* We need an additional wait loop around this, because in some cases
  5629. * with TLSwe may get data from the socket but not from SSL_read.
  5630. * In this case we need to repeat at least once.
  5631. */
  5632. if (fp != NULL) {
  5633. #if !defined(_WIN32_WCE)
  5634. /* Use read() instead of fread(), because if we're reading from the
  5635. * CGI pipe, fread() may block until IO buffer is filled up. We
  5636. * cannot afford to block and must pass all read bytes immediately
  5637. * to the client. */
  5638. nread = (int)read(fileno(fp), buf, (size_t)len);
  5639. #else
  5640. /* WinCE does not support CGI pipes */
  5641. nread = (int)fread(buf, 1, (size_t)len, fp);
  5642. #endif
  5643. err = (nread < 0) ? ERRNO : 0;
  5644. if ((nread == 0) && (len > 0)) {
  5645. /* Should get data, but got EOL */
  5646. return -2;
  5647. }
  5648. #if !defined(NO_SSL)
  5649. } else if (conn->ssl != NULL) {
  5650. int ssl_pending;
  5651. struct mg_pollfd pfd[1];
  5652. int pollres;
  5653. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5654. /* We already know there is no more data buffered in conn->buf
  5655. * but there is more available in the SSL layer. So don't poll
  5656. * conn->client.sock yet. */
  5657. if (ssl_pending > len) {
  5658. ssl_pending = len;
  5659. }
  5660. pollres = 1;
  5661. } else {
  5662. pfd[0].fd = conn->client.sock;
  5663. pfd[0].events = POLLIN;
  5664. pollres = mg_poll(pfd,
  5665. 1,
  5666. (int)(timeout * 1000.0),
  5667. &(conn->phys_ctx->stop_flag));
  5668. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5669. return -2;
  5670. }
  5671. }
  5672. if (pollres > 0) {
  5673. ERR_clear_error();
  5674. nread =
  5675. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5676. if (nread <= 0) {
  5677. err = SSL_get_error(conn->ssl, nread);
  5678. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5679. err = ERRNO;
  5680. } else if ((err == SSL_ERROR_WANT_READ)
  5681. || (err == SSL_ERROR_WANT_WRITE)) {
  5682. nread = 0;
  5683. } else {
  5684. /* All errors should return -2 */
  5685. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5686. ERR_clear_error();
  5687. return -2;
  5688. }
  5689. ERR_clear_error();
  5690. } else {
  5691. err = 0;
  5692. }
  5693. } else if (pollres < 0) {
  5694. /* Error */
  5695. return -2;
  5696. } else {
  5697. /* pollres = 0 means timeout */
  5698. nread = 0;
  5699. }
  5700. #endif
  5701. } else {
  5702. struct mg_pollfd pfd[1];
  5703. int pollres;
  5704. pfd[0].fd = conn->client.sock;
  5705. pfd[0].events = POLLIN;
  5706. pollres = mg_poll(pfd,
  5707. 1,
  5708. (int)(timeout * 1000.0),
  5709. &(conn->phys_ctx->stop_flag));
  5710. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5711. return -2;
  5712. }
  5713. if (pollres > 0) {
  5714. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5715. err = (nread < 0) ? ERRNO : 0;
  5716. if (nread <= 0) {
  5717. /* shutdown of the socket at client side */
  5718. return -2;
  5719. }
  5720. } else if (pollres < 0) {
  5721. /* error callint poll */
  5722. return -2;
  5723. } else {
  5724. /* pollres = 0 means timeout */
  5725. nread = 0;
  5726. }
  5727. }
  5728. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5729. return -2;
  5730. }
  5731. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5732. /* some data has been read, or no data was requested */
  5733. return nread;
  5734. }
  5735. if (nread < 0) {
  5736. /* socket error - check errno */
  5737. #if defined(_WIN32)
  5738. if (err == WSAEWOULDBLOCK) {
  5739. /* TODO (low): check if this is still required */
  5740. /* standard case if called from close_socket_gracefully */
  5741. return -2;
  5742. } else if (err == WSAETIMEDOUT) {
  5743. /* TODO (low): check if this is still required */
  5744. /* timeout is handled by the while loop */
  5745. return 0;
  5746. } else if (err == WSAECONNABORTED) {
  5747. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5748. return -2;
  5749. } else {
  5750. DEBUG_TRACE("recv() failed, error %d", err);
  5751. return -2;
  5752. }
  5753. #else
  5754. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5755. * if the timeout is reached and if the socket was set to non-
  5756. * blocking in close_socket_gracefully, so we can not distinguish
  5757. * here. We have to wait for the timeout in both cases for now.
  5758. */
  5759. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5760. /* TODO (low): check if this is still required */
  5761. /* EAGAIN/EWOULDBLOCK:
  5762. * standard case if called from close_socket_gracefully
  5763. * => should return -1 */
  5764. /* or timeout occurred
  5765. * => the code must stay in the while loop */
  5766. /* EINTR can be generated on a socket with a timeout set even
  5767. * when SA_RESTART is effective for all relevant signals
  5768. * (see signal(7)).
  5769. * => stay in the while loop */
  5770. } else {
  5771. DEBUG_TRACE("recv() failed, error %d", err);
  5772. return -2;
  5773. }
  5774. #endif
  5775. }
  5776. /* Timeout occurred, but no data available. */
  5777. return -1;
  5778. }
  5779. static int
  5780. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5781. {
  5782. int n, nread = 0;
  5783. double timeout = -1.0;
  5784. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5785. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5786. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5787. }
  5788. if (timeout >= 0.0) {
  5789. start_time = mg_get_current_time_ns();
  5790. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5791. }
  5792. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5793. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5794. if (n == -2) {
  5795. if (nread == 0) {
  5796. nread = -1; /* Propagate the error */
  5797. }
  5798. break;
  5799. } else if (n == -1) {
  5800. /* timeout */
  5801. if (timeout >= 0.0) {
  5802. now = mg_get_current_time_ns();
  5803. if ((now - start_time) <= timeout_ns) {
  5804. continue;
  5805. }
  5806. }
  5807. break;
  5808. } else if (n == 0) {
  5809. break; /* No more data to read */
  5810. } else {
  5811. nread += n;
  5812. len -= n;
  5813. }
  5814. }
  5815. return nread;
  5816. }
  5817. static void
  5818. discard_unread_request_data(struct mg_connection *conn)
  5819. {
  5820. char buf[MG_BUF_LEN];
  5821. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5822. ;
  5823. }
  5824. static int
  5825. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5826. {
  5827. int64_t content_len, n, buffered_len, nread;
  5828. int64_t len64 =
  5829. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5830. * int, we may not read more
  5831. * bytes */
  5832. const char *body;
  5833. if (conn == NULL) {
  5834. return 0;
  5835. }
  5836. /* If Content-Length is not set for a response with body data,
  5837. * we do not know in advance how much data should be read. */
  5838. content_len = conn->content_len;
  5839. if (content_len < 0) {
  5840. /* The body data is completed when the connection is closed. */
  5841. content_len = INT64_MAX;
  5842. }
  5843. nread = 0;
  5844. if (conn->consumed_content < content_len) {
  5845. /* Adjust number of bytes to read. */
  5846. int64_t left_to_read = content_len - conn->consumed_content;
  5847. if (left_to_read < len64) {
  5848. /* Do not read more than the total content length of the
  5849. * request.
  5850. */
  5851. len64 = left_to_read;
  5852. }
  5853. /* Return buffered data */
  5854. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5855. - conn->consumed_content;
  5856. if (buffered_len > 0) {
  5857. if (len64 < buffered_len) {
  5858. buffered_len = len64;
  5859. }
  5860. body = conn->buf + conn->request_len + conn->consumed_content;
  5861. memcpy(buf, body, (size_t)buffered_len);
  5862. len64 -= buffered_len;
  5863. conn->consumed_content += buffered_len;
  5864. nread += buffered_len;
  5865. buf = (char *)buf + buffered_len;
  5866. }
  5867. /* We have returned all buffered data. Read new data from the remote
  5868. * socket.
  5869. */
  5870. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5871. conn->consumed_content += n;
  5872. nread += n;
  5873. } else {
  5874. nread = ((nread > 0) ? nread : n);
  5875. }
  5876. }
  5877. return (int)nread;
  5878. }
  5879. int
  5880. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5881. {
  5882. if (len > INT_MAX) {
  5883. len = INT_MAX;
  5884. }
  5885. if (conn == NULL) {
  5886. return 0;
  5887. }
  5888. if (conn->is_chunked) {
  5889. size_t all_read = 0;
  5890. while (len > 0) {
  5891. if (conn->is_chunked >= 3) {
  5892. /* No more data left to read */
  5893. return 0;
  5894. }
  5895. if (conn->is_chunked != 1) {
  5896. /* Has error */
  5897. return -1;
  5898. }
  5899. if (conn->consumed_content != conn->content_len) {
  5900. /* copy from the current chunk */
  5901. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5902. if (read_ret < 1) {
  5903. /* read error */
  5904. conn->is_chunked = 2;
  5905. return -1;
  5906. }
  5907. all_read += (size_t)read_ret;
  5908. len -= (size_t)read_ret;
  5909. if (conn->consumed_content == conn->content_len) {
  5910. /* Add data bytes in the current chunk have been read,
  5911. * so we are expecting \r\n now. */
  5912. char x[2];
  5913. conn->content_len += 2;
  5914. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5915. || (x[1] != '\n')) {
  5916. /* Protocol violation */
  5917. conn->is_chunked = 2;
  5918. return -1;
  5919. }
  5920. }
  5921. } else {
  5922. /* fetch a new chunk */
  5923. size_t i;
  5924. char lenbuf[64];
  5925. char *end = NULL;
  5926. unsigned long chunkSize = 0;
  5927. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5928. conn->content_len++;
  5929. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5930. lenbuf[i] = 0;
  5931. }
  5932. if ((i > 0) && (lenbuf[i] == '\r')
  5933. && (lenbuf[i - 1] != '\r')) {
  5934. continue;
  5935. }
  5936. if ((i > 1) && (lenbuf[i] == '\n')
  5937. && (lenbuf[i - 1] == '\r')) {
  5938. lenbuf[i + 1] = 0;
  5939. chunkSize = strtoul(lenbuf, &end, 16);
  5940. if (chunkSize == 0) {
  5941. /* regular end of content */
  5942. conn->is_chunked = 3;
  5943. }
  5944. break;
  5945. }
  5946. if (!isxdigit((unsigned char)lenbuf[i])) {
  5947. /* illegal character for chunk length */
  5948. conn->is_chunked = 2;
  5949. return -1;
  5950. }
  5951. }
  5952. if ((end == NULL) || (*end != '\r')) {
  5953. /* chunksize not set correctly */
  5954. conn->is_chunked = 2;
  5955. return -1;
  5956. }
  5957. if (chunkSize == 0) {
  5958. /* try discarding trailer for keep-alive */
  5959. conn->content_len += 2;
  5960. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5961. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5962. conn->is_chunked = 4;
  5963. }
  5964. break;
  5965. }
  5966. /* append a new chunk */
  5967. conn->content_len += (int64_t)chunkSize;
  5968. }
  5969. }
  5970. return (int)all_read;
  5971. }
  5972. return mg_read_inner(conn, buf, len);
  5973. }
  5974. int
  5975. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5976. {
  5977. time_t now;
  5978. int n, total, allowed;
  5979. if (conn == NULL) {
  5980. return 0;
  5981. }
  5982. if (len > INT_MAX) {
  5983. return -1;
  5984. }
  5985. if (conn->throttle > 0) {
  5986. if ((now = time(NULL)) != conn->last_throttle_time) {
  5987. conn->last_throttle_time = now;
  5988. conn->last_throttle_bytes = 0;
  5989. }
  5990. allowed = conn->throttle - conn->last_throttle_bytes;
  5991. if (allowed > (int)len) {
  5992. allowed = (int)len;
  5993. }
  5994. if ((total = push_all(conn->phys_ctx,
  5995. NULL,
  5996. conn->client.sock,
  5997. conn->ssl,
  5998. (const char *)buf,
  5999. allowed))
  6000. == allowed) {
  6001. buf = (const char *)buf + total;
  6002. conn->last_throttle_bytes += total;
  6003. while ((total < (int)len)
  6004. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6005. allowed = (conn->throttle > ((int)len - total))
  6006. ? (int)len - total
  6007. : conn->throttle;
  6008. if ((n = push_all(conn->phys_ctx,
  6009. NULL,
  6010. conn->client.sock,
  6011. conn->ssl,
  6012. (const char *)buf,
  6013. allowed))
  6014. != allowed) {
  6015. break;
  6016. }
  6017. sleep(1);
  6018. conn->last_throttle_bytes = allowed;
  6019. conn->last_throttle_time = time(NULL);
  6020. buf = (const char *)buf + n;
  6021. total += n;
  6022. }
  6023. }
  6024. } else {
  6025. total = push_all(conn->phys_ctx,
  6026. NULL,
  6027. conn->client.sock,
  6028. conn->ssl,
  6029. (const char *)buf,
  6030. (int)len);
  6031. }
  6032. if (total > 0) {
  6033. conn->num_bytes_sent += total;
  6034. }
  6035. return total;
  6036. }
  6037. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6038. int
  6039. mg_send_chunk(struct mg_connection *conn,
  6040. const char *chunk,
  6041. unsigned int chunk_len)
  6042. {
  6043. char lenbuf[16];
  6044. size_t lenbuf_len;
  6045. int ret;
  6046. int t;
  6047. /* First store the length information in a text buffer. */
  6048. sprintf(lenbuf, "%x\r\n", chunk_len);
  6049. lenbuf_len = strlen(lenbuf);
  6050. /* Then send length information, chunk and terminating \r\n. */
  6051. ret = mg_write(conn, lenbuf, lenbuf_len);
  6052. if (ret != (int)lenbuf_len) {
  6053. return -1;
  6054. }
  6055. t = ret;
  6056. ret = mg_write(conn, chunk, chunk_len);
  6057. if (ret != (int)chunk_len) {
  6058. return -1;
  6059. }
  6060. t += ret;
  6061. ret = mg_write(conn, "\r\n", 2);
  6062. if (ret != 2) {
  6063. return -1;
  6064. }
  6065. t += ret;
  6066. return t;
  6067. }
  6068. #if defined(GCC_DIAGNOSTIC)
  6069. /* This block forwards format strings to printf implementations,
  6070. * so we need to disable the format-nonliteral warning. */
  6071. #pragma GCC diagnostic push
  6072. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6073. #endif
  6074. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6075. static int
  6076. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6077. {
  6078. va_list ap_copy;
  6079. size_t size = MG_BUF_LEN / 4;
  6080. int len = -1;
  6081. *buf = NULL;
  6082. while (len < 0) {
  6083. if (*buf) {
  6084. mg_free(*buf);
  6085. }
  6086. size *= 4;
  6087. *buf = (char *)mg_malloc(size);
  6088. if (!*buf) {
  6089. break;
  6090. }
  6091. va_copy(ap_copy, ap);
  6092. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6093. va_end(ap_copy);
  6094. (*buf)[size - 1] = 0;
  6095. }
  6096. return len;
  6097. }
  6098. /* Print message to buffer. If buffer is large enough to hold the message,
  6099. * return buffer. If buffer is to small, allocate large enough buffer on
  6100. * heap,
  6101. * and return allocated buffer. */
  6102. static int
  6103. alloc_vprintf(char **out_buf,
  6104. char *prealloc_buf,
  6105. size_t prealloc_size,
  6106. const char *fmt,
  6107. va_list ap)
  6108. {
  6109. va_list ap_copy;
  6110. int len;
  6111. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6112. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6113. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6114. * Therefore, we make two passes: on first pass, get required message
  6115. * length.
  6116. * On second pass, actually print the message. */
  6117. va_copy(ap_copy, ap);
  6118. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6119. va_end(ap_copy);
  6120. if (len < 0) {
  6121. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6122. * Switch to alternative code path that uses incremental
  6123. * allocations.
  6124. */
  6125. va_copy(ap_copy, ap);
  6126. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6127. va_end(ap_copy);
  6128. } else if ((size_t)(len) >= prealloc_size) {
  6129. /* The pre-allocated buffer not large enough. */
  6130. /* Allocate a new buffer. */
  6131. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6132. if (!*out_buf) {
  6133. /* Allocation failed. Return -1 as "out of memory" error. */
  6134. return -1;
  6135. }
  6136. /* Buffer allocation successful. Store the string there. */
  6137. va_copy(ap_copy, ap);
  6138. IGNORE_UNUSED_RESULT(
  6139. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6140. va_end(ap_copy);
  6141. } else {
  6142. /* The pre-allocated buffer is large enough.
  6143. * Use it to store the string and return the address. */
  6144. va_copy(ap_copy, ap);
  6145. IGNORE_UNUSED_RESULT(
  6146. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6147. va_end(ap_copy);
  6148. *out_buf = prealloc_buf;
  6149. }
  6150. return len;
  6151. }
  6152. #if defined(GCC_DIAGNOSTIC)
  6153. /* Enable format-nonliteral warning again. */
  6154. #pragma GCC diagnostic pop
  6155. #endif
  6156. static int
  6157. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6158. {
  6159. char mem[MG_BUF_LEN];
  6160. char *buf = NULL;
  6161. int len;
  6162. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6163. len = mg_write(conn, buf, (size_t)len);
  6164. }
  6165. if (buf != mem) {
  6166. mg_free(buf);
  6167. }
  6168. return len;
  6169. }
  6170. int
  6171. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6172. {
  6173. va_list ap;
  6174. int result;
  6175. va_start(ap, fmt);
  6176. result = mg_vprintf(conn, fmt, ap);
  6177. va_end(ap);
  6178. return result;
  6179. }
  6180. int
  6181. mg_url_decode(const char *src,
  6182. int src_len,
  6183. char *dst,
  6184. int dst_len,
  6185. int is_form_url_encoded)
  6186. {
  6187. int i, j, a, b;
  6188. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6189. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6190. if ((i < src_len - 2) && (src[i] == '%')
  6191. && isxdigit((unsigned char)src[i + 1])
  6192. && isxdigit((unsigned char)src[i + 2])) {
  6193. a = tolower((unsigned char)src[i + 1]);
  6194. b = tolower((unsigned char)src[i + 2]);
  6195. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6196. i += 2;
  6197. } else if (is_form_url_encoded && (src[i] == '+')) {
  6198. dst[j] = ' ';
  6199. } else {
  6200. dst[j] = src[i];
  6201. }
  6202. }
  6203. dst[j] = '\0'; /* Null-terminate the destination */
  6204. return (i >= src_len) ? j : -1;
  6205. }
  6206. /* form url decoding of an entire string */
  6207. static void
  6208. url_decode_in_place(char *buf)
  6209. {
  6210. int len = (int)strlen(buf);
  6211. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6212. }
  6213. int
  6214. mg_get_var(const char *data,
  6215. size_t data_len,
  6216. const char *name,
  6217. char *dst,
  6218. size_t dst_len)
  6219. {
  6220. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6221. }
  6222. int
  6223. mg_get_var2(const char *data,
  6224. size_t data_len,
  6225. const char *name,
  6226. char *dst,
  6227. size_t dst_len,
  6228. size_t occurrence)
  6229. {
  6230. const char *p, *e, *s;
  6231. size_t name_len;
  6232. int len;
  6233. if ((dst == NULL) || (dst_len == 0)) {
  6234. len = -2;
  6235. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6236. len = -1;
  6237. dst[0] = '\0';
  6238. } else {
  6239. name_len = strlen(name);
  6240. e = data + data_len;
  6241. len = -1;
  6242. dst[0] = '\0';
  6243. /* data is "var1=val1&var2=val2...". Find variable first */
  6244. for (p = data; p + name_len < e; p++) {
  6245. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6246. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6247. /* Point p to variable value */
  6248. p += name_len + 1;
  6249. /* Point s to the end of the value */
  6250. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6251. if (s == NULL) {
  6252. s = e;
  6253. }
  6254. DEBUG_ASSERT(s >= p);
  6255. if (s < p) {
  6256. return -3;
  6257. }
  6258. /* Decode variable into destination buffer */
  6259. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6260. /* Redirect error code from -1 to -2 (destination buffer too
  6261. * small). */
  6262. if (len == -1) {
  6263. len = -2;
  6264. }
  6265. break;
  6266. }
  6267. }
  6268. }
  6269. return len;
  6270. }
  6271. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6272. int
  6273. mg_split_form_urlencoded(char *data,
  6274. struct mg_header *form_fields,
  6275. unsigned num_form_fields)
  6276. {
  6277. char *b;
  6278. int i;
  6279. int num = 0;
  6280. if (data == NULL) {
  6281. /* parameter error */
  6282. return -1;
  6283. }
  6284. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6285. /* determine the number of expected fields */
  6286. if (data[0] == 0) {
  6287. return 0;
  6288. }
  6289. /* count number of & to return the number of key-value-pairs */
  6290. num = 1;
  6291. while (*data) {
  6292. if (*data == '&') {
  6293. num++;
  6294. }
  6295. data++;
  6296. }
  6297. return num;
  6298. }
  6299. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6300. /* parameter error */
  6301. return -1;
  6302. }
  6303. for (i = 0; i < (int)num_form_fields; i++) {
  6304. /* extract key-value pairs from input data */
  6305. while ((*data == ' ') || (*data == '\t')) {
  6306. /* skip initial spaces */
  6307. data++;
  6308. }
  6309. if (*data == 0) {
  6310. /* end of string reached */
  6311. break;
  6312. }
  6313. form_fields[num].name = data;
  6314. /* find & or = */
  6315. b = data;
  6316. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6317. b++;
  6318. }
  6319. if (*b == 0) {
  6320. /* last key without value */
  6321. form_fields[num].value = NULL;
  6322. } else if (*b == '&') {
  6323. /* mid key without value */
  6324. form_fields[num].value = NULL;
  6325. } else {
  6326. /* terminate string */
  6327. *b = 0;
  6328. /* value starts after '=' */
  6329. data = b + 1;
  6330. form_fields[num].value = data;
  6331. }
  6332. /* new field is stored */
  6333. num++;
  6334. /* find a next key */
  6335. b = strchr(data, '&');
  6336. if (b == 0) {
  6337. /* no more data */
  6338. break;
  6339. } else {
  6340. /* terminate value of last field at '&' */
  6341. *b = 0;
  6342. /* next key-value-pairs starts after '&' */
  6343. data = b + 1;
  6344. }
  6345. }
  6346. /* Decode all values */
  6347. for (i = 0; i < num; i++) {
  6348. if (form_fields[i].name) {
  6349. url_decode_in_place((char *)form_fields[i].name);
  6350. }
  6351. if (form_fields[i].value) {
  6352. url_decode_in_place((char *)form_fields[i].value);
  6353. }
  6354. }
  6355. /* return number of fields found */
  6356. return num;
  6357. }
  6358. /* HCP24: some changes to compare hole var_name */
  6359. int
  6360. mg_get_cookie(const char *cookie_header,
  6361. const char *var_name,
  6362. char *dst,
  6363. size_t dst_size)
  6364. {
  6365. const char *s, *p, *end;
  6366. int name_len, len = -1;
  6367. if ((dst == NULL) || (dst_size == 0)) {
  6368. return -2;
  6369. }
  6370. dst[0] = '\0';
  6371. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6372. return -1;
  6373. }
  6374. name_len = (int)strlen(var_name);
  6375. end = s + strlen(s);
  6376. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6377. if (s[name_len] == '=') {
  6378. /* HCP24: now check is it a substring or a full cookie name */
  6379. if ((s == cookie_header) || (s[-1] == ' ')) {
  6380. s += name_len + 1;
  6381. if ((p = strchr(s, ' ')) == NULL) {
  6382. p = end;
  6383. }
  6384. if (p[-1] == ';') {
  6385. p--;
  6386. }
  6387. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6388. s++;
  6389. p--;
  6390. }
  6391. if ((size_t)(p - s) < dst_size) {
  6392. len = (int)(p - s);
  6393. mg_strlcpy(dst, s, (size_t)len + 1);
  6394. } else {
  6395. len = -3;
  6396. }
  6397. break;
  6398. }
  6399. }
  6400. }
  6401. return len;
  6402. }
  6403. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6404. static void
  6405. base64_encode(const unsigned char *src, int src_len, char *dst)
  6406. {
  6407. static const char *b64 =
  6408. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6409. int i, j, a, b, c;
  6410. for (i = j = 0; i < src_len; i += 3) {
  6411. a = src[i];
  6412. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6413. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6414. dst[j++] = b64[a >> 2];
  6415. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6416. if (i + 1 < src_len) {
  6417. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6418. }
  6419. if (i + 2 < src_len) {
  6420. dst[j++] = b64[c & 63];
  6421. }
  6422. }
  6423. while (j % 4 != 0) {
  6424. dst[j++] = '=';
  6425. }
  6426. dst[j++] = '\0';
  6427. }
  6428. #endif
  6429. #if defined(USE_LUA)
  6430. static unsigned char
  6431. b64reverse(char letter)
  6432. {
  6433. if ((letter >= 'A') && (letter <= 'Z')) {
  6434. return letter - 'A';
  6435. }
  6436. if ((letter >= 'a') && (letter <= 'z')) {
  6437. return letter - 'a' + 26;
  6438. }
  6439. if ((letter >= '0') && (letter <= '9')) {
  6440. return letter - '0' + 52;
  6441. }
  6442. if (letter == '+') {
  6443. return 62;
  6444. }
  6445. if (letter == '/') {
  6446. return 63;
  6447. }
  6448. if (letter == '=') {
  6449. return 255; /* normal end */
  6450. }
  6451. return 254; /* error */
  6452. }
  6453. static int
  6454. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6455. {
  6456. int i;
  6457. unsigned char a, b, c, d;
  6458. *dst_len = 0;
  6459. for (i = 0; i < src_len; i += 4) {
  6460. a = b64reverse(src[i]);
  6461. if (a >= 254) {
  6462. return i;
  6463. }
  6464. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6465. if (b >= 254) {
  6466. return i + 1;
  6467. }
  6468. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6469. if (c == 254) {
  6470. return i + 2;
  6471. }
  6472. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6473. if (d == 254) {
  6474. return i + 3;
  6475. }
  6476. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6477. if (c != 255) {
  6478. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6479. if (d != 255) {
  6480. dst[(*dst_len)++] = (c << 6) + d;
  6481. }
  6482. }
  6483. }
  6484. return -1;
  6485. }
  6486. #endif
  6487. static int
  6488. is_put_or_delete_method(const struct mg_connection *conn)
  6489. {
  6490. if (conn) {
  6491. const char *s = conn->request_info.request_method;
  6492. return (s != NULL)
  6493. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6494. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6495. }
  6496. return 0;
  6497. }
  6498. #if !defined(NO_FILES)
  6499. static int
  6500. extention_matches_script(
  6501. struct mg_connection *conn, /* in: request (must be valid) */
  6502. const char *filename /* in: filename (must be valid) */
  6503. )
  6504. {
  6505. #if !defined(NO_CGI)
  6506. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6507. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6508. filename)
  6509. > 0) {
  6510. return 1;
  6511. }
  6512. #endif
  6513. #if defined(USE_LUA)
  6514. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6515. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6516. filename)
  6517. > 0) {
  6518. return 1;
  6519. }
  6520. #endif
  6521. #if defined(USE_DUKTAPE)
  6522. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6523. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6524. filename)
  6525. > 0) {
  6526. return 1;
  6527. }
  6528. #endif
  6529. /* filename and conn could be unused, if all preocessor conditions
  6530. * are false (no script language supported). */
  6531. (void)filename;
  6532. (void)conn;
  6533. return 0;
  6534. }
  6535. /* For given directory path, substitute it to valid index file.
  6536. * Return 1 if index file has been found, 0 if not found.
  6537. * If the file is found, it's stats is returned in stp. */
  6538. static int
  6539. substitute_index_file(struct mg_connection *conn,
  6540. char *path,
  6541. size_t path_len,
  6542. struct mg_file_stat *filestat)
  6543. {
  6544. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6545. struct vec filename_vec;
  6546. size_t n = strlen(path);
  6547. int found = 0;
  6548. /* The 'path' given to us points to the directory. Remove all trailing
  6549. * directory separator characters from the end of the path, and
  6550. * then append single directory separator character. */
  6551. while ((n > 0) && (path[n - 1] == '/')) {
  6552. n--;
  6553. }
  6554. path[n] = '/';
  6555. /* Traverse index files list. For each entry, append it to the given
  6556. * path and see if the file exists. If it exists, break the loop */
  6557. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6558. /* Ignore too long entries that may overflow path buffer */
  6559. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6560. continue;
  6561. }
  6562. /* Prepare full path to the index file */
  6563. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6564. /* Does it exist? */
  6565. if (mg_stat(conn, path, filestat)) {
  6566. /* Yes it does, break the loop */
  6567. found = 1;
  6568. break;
  6569. }
  6570. }
  6571. /* If no index file exists, restore directory path */
  6572. if (!found) {
  6573. path[n] = '\0';
  6574. }
  6575. return found;
  6576. }
  6577. #endif
  6578. static void
  6579. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6580. char *filename, /* out: filename */
  6581. size_t filename_buf_len, /* in: size of filename buffer */
  6582. struct mg_file_stat *filestat, /* out: file status structure */
  6583. int *is_found, /* out: file found (directly) */
  6584. int *is_script_resource, /* out: handled by a script? */
  6585. int *is_websocket_request, /* out: websocket connetion? */
  6586. int *is_put_or_delete_request /* out: put/delete a file? */
  6587. )
  6588. {
  6589. char const *accept_encoding;
  6590. #if !defined(NO_FILES)
  6591. const char *uri = conn->request_info.local_uri;
  6592. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6593. const char *rewrite;
  6594. struct vec a, b;
  6595. ptrdiff_t match_len;
  6596. char gz_path[PATH_MAX];
  6597. int truncated;
  6598. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6599. char *tmp_str;
  6600. size_t tmp_str_len, sep_pos;
  6601. int allow_substitute_script_subresources;
  6602. #endif
  6603. #else
  6604. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6605. #endif
  6606. /* Step 1: Set all initially unknown outputs to zero */
  6607. memset(filestat, 0, sizeof(*filestat));
  6608. *filename = 0;
  6609. *is_found = 0;
  6610. *is_script_resource = 0;
  6611. /* Step 2: Check if the request attempts to modify the file system */
  6612. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6613. /* Step 3: Check if it is a websocket request, and modify the document
  6614. * root if required */
  6615. #if defined(USE_WEBSOCKET)
  6616. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6617. #if !defined(NO_FILES)
  6618. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6619. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6620. }
  6621. #endif /* !NO_FILES */
  6622. #else /* USE_WEBSOCKET */
  6623. *is_websocket_request = 0;
  6624. #endif /* USE_WEBSOCKET */
  6625. /* Step 4: Check if gzip encoded response is allowed */
  6626. conn->accept_gzip = 0;
  6627. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6628. if (strstr(accept_encoding, "gzip") != NULL) {
  6629. conn->accept_gzip = 1;
  6630. }
  6631. }
  6632. #if !defined(NO_FILES)
  6633. /* Step 5: If there is no root directory, don't look for files. */
  6634. /* Note that root == NULL is a regular use case here. This occurs,
  6635. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6636. * config is not required. */
  6637. if (root == NULL) {
  6638. /* all file related outputs have already been set to 0, just return
  6639. */
  6640. return;
  6641. }
  6642. /* Step 6: Determine the local file path from the root path and the
  6643. * request uri. */
  6644. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6645. * part of the path one byte on the right. */
  6646. mg_snprintf(
  6647. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6648. if (truncated) {
  6649. goto interpret_cleanup;
  6650. }
  6651. /* Step 7: URI rewriting */
  6652. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6653. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6654. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6655. mg_snprintf(conn,
  6656. &truncated,
  6657. filename,
  6658. filename_buf_len - 1,
  6659. "%.*s%s",
  6660. (int)b.len,
  6661. b.ptr,
  6662. uri + match_len);
  6663. break;
  6664. }
  6665. }
  6666. if (truncated) {
  6667. goto interpret_cleanup;
  6668. }
  6669. /* Step 8: Check if the file exists at the server */
  6670. /* Local file path and name, corresponding to requested URI
  6671. * is now stored in "filename" variable. */
  6672. if (mg_stat(conn, filename, filestat)) {
  6673. int uri_len = (int)strlen(uri);
  6674. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6675. /* 8.1: File exists. */
  6676. *is_found = 1;
  6677. /* 8.2: Check if it is a script type. */
  6678. if (extention_matches_script(conn, filename)) {
  6679. /* The request addresses a CGI resource, Lua script or
  6680. * server-side javascript.
  6681. * The URI corresponds to the script itself (like
  6682. * /path/script.cgi), and there is no additional resource
  6683. * path (like /path/script.cgi/something).
  6684. * Requests that modify (replace or delete) a resource, like
  6685. * PUT and DELETE requests, should replace/delete the script
  6686. * file.
  6687. * Requests that read or write from/to a resource, like GET and
  6688. * POST requests, should call the script and return the
  6689. * generated response. */
  6690. *is_script_resource = (!*is_put_or_delete_request);
  6691. }
  6692. /* 8.3: If the request target is a directory, there could be
  6693. * a substitute file (index.html, index.cgi, ...). */
  6694. if (filestat->is_directory && is_uri_end_slash) {
  6695. /* Use a local copy here, since substitute_index_file will
  6696. * change the content of the file status */
  6697. struct mg_file_stat tmp_filestat;
  6698. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6699. if (substitute_index_file(
  6700. conn, filename, filename_buf_len, &tmp_filestat)) {
  6701. /* Substitute file found. Copy stat to the output, then
  6702. * check if the file is a script file */
  6703. *filestat = tmp_filestat;
  6704. if (extention_matches_script(conn, filename)) {
  6705. /* Substitute file is a script file */
  6706. *is_script_resource = 1;
  6707. } else {
  6708. /* Substitute file is a regular file */
  6709. *is_script_resource = 0;
  6710. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6711. }
  6712. }
  6713. /* If there is no substitute file, the server could return
  6714. * a directory listing in a later step */
  6715. }
  6716. return;
  6717. }
  6718. /* Step 9: Check for zipped files: */
  6719. /* If we can't find the actual file, look for the file
  6720. * with the same name but a .gz extension. If we find it,
  6721. * use that and set the gzipped flag in the file struct
  6722. * to indicate that the response need to have the content-
  6723. * encoding: gzip header.
  6724. * We can only do this if the browser declares support. */
  6725. if (conn->accept_gzip) {
  6726. mg_snprintf(
  6727. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6728. if (truncated) {
  6729. goto interpret_cleanup;
  6730. }
  6731. if (mg_stat(conn, gz_path, filestat)) {
  6732. if (filestat) {
  6733. filestat->is_gzipped = 1;
  6734. *is_found = 1;
  6735. }
  6736. /* Currently gz files can not be scripts. */
  6737. return;
  6738. }
  6739. }
  6740. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6741. /* Step 10: Script resources may handle sub-resources */
  6742. /* Support PATH_INFO for CGI scripts. */
  6743. tmp_str_len = strlen(filename);
  6744. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6745. if (!tmp_str) {
  6746. /* Out of memory */
  6747. goto interpret_cleanup;
  6748. }
  6749. memcpy(tmp_str, filename, tmp_str_len + 1);
  6750. /* Check config, if index scripts may have sub-resources */
  6751. allow_substitute_script_subresources =
  6752. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6753. "yes");
  6754. sep_pos = tmp_str_len;
  6755. while (sep_pos > 0) {
  6756. sep_pos--;
  6757. if (tmp_str[sep_pos] == '/') {
  6758. int is_script = 0, does_exist = 0;
  6759. tmp_str[sep_pos] = 0;
  6760. if (tmp_str[0]) {
  6761. is_script = extention_matches_script(conn, tmp_str);
  6762. does_exist = mg_stat(conn, tmp_str, filestat);
  6763. }
  6764. if (does_exist && is_script) {
  6765. filename[sep_pos] = 0;
  6766. memmove(filename + sep_pos + 2,
  6767. filename + sep_pos + 1,
  6768. strlen(filename + sep_pos + 1) + 1);
  6769. conn->path_info = filename + sep_pos + 1;
  6770. filename[sep_pos + 1] = '/';
  6771. *is_script_resource = 1;
  6772. *is_found = 1;
  6773. break;
  6774. }
  6775. if (allow_substitute_script_subresources) {
  6776. if (substitute_index_file(
  6777. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6778. /* some intermediate directory has an index file */
  6779. if (extention_matches_script(conn, tmp_str)) {
  6780. DEBUG_TRACE("Substitute script %s serving path %s",
  6781. tmp_str,
  6782. filename);
  6783. /* this index file is a script */
  6784. mg_snprintf(conn,
  6785. &truncated,
  6786. filename,
  6787. filename_buf_len,
  6788. "%s//%s",
  6789. tmp_str,
  6790. filename + sep_pos + 1);
  6791. if (truncated) {
  6792. mg_free(tmp_str);
  6793. goto interpret_cleanup;
  6794. }
  6795. sep_pos = strlen(tmp_str);
  6796. filename[sep_pos] = 0;
  6797. conn->path_info = filename + sep_pos + 1;
  6798. *is_script_resource = 1;
  6799. *is_found = 1;
  6800. break;
  6801. } else {
  6802. DEBUG_TRACE("Substitute file %s serving path %s",
  6803. tmp_str,
  6804. filename);
  6805. /* non-script files will not have sub-resources */
  6806. filename[sep_pos] = 0;
  6807. conn->path_info = 0;
  6808. *is_script_resource = 0;
  6809. *is_found = 0;
  6810. break;
  6811. }
  6812. }
  6813. }
  6814. tmp_str[sep_pos] = '/';
  6815. }
  6816. }
  6817. mg_free(tmp_str);
  6818. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6819. #endif /* !defined(NO_FILES) */
  6820. return;
  6821. #if !defined(NO_FILES)
  6822. /* Reset all outputs */
  6823. interpret_cleanup:
  6824. memset(filestat, 0, sizeof(*filestat));
  6825. *filename = 0;
  6826. *is_found = 0;
  6827. *is_script_resource = 0;
  6828. *is_websocket_request = 0;
  6829. *is_put_or_delete_request = 0;
  6830. #endif /* !defined(NO_FILES) */
  6831. }
  6832. /* Check whether full request is buffered. Return:
  6833. * -1 if request or response is malformed
  6834. * 0 if request or response is not yet fully buffered
  6835. * >0 actual request length, including last \r\n\r\n */
  6836. static int
  6837. get_http_header_len(const char *buf, int buflen)
  6838. {
  6839. int i;
  6840. for (i = 0; i < buflen; i++) {
  6841. /* Do an unsigned comparison in some conditions below */
  6842. const unsigned char c = (unsigned char)buf[i];
  6843. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6844. && !isprint(c)) {
  6845. /* abort scan as soon as one malformed character is found */
  6846. return -1;
  6847. }
  6848. if (i < buflen - 1) {
  6849. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6850. /* Two newline, no carriage return - not standard compliant,
  6851. * but it should be accepted */
  6852. return i + 2;
  6853. }
  6854. }
  6855. if (i < buflen - 3) {
  6856. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6857. && (buf[i + 3] == '\n')) {
  6858. /* Two \r\n - standard compliant */
  6859. return i + 4;
  6860. }
  6861. }
  6862. }
  6863. return 0;
  6864. }
  6865. #if !defined(NO_CACHING)
  6866. /* Convert month to the month number. Return -1 on error, or month number */
  6867. static int
  6868. get_month_index(const char *s)
  6869. {
  6870. size_t i;
  6871. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6872. if (!strcmp(s, month_names[i])) {
  6873. return (int)i;
  6874. }
  6875. }
  6876. return -1;
  6877. }
  6878. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6879. static time_t
  6880. parse_date_string(const char *datetime)
  6881. {
  6882. char month_str[32] = {0};
  6883. int second, minute, hour, day, month, year;
  6884. time_t result = (time_t)0;
  6885. struct tm tm;
  6886. if ((sscanf(datetime,
  6887. "%d/%3s/%d %d:%d:%d",
  6888. &day,
  6889. month_str,
  6890. &year,
  6891. &hour,
  6892. &minute,
  6893. &second)
  6894. == 6)
  6895. || (sscanf(datetime,
  6896. "%d %3s %d %d:%d:%d",
  6897. &day,
  6898. month_str,
  6899. &year,
  6900. &hour,
  6901. &minute,
  6902. &second)
  6903. == 6)
  6904. || (sscanf(datetime,
  6905. "%*3s, %d %3s %d %d:%d:%d",
  6906. &day,
  6907. month_str,
  6908. &year,
  6909. &hour,
  6910. &minute,
  6911. &second)
  6912. == 6)
  6913. || (sscanf(datetime,
  6914. "%d-%3s-%d %d:%d:%d",
  6915. &day,
  6916. month_str,
  6917. &year,
  6918. &hour,
  6919. &minute,
  6920. &second)
  6921. == 6)) {
  6922. month = get_month_index(month_str);
  6923. if ((month >= 0) && (year >= 1970)) {
  6924. memset(&tm, 0, sizeof(tm));
  6925. tm.tm_year = year - 1900;
  6926. tm.tm_mon = month;
  6927. tm.tm_mday = day;
  6928. tm.tm_hour = hour;
  6929. tm.tm_min = minute;
  6930. tm.tm_sec = second;
  6931. result = timegm(&tm);
  6932. }
  6933. }
  6934. return result;
  6935. }
  6936. #endif /* !NO_CACHING */
  6937. /* Pre-process URIs according to RFC + protect against directory disclosure
  6938. * attacks by removing '..', excessive '/' and '\' characters */
  6939. static void
  6940. remove_dot_segments(char *inout)
  6941. {
  6942. /* Windows backend protection
  6943. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6944. * in URI by slash */
  6945. char *out_end = inout;
  6946. char *in = inout;
  6947. if (!in) {
  6948. /* Param error. */
  6949. return;
  6950. }
  6951. while (*in) {
  6952. if (*in == '\\') {
  6953. *in = '/';
  6954. }
  6955. in++;
  6956. }
  6957. /* Algorithm "remove_dot_segments" from
  6958. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6959. /* Step 1:
  6960. * The input buffer is initialized.
  6961. * The output buffer is initialized to the empty string.
  6962. */
  6963. in = inout;
  6964. /* Step 2:
  6965. * While the input buffer is not empty, loop as follows:
  6966. */
  6967. /* Less than out_end of the inout buffer is used as output, so keep
  6968. * condition: out_end <= in */
  6969. while (*in) {
  6970. /* Step 2a:
  6971. * If the input buffer begins with a prefix of "../" or "./",
  6972. * then remove that prefix from the input buffer;
  6973. */
  6974. if (!strncmp(in, "../", 3)) {
  6975. in += 3;
  6976. } else if (!strncmp(in, "./", 2)) {
  6977. in += 2;
  6978. }
  6979. /* otherwise */
  6980. /* Step 2b:
  6981. * if the input buffer begins with a prefix of "/./" or "/.",
  6982. * where "." is a complete path segment, then replace that
  6983. * prefix with "/" in the input buffer;
  6984. */
  6985. else if (!strncmp(in, "/./", 3)) {
  6986. in += 2;
  6987. } else if (!strcmp(in, "/.")) {
  6988. in[1] = 0;
  6989. }
  6990. /* otherwise */
  6991. /* Step 2c:
  6992. * if the input buffer begins with a prefix of "/../" or "/..",
  6993. * where ".." is a complete path segment, then replace that
  6994. * prefix with "/" in the input buffer and remove the last
  6995. * segment and its preceding "/" (if any) from the output
  6996. * buffer;
  6997. */
  6998. else if (!strncmp(in, "/../", 4)) {
  6999. in += 3;
  7000. if (inout != out_end) {
  7001. /* remove last segment */
  7002. do {
  7003. out_end--;
  7004. } while ((inout != out_end) && (*out_end != '/'));
  7005. }
  7006. } else if (!strcmp(in, "/..")) {
  7007. in[1] = 0;
  7008. if (inout != out_end) {
  7009. /* remove last segment */
  7010. do {
  7011. out_end--;
  7012. } while ((inout != out_end) && (*out_end != '/'));
  7013. }
  7014. }
  7015. /* otherwise */
  7016. /* Step 2d:
  7017. * if the input buffer consists only of "." or "..", then remove
  7018. * that from the input buffer;
  7019. */
  7020. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7021. *in = 0;
  7022. }
  7023. /* otherwise */
  7024. /* Step 2e:
  7025. * move the first path segment in the input buffer to the end of
  7026. * the output buffer, including the initial "/" character (if
  7027. * any) and any subsequent characters up to, but not including,
  7028. * the next "/" character or the end of the input buffer.
  7029. */
  7030. else {
  7031. do {
  7032. *out_end = *in;
  7033. out_end++;
  7034. in++;
  7035. } while ((*in != 0) && (*in != '/'));
  7036. }
  7037. }
  7038. /* Step 3:
  7039. * Finally, the output buffer is returned as the result of
  7040. * remove_dot_segments.
  7041. */
  7042. /* Terminate output */
  7043. *out_end = 0;
  7044. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7045. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7046. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7047. * or "//" anymore.
  7048. */
  7049. out_end = in = inout;
  7050. while (*in) {
  7051. if (*in == '.') {
  7052. /* remove . at the end or preceding of / */
  7053. char *in_ahead = in;
  7054. do {
  7055. in_ahead++;
  7056. } while (*in_ahead == '.');
  7057. if (*in_ahead == '/') {
  7058. in = in_ahead;
  7059. if ((out_end != inout) && (out_end[-1] == '/')) {
  7060. /* remove generated // */
  7061. out_end--;
  7062. }
  7063. } else if (*in_ahead == 0) {
  7064. in = in_ahead;
  7065. } else {
  7066. do {
  7067. *out_end++ = '.';
  7068. in++;
  7069. } while (in != in_ahead);
  7070. }
  7071. } else if (*in == '/') {
  7072. /* replace // by / */
  7073. *out_end++ = '/';
  7074. do {
  7075. in++;
  7076. } while (*in == '/');
  7077. } else {
  7078. *out_end++ = *in;
  7079. in++;
  7080. }
  7081. }
  7082. *out_end = 0;
  7083. }
  7084. static const struct {
  7085. const char *extension;
  7086. size_t ext_len;
  7087. const char *mime_type;
  7088. } builtin_mime_types[] = {
  7089. /* IANA registered MIME types
  7090. * (http://www.iana.org/assignments/media-types)
  7091. * application types */
  7092. {".doc", 4, "application/msword"},
  7093. {".eps", 4, "application/postscript"},
  7094. {".exe", 4, "application/octet-stream"},
  7095. {".js", 3, "application/javascript"},
  7096. {".json", 5, "application/json"},
  7097. {".pdf", 4, "application/pdf"},
  7098. {".ps", 3, "application/postscript"},
  7099. {".rtf", 4, "application/rtf"},
  7100. {".xhtml", 6, "application/xhtml+xml"},
  7101. {".xsl", 4, "application/xml"},
  7102. {".xslt", 5, "application/xml"},
  7103. /* fonts */
  7104. {".ttf", 4, "application/font-sfnt"},
  7105. {".cff", 4, "application/font-sfnt"},
  7106. {".otf", 4, "application/font-sfnt"},
  7107. {".aat", 4, "application/font-sfnt"},
  7108. {".sil", 4, "application/font-sfnt"},
  7109. {".pfr", 4, "application/font-tdpfr"},
  7110. {".woff", 5, "application/font-woff"},
  7111. /* audio */
  7112. {".mp3", 4, "audio/mpeg"},
  7113. {".oga", 4, "audio/ogg"},
  7114. {".ogg", 4, "audio/ogg"},
  7115. /* image */
  7116. {".gif", 4, "image/gif"},
  7117. {".ief", 4, "image/ief"},
  7118. {".jpeg", 5, "image/jpeg"},
  7119. {".jpg", 4, "image/jpeg"},
  7120. {".jpm", 4, "image/jpm"},
  7121. {".jpx", 4, "image/jpx"},
  7122. {".png", 4, "image/png"},
  7123. {".svg", 4, "image/svg+xml"},
  7124. {".tif", 4, "image/tiff"},
  7125. {".tiff", 5, "image/tiff"},
  7126. /* model */
  7127. {".wrl", 4, "model/vrml"},
  7128. /* text */
  7129. {".css", 4, "text/css"},
  7130. {".csv", 4, "text/csv"},
  7131. {".htm", 4, "text/html"},
  7132. {".html", 5, "text/html"},
  7133. {".sgm", 4, "text/sgml"},
  7134. {".shtm", 5, "text/html"},
  7135. {".shtml", 6, "text/html"},
  7136. {".txt", 4, "text/plain"},
  7137. {".xml", 4, "text/xml"},
  7138. /* video */
  7139. {".mov", 4, "video/quicktime"},
  7140. {".mp4", 4, "video/mp4"},
  7141. {".mpeg", 5, "video/mpeg"},
  7142. {".mpg", 4, "video/mpeg"},
  7143. {".ogv", 4, "video/ogg"},
  7144. {".qt", 3, "video/quicktime"},
  7145. /* not registered types
  7146. * (http://reference.sitepoint.com/html/mime-types-full,
  7147. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7148. {".arj", 4, "application/x-arj-compressed"},
  7149. {".gz", 3, "application/x-gunzip"},
  7150. {".rar", 4, "application/x-arj-compressed"},
  7151. {".swf", 4, "application/x-shockwave-flash"},
  7152. {".tar", 4, "application/x-tar"},
  7153. {".tgz", 4, "application/x-tar-gz"},
  7154. {".torrent", 8, "application/x-bittorrent"},
  7155. {".ppt", 4, "application/x-mspowerpoint"},
  7156. {".xls", 4, "application/x-msexcel"},
  7157. {".zip", 4, "application/x-zip-compressed"},
  7158. {".aac",
  7159. 4,
  7160. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7161. {".aif", 4, "audio/x-aif"},
  7162. {".m3u", 4, "audio/x-mpegurl"},
  7163. {".mid", 4, "audio/x-midi"},
  7164. {".ra", 3, "audio/x-pn-realaudio"},
  7165. {".ram", 4, "audio/x-pn-realaudio"},
  7166. {".wav", 4, "audio/x-wav"},
  7167. {".bmp", 4, "image/bmp"},
  7168. {".ico", 4, "image/x-icon"},
  7169. {".pct", 4, "image/x-pct"},
  7170. {".pict", 5, "image/pict"},
  7171. {".rgb", 4, "image/x-rgb"},
  7172. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7173. {".asf", 4, "video/x-ms-asf"},
  7174. {".avi", 4, "video/x-msvideo"},
  7175. {".m4v", 4, "video/x-m4v"},
  7176. {NULL, 0, NULL}};
  7177. const char *
  7178. mg_get_builtin_mime_type(const char *path)
  7179. {
  7180. const char *ext;
  7181. size_t i, path_len;
  7182. path_len = strlen(path);
  7183. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7184. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7185. if ((path_len > builtin_mime_types[i].ext_len)
  7186. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7187. return builtin_mime_types[i].mime_type;
  7188. }
  7189. }
  7190. return "text/plain";
  7191. }
  7192. /* Look at the "path" extension and figure what mime type it has.
  7193. * Store mime type in the vector. */
  7194. static void
  7195. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7196. {
  7197. struct vec ext_vec, mime_vec;
  7198. const char *list, *ext;
  7199. size_t path_len;
  7200. path_len = strlen(path);
  7201. if ((conn == NULL) || (vec == NULL)) {
  7202. if (vec != NULL) {
  7203. memset(vec, '\0', sizeof(struct vec));
  7204. }
  7205. return;
  7206. }
  7207. /* Scan user-defined mime types first, in case user wants to
  7208. * override default mime types. */
  7209. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7210. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7211. /* ext now points to the path suffix */
  7212. ext = path + path_len - ext_vec.len;
  7213. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7214. *vec = mime_vec;
  7215. return;
  7216. }
  7217. }
  7218. vec->ptr = mg_get_builtin_mime_type(path);
  7219. vec->len = strlen(vec->ptr);
  7220. }
  7221. /* Stringify binary data. Output buffer must be twice as big as input,
  7222. * because each byte takes 2 bytes in string representation */
  7223. static void
  7224. bin2str(char *to, const unsigned char *p, size_t len)
  7225. {
  7226. static const char *hex = "0123456789abcdef";
  7227. for (; len--; p++) {
  7228. *to++ = hex[p[0] >> 4];
  7229. *to++ = hex[p[0] & 0x0f];
  7230. }
  7231. *to = '\0';
  7232. }
  7233. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7234. */
  7235. char *
  7236. mg_md5(char buf[33], ...)
  7237. {
  7238. md5_byte_t hash[16];
  7239. const char *p;
  7240. va_list ap;
  7241. md5_state_t ctx;
  7242. md5_init(&ctx);
  7243. va_start(ap, buf);
  7244. while ((p = va_arg(ap, const char *)) != NULL) {
  7245. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7246. }
  7247. va_end(ap);
  7248. md5_finish(&ctx, hash);
  7249. bin2str(buf, hash, sizeof(hash));
  7250. return buf;
  7251. }
  7252. /* Check the user's password, return 1 if OK */
  7253. static int
  7254. check_password(const char *method,
  7255. const char *ha1,
  7256. const char *uri,
  7257. const char *nonce,
  7258. const char *nc,
  7259. const char *cnonce,
  7260. const char *qop,
  7261. const char *response)
  7262. {
  7263. char ha2[32 + 1], expected_response[32 + 1];
  7264. /* Some of the parameters may be NULL */
  7265. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7266. || (qop == NULL) || (response == NULL)) {
  7267. return 0;
  7268. }
  7269. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7270. if (strlen(response) != 32) {
  7271. return 0;
  7272. }
  7273. mg_md5(ha2, method, ":", uri, NULL);
  7274. mg_md5(expected_response,
  7275. ha1,
  7276. ":",
  7277. nonce,
  7278. ":",
  7279. nc,
  7280. ":",
  7281. cnonce,
  7282. ":",
  7283. qop,
  7284. ":",
  7285. ha2,
  7286. NULL);
  7287. return mg_strcasecmp(response, expected_response) == 0;
  7288. }
  7289. #if !defined(NO_FILESYSTEMS)
  7290. /* Use the global passwords file, if specified by auth_gpass option,
  7291. * or search for .htpasswd in the requested directory. */
  7292. static void
  7293. open_auth_file(struct mg_connection *conn,
  7294. const char *path,
  7295. struct mg_file *filep)
  7296. {
  7297. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7298. char name[PATH_MAX];
  7299. const char *p, *e,
  7300. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7301. int truncated;
  7302. if (gpass != NULL) {
  7303. /* Use global passwords file */
  7304. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7305. #if defined(DEBUG)
  7306. /* Use mg_cry_internal here, since gpass has been
  7307. * configured. */
  7308. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7309. #endif
  7310. }
  7311. /* Important: using local struct mg_file to test path for
  7312. * is_directory flag. If filep is used, mg_stat() makes it
  7313. * appear as if auth file was opened.
  7314. * TODO(mid): Check if this is still required after rewriting
  7315. * mg_stat */
  7316. } else if (mg_stat(conn, path, &filep->stat)
  7317. && filep->stat.is_directory) {
  7318. mg_snprintf(conn,
  7319. &truncated,
  7320. name,
  7321. sizeof(name),
  7322. "%s/%s",
  7323. path,
  7324. PASSWORDS_FILE_NAME);
  7325. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7326. #if defined(DEBUG)
  7327. /* Don't use mg_cry_internal here, but only a trace, since
  7328. * this is a typical case. It will occur for every directory
  7329. * without a password file. */
  7330. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7331. #endif
  7332. }
  7333. } else {
  7334. /* Try to find .htpasswd in requested directory. */
  7335. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7336. if (e[0] == '/') {
  7337. break;
  7338. }
  7339. }
  7340. mg_snprintf(conn,
  7341. &truncated,
  7342. name,
  7343. sizeof(name),
  7344. "%.*s/%s",
  7345. (int)(e - p),
  7346. p,
  7347. PASSWORDS_FILE_NAME);
  7348. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7349. #if defined(DEBUG)
  7350. /* Don't use mg_cry_internal here, but only a trace, since
  7351. * this is a typical case. It will occur for every directory
  7352. * without a password file. */
  7353. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7354. #endif
  7355. }
  7356. }
  7357. }
  7358. }
  7359. #endif /* NO_FILESYSTEMS */
  7360. /* Parsed Authorization header */
  7361. struct ah {
  7362. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7363. };
  7364. /* Return 1 on success. Always initializes the ah structure. */
  7365. static int
  7366. parse_auth_header(struct mg_connection *conn,
  7367. char *buf,
  7368. size_t buf_size,
  7369. struct ah *ah)
  7370. {
  7371. char *name, *value, *s;
  7372. const char *auth_header;
  7373. uint64_t nonce;
  7374. if (!ah || !conn) {
  7375. return 0;
  7376. }
  7377. (void)memset(ah, 0, sizeof(*ah));
  7378. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7379. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7380. return 0;
  7381. }
  7382. /* Make modifiable copy of the auth header */
  7383. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7384. s = buf;
  7385. /* Parse authorization header */
  7386. for (;;) {
  7387. /* Gobble initial spaces */
  7388. while (isspace((unsigned char)*s)) {
  7389. s++;
  7390. }
  7391. name = skip_quoted(&s, "=", " ", 0);
  7392. /* Value is either quote-delimited, or ends at first comma or space.
  7393. */
  7394. if (s[0] == '\"') {
  7395. s++;
  7396. value = skip_quoted(&s, "\"", " ", '\\');
  7397. if (s[0] == ',') {
  7398. s++;
  7399. }
  7400. } else {
  7401. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7402. * uses spaces */
  7403. }
  7404. if (*name == '\0') {
  7405. break;
  7406. }
  7407. if (!strcmp(name, "username")) {
  7408. ah->user = value;
  7409. } else if (!strcmp(name, "cnonce")) {
  7410. ah->cnonce = value;
  7411. } else if (!strcmp(name, "response")) {
  7412. ah->response = value;
  7413. } else if (!strcmp(name, "uri")) {
  7414. ah->uri = value;
  7415. } else if (!strcmp(name, "qop")) {
  7416. ah->qop = value;
  7417. } else if (!strcmp(name, "nc")) {
  7418. ah->nc = value;
  7419. } else if (!strcmp(name, "nonce")) {
  7420. ah->nonce = value;
  7421. }
  7422. }
  7423. #if !defined(NO_NONCE_CHECK)
  7424. /* Read the nonce from the response. */
  7425. if (ah->nonce == NULL) {
  7426. return 0;
  7427. }
  7428. s = NULL;
  7429. nonce = strtoull(ah->nonce, &s, 10);
  7430. if ((s == NULL) || (*s != 0)) {
  7431. return 0;
  7432. }
  7433. /* Convert the nonce from the client to a number. */
  7434. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7435. /* The converted number corresponds to the time the nounce has been
  7436. * created. This should not be earlier than the server start. */
  7437. /* Server side nonce check is valuable in all situations but one:
  7438. * if the server restarts frequently, but the client should not see
  7439. * that, so the server should accept nonces from previous starts. */
  7440. /* However, the reasonable default is to not accept a nonce from a
  7441. * previous start, so if anyone changed the access rights between
  7442. * two restarts, a new login is required. */
  7443. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7444. /* nonce is from a previous start of the server and no longer valid
  7445. * (replay attack?) */
  7446. return 0;
  7447. }
  7448. /* Check if the nonce is too high, so it has not (yet) been used by the
  7449. * server. */
  7450. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7451. + conn->dom_ctx->nonce_count)) {
  7452. return 0;
  7453. }
  7454. #else
  7455. (void)nonce;
  7456. #endif
  7457. /* CGI needs it as REMOTE_USER */
  7458. if (ah->user != NULL) {
  7459. conn->request_info.remote_user =
  7460. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7461. } else {
  7462. return 0;
  7463. }
  7464. return 1;
  7465. }
  7466. static const char *
  7467. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7468. {
  7469. #if defined(MG_USE_OPEN_FILE)
  7470. const char *eof;
  7471. size_t len;
  7472. const char *memend;
  7473. #else
  7474. (void)p; /* parameter is unused */
  7475. #endif
  7476. if (!filep) {
  7477. return NULL;
  7478. }
  7479. #if defined(MG_USE_OPEN_FILE)
  7480. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7481. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7482. /* Search for \n from p till the end of stream */
  7483. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7484. if (eof != NULL) {
  7485. eof += 1; /* Include \n */
  7486. } else {
  7487. eof = memend; /* Copy remaining data */
  7488. }
  7489. len =
  7490. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7491. memcpy(buf, *p, len);
  7492. buf[len] = '\0';
  7493. *p += len;
  7494. return len ? eof : NULL;
  7495. } else /* filep->access.fp block below */
  7496. #endif
  7497. if (filep->access.fp != NULL) {
  7498. return fgets(buf, (int)size, filep->access.fp);
  7499. } else {
  7500. return NULL;
  7501. }
  7502. }
  7503. /* Define the initial recursion depth for procesesing htpasswd files that
  7504. * include other htpasswd
  7505. * (or even the same) files. It is not difficult to provide a file or files
  7506. * s.t. they force civetweb
  7507. * to infinitely recurse and then crash.
  7508. */
  7509. #define INITIAL_DEPTH 9
  7510. #if INITIAL_DEPTH <= 0
  7511. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7512. #endif
  7513. #if !defined(NO_FILESYSTEMS)
  7514. struct read_auth_file_struct {
  7515. struct mg_connection *conn;
  7516. struct ah ah;
  7517. const char *domain;
  7518. char buf[256 + 256 + 40];
  7519. const char *f_user;
  7520. const char *f_domain;
  7521. const char *f_ha1;
  7522. };
  7523. static int
  7524. read_auth_file(struct mg_file *filep,
  7525. struct read_auth_file_struct *workdata,
  7526. int depth)
  7527. {
  7528. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7529. int is_authorized = 0;
  7530. struct mg_file fp;
  7531. size_t l;
  7532. if (!filep || !workdata || (0 == depth)) {
  7533. return 0;
  7534. }
  7535. /* Loop over passwords file */
  7536. #if defined(MG_USE_OPEN_FILE)
  7537. p = (char *)filep->access.membuf;
  7538. #endif
  7539. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7540. l = strlen(workdata->buf);
  7541. while (l > 0) {
  7542. if (isspace((unsigned char)workdata->buf[l - 1])
  7543. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7544. l--;
  7545. workdata->buf[l] = 0;
  7546. } else
  7547. break;
  7548. }
  7549. if (l < 1) {
  7550. continue;
  7551. }
  7552. workdata->f_user = workdata->buf;
  7553. if (workdata->f_user[0] == ':') {
  7554. /* user names may not contain a ':' and may not be empty,
  7555. * so lines starting with ':' may be used for a special purpose
  7556. */
  7557. if (workdata->f_user[1] == '#') {
  7558. /* :# is a comment */
  7559. continue;
  7560. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7561. if (mg_fopen(workdata->conn,
  7562. workdata->f_user + 9,
  7563. MG_FOPEN_MODE_READ,
  7564. &fp)) {
  7565. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7566. (void)mg_fclose(
  7567. &fp.access); /* ignore error on read only file */
  7568. /* No need to continue processing files once we have a
  7569. * match, since nothing will reset it back
  7570. * to 0.
  7571. */
  7572. if (is_authorized) {
  7573. return is_authorized;
  7574. }
  7575. } else {
  7576. mg_cry_internal(workdata->conn,
  7577. "%s: cannot open authorization file: %s",
  7578. __func__,
  7579. workdata->buf);
  7580. }
  7581. continue;
  7582. }
  7583. /* everything is invalid for the moment (might change in the
  7584. * future) */
  7585. mg_cry_internal(workdata->conn,
  7586. "%s: syntax error in authorization file: %s",
  7587. __func__,
  7588. workdata->buf);
  7589. continue;
  7590. }
  7591. workdata->f_domain = strchr(workdata->f_user, ':');
  7592. if (workdata->f_domain == NULL) {
  7593. mg_cry_internal(workdata->conn,
  7594. "%s: syntax error in authorization file: %s",
  7595. __func__,
  7596. workdata->buf);
  7597. continue;
  7598. }
  7599. *(char *)(workdata->f_domain) = 0;
  7600. (workdata->f_domain)++;
  7601. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7602. if (workdata->f_ha1 == NULL) {
  7603. mg_cry_internal(workdata->conn,
  7604. "%s: syntax error in authorization file: %s",
  7605. __func__,
  7606. workdata->buf);
  7607. continue;
  7608. }
  7609. *(char *)(workdata->f_ha1) = 0;
  7610. (workdata->f_ha1)++;
  7611. if (!strcmp(workdata->ah.user, workdata->f_user)
  7612. && !strcmp(workdata->domain, workdata->f_domain)) {
  7613. return check_password(workdata->conn->request_info.request_method,
  7614. workdata->f_ha1,
  7615. workdata->ah.uri,
  7616. workdata->ah.nonce,
  7617. workdata->ah.nc,
  7618. workdata->ah.cnonce,
  7619. workdata->ah.qop,
  7620. workdata->ah.response);
  7621. }
  7622. }
  7623. return is_authorized;
  7624. }
  7625. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7626. static int
  7627. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7628. {
  7629. struct read_auth_file_struct workdata;
  7630. char buf[MG_BUF_LEN];
  7631. if (!conn || !conn->dom_ctx) {
  7632. return 0;
  7633. }
  7634. memset(&workdata, 0, sizeof(workdata));
  7635. workdata.conn = conn;
  7636. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7637. return 0;
  7638. }
  7639. if (realm) {
  7640. workdata.domain = realm;
  7641. } else {
  7642. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7643. }
  7644. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7645. }
  7646. /* Public function to check http digest authentication header */
  7647. int
  7648. mg_check_digest_access_authentication(struct mg_connection *conn,
  7649. const char *realm,
  7650. const char *filename)
  7651. {
  7652. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7653. int auth;
  7654. if (!conn || !filename) {
  7655. return -1;
  7656. }
  7657. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7658. return -2;
  7659. }
  7660. auth = authorize(conn, &file, realm);
  7661. mg_fclose(&file.access);
  7662. return auth;
  7663. }
  7664. #endif /* NO_FILESYSTEMS */
  7665. /* Return 1 if request is authorised, 0 otherwise. */
  7666. static int
  7667. check_authorization(struct mg_connection *conn, const char *path)
  7668. {
  7669. #if !defined(NO_FILESYSTEMS)
  7670. char fname[PATH_MAX];
  7671. struct vec uri_vec, filename_vec;
  7672. const char *list;
  7673. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7674. int authorized = 1, truncated;
  7675. if (!conn || !conn->dom_ctx) {
  7676. return 0;
  7677. }
  7678. list = conn->dom_ctx->config[PROTECT_URI];
  7679. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7680. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7681. mg_snprintf(conn,
  7682. &truncated,
  7683. fname,
  7684. sizeof(fname),
  7685. "%.*s",
  7686. (int)filename_vec.len,
  7687. filename_vec.ptr);
  7688. if (truncated
  7689. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7690. mg_cry_internal(conn,
  7691. "%s: cannot open %s: %s",
  7692. __func__,
  7693. fname,
  7694. strerror(errno));
  7695. }
  7696. break;
  7697. }
  7698. }
  7699. if (!is_file_opened(&file.access)) {
  7700. open_auth_file(conn, path, &file);
  7701. }
  7702. if (is_file_opened(&file.access)) {
  7703. authorized = authorize(conn, &file, NULL);
  7704. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7705. }
  7706. return authorized;
  7707. #else
  7708. (void)conn;
  7709. (void)path;
  7710. return 1;
  7711. #endif /* NO_FILESYSTEMS */
  7712. }
  7713. /* Internal function. Assumes conn is valid */
  7714. static void
  7715. send_authorization_request(struct mg_connection *conn, const char *realm)
  7716. {
  7717. char date[64];
  7718. time_t curtime = time(NULL);
  7719. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7720. if (!realm) {
  7721. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7722. }
  7723. mg_lock_context(conn->phys_ctx);
  7724. nonce += conn->dom_ctx->nonce_count;
  7725. ++conn->dom_ctx->nonce_count;
  7726. mg_unlock_context(conn->phys_ctx);
  7727. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7728. conn->status_code = 401;
  7729. conn->must_close = 1;
  7730. gmt_time_string(date, sizeof(date), &curtime);
  7731. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7732. send_no_cache_header(conn);
  7733. send_additional_header(conn);
  7734. mg_printf(conn,
  7735. "Date: %s\r\n"
  7736. "Connection: %s\r\n"
  7737. "Content-Length: 0\r\n"
  7738. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7739. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7740. date,
  7741. suggest_connection_header(conn),
  7742. realm,
  7743. nonce);
  7744. }
  7745. /* Interface function. Parameters are provided by the user, so do
  7746. * at least some basic checks.
  7747. */
  7748. int
  7749. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7750. const char *realm)
  7751. {
  7752. if (conn && conn->dom_ctx) {
  7753. send_authorization_request(conn, realm);
  7754. return 0;
  7755. }
  7756. return -1;
  7757. }
  7758. #if !defined(NO_FILES)
  7759. static int
  7760. is_authorized_for_put(struct mg_connection *conn)
  7761. {
  7762. if (conn) {
  7763. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7764. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7765. int ret = 0;
  7766. if (passfile != NULL
  7767. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7768. ret = authorize(conn, &file, NULL);
  7769. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7770. }
  7771. return ret;
  7772. }
  7773. return 0;
  7774. }
  7775. #endif
  7776. int
  7777. mg_modify_passwords_file(const char *fname,
  7778. const char *domain,
  7779. const char *user,
  7780. const char *pass)
  7781. {
  7782. int found, i;
  7783. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7784. FILE *fp, *fp2;
  7785. found = 0;
  7786. fp = fp2 = NULL;
  7787. /* Regard empty password as no password - remove user record. */
  7788. if ((pass != NULL) && (pass[0] == '\0')) {
  7789. pass = NULL;
  7790. }
  7791. /* Other arguments must not be empty */
  7792. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7793. return 0;
  7794. }
  7795. /* Using the given file format, user name and domain must not contain
  7796. * ':'
  7797. */
  7798. if (strchr(user, ':') != NULL) {
  7799. return 0;
  7800. }
  7801. if (strchr(domain, ':') != NULL) {
  7802. return 0;
  7803. }
  7804. /* Do not allow control characters like newline in user name and domain.
  7805. * Do not allow excessively long names either. */
  7806. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7807. if (iscntrl((unsigned char)user[i])) {
  7808. return 0;
  7809. }
  7810. }
  7811. if (user[i]) {
  7812. return 0;
  7813. }
  7814. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7815. if (iscntrl((unsigned char)domain[i])) {
  7816. return 0;
  7817. }
  7818. }
  7819. if (domain[i]) {
  7820. return 0;
  7821. }
  7822. /* The maximum length of the path to the password file is limited */
  7823. if ((strlen(fname) + 4) >= PATH_MAX) {
  7824. return 0;
  7825. }
  7826. /* Create a temporary file name. Length has been checked before. */
  7827. strcpy(tmp, fname);
  7828. strcat(tmp, ".tmp");
  7829. /* Create the file if does not exist */
  7830. /* Use of fopen here is OK, since fname is only ASCII */
  7831. if ((fp = fopen(fname, "a+")) != NULL) {
  7832. (void)fclose(fp);
  7833. }
  7834. /* Open the given file and temporary file */
  7835. if ((fp = fopen(fname, "r")) == NULL) {
  7836. return 0;
  7837. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7838. fclose(fp);
  7839. return 0;
  7840. }
  7841. /* Copy the stuff to temporary file */
  7842. while (fgets(line, sizeof(line), fp) != NULL) {
  7843. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7844. continue;
  7845. }
  7846. u[255] = 0;
  7847. d[255] = 0;
  7848. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7849. found++;
  7850. if (pass != NULL) {
  7851. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7852. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7853. }
  7854. } else {
  7855. fprintf(fp2, "%s", line);
  7856. }
  7857. }
  7858. /* If new user, just add it */
  7859. if (!found && (pass != NULL)) {
  7860. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7861. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7862. }
  7863. /* Close files */
  7864. fclose(fp);
  7865. fclose(fp2);
  7866. /* Put the temp file in place of real file */
  7867. IGNORE_UNUSED_RESULT(remove(fname));
  7868. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7869. return 1;
  7870. }
  7871. static int
  7872. is_valid_port(unsigned long port)
  7873. {
  7874. return (port <= 0xffff);
  7875. }
  7876. static int
  7877. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7878. {
  7879. struct addrinfo hints, *res, *ressave;
  7880. int func_ret = 0;
  7881. int gai_ret;
  7882. memset(&hints, 0, sizeof(struct addrinfo));
  7883. hints.ai_family = af;
  7884. if (!resolve_src) {
  7885. hints.ai_flags = AI_NUMERICHOST;
  7886. }
  7887. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7888. if (gai_ret != 0) {
  7889. /* gai_strerror could be used to convert gai_ret to a string */
  7890. /* POSIX return values: see
  7891. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7892. */
  7893. /* Windows return values: see
  7894. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7895. */
  7896. return 0;
  7897. }
  7898. ressave = res;
  7899. while (res) {
  7900. if ((dstlen >= (size_t)res->ai_addrlen)
  7901. && (res->ai_addr->sa_family == af)) {
  7902. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7903. func_ret = 1;
  7904. }
  7905. res = res->ai_next;
  7906. }
  7907. freeaddrinfo(ressave);
  7908. return func_ret;
  7909. }
  7910. static int
  7911. connect_socket(struct mg_context *ctx /* may be NULL */,
  7912. const char *host,
  7913. int port,
  7914. int use_ssl,
  7915. char *ebuf,
  7916. size_t ebuf_len,
  7917. SOCKET *sock /* output: socket, must not be NULL */,
  7918. union usa *sa /* output: socket address, must not be NULL */
  7919. )
  7920. {
  7921. int ip_ver = 0;
  7922. int conn_ret = -1;
  7923. int sockerr = 0;
  7924. *sock = INVALID_SOCKET;
  7925. memset(sa, 0, sizeof(*sa));
  7926. if (ebuf_len > 0) {
  7927. *ebuf = 0;
  7928. }
  7929. if (host == NULL) {
  7930. mg_snprintf(NULL,
  7931. NULL, /* No truncation check for ebuf */
  7932. ebuf,
  7933. ebuf_len,
  7934. "%s",
  7935. "NULL host");
  7936. return 0;
  7937. }
  7938. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7939. mg_snprintf(NULL,
  7940. NULL, /* No truncation check for ebuf */
  7941. ebuf,
  7942. ebuf_len,
  7943. "%s",
  7944. "invalid port");
  7945. return 0;
  7946. }
  7947. #if !defined(NO_SSL)
  7948. #if !defined(NO_SSL_DL)
  7949. #if defined(OPENSSL_API_1_1)
  7950. if (use_ssl && (TLS_client_method == NULL)) {
  7951. mg_snprintf(NULL,
  7952. NULL, /* No truncation check for ebuf */
  7953. ebuf,
  7954. ebuf_len,
  7955. "%s",
  7956. "SSL is not initialized");
  7957. return 0;
  7958. }
  7959. #else
  7960. if (use_ssl && (SSLv23_client_method == NULL)) {
  7961. mg_snprintf(NULL,
  7962. NULL, /* No truncation check for ebuf */
  7963. ebuf,
  7964. ebuf_len,
  7965. "%s",
  7966. "SSL is not initialized");
  7967. return 0;
  7968. }
  7969. #endif /* OPENSSL_API_1_1 */
  7970. #else
  7971. (void)use_ssl;
  7972. #endif /* NO_SSL_DL */
  7973. #else
  7974. (void)use_ssl;
  7975. #endif /* !defined(NO_SSL) */
  7976. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7977. sa->sin.sin_port = htons((uint16_t)port);
  7978. ip_ver = 4;
  7979. #if defined(USE_IPV6)
  7980. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7981. sa->sin6.sin6_port = htons((uint16_t)port);
  7982. ip_ver = 6;
  7983. } else if (host[0] == '[') {
  7984. /* While getaddrinfo on Windows will work with [::1],
  7985. * getaddrinfo on Linux only works with ::1 (without []). */
  7986. size_t l = strlen(host + 1);
  7987. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7988. if (h) {
  7989. h[l - 1] = 0;
  7990. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7991. sa->sin6.sin6_port = htons((uint16_t)port);
  7992. ip_ver = 6;
  7993. }
  7994. mg_free(h);
  7995. }
  7996. #endif
  7997. }
  7998. if (ip_ver == 0) {
  7999. mg_snprintf(NULL,
  8000. NULL, /* No truncation check for ebuf */
  8001. ebuf,
  8002. ebuf_len,
  8003. "%s",
  8004. "host not found");
  8005. return 0;
  8006. }
  8007. if (ip_ver == 4) {
  8008. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8009. }
  8010. #if defined(USE_IPV6)
  8011. else if (ip_ver == 6) {
  8012. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8013. }
  8014. #endif
  8015. if (*sock == INVALID_SOCKET) {
  8016. mg_snprintf(NULL,
  8017. NULL, /* No truncation check for ebuf */
  8018. ebuf,
  8019. ebuf_len,
  8020. "socket(): %s",
  8021. strerror(ERRNO));
  8022. return 0;
  8023. }
  8024. if (0 != set_non_blocking_mode(*sock)) {
  8025. mg_snprintf(NULL,
  8026. NULL, /* No truncation check for ebuf */
  8027. ebuf,
  8028. ebuf_len,
  8029. "Cannot set socket to non-blocking: %s",
  8030. strerror(ERRNO));
  8031. closesocket(*sock);
  8032. *sock = INVALID_SOCKET;
  8033. return 0;
  8034. }
  8035. set_close_on_exec(*sock, NULL, ctx);
  8036. if (ip_ver == 4) {
  8037. /* connected with IPv4 */
  8038. conn_ret = connect(*sock,
  8039. (struct sockaddr *)((void *)&sa->sin),
  8040. sizeof(sa->sin));
  8041. }
  8042. #if defined(USE_IPV6)
  8043. else if (ip_ver == 6) {
  8044. /* connected with IPv6 */
  8045. conn_ret = connect(*sock,
  8046. (struct sockaddr *)((void *)&sa->sin6),
  8047. sizeof(sa->sin6));
  8048. }
  8049. #endif
  8050. if (conn_ret != 0) {
  8051. sockerr = ERRNO;
  8052. }
  8053. #if defined(_WIN32)
  8054. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8055. #else
  8056. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8057. #endif
  8058. /* Data for getsockopt */
  8059. void *psockerr = &sockerr;
  8060. int ret;
  8061. #if defined(_WIN32)
  8062. int len = (int)sizeof(sockerr);
  8063. #else
  8064. socklen_t len = (socklen_t)sizeof(sockerr);
  8065. #endif
  8066. /* Data for poll */
  8067. struct mg_pollfd pfd[1];
  8068. int pollres;
  8069. int ms_wait = 10000; /* 10 second timeout */
  8070. stop_flag_t nonstop;
  8071. STOP_FLAG_ASSIGN(&nonstop, 0);
  8072. /* For a non-blocking socket, the connect sequence is:
  8073. * 1) call connect (will not block)
  8074. * 2) wait until the socket is ready for writing (select or poll)
  8075. * 3) check connection state with getsockopt
  8076. */
  8077. pfd[0].fd = *sock;
  8078. pfd[0].events = POLLOUT;
  8079. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8080. if (pollres != 1) {
  8081. /* Not connected */
  8082. mg_snprintf(NULL,
  8083. NULL, /* No truncation check for ebuf */
  8084. ebuf,
  8085. ebuf_len,
  8086. "connect(%s:%d): timeout",
  8087. host,
  8088. port);
  8089. closesocket(*sock);
  8090. *sock = INVALID_SOCKET;
  8091. return 0;
  8092. }
  8093. #if defined(_WIN32)
  8094. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8095. #else
  8096. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8097. #endif
  8098. if ((ret == 0) && (sockerr == 0)) {
  8099. conn_ret = 0;
  8100. }
  8101. }
  8102. if (conn_ret != 0) {
  8103. /* Not connected */
  8104. mg_snprintf(NULL,
  8105. NULL, /* No truncation check for ebuf */
  8106. ebuf,
  8107. ebuf_len,
  8108. "connect(%s:%d): error %s",
  8109. host,
  8110. port,
  8111. strerror(sockerr));
  8112. closesocket(*sock);
  8113. *sock = INVALID_SOCKET;
  8114. return 0;
  8115. }
  8116. return 1;
  8117. }
  8118. int
  8119. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8120. {
  8121. static const char *dont_escape = "._-$,;~()";
  8122. static const char *hex = "0123456789abcdef";
  8123. char *pos = dst;
  8124. const char *end = dst + dst_len - 1;
  8125. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8126. if (isalnum((unsigned char)*src)
  8127. || (strchr(dont_escape, *src) != NULL)) {
  8128. *pos = *src;
  8129. } else if (pos + 2 < end) {
  8130. pos[0] = '%';
  8131. pos[1] = hex[(unsigned char)*src >> 4];
  8132. pos[2] = hex[(unsigned char)*src & 0xf];
  8133. pos += 2;
  8134. } else {
  8135. break;
  8136. }
  8137. }
  8138. *pos = '\0';
  8139. return (*src == '\0') ? (int)(pos - dst) : -1;
  8140. }
  8141. /* Return 0 on success, non-zero if an error occurs. */
  8142. static int
  8143. print_dir_entry(struct de *de)
  8144. {
  8145. size_t namesize, escsize, i;
  8146. char *href, *esc, *p;
  8147. char size[64], mod[64];
  8148. #if defined(REENTRANT_TIME)
  8149. struct tm _tm;
  8150. struct tm *tm = &_tm;
  8151. #else
  8152. struct tm *tm;
  8153. #endif
  8154. /* Estimate worst case size for encoding and escaping */
  8155. namesize = strlen(de->file_name) + 1;
  8156. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8157. href = (char *)mg_malloc(namesize * 3 + escsize);
  8158. if (href == NULL) {
  8159. return -1;
  8160. }
  8161. mg_url_encode(de->file_name, href, namesize * 3);
  8162. esc = NULL;
  8163. if (escsize > 0) {
  8164. /* HTML escaping needed */
  8165. esc = href + namesize * 3;
  8166. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8167. mg_strlcpy(p, de->file_name + i, 2);
  8168. if (*p == '&') {
  8169. strcpy(p, "&amp;");
  8170. } else if (*p == '<') {
  8171. strcpy(p, "&lt;");
  8172. } else if (*p == '>') {
  8173. strcpy(p, "&gt;");
  8174. }
  8175. }
  8176. }
  8177. if (de->file.is_directory) {
  8178. mg_snprintf(de->conn,
  8179. NULL, /* Buffer is big enough */
  8180. size,
  8181. sizeof(size),
  8182. "%s",
  8183. "[DIRECTORY]");
  8184. } else {
  8185. /* We use (signed) cast below because MSVC 6 compiler cannot
  8186. * convert unsigned __int64 to double. Sigh. */
  8187. if (de->file.size < 1024) {
  8188. mg_snprintf(de->conn,
  8189. NULL, /* Buffer is big enough */
  8190. size,
  8191. sizeof(size),
  8192. "%d",
  8193. (int)de->file.size);
  8194. } else if (de->file.size < 0x100000) {
  8195. mg_snprintf(de->conn,
  8196. NULL, /* Buffer is big enough */
  8197. size,
  8198. sizeof(size),
  8199. "%.1fk",
  8200. (double)de->file.size / 1024.0);
  8201. } else if (de->file.size < 0x40000000) {
  8202. mg_snprintf(de->conn,
  8203. NULL, /* Buffer is big enough */
  8204. size,
  8205. sizeof(size),
  8206. "%.1fM",
  8207. (double)de->file.size / 1048576);
  8208. } else {
  8209. mg_snprintf(de->conn,
  8210. NULL, /* Buffer is big enough */
  8211. size,
  8212. sizeof(size),
  8213. "%.1fG",
  8214. (double)de->file.size / 1073741824);
  8215. }
  8216. }
  8217. /* Note: mg_snprintf will not cause a buffer overflow above.
  8218. * So, string truncation checks are not required here. */
  8219. #if defined(REENTRANT_TIME)
  8220. localtime_r(&de->file.last_modified, tm);
  8221. #else
  8222. tm = localtime(&de->file.last_modified);
  8223. #endif
  8224. if (tm != NULL) {
  8225. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8226. } else {
  8227. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8228. mod[sizeof(mod) - 1] = '\0';
  8229. }
  8230. mg_printf(de->conn,
  8231. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8232. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8233. href,
  8234. de->file.is_directory ? "/" : "",
  8235. esc ? esc : de->file_name,
  8236. de->file.is_directory ? "/" : "",
  8237. mod,
  8238. size);
  8239. mg_free(href);
  8240. return 0;
  8241. }
  8242. /* This function is called from send_directory() and used for
  8243. * sorting directory entries by size, or name, or modification time.
  8244. * On windows, __cdecl specification is needed in case if project is built
  8245. * with __stdcall convention. qsort always requires __cdels callback. */
  8246. static int WINCDECL
  8247. compare_dir_entries(const void *p1, const void *p2)
  8248. {
  8249. if (p1 && p2) {
  8250. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8251. const char *query_string = a->conn->request_info.query_string;
  8252. int cmp_result = 0;
  8253. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8254. query_string = "n";
  8255. }
  8256. if (a->file.is_directory && !b->file.is_directory) {
  8257. return -1; /* Always put directories on top */
  8258. } else if (!a->file.is_directory && b->file.is_directory) {
  8259. return 1; /* Always put directories on top */
  8260. } else if (*query_string == 'n') {
  8261. cmp_result = strcmp(a->file_name, b->file_name);
  8262. } else if (*query_string == 's') {
  8263. cmp_result = (a->file.size == b->file.size)
  8264. ? 0
  8265. : ((a->file.size > b->file.size) ? 1 : -1);
  8266. } else if (*query_string == 'd') {
  8267. cmp_result =
  8268. (a->file.last_modified == b->file.last_modified)
  8269. ? 0
  8270. : ((a->file.last_modified > b->file.last_modified) ? 1
  8271. : -1);
  8272. }
  8273. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8274. }
  8275. return 0;
  8276. }
  8277. static int
  8278. must_hide_file(struct mg_connection *conn, const char *path)
  8279. {
  8280. if (conn && conn->dom_ctx) {
  8281. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8282. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8283. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8284. || ((pattern != NULL)
  8285. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8286. }
  8287. return 0;
  8288. }
  8289. #if !defined(NO_FILESYSTEMS)
  8290. static int
  8291. scan_directory(struct mg_connection *conn,
  8292. const char *dir,
  8293. void *data,
  8294. int (*cb)(struct de *, void *))
  8295. {
  8296. char path[PATH_MAX];
  8297. struct dirent *dp;
  8298. DIR *dirp;
  8299. struct de de;
  8300. int truncated;
  8301. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8302. return 0;
  8303. } else {
  8304. de.conn = conn;
  8305. while ((dp = mg_readdir(dirp)) != NULL) {
  8306. /* Do not show current dir and hidden files */
  8307. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8308. || must_hide_file(conn, dp->d_name)) {
  8309. continue;
  8310. }
  8311. mg_snprintf(
  8312. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8313. /* If we don't memset stat structure to zero, mtime will have
  8314. * garbage and strftime() will segfault later on in
  8315. * print_dir_entry(). memset is required only if mg_stat()
  8316. * fails. For more details, see
  8317. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8318. memset(&de.file, 0, sizeof(de.file));
  8319. if (truncated) {
  8320. /* If the path is not complete, skip processing. */
  8321. continue;
  8322. }
  8323. if (!mg_stat(conn, path, &de.file)) {
  8324. mg_cry_internal(conn,
  8325. "%s: mg_stat(%s) failed: %s",
  8326. __func__,
  8327. path,
  8328. strerror(ERRNO));
  8329. }
  8330. de.file_name = dp->d_name;
  8331. if (cb(&de, data)) {
  8332. /* stopped */
  8333. break;
  8334. }
  8335. }
  8336. (void)mg_closedir(dirp);
  8337. }
  8338. return 1;
  8339. }
  8340. #endif /* NO_FILESYSTEMS */
  8341. #if !defined(NO_FILES)
  8342. static int
  8343. remove_directory(struct mg_connection *conn, const char *dir)
  8344. {
  8345. char path[PATH_MAX];
  8346. struct dirent *dp;
  8347. DIR *dirp;
  8348. struct de de;
  8349. int truncated;
  8350. int ok = 1;
  8351. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8352. return 0;
  8353. } else {
  8354. de.conn = conn;
  8355. while ((dp = mg_readdir(dirp)) != NULL) {
  8356. /* Do not show current dir (but show hidden files as they will
  8357. * also be removed) */
  8358. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8359. continue;
  8360. }
  8361. mg_snprintf(
  8362. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8363. /* If we don't memset stat structure to zero, mtime will have
  8364. * garbage and strftime() will segfault later on in
  8365. * print_dir_entry(). memset is required only if mg_stat()
  8366. * fails. For more details, see
  8367. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8368. memset(&de.file, 0, sizeof(de.file));
  8369. if (truncated) {
  8370. /* Do not delete anything shorter */
  8371. ok = 0;
  8372. continue;
  8373. }
  8374. if (!mg_stat(conn, path, &de.file)) {
  8375. mg_cry_internal(conn,
  8376. "%s: mg_stat(%s) failed: %s",
  8377. __func__,
  8378. path,
  8379. strerror(ERRNO));
  8380. ok = 0;
  8381. }
  8382. if (de.file.is_directory) {
  8383. if (remove_directory(conn, path) == 0) {
  8384. ok = 0;
  8385. }
  8386. } else {
  8387. /* This will fail file is the file is in memory */
  8388. if (mg_remove(conn, path) == 0) {
  8389. ok = 0;
  8390. }
  8391. }
  8392. }
  8393. (void)mg_closedir(dirp);
  8394. IGNORE_UNUSED_RESULT(rmdir(dir));
  8395. }
  8396. return ok;
  8397. }
  8398. #endif
  8399. struct dir_scan_data {
  8400. struct de *entries;
  8401. size_t num_entries;
  8402. size_t arr_size;
  8403. };
  8404. #if !defined(NO_FILESYSTEMS)
  8405. static int
  8406. dir_scan_callback(struct de *de, void *data)
  8407. {
  8408. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8409. struct de *entries = dsd->entries;
  8410. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8411. entries =
  8412. (struct de *)mg_realloc(entries,
  8413. dsd->arr_size * 2 * sizeof(entries[0]));
  8414. if (entries == NULL) {
  8415. /* stop scan */
  8416. return 1;
  8417. }
  8418. dsd->entries = entries;
  8419. dsd->arr_size *= 2;
  8420. }
  8421. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8422. if (entries[dsd->num_entries].file_name == NULL) {
  8423. /* stop scan */
  8424. return 1;
  8425. }
  8426. entries[dsd->num_entries].file = de->file;
  8427. entries[dsd->num_entries].conn = de->conn;
  8428. dsd->num_entries++;
  8429. return 0;
  8430. }
  8431. static void
  8432. handle_directory_request(struct mg_connection *conn, const char *dir)
  8433. {
  8434. size_t i;
  8435. int sort_direction;
  8436. struct dir_scan_data data = {NULL, 0, 128};
  8437. char date[64], *esc, *p;
  8438. const char *title;
  8439. time_t curtime = time(NULL);
  8440. if (!conn) {
  8441. return;
  8442. }
  8443. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8444. mg_send_http_error(conn,
  8445. 500,
  8446. "Error: Cannot open directory\nopendir(%s): %s",
  8447. dir,
  8448. strerror(ERRNO));
  8449. return;
  8450. }
  8451. gmt_time_string(date, sizeof(date), &curtime);
  8452. esc = NULL;
  8453. title = conn->request_info.local_uri;
  8454. if (title[strcspn(title, "&<>")]) {
  8455. /* HTML escaping needed */
  8456. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8457. if (esc) {
  8458. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8459. mg_strlcpy(p, title + i, 2);
  8460. if (*p == '&') {
  8461. strcpy(p, "&amp;");
  8462. } else if (*p == '<') {
  8463. strcpy(p, "&lt;");
  8464. } else if (*p == '>') {
  8465. strcpy(p, "&gt;");
  8466. }
  8467. }
  8468. } else {
  8469. title = "";
  8470. }
  8471. }
  8472. sort_direction = ((conn->request_info.query_string != NULL)
  8473. && (conn->request_info.query_string[0] != '\0')
  8474. && (conn->request_info.query_string[1] == 'd'))
  8475. ? 'a'
  8476. : 'd';
  8477. conn->must_close = 1;
  8478. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8479. send_static_cache_header(conn);
  8480. send_additional_header(conn);
  8481. mg_printf(conn,
  8482. "Date: %s\r\n"
  8483. "Connection: close\r\n"
  8484. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8485. date);
  8486. mg_printf(conn,
  8487. "<html><head><title>Index of %s</title>"
  8488. "<style>th {text-align: left;}</style></head>"
  8489. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8490. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8491. "<th><a href=\"?d%c\">Modified</a></th>"
  8492. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8493. "<tr><td colspan=\"3\"><hr></td></tr>",
  8494. esc ? esc : title,
  8495. esc ? esc : title,
  8496. sort_direction,
  8497. sort_direction,
  8498. sort_direction);
  8499. mg_free(esc);
  8500. /* Print first entry - link to a parent directory */
  8501. mg_printf(conn,
  8502. "<tr><td><a href=\"%s\">%s</a></td>"
  8503. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8504. "..",
  8505. "Parent directory",
  8506. "-",
  8507. "-");
  8508. /* Sort and print directory entries */
  8509. if (data.entries != NULL) {
  8510. qsort(data.entries,
  8511. data.num_entries,
  8512. sizeof(data.entries[0]),
  8513. compare_dir_entries);
  8514. for (i = 0; i < data.num_entries; i++) {
  8515. print_dir_entry(&data.entries[i]);
  8516. mg_free(data.entries[i].file_name);
  8517. }
  8518. mg_free(data.entries);
  8519. }
  8520. mg_printf(conn, "%s", "</table></pre></body></html>");
  8521. conn->status_code = 200;
  8522. }
  8523. #endif /* NO_FILESYSTEMS */
  8524. /* Send len bytes from the opened file to the client. */
  8525. static void
  8526. send_file_data(struct mg_connection *conn,
  8527. struct mg_file *filep,
  8528. int64_t offset,
  8529. int64_t len)
  8530. {
  8531. char buf[MG_BUF_LEN];
  8532. int to_read, num_read, num_written;
  8533. int64_t size;
  8534. if (!filep || !conn) {
  8535. return;
  8536. }
  8537. /* Sanity check the offset */
  8538. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8539. : (int64_t)(filep->stat.size);
  8540. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8541. #if defined(MG_USE_OPEN_FILE)
  8542. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8543. /* file stored in memory */
  8544. if (len > size - offset) {
  8545. len = size - offset;
  8546. }
  8547. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8548. } else /* else block below */
  8549. #endif
  8550. if (len > 0 && filep->access.fp != NULL) {
  8551. /* file stored on disk */
  8552. #if defined(__linux__)
  8553. /* sendfile is only available for Linux */
  8554. if ((conn->ssl == 0) && (conn->throttle == 0)
  8555. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8556. "yes"))) {
  8557. off_t sf_offs = (off_t)offset;
  8558. ssize_t sf_sent;
  8559. int sf_file = fileno(filep->access.fp);
  8560. int loop_cnt = 0;
  8561. do {
  8562. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8563. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8564. size_t sf_tosend =
  8565. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8566. sf_sent =
  8567. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8568. if (sf_sent > 0) {
  8569. len -= sf_sent;
  8570. offset += sf_sent;
  8571. } else if (loop_cnt == 0) {
  8572. /* This file can not be sent using sendfile.
  8573. * This might be the case for pseudo-files in the
  8574. * /sys/ and /proc/ file system.
  8575. * Use the regular user mode copy code instead. */
  8576. break;
  8577. } else if (sf_sent == 0) {
  8578. /* No error, but 0 bytes sent. May be EOF? */
  8579. return;
  8580. }
  8581. loop_cnt++;
  8582. } while ((len > 0) && (sf_sent >= 0));
  8583. if (sf_sent > 0) {
  8584. return; /* OK */
  8585. }
  8586. /* sf_sent<0 means error, thus fall back to the classic way */
  8587. /* This is always the case, if sf_file is not a "normal" file,
  8588. * e.g., for sending data from the output of a CGI process. */
  8589. offset = (int64_t)sf_offs;
  8590. }
  8591. #endif
  8592. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8593. mg_cry_internal(conn,
  8594. "%s: fseeko() failed: %s",
  8595. __func__,
  8596. strerror(ERRNO));
  8597. mg_send_http_error(
  8598. conn,
  8599. 500,
  8600. "%s",
  8601. "Error: Unable to access file at requested position.");
  8602. } else {
  8603. while (len > 0) {
  8604. /* Calculate how much to read from the file in the buffer */
  8605. to_read = sizeof(buf);
  8606. if ((int64_t)to_read > len) {
  8607. to_read = (int)len;
  8608. }
  8609. /* Read from file, exit the loop on error */
  8610. if ((num_read =
  8611. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8612. <= 0) {
  8613. break;
  8614. }
  8615. /* Send read bytes to the client, exit the loop on error */
  8616. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8617. != num_read) {
  8618. break;
  8619. }
  8620. /* Both read and were successful, adjust counters */
  8621. len -= num_written;
  8622. }
  8623. }
  8624. }
  8625. }
  8626. static int
  8627. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8628. {
  8629. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8630. }
  8631. static void
  8632. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8633. {
  8634. if ((filestat != NULL) && (buf != NULL)) {
  8635. mg_snprintf(NULL,
  8636. NULL, /* All calls to construct_etag use 64 byte buffer */
  8637. buf,
  8638. buf_len,
  8639. "\"%lx.%" INT64_FMT "\"",
  8640. (unsigned long)filestat->last_modified,
  8641. filestat->size);
  8642. }
  8643. }
  8644. static void
  8645. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8646. {
  8647. if (filep != NULL && filep->fp != NULL) {
  8648. #if defined(_WIN32)
  8649. (void)conn; /* Unused. */
  8650. #else
  8651. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8652. mg_cry_internal(conn,
  8653. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8654. __func__,
  8655. strerror(ERRNO));
  8656. }
  8657. #endif
  8658. }
  8659. }
  8660. #if defined(USE_ZLIB)
  8661. #include "mod_zlib.inl"
  8662. #endif
  8663. #if !defined(NO_FILESYSTEMS)
  8664. static void
  8665. handle_static_file_request(struct mg_connection *conn,
  8666. const char *path,
  8667. struct mg_file *filep,
  8668. const char *mime_type,
  8669. const char *additional_headers)
  8670. {
  8671. char date[64], lm[64], etag[64];
  8672. char range[128]; /* large enough, so there will be no overflow */
  8673. const char *msg = "OK";
  8674. const char *range_hdr;
  8675. time_t curtime = time(NULL);
  8676. int64_t cl, r1, r2;
  8677. struct vec mime_vec;
  8678. int n, truncated;
  8679. char gz_path[PATH_MAX];
  8680. const char *encoding = "";
  8681. const char *origin_hdr;
  8682. const char *cors_orig_cfg;
  8683. const char *cors1, *cors2, *cors3;
  8684. int is_head_request;
  8685. #if defined(USE_ZLIB)
  8686. /* Compression is allowed, unless there is a reason not to use
  8687. * compression. If the file is already compressed, too small or a
  8688. * "range" request was made, on the fly compression is not possible. */
  8689. int allow_on_the_fly_compression = 1;
  8690. #endif
  8691. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8692. return;
  8693. }
  8694. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8695. if (mime_type == NULL) {
  8696. get_mime_type(conn, path, &mime_vec);
  8697. } else {
  8698. mime_vec.ptr = mime_type;
  8699. mime_vec.len = strlen(mime_type);
  8700. }
  8701. if (filep->stat.size > INT64_MAX) {
  8702. mg_send_http_error(conn,
  8703. 500,
  8704. "Error: File size is too large to send\n%" INT64_FMT,
  8705. filep->stat.size);
  8706. return;
  8707. }
  8708. cl = (int64_t)filep->stat.size;
  8709. conn->status_code = 200;
  8710. range[0] = '\0';
  8711. #if defined(USE_ZLIB)
  8712. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8713. * it's important to rewrite the filename after resolving
  8714. * the mime type from it, to preserve the actual file's type */
  8715. if (!conn->accept_gzip) {
  8716. allow_on_the_fly_compression = 0;
  8717. }
  8718. #endif
  8719. /* Check if there is a range header */
  8720. range_hdr = mg_get_header(conn, "Range");
  8721. /* For gzipped files, add *.gz */
  8722. if (filep->stat.is_gzipped) {
  8723. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8724. if (truncated) {
  8725. mg_send_http_error(conn,
  8726. 500,
  8727. "Error: Path of zipped file too long (%s)",
  8728. path);
  8729. return;
  8730. }
  8731. path = gz_path;
  8732. encoding = "Content-Encoding: gzip\r\n";
  8733. #if defined(USE_ZLIB)
  8734. /* File is already compressed. No "on the fly" compression. */
  8735. allow_on_the_fly_compression = 0;
  8736. #endif
  8737. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8738. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8739. struct mg_file_stat file_stat;
  8740. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8741. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8742. && !file_stat.is_directory) {
  8743. file_stat.is_gzipped = 1;
  8744. filep->stat = file_stat;
  8745. cl = (int64_t)filep->stat.size;
  8746. path = gz_path;
  8747. encoding = "Content-Encoding: gzip\r\n";
  8748. #if defined(USE_ZLIB)
  8749. /* File is already compressed. No "on the fly" compression. */
  8750. allow_on_the_fly_compression = 0;
  8751. #endif
  8752. }
  8753. }
  8754. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8755. mg_send_http_error(conn,
  8756. 500,
  8757. "Error: Cannot open file\nfopen(%s): %s",
  8758. path,
  8759. strerror(ERRNO));
  8760. return;
  8761. }
  8762. fclose_on_exec(&filep->access, conn);
  8763. /* If "Range" request was made: parse header, send only selected part
  8764. * of the file. */
  8765. r1 = r2 = 0;
  8766. if ((range_hdr != NULL)
  8767. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8768. && (r2 >= 0)) {
  8769. /* actually, range requests don't play well with a pre-gzipped
  8770. * file (since the range is specified in the uncompressed space) */
  8771. if (filep->stat.is_gzipped) {
  8772. mg_send_http_error(
  8773. conn,
  8774. 416, /* 416 = Range Not Satisfiable */
  8775. "%s",
  8776. "Error: Range requests in gzipped files are not supported");
  8777. (void)mg_fclose(
  8778. &filep->access); /* ignore error on read only file */
  8779. return;
  8780. }
  8781. conn->status_code = 206;
  8782. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8783. mg_snprintf(conn,
  8784. NULL, /* range buffer is big enough */
  8785. range,
  8786. sizeof(range),
  8787. "Content-Range: bytes "
  8788. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8789. r1,
  8790. r1 + cl - 1,
  8791. filep->stat.size);
  8792. msg = "Partial Content";
  8793. #if defined(USE_ZLIB)
  8794. /* Do not compress ranges. */
  8795. allow_on_the_fly_compression = 0;
  8796. #endif
  8797. }
  8798. /* Do not compress small files. Small files do not benefit from file
  8799. * compression, but there is still some overhead. */
  8800. #if defined(USE_ZLIB)
  8801. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8802. /* File is below the size limit. */
  8803. allow_on_the_fly_compression = 0;
  8804. }
  8805. #endif
  8806. /* Standard CORS header */
  8807. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8808. origin_hdr = mg_get_header(conn, "Origin");
  8809. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8810. /* Cross-origin resource sharing (CORS), see
  8811. * http://www.html5rocks.com/en/tutorials/cors/,
  8812. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8813. * -
  8814. * preflight is not supported for files. */
  8815. cors1 = "Access-Control-Allow-Origin: ";
  8816. cors2 = cors_orig_cfg;
  8817. cors3 = "\r\n";
  8818. } else {
  8819. cors1 = cors2 = cors3 = "";
  8820. }
  8821. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8822. * according to
  8823. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8824. gmt_time_string(date, sizeof(date), &curtime);
  8825. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8826. construct_etag(etag, sizeof(etag), &filep->stat);
  8827. /* Send header */
  8828. (void)mg_printf(conn,
  8829. "HTTP/1.1 %d %s\r\n"
  8830. "%s%s%s" /* CORS */
  8831. "Date: %s\r\n"
  8832. "Last-Modified: %s\r\n"
  8833. "Etag: %s\r\n"
  8834. "Content-Type: %.*s\r\n"
  8835. "Connection: %s\r\n",
  8836. conn->status_code,
  8837. msg,
  8838. cors1,
  8839. cors2,
  8840. cors3,
  8841. date,
  8842. lm,
  8843. etag,
  8844. (int)mime_vec.len,
  8845. mime_vec.ptr,
  8846. suggest_connection_header(conn));
  8847. send_static_cache_header(conn);
  8848. send_additional_header(conn);
  8849. #if defined(USE_ZLIB)
  8850. /* On the fly compression allowed */
  8851. if (allow_on_the_fly_compression) {
  8852. /* For on the fly compression, we don't know the content size in
  8853. * advance, so we have to use chunked encoding */
  8854. (void)mg_printf(conn,
  8855. "Content-Encoding: gzip\r\n"
  8856. "Transfer-Encoding: chunked\r\n");
  8857. } else
  8858. #endif
  8859. {
  8860. /* Without on-the-fly compression, we know the content-length
  8861. * and we can use ranges (with on-the-fly compression we cannot).
  8862. * So we send these response headers only in this case. */
  8863. (void)mg_printf(conn,
  8864. "Content-Length: %" INT64_FMT "\r\n"
  8865. "Accept-Ranges: bytes\r\n"
  8866. "%s" /* range */
  8867. "%s" /* encoding */,
  8868. cl,
  8869. range,
  8870. encoding);
  8871. }
  8872. /* The previous code must not add any header starting with X- to make
  8873. * sure no one of the additional_headers is included twice */
  8874. if (additional_headers != NULL) {
  8875. (void)mg_printf(conn,
  8876. "%.*s\r\n\r\n",
  8877. (int)strlen(additional_headers),
  8878. additional_headers);
  8879. } else {
  8880. (void)mg_printf(conn, "\r\n");
  8881. }
  8882. if (!is_head_request) {
  8883. #if defined(USE_ZLIB)
  8884. if (allow_on_the_fly_compression) {
  8885. /* Compress and send */
  8886. send_compressed_data(conn, filep);
  8887. } else
  8888. #endif
  8889. {
  8890. /* Send file directly */
  8891. send_file_data(conn, filep, r1, cl);
  8892. }
  8893. }
  8894. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8895. }
  8896. int
  8897. mg_send_file_body(struct mg_connection *conn, const char *path)
  8898. {
  8899. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8900. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8901. return -1;
  8902. }
  8903. fclose_on_exec(&file.access, conn);
  8904. send_file_data(conn, &file, 0, INT64_MAX);
  8905. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8906. return 0; /* >= 0 for OK */
  8907. }
  8908. #endif /* NO_FILESYSTEMS */
  8909. #if !defined(NO_CACHING)
  8910. /* Return True if we should reply 304 Not Modified. */
  8911. static int
  8912. is_not_modified(const struct mg_connection *conn,
  8913. const struct mg_file_stat *filestat)
  8914. {
  8915. char etag[64];
  8916. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8917. const char *inm = mg_get_header(conn, "If-None-Match");
  8918. construct_etag(etag, sizeof(etag), filestat);
  8919. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8920. || ((ims != NULL)
  8921. && (filestat->last_modified <= parse_date_string(ims)));
  8922. }
  8923. static void
  8924. handle_not_modified_static_file_request(struct mg_connection *conn,
  8925. struct mg_file *filep)
  8926. {
  8927. char date[64], lm[64], etag[64];
  8928. time_t curtime = time(NULL);
  8929. if ((conn == NULL) || (filep == NULL)) {
  8930. return;
  8931. }
  8932. conn->status_code = 304;
  8933. gmt_time_string(date, sizeof(date), &curtime);
  8934. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8935. construct_etag(etag, sizeof(etag), &filep->stat);
  8936. (void)mg_printf(conn,
  8937. "HTTP/1.1 %d %s\r\n"
  8938. "Date: %s\r\n",
  8939. conn->status_code,
  8940. mg_get_response_code_text(conn, conn->status_code),
  8941. date);
  8942. send_static_cache_header(conn);
  8943. send_additional_header(conn);
  8944. (void)mg_printf(conn,
  8945. "Last-Modified: %s\r\n"
  8946. "Etag: %s\r\n"
  8947. "Connection: %s\r\n"
  8948. "\r\n",
  8949. lm,
  8950. etag,
  8951. suggest_connection_header(conn));
  8952. }
  8953. #endif
  8954. #if !defined(NO_FILESYSTEMS)
  8955. void
  8956. mg_send_file(struct mg_connection *conn, const char *path)
  8957. {
  8958. mg_send_mime_file2(conn, path, NULL, NULL);
  8959. }
  8960. void
  8961. mg_send_mime_file(struct mg_connection *conn,
  8962. const char *path,
  8963. const char *mime_type)
  8964. {
  8965. mg_send_mime_file2(conn, path, mime_type, NULL);
  8966. }
  8967. void
  8968. mg_send_mime_file2(struct mg_connection *conn,
  8969. const char *path,
  8970. const char *mime_type,
  8971. const char *additional_headers)
  8972. {
  8973. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8974. if (!conn) {
  8975. /* No conn */
  8976. return;
  8977. }
  8978. if (mg_stat(conn, path, &file.stat)) {
  8979. #if !defined(NO_CACHING)
  8980. if (is_not_modified(conn, &file.stat)) {
  8981. /* Send 304 "Not Modified" - this must not send any body data */
  8982. handle_not_modified_static_file_request(conn, &file);
  8983. } else
  8984. #endif /* NO_CACHING */
  8985. if (file.stat.is_directory) {
  8986. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8987. "yes")) {
  8988. handle_directory_request(conn, path);
  8989. } else {
  8990. mg_send_http_error(conn,
  8991. 403,
  8992. "%s",
  8993. "Error: Directory listing denied");
  8994. }
  8995. } else {
  8996. handle_static_file_request(
  8997. conn, path, &file, mime_type, additional_headers);
  8998. }
  8999. } else {
  9000. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9001. }
  9002. }
  9003. /* For a given PUT path, create all intermediate subdirectories.
  9004. * Return 0 if the path itself is a directory.
  9005. * Return 1 if the path leads to a file.
  9006. * Return -1 for if the path is too long.
  9007. * Return -2 if path can not be created.
  9008. */
  9009. static int
  9010. put_dir(struct mg_connection *conn, const char *path)
  9011. {
  9012. char buf[PATH_MAX];
  9013. const char *s, *p;
  9014. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9015. size_t len;
  9016. int res = 1;
  9017. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9018. len = (size_t)(p - path);
  9019. if (len >= sizeof(buf)) {
  9020. /* path too long */
  9021. res = -1;
  9022. break;
  9023. }
  9024. memcpy(buf, path, len);
  9025. buf[len] = '\0';
  9026. /* Try to create intermediate directory */
  9027. DEBUG_TRACE("mkdir(%s)", buf);
  9028. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9029. /* path does not exixt and can not be created */
  9030. res = -2;
  9031. break;
  9032. }
  9033. /* Is path itself a directory? */
  9034. if (p[1] == '\0') {
  9035. res = 0;
  9036. }
  9037. }
  9038. return res;
  9039. }
  9040. static void
  9041. remove_bad_file(const struct mg_connection *conn, const char *path)
  9042. {
  9043. int r = mg_remove(conn, path);
  9044. if (r != 0) {
  9045. mg_cry_internal(conn,
  9046. "%s: Cannot remove invalid file %s",
  9047. __func__,
  9048. path);
  9049. }
  9050. }
  9051. long long
  9052. mg_store_body(struct mg_connection *conn, const char *path)
  9053. {
  9054. char buf[MG_BUF_LEN];
  9055. long long len = 0;
  9056. int ret, n;
  9057. struct mg_file fi;
  9058. if (conn->consumed_content != 0) {
  9059. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9060. return -11;
  9061. }
  9062. ret = put_dir(conn, path);
  9063. if (ret < 0) {
  9064. /* -1 for path too long,
  9065. * -2 for path can not be created. */
  9066. return ret;
  9067. }
  9068. if (ret != 1) {
  9069. /* Return 0 means, path itself is a directory. */
  9070. return 0;
  9071. }
  9072. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9073. return -12;
  9074. }
  9075. ret = mg_read(conn, buf, sizeof(buf));
  9076. while (ret > 0) {
  9077. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9078. if (n != ret) {
  9079. (void)mg_fclose(
  9080. &fi.access); /* File is bad and will be removed anyway. */
  9081. remove_bad_file(conn, path);
  9082. return -13;
  9083. }
  9084. len += ret;
  9085. ret = mg_read(conn, buf, sizeof(buf));
  9086. }
  9087. /* File is open for writing. If fclose fails, there was probably an
  9088. * error flushing the buffer to disk, so the file on disk might be
  9089. * broken. Delete it and return an error to the caller. */
  9090. if (mg_fclose(&fi.access) != 0) {
  9091. remove_bad_file(conn, path);
  9092. return -14;
  9093. }
  9094. return len;
  9095. }
  9096. #endif /* NO_FILESYSTEMS */
  9097. /* Parse a buffer:
  9098. * Forward the string pointer till the end of a word, then
  9099. * terminate it and forward till the begin of the next word.
  9100. */
  9101. static int
  9102. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9103. {
  9104. /* Forward until a space is found - use isgraph here */
  9105. /* See http://www.cplusplus.com/reference/cctype/ */
  9106. while (isgraph((unsigned char)**ppw)) {
  9107. (*ppw)++;
  9108. }
  9109. /* Check end of word */
  9110. if (eol) {
  9111. /* must be a end of line */
  9112. if ((**ppw != '\r') && (**ppw != '\n')) {
  9113. return -1;
  9114. }
  9115. } else {
  9116. /* must be a end of a word, but not a line */
  9117. if (**ppw != ' ') {
  9118. return -1;
  9119. }
  9120. }
  9121. /* Terminate and forward to the next word */
  9122. do {
  9123. **ppw = 0;
  9124. (*ppw)++;
  9125. } while (isspace((unsigned char)**ppw));
  9126. /* Check after term */
  9127. if (!eol) {
  9128. /* if it's not the end of line, there must be a next word */
  9129. if (!isgraph((unsigned char)**ppw)) {
  9130. return -1;
  9131. }
  9132. }
  9133. /* ok */
  9134. return 1;
  9135. }
  9136. /* Parse HTTP headers from the given buffer, advance buf pointer
  9137. * to the point where parsing stopped.
  9138. * All parameters must be valid pointers (not NULL).
  9139. * Return <0 on error. */
  9140. static int
  9141. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9142. {
  9143. int i;
  9144. int num_headers = 0;
  9145. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9146. char *dp = *buf;
  9147. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9148. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9149. dp++;
  9150. }
  9151. if (dp == *buf) {
  9152. /* End of headers reached. */
  9153. break;
  9154. }
  9155. if (*dp != ':') {
  9156. /* This is not a valid field. */
  9157. return -1;
  9158. }
  9159. /* End of header key (*dp == ':') */
  9160. /* Truncate here and set the key name */
  9161. *dp = 0;
  9162. hdr[i].name = *buf;
  9163. /* Skip all spaces */
  9164. do {
  9165. dp++;
  9166. } while ((*dp == ' ') || (*dp == '\t'));
  9167. /* The rest of the line is the value */
  9168. hdr[i].value = dp;
  9169. /* Find end of line */
  9170. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9171. dp++;
  9172. };
  9173. /* eliminate \r */
  9174. if (*dp == '\r') {
  9175. *dp = 0;
  9176. dp++;
  9177. if (*dp != '\n') {
  9178. /* This is not a valid line. */
  9179. return -1;
  9180. }
  9181. }
  9182. /* here *dp is either 0 or '\n' */
  9183. /* in any case, we have a new header */
  9184. num_headers = i + 1;
  9185. if (*dp) {
  9186. *dp = 0;
  9187. dp++;
  9188. *buf = dp;
  9189. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9190. /* This is the end of the header */
  9191. break;
  9192. }
  9193. } else {
  9194. *buf = dp;
  9195. break;
  9196. }
  9197. }
  9198. return num_headers;
  9199. }
  9200. struct mg_http_method_info {
  9201. const char *name;
  9202. int request_has_body;
  9203. int response_has_body;
  9204. int is_safe;
  9205. int is_idempotent;
  9206. int is_cacheable;
  9207. };
  9208. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9209. static const struct mg_http_method_info http_methods[] = {
  9210. /* HTTP (RFC 2616) */
  9211. {"GET", 0, 1, 1, 1, 1},
  9212. {"POST", 1, 1, 0, 0, 0},
  9213. {"PUT", 1, 0, 0, 1, 0},
  9214. {"DELETE", 0, 0, 0, 1, 0},
  9215. {"HEAD", 0, 0, 1, 1, 1},
  9216. {"OPTIONS", 0, 0, 1, 1, 0},
  9217. {"CONNECT", 1, 1, 0, 0, 0},
  9218. /* TRACE method (RFC 2616) is not supported for security reasons */
  9219. /* PATCH method (RFC 5789) */
  9220. {"PATCH", 1, 0, 0, 0, 0},
  9221. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9222. /* WEBDAV (RFC 2518) */
  9223. {"PROPFIND", 0, 1, 1, 1, 0},
  9224. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9225. * Some PROPFIND results MAY be cached, with care,
  9226. * as there is no cache validation mechanism for
  9227. * most properties. This method is both safe and
  9228. * idempotent (see Section 9.1 of [RFC2616]). */
  9229. {"MKCOL", 0, 0, 0, 1, 0},
  9230. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9231. * When MKCOL is invoked without a request body,
  9232. * the newly created collection SHOULD have no
  9233. * members. A MKCOL request message may contain
  9234. * a message body. The precise behavior of a MKCOL
  9235. * request when the body is present is undefined,
  9236. * ... ==> We do not support MKCOL with body data.
  9237. * This method is idempotent, but not safe (see
  9238. * Section 9.1 of [RFC2616]). Responses to this
  9239. * method MUST NOT be cached. */
  9240. /* Unsupported WEBDAV Methods: */
  9241. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9242. /* + 11 methods from RFC 3253 */
  9243. /* ORDERPATCH (RFC 3648) */
  9244. /* ACL (RFC 3744) */
  9245. /* SEARCH (RFC 5323) */
  9246. /* + MicroSoft extensions
  9247. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9248. /* REPORT method (RFC 3253) */
  9249. {"REPORT", 1, 1, 1, 1, 1},
  9250. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9251. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9252. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9253. * to be useful for REST in case a "GET request with body" is
  9254. * required. */
  9255. {NULL, 0, 0, 0, 0, 0}
  9256. /* end of list */
  9257. };
  9258. static const struct mg_http_method_info *
  9259. get_http_method_info(const char *method)
  9260. {
  9261. /* Check if the method is known to the server. The list of all known
  9262. * HTTP methods can be found here at
  9263. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9264. */
  9265. const struct mg_http_method_info *m = http_methods;
  9266. while (m->name) {
  9267. if (!strcmp(m->name, method)) {
  9268. return m;
  9269. }
  9270. m++;
  9271. }
  9272. return NULL;
  9273. }
  9274. static int
  9275. is_valid_http_method(const char *method)
  9276. {
  9277. return (get_http_method_info(method) != NULL);
  9278. }
  9279. /* Parse HTTP request, fill in mg_request_info structure.
  9280. * This function modifies the buffer by NUL-terminating
  9281. * HTTP request components, header names and header values.
  9282. * Parameters:
  9283. * buf (in/out): pointer to the HTTP header to parse and split
  9284. * len (in): length of HTTP header buffer
  9285. * re (out): parsed header as mg_request_info
  9286. * buf and ri must be valid pointers (not NULL), len>0.
  9287. * Returns <0 on error. */
  9288. static int
  9289. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9290. {
  9291. int request_length;
  9292. int init_skip = 0;
  9293. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9294. * remote_port */
  9295. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9296. NULL;
  9297. ri->num_headers = 0;
  9298. /* RFC says that all initial whitespaces should be ingored */
  9299. /* This included all leading \r and \n (isspace) */
  9300. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9301. while ((len > 0) && isspace((unsigned char)*buf)) {
  9302. buf++;
  9303. len--;
  9304. init_skip++;
  9305. }
  9306. if (len == 0) {
  9307. /* Incomplete request */
  9308. return 0;
  9309. }
  9310. /* Control characters are not allowed, including zero */
  9311. if (iscntrl((unsigned char)*buf)) {
  9312. return -1;
  9313. }
  9314. /* Find end of HTTP header */
  9315. request_length = get_http_header_len(buf, len);
  9316. if (request_length <= 0) {
  9317. return request_length;
  9318. }
  9319. buf[request_length - 1] = '\0';
  9320. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9321. return -1;
  9322. }
  9323. /* The first word has to be the HTTP method */
  9324. ri->request_method = buf;
  9325. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9326. return -1;
  9327. }
  9328. /* Check for a valid http method */
  9329. if (!is_valid_http_method(ri->request_method)) {
  9330. return -1;
  9331. }
  9332. /* The second word is the URI */
  9333. ri->request_uri = buf;
  9334. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9335. return -1;
  9336. }
  9337. /* Next would be the HTTP version */
  9338. ri->http_version = buf;
  9339. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9340. return -1;
  9341. }
  9342. /* Check for a valid HTTP version key */
  9343. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9344. /* Invalid request */
  9345. return -1;
  9346. }
  9347. ri->http_version += 5;
  9348. /* Parse all HTTP headers */
  9349. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9350. if (ri->num_headers < 0) {
  9351. /* Error while parsing headers */
  9352. return -1;
  9353. }
  9354. return request_length + init_skip;
  9355. }
  9356. static int
  9357. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9358. {
  9359. int response_length;
  9360. int init_skip = 0;
  9361. char *tmp, *tmp2;
  9362. long l;
  9363. /* Initialize elements. */
  9364. ri->http_version = ri->status_text = NULL;
  9365. ri->num_headers = ri->status_code = 0;
  9366. /* RFC says that all initial whitespaces should be ingored */
  9367. /* This included all leading \r and \n (isspace) */
  9368. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9369. while ((len > 0) && isspace((unsigned char)*buf)) {
  9370. buf++;
  9371. len--;
  9372. init_skip++;
  9373. }
  9374. if (len == 0) {
  9375. /* Incomplete request */
  9376. return 0;
  9377. }
  9378. /* Control characters are not allowed, including zero */
  9379. if (iscntrl((unsigned char)*buf)) {
  9380. return -1;
  9381. }
  9382. /* Find end of HTTP header */
  9383. response_length = get_http_header_len(buf, len);
  9384. if (response_length <= 0) {
  9385. return response_length;
  9386. }
  9387. buf[response_length - 1] = '\0';
  9388. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9389. return -1;
  9390. }
  9391. /* The first word is the HTTP version */
  9392. /* Check for a valid HTTP version key */
  9393. if (strncmp(buf, "HTTP/", 5) != 0) {
  9394. /* Invalid request */
  9395. return -1;
  9396. }
  9397. buf += 5;
  9398. if (!isgraph((unsigned char)buf[0])) {
  9399. /* Invalid request */
  9400. return -1;
  9401. }
  9402. ri->http_version = buf;
  9403. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9404. return -1;
  9405. }
  9406. /* The second word is the status as a number */
  9407. tmp = buf;
  9408. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9409. return -1;
  9410. }
  9411. l = strtol(tmp, &tmp2, 10);
  9412. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9413. /* Everything else but a 3 digit code is invalid */
  9414. return -1;
  9415. }
  9416. ri->status_code = (int)l;
  9417. /* The rest of the line is the status text */
  9418. ri->status_text = buf;
  9419. /* Find end of status text */
  9420. /* isgraph or isspace = isprint */
  9421. while (isprint((unsigned char)*buf)) {
  9422. buf++;
  9423. }
  9424. if ((*buf != '\r') && (*buf != '\n')) {
  9425. return -1;
  9426. }
  9427. /* Terminate string and forward buf to next line */
  9428. do {
  9429. *buf = 0;
  9430. buf++;
  9431. } while (isspace((unsigned char)*buf));
  9432. /* Parse all HTTP headers */
  9433. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9434. if (ri->num_headers < 0) {
  9435. /* Error while parsing headers */
  9436. return -1;
  9437. }
  9438. return response_length + init_skip;
  9439. }
  9440. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9441. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9442. * buffer (which marks the end of HTTP request). Buffer buf may already
  9443. * have some data. The length of the data is stored in nread.
  9444. * Upon every read operation, increase nread by the number of bytes read. */
  9445. static int
  9446. read_message(FILE *fp,
  9447. struct mg_connection *conn,
  9448. char *buf,
  9449. int bufsiz,
  9450. int *nread)
  9451. {
  9452. int request_len, n = 0;
  9453. struct timespec last_action_time;
  9454. double request_timeout;
  9455. if (!conn) {
  9456. return 0;
  9457. }
  9458. memset(&last_action_time, 0, sizeof(last_action_time));
  9459. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9460. /* value of request_timeout is in seconds, config in milliseconds */
  9461. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9462. } else {
  9463. request_timeout = -1.0;
  9464. }
  9465. if (conn->handled_requests > 0) {
  9466. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9467. request_timeout =
  9468. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9469. }
  9470. }
  9471. request_len = get_http_header_len(buf, *nread);
  9472. while (request_len == 0) {
  9473. /* Full request not yet received */
  9474. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9475. /* Server is to be stopped. */
  9476. return -1;
  9477. }
  9478. if (*nread >= bufsiz) {
  9479. /* Request too long */
  9480. return -2;
  9481. }
  9482. n = pull_inner(
  9483. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9484. if (n == -2) {
  9485. /* Receive error */
  9486. return -1;
  9487. }
  9488. /* update clock after every read request */
  9489. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9490. if (n > 0) {
  9491. *nread += n;
  9492. request_len = get_http_header_len(buf, *nread);
  9493. }
  9494. if ((request_len == 0) && (request_timeout >= 0)) {
  9495. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9496. > request_timeout) {
  9497. /* Timeout */
  9498. return -1;
  9499. }
  9500. }
  9501. }
  9502. return request_len;
  9503. }
  9504. #if !defined(NO_CGI) || !defined(NO_FILES)
  9505. static int
  9506. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9507. {
  9508. const char *expect;
  9509. char buf[MG_BUF_LEN];
  9510. int success = 0;
  9511. if (!conn) {
  9512. return 0;
  9513. }
  9514. expect = mg_get_header(conn, "Expect");
  9515. DEBUG_ASSERT(fp != NULL);
  9516. if (!fp) {
  9517. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9518. return 0;
  9519. }
  9520. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9521. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9522. */
  9523. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9524. } else {
  9525. if (expect != NULL) {
  9526. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9527. conn->status_code = 100;
  9528. } else {
  9529. conn->status_code = 200;
  9530. }
  9531. DEBUG_ASSERT(conn->consumed_content == 0);
  9532. if (conn->consumed_content != 0) {
  9533. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9534. return 0;
  9535. }
  9536. for (;;) {
  9537. int nread = mg_read(conn, buf, sizeof(buf));
  9538. if (nread <= 0) {
  9539. success = (nread == 0);
  9540. break;
  9541. }
  9542. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9543. break;
  9544. }
  9545. }
  9546. /* Each error code path in this function must send an error */
  9547. if (!success) {
  9548. /* NOTE: Maybe some data has already been sent. */
  9549. /* TODO (low): If some data has been sent, a correct error
  9550. * reply can no longer be sent, so just close the connection */
  9551. mg_send_http_error(conn, 500, "%s", "");
  9552. }
  9553. }
  9554. return success;
  9555. }
  9556. #endif
  9557. #if defined(USE_TIMERS)
  9558. #define TIMER_API static
  9559. #include "timer.inl"
  9560. #endif /* USE_TIMERS */
  9561. #if !defined(NO_CGI)
  9562. /* This structure helps to create an environment for the spawned CGI
  9563. * program.
  9564. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9565. * last element must be NULL.
  9566. * However, on Windows there is a requirement that all these
  9567. * VARIABLE=VALUE\0
  9568. * strings must reside in a contiguous buffer. The end of the buffer is
  9569. * marked by two '\0' characters.
  9570. * We satisfy both worlds: we create an envp array (which is vars), all
  9571. * entries are actually pointers inside buf. */
  9572. struct cgi_environment {
  9573. struct mg_connection *conn;
  9574. /* Data block */
  9575. char *buf; /* Environment buffer */
  9576. size_t buflen; /* Space available in buf */
  9577. size_t bufused; /* Space taken in buf */
  9578. /* Index block */
  9579. char **var; /* char **envp */
  9580. size_t varlen; /* Number of variables available in var */
  9581. size_t varused; /* Number of variables stored in var */
  9582. };
  9583. static void addenv(struct cgi_environment *env,
  9584. PRINTF_FORMAT_STRING(const char *fmt),
  9585. ...) PRINTF_ARGS(2, 3);
  9586. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9587. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9588. static void
  9589. addenv(struct cgi_environment *env, const char *fmt, ...)
  9590. {
  9591. size_t i, n, space;
  9592. int truncated = 0;
  9593. char *added;
  9594. va_list ap;
  9595. if ((env->varlen - env->varused) < 2) {
  9596. mg_cry_internal(env->conn,
  9597. "%s: Cannot register CGI variable [%s]",
  9598. __func__,
  9599. fmt);
  9600. return;
  9601. }
  9602. /* Calculate how much space is left in the buffer */
  9603. space = (env->buflen - env->bufused);
  9604. do {
  9605. /* Space for "\0\0" is always needed. */
  9606. if (space <= 2) {
  9607. /* Allocate new buffer */
  9608. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9609. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9610. if (!added) {
  9611. /* Out of memory */
  9612. mg_cry_internal(
  9613. env->conn,
  9614. "%s: Cannot allocate memory for CGI variable [%s]",
  9615. __func__,
  9616. fmt);
  9617. return;
  9618. }
  9619. /* Retarget pointers */
  9620. env->buf = added;
  9621. env->buflen = n;
  9622. for (i = 0, n = 0; i < env->varused; i++) {
  9623. env->var[i] = added + n;
  9624. n += strlen(added + n) + 1;
  9625. }
  9626. space = (env->buflen - env->bufused);
  9627. }
  9628. /* Make a pointer to the free space int the buffer */
  9629. added = env->buf + env->bufused;
  9630. /* Copy VARIABLE=VALUE\0 string into the free space */
  9631. va_start(ap, fmt);
  9632. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9633. va_end(ap);
  9634. /* Do not add truncated strings to the environment */
  9635. if (truncated) {
  9636. /* Reallocate the buffer */
  9637. space = 0;
  9638. }
  9639. } while (truncated);
  9640. /* Calculate number of bytes added to the environment */
  9641. n = strlen(added) + 1;
  9642. env->bufused += n;
  9643. /* Append a pointer to the added string into the envp array */
  9644. env->var[env->varused] = added;
  9645. env->varused++;
  9646. }
  9647. /* Return 0 on success, non-zero if an error occurs. */
  9648. static int
  9649. prepare_cgi_environment(struct mg_connection *conn,
  9650. const char *prog,
  9651. struct cgi_environment *env)
  9652. {
  9653. const char *s;
  9654. struct vec var_vec;
  9655. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9656. int i, truncated, uri_len;
  9657. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9658. return -1;
  9659. }
  9660. env->conn = conn;
  9661. env->buflen = CGI_ENVIRONMENT_SIZE;
  9662. env->bufused = 0;
  9663. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9664. if (env->buf == NULL) {
  9665. mg_cry_internal(conn,
  9666. "%s: Not enough memory for environmental buffer",
  9667. __func__);
  9668. return -1;
  9669. }
  9670. env->varlen = MAX_CGI_ENVIR_VARS;
  9671. env->varused = 0;
  9672. env->var =
  9673. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9674. if (env->var == NULL) {
  9675. mg_cry_internal(conn,
  9676. "%s: Not enough memory for environmental variables",
  9677. __func__);
  9678. mg_free(env->buf);
  9679. return -1;
  9680. }
  9681. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9682. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9683. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9684. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9685. /* Prepare the environment block */
  9686. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9687. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9688. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9689. addenv(env, "SERVER_PORT=%d", ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)));
  9690. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9691. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9692. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9693. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9694. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9695. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9696. /* SCRIPT_NAME */
  9697. uri_len = (int)strlen(conn->request_info.local_uri);
  9698. if (conn->path_info == NULL) {
  9699. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9700. /* URI: /path_to_script/script.cgi */
  9701. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9702. } else {
  9703. /* URI: /path_to_script/ ... using index.cgi */
  9704. const char *index_file = strrchr(prog, '/');
  9705. if (index_file) {
  9706. addenv(env,
  9707. "SCRIPT_NAME=%s%s",
  9708. conn->request_info.local_uri,
  9709. index_file + 1);
  9710. }
  9711. }
  9712. } else {
  9713. /* URI: /path_to_script/script.cgi/path_info */
  9714. addenv(env,
  9715. "SCRIPT_NAME=%.*s",
  9716. uri_len - (int)strlen(conn->path_info),
  9717. conn->request_info.local_uri);
  9718. }
  9719. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9720. if (conn->path_info == NULL) {
  9721. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9722. } else {
  9723. addenv(env,
  9724. "PATH_TRANSLATED=%s%s",
  9725. conn->dom_ctx->config[DOCUMENT_ROOT],
  9726. conn->path_info);
  9727. }
  9728. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9729. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9730. addenv(env, "CONTENT_TYPE=%s", s);
  9731. }
  9732. if (conn->request_info.query_string != NULL) {
  9733. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9734. }
  9735. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9736. addenv(env, "CONTENT_LENGTH=%s", s);
  9737. }
  9738. if ((s = getenv("PATH")) != NULL) {
  9739. addenv(env, "PATH=%s", s);
  9740. }
  9741. if (conn->path_info != NULL) {
  9742. addenv(env, "PATH_INFO=%s", conn->path_info);
  9743. }
  9744. if (conn->status_code > 0) {
  9745. /* CGI error handler should show the status code */
  9746. addenv(env, "STATUS=%d", conn->status_code);
  9747. }
  9748. #if defined(_WIN32)
  9749. if ((s = getenv("COMSPEC")) != NULL) {
  9750. addenv(env, "COMSPEC=%s", s);
  9751. }
  9752. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9753. addenv(env, "SYSTEMROOT=%s", s);
  9754. }
  9755. if ((s = getenv("SystemDrive")) != NULL) {
  9756. addenv(env, "SystemDrive=%s", s);
  9757. }
  9758. if ((s = getenv("ProgramFiles")) != NULL) {
  9759. addenv(env, "ProgramFiles=%s", s);
  9760. }
  9761. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9762. addenv(env, "ProgramFiles(x86)=%s", s);
  9763. }
  9764. #else
  9765. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9766. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9767. }
  9768. #endif /* _WIN32 */
  9769. if ((s = getenv("PERLLIB")) != NULL) {
  9770. addenv(env, "PERLLIB=%s", s);
  9771. }
  9772. if (conn->request_info.remote_user != NULL) {
  9773. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9774. addenv(env, "%s", "AUTH_TYPE=Digest");
  9775. }
  9776. /* Add all headers as HTTP_* variables */
  9777. for (i = 0; i < conn->request_info.num_headers; i++) {
  9778. (void)mg_snprintf(conn,
  9779. &truncated,
  9780. http_var_name,
  9781. sizeof(http_var_name),
  9782. "HTTP_%s",
  9783. conn->request_info.http_headers[i].name);
  9784. if (truncated) {
  9785. mg_cry_internal(conn,
  9786. "%s: HTTP header variable too long [%s]",
  9787. __func__,
  9788. conn->request_info.http_headers[i].name);
  9789. continue;
  9790. }
  9791. /* Convert variable name into uppercase, and change - to _ */
  9792. for (p = http_var_name; *p != '\0'; p++) {
  9793. if (*p == '-') {
  9794. *p = '_';
  9795. }
  9796. *p = (char)toupper((unsigned char)*p);
  9797. }
  9798. addenv(env,
  9799. "%s=%s",
  9800. http_var_name,
  9801. conn->request_info.http_headers[i].value);
  9802. }
  9803. /* Add user-specified variables */
  9804. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9805. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9806. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9807. }
  9808. env->var[env->varused] = NULL;
  9809. env->buf[env->bufused] = '\0';
  9810. return 0;
  9811. }
  9812. /* Data for CGI process control: PID and number of references */
  9813. struct process_control_data {
  9814. pid_t pid;
  9815. int references;
  9816. };
  9817. static int
  9818. abort_process(void *data)
  9819. {
  9820. /* Waitpid checks for child status and won't work for a pid that does
  9821. * not identify a child of the current process. Thus, if the pid is
  9822. * reused, we will not affect a different process. */
  9823. struct process_control_data *proc = (struct process_control_data *)data;
  9824. int status = 0;
  9825. int refs;
  9826. pid_t ret_pid;
  9827. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9828. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9829. /* Stop child process */
  9830. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9831. kill(proc->pid, SIGABRT);
  9832. /* Wait until process is terminated (don't leave zombies) */
  9833. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9834. ;
  9835. } else {
  9836. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9837. }
  9838. /* Dec reference counter */
  9839. refs = mg_atomic_dec(&proc->references);
  9840. if (refs == 0) {
  9841. /* no more references - free data */
  9842. mg_free(data);
  9843. }
  9844. return 0;
  9845. }
  9846. /* Local (static) function assumes all arguments are valid. */
  9847. static void
  9848. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9849. {
  9850. char *buf;
  9851. size_t buflen;
  9852. int headers_len, data_len, i, truncated;
  9853. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9854. const char *status, *status_text, *connection_state;
  9855. char *pbuf, dir[PATH_MAX], *p;
  9856. struct mg_request_info ri;
  9857. struct cgi_environment blk;
  9858. FILE *in = NULL, *out = NULL, *err = NULL;
  9859. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9860. pid_t pid = (pid_t)-1;
  9861. struct process_control_data *proc = NULL;
  9862. #if defined(USE_TIMERS)
  9863. double cgi_timeout = -1.0;
  9864. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9865. /* Get timeout in seconds */
  9866. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9867. }
  9868. #endif
  9869. buf = NULL;
  9870. buflen = conn->phys_ctx->max_request_size;
  9871. i = prepare_cgi_environment(conn, prog, &blk);
  9872. if (i != 0) {
  9873. blk.buf = NULL;
  9874. blk.var = NULL;
  9875. goto done;
  9876. }
  9877. /* CGI must be executed in its own directory. 'dir' must point to the
  9878. * directory containing executable program, 'p' must point to the
  9879. * executable program name relative to 'dir'. */
  9880. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9881. if (truncated) {
  9882. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9883. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9884. goto done;
  9885. }
  9886. if ((p = strrchr(dir, '/')) != NULL) {
  9887. *p++ = '\0';
  9888. } else {
  9889. dir[0] = '.';
  9890. dir[1] = '\0';
  9891. p = (char *)prog;
  9892. }
  9893. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9894. status = strerror(ERRNO);
  9895. mg_cry_internal(
  9896. conn,
  9897. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9898. prog,
  9899. status);
  9900. mg_send_http_error(conn,
  9901. 500,
  9902. "Error: Cannot create CGI pipe: %s",
  9903. status);
  9904. goto done;
  9905. }
  9906. proc = (struct process_control_data *)
  9907. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9908. if (proc == NULL) {
  9909. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9910. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9911. goto done;
  9912. }
  9913. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9914. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9915. if (pid == (pid_t)-1) {
  9916. status = strerror(ERRNO);
  9917. mg_cry_internal(
  9918. conn,
  9919. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9920. prog,
  9921. status);
  9922. mg_send_http_error(conn,
  9923. 500,
  9924. "Error: Cannot spawn CGI process [%s]: %s",
  9925. prog,
  9926. status);
  9927. mg_free(proc);
  9928. proc = NULL;
  9929. goto done;
  9930. }
  9931. /* Store data in shared process_control_data */
  9932. proc->pid = pid;
  9933. proc->references = 1;
  9934. #if defined(USE_TIMERS)
  9935. if (cgi_timeout > 0.0) {
  9936. proc->references = 2;
  9937. // Start a timer for CGI
  9938. timer_add(conn->phys_ctx,
  9939. cgi_timeout /* in seconds */,
  9940. 0.0,
  9941. 1,
  9942. abort_process,
  9943. (void *)proc);
  9944. }
  9945. #endif
  9946. /* Parent closes only one side of the pipes.
  9947. * If we don't mark them as closed, close() attempt before
  9948. * return from this function throws an exception on Windows.
  9949. * Windows does not like when closed descriptor is closed again. */
  9950. (void)close(fdin[0]);
  9951. (void)close(fdout[1]);
  9952. (void)close(fderr[1]);
  9953. fdin[0] = fdout[1] = fderr[1] = -1;
  9954. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9955. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9956. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9957. status = strerror(ERRNO);
  9958. mg_cry_internal(conn,
  9959. "Error: CGI program \"%s\": Can not open fd: %s",
  9960. prog,
  9961. status);
  9962. mg_send_http_error(conn,
  9963. 500,
  9964. "Error: CGI can not open fd\nfdopen: %s",
  9965. status);
  9966. goto done;
  9967. }
  9968. setbuf(in, NULL);
  9969. setbuf(out, NULL);
  9970. setbuf(err, NULL);
  9971. fout.access.fp = out;
  9972. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9973. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9974. conn->content_len);
  9975. /* This is a POST/PUT request, or another request with body data. */
  9976. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9977. /* Error sending the body data */
  9978. mg_cry_internal(
  9979. conn,
  9980. "Error: CGI program \"%s\": Forward body data failed",
  9981. prog);
  9982. goto done;
  9983. }
  9984. }
  9985. /* Close so child gets an EOF. */
  9986. fclose(in);
  9987. in = NULL;
  9988. fdin[1] = -1;
  9989. /* Now read CGI reply into a buffer. We need to set correct
  9990. * status code, thus we need to see all HTTP headers first.
  9991. * Do not send anything back to client, until we buffer in all
  9992. * HTTP headers. */
  9993. data_len = 0;
  9994. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9995. if (buf == NULL) {
  9996. mg_send_http_error(conn,
  9997. 500,
  9998. "Error: Not enough memory for CGI buffer (%u bytes)",
  9999. (unsigned int)buflen);
  10000. mg_cry_internal(
  10001. conn,
  10002. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10003. "bytes)",
  10004. prog,
  10005. (unsigned int)buflen);
  10006. goto done;
  10007. }
  10008. DEBUG_TRACE("CGI: %s", "wait for response");
  10009. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10010. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10011. if (headers_len <= 0) {
  10012. /* Could not parse the CGI response. Check if some error message on
  10013. * stderr. */
  10014. i = pull_all(err, conn, buf, (int)buflen);
  10015. if (i > 0) {
  10016. /* CGI program explicitly sent an error */
  10017. /* Write the error message to the internal log */
  10018. mg_cry_internal(conn,
  10019. "Error: CGI program \"%s\" sent error "
  10020. "message: [%.*s]",
  10021. prog,
  10022. i,
  10023. buf);
  10024. /* Don't send the error message back to the client */
  10025. mg_send_http_error(conn,
  10026. 500,
  10027. "Error: CGI program \"%s\" failed.",
  10028. prog);
  10029. } else {
  10030. /* CGI program did not explicitly send an error, but a broken
  10031. * respon header */
  10032. mg_cry_internal(conn,
  10033. "Error: CGI program sent malformed or too big "
  10034. "(>%u bytes) HTTP headers: [%.*s]",
  10035. (unsigned)buflen,
  10036. data_len,
  10037. buf);
  10038. mg_send_http_error(conn,
  10039. 500,
  10040. "Error: CGI program sent malformed or too big "
  10041. "(>%u bytes) HTTP headers: [%.*s]",
  10042. (unsigned)buflen,
  10043. data_len,
  10044. buf);
  10045. }
  10046. /* in both cases, abort processing CGI */
  10047. goto done;
  10048. }
  10049. pbuf = buf;
  10050. buf[headers_len - 1] = '\0';
  10051. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10052. /* Make up and send the status line */
  10053. status_text = "OK";
  10054. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10055. != NULL) {
  10056. conn->status_code = atoi(status);
  10057. status_text = status;
  10058. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10059. status_text++;
  10060. }
  10061. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10062. != NULL) {
  10063. conn->status_code = 307;
  10064. } else {
  10065. conn->status_code = 200;
  10066. }
  10067. connection_state =
  10068. get_header(ri.http_headers, ri.num_headers, "Connection");
  10069. if (!header_has_option(connection_state, "keep-alive")) {
  10070. conn->must_close = 1;
  10071. }
  10072. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10073. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10074. /* Send headers */
  10075. for (i = 0; i < ri.num_headers; i++) {
  10076. DEBUG_TRACE("CGI header: %s: %s",
  10077. ri.http_headers[i].name,
  10078. ri.http_headers[i].value);
  10079. mg_printf(conn,
  10080. "%s: %s\r\n",
  10081. ri.http_headers[i].name,
  10082. ri.http_headers[i].value);
  10083. }
  10084. mg_write(conn, "\r\n", 2);
  10085. /* Send chunk of data that may have been read after the headers */
  10086. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10087. /* Read the rest of CGI output and send to the client */
  10088. DEBUG_TRACE("CGI: %s", "forward all data");
  10089. send_file_data(conn, &fout, 0, INT64_MAX);
  10090. DEBUG_TRACE("CGI: %s", "all data sent");
  10091. done:
  10092. mg_free(blk.var);
  10093. mg_free(blk.buf);
  10094. if (pid != (pid_t)-1) {
  10095. abort_process((void *)proc);
  10096. }
  10097. if (fdin[0] != -1) {
  10098. close(fdin[0]);
  10099. }
  10100. if (fdout[1] != -1) {
  10101. close(fdout[1]);
  10102. }
  10103. if (fderr[1] != -1) {
  10104. close(fderr[1]);
  10105. }
  10106. if (in != NULL) {
  10107. fclose(in);
  10108. } else if (fdin[1] != -1) {
  10109. close(fdin[1]);
  10110. }
  10111. if (out != NULL) {
  10112. fclose(out);
  10113. } else if (fdout[0] != -1) {
  10114. close(fdout[0]);
  10115. }
  10116. if (err != NULL) {
  10117. fclose(err);
  10118. } else if (fderr[0] != -1) {
  10119. close(fderr[0]);
  10120. }
  10121. mg_free(buf);
  10122. }
  10123. #endif /* !NO_CGI */
  10124. #if !defined(NO_FILES)
  10125. static void
  10126. mkcol(struct mg_connection *conn, const char *path)
  10127. {
  10128. int rc, body_len;
  10129. struct de de;
  10130. char date[64];
  10131. time_t curtime = time(NULL);
  10132. if (conn == NULL) {
  10133. return;
  10134. }
  10135. /* TODO (mid): Check the mg_send_http_error situations in this function
  10136. */
  10137. memset(&de.file, 0, sizeof(de.file));
  10138. if (!mg_stat(conn, path, &de.file)) {
  10139. mg_cry_internal(conn,
  10140. "%s: mg_stat(%s) failed: %s",
  10141. __func__,
  10142. path,
  10143. strerror(ERRNO));
  10144. }
  10145. if (de.file.last_modified) {
  10146. /* TODO (mid): This check does not seem to make any sense ! */
  10147. /* TODO (mid): Add a webdav unit test first, before changing
  10148. * anything here. */
  10149. mg_send_http_error(
  10150. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10151. return;
  10152. }
  10153. body_len = conn->data_len - conn->request_len;
  10154. if (body_len > 0) {
  10155. mg_send_http_error(
  10156. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10157. return;
  10158. }
  10159. rc = mg_mkdir(conn, path, 0755);
  10160. if (rc == 0) {
  10161. conn->status_code = 201;
  10162. gmt_time_string(date, sizeof(date), &curtime);
  10163. mg_printf(conn,
  10164. "HTTP/1.1 %d Created\r\n"
  10165. "Date: %s\r\n",
  10166. conn->status_code,
  10167. date);
  10168. send_static_cache_header(conn);
  10169. send_additional_header(conn);
  10170. mg_printf(conn,
  10171. "Content-Length: 0\r\n"
  10172. "Connection: %s\r\n\r\n",
  10173. suggest_connection_header(conn));
  10174. } else {
  10175. if (errno == EEXIST) {
  10176. mg_send_http_error(
  10177. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10178. } else if (errno == EACCES) {
  10179. mg_send_http_error(
  10180. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10181. } else if (errno == ENOENT) {
  10182. mg_send_http_error(
  10183. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10184. } else {
  10185. mg_send_http_error(
  10186. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10187. }
  10188. }
  10189. }
  10190. static void
  10191. put_file(struct mg_connection *conn, const char *path)
  10192. {
  10193. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10194. const char *range;
  10195. int64_t r1, r2;
  10196. int rc;
  10197. char date[64];
  10198. time_t curtime = time(NULL);
  10199. if (conn == NULL) {
  10200. return;
  10201. }
  10202. if (mg_stat(conn, path, &file.stat)) {
  10203. /* File already exists */
  10204. conn->status_code = 200;
  10205. if (file.stat.is_directory) {
  10206. /* This is an already existing directory,
  10207. * so there is nothing to do for the server. */
  10208. rc = 0;
  10209. } else {
  10210. /* File exists and is not a directory. */
  10211. /* Can it be replaced? */
  10212. #if defined(MG_USE_OPEN_FILE)
  10213. if (file.access.membuf != NULL) {
  10214. /* This is an "in-memory" file, that can not be replaced */
  10215. mg_send_http_error(conn,
  10216. 405,
  10217. "Error: Put not possible\nReplacing %s "
  10218. "is not supported",
  10219. path);
  10220. return;
  10221. }
  10222. #endif
  10223. /* Check if the server may write this file */
  10224. if (access(path, W_OK) == 0) {
  10225. /* Access granted */
  10226. rc = 1;
  10227. } else {
  10228. mg_send_http_error(
  10229. conn,
  10230. 403,
  10231. "Error: Put not possible\nReplacing %s is not allowed",
  10232. path);
  10233. return;
  10234. }
  10235. }
  10236. } else {
  10237. /* File should be created */
  10238. conn->status_code = 201;
  10239. rc = put_dir(conn, path);
  10240. }
  10241. if (rc == 0) {
  10242. /* put_dir returns 0 if path is a directory */
  10243. gmt_time_string(date, sizeof(date), &curtime);
  10244. mg_printf(conn,
  10245. "HTTP/1.1 %d %s\r\n",
  10246. conn->status_code,
  10247. mg_get_response_code_text(NULL, conn->status_code));
  10248. send_no_cache_header(conn);
  10249. send_additional_header(conn);
  10250. mg_printf(conn,
  10251. "Date: %s\r\n"
  10252. "Content-Length: 0\r\n"
  10253. "Connection: %s\r\n\r\n",
  10254. date,
  10255. suggest_connection_header(conn));
  10256. /* Request to create a directory has been fulfilled successfully.
  10257. * No need to put a file. */
  10258. return;
  10259. }
  10260. if (rc == -1) {
  10261. /* put_dir returns -1 if the path is too long */
  10262. mg_send_http_error(conn,
  10263. 414,
  10264. "Error: Path too long\nput_dir(%s): %s",
  10265. path,
  10266. strerror(ERRNO));
  10267. return;
  10268. }
  10269. if (rc == -2) {
  10270. /* put_dir returns -2 if the directory can not be created */
  10271. mg_send_http_error(conn,
  10272. 500,
  10273. "Error: Can not create directory\nput_dir(%s): %s",
  10274. path,
  10275. strerror(ERRNO));
  10276. return;
  10277. }
  10278. /* A file should be created or overwritten. */
  10279. /* Currently CivetWeb does not nead read+write access. */
  10280. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10281. || file.access.fp == NULL) {
  10282. (void)mg_fclose(&file.access);
  10283. mg_send_http_error(conn,
  10284. 500,
  10285. "Error: Can not create file\nfopen(%s): %s",
  10286. path,
  10287. strerror(ERRNO));
  10288. return;
  10289. }
  10290. fclose_on_exec(&file.access, conn);
  10291. range = mg_get_header(conn, "Content-Range");
  10292. r1 = r2 = 0;
  10293. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10294. conn->status_code = 206; /* Partial content */
  10295. fseeko(file.access.fp, r1, SEEK_SET);
  10296. }
  10297. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10298. /* forward_body_data failed.
  10299. * The error code has already been sent to the client,
  10300. * and conn->status_code is already set. */
  10301. (void)mg_fclose(&file.access);
  10302. return;
  10303. }
  10304. if (mg_fclose(&file.access) != 0) {
  10305. /* fclose failed. This might have different reasons, but a likely
  10306. * one is "no space on disk", http 507. */
  10307. conn->status_code = 507;
  10308. }
  10309. gmt_time_string(date, sizeof(date), &curtime);
  10310. mg_printf(conn,
  10311. "HTTP/1.1 %d %s\r\n",
  10312. conn->status_code,
  10313. mg_get_response_code_text(NULL, conn->status_code));
  10314. send_no_cache_header(conn);
  10315. send_additional_header(conn);
  10316. mg_printf(conn,
  10317. "Date: %s\r\n"
  10318. "Content-Length: 0\r\n"
  10319. "Connection: %s\r\n\r\n",
  10320. date,
  10321. suggest_connection_header(conn));
  10322. }
  10323. static void
  10324. delete_file(struct mg_connection *conn, const char *path)
  10325. {
  10326. struct de de;
  10327. memset(&de.file, 0, sizeof(de.file));
  10328. if (!mg_stat(conn, path, &de.file)) {
  10329. /* mg_stat returns 0 if the file does not exist */
  10330. mg_send_http_error(conn,
  10331. 404,
  10332. "Error: Cannot delete file\nFile %s not found",
  10333. path);
  10334. return;
  10335. }
  10336. #if 0 /* Ignore if a file in memory is inside a folder */
  10337. if (de.access.membuf != NULL) {
  10338. /* the file is cached in memory */
  10339. mg_send_http_error(
  10340. conn,
  10341. 405,
  10342. "Error: Delete not possible\nDeleting %s is not supported",
  10343. path);
  10344. return;
  10345. }
  10346. #endif
  10347. if (de.file.is_directory) {
  10348. if (remove_directory(conn, path)) {
  10349. /* Delete is successful: Return 204 without content. */
  10350. mg_send_http_error(conn, 204, "%s", "");
  10351. } else {
  10352. /* Delete is not successful: Return 500 (Server error). */
  10353. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10354. }
  10355. return;
  10356. }
  10357. /* This is an existing file (not a directory).
  10358. * Check if write permission is granted. */
  10359. if (access(path, W_OK) != 0) {
  10360. /* File is read only */
  10361. mg_send_http_error(
  10362. conn,
  10363. 403,
  10364. "Error: Delete not possible\nDeleting %s is not allowed",
  10365. path);
  10366. return;
  10367. }
  10368. /* Try to delete it. */
  10369. if (mg_remove(conn, path) == 0) {
  10370. /* Delete was successful: Return 204 without content. */
  10371. mg_send_http_error(conn, 204, "%s", "");
  10372. } else {
  10373. /* Delete not successful (file locked). */
  10374. mg_send_http_error(conn,
  10375. 423,
  10376. "Error: Cannot delete file\nremove(%s): %s",
  10377. path,
  10378. strerror(ERRNO));
  10379. }
  10380. }
  10381. #endif /* !NO_FILES */
  10382. #if !defined(NO_FILESYSTEMS)
  10383. static void
  10384. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10385. static void
  10386. do_ssi_include(struct mg_connection *conn,
  10387. const char *ssi,
  10388. char *tag,
  10389. int include_level)
  10390. {
  10391. char file_name[MG_BUF_LEN], path[512], *p;
  10392. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10393. size_t len;
  10394. int truncated = 0;
  10395. if (conn == NULL) {
  10396. return;
  10397. }
  10398. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10399. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10400. * always < MG_BUF_LEN. */
  10401. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10402. /* File name is relative to the webserver root */
  10403. file_name[511] = 0;
  10404. (void)mg_snprintf(conn,
  10405. &truncated,
  10406. path,
  10407. sizeof(path),
  10408. "%s/%s",
  10409. conn->dom_ctx->config[DOCUMENT_ROOT],
  10410. file_name);
  10411. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10412. /* File name is relative to the webserver working directory
  10413. * or it is absolute system path */
  10414. file_name[511] = 0;
  10415. (void)
  10416. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10417. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10418. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10419. /* File name is relative to the currect document */
  10420. file_name[511] = 0;
  10421. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10422. if (!truncated) {
  10423. if ((p = strrchr(path, '/')) != NULL) {
  10424. p[1] = '\0';
  10425. }
  10426. len = strlen(path);
  10427. (void)mg_snprintf(conn,
  10428. &truncated,
  10429. path + len,
  10430. sizeof(path) - len,
  10431. "%s",
  10432. file_name);
  10433. }
  10434. } else {
  10435. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10436. return;
  10437. }
  10438. if (truncated) {
  10439. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10440. return;
  10441. }
  10442. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10443. mg_cry_internal(conn,
  10444. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10445. tag,
  10446. path,
  10447. strerror(ERRNO));
  10448. } else {
  10449. fclose_on_exec(&file.access, conn);
  10450. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10451. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10452. path)
  10453. > 0) {
  10454. send_ssi_file(conn, path, &file, include_level + 1);
  10455. } else {
  10456. send_file_data(conn, &file, 0, INT64_MAX);
  10457. }
  10458. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10459. }
  10460. }
  10461. #if !defined(NO_POPEN)
  10462. static void
  10463. do_ssi_exec(struct mg_connection *conn, char *tag)
  10464. {
  10465. char cmd[1024] = "";
  10466. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10467. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10468. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10469. } else {
  10470. cmd[1023] = 0;
  10471. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10472. mg_cry_internal(conn,
  10473. "Cannot SSI #exec: [%s]: %s",
  10474. cmd,
  10475. strerror(ERRNO));
  10476. } else {
  10477. send_file_data(conn, &file, 0, INT64_MAX);
  10478. pclose(file.access.fp);
  10479. }
  10480. }
  10481. }
  10482. #endif /* !NO_POPEN */
  10483. static int
  10484. mg_fgetc(struct mg_file *filep, int offset)
  10485. {
  10486. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10487. if (filep == NULL) {
  10488. return EOF;
  10489. }
  10490. #if defined(MG_USE_OPEN_FILE)
  10491. if ((filep->access.membuf != NULL) && (offset >= 0)
  10492. && (((unsigned int)(offset)) < filep->stat.size)) {
  10493. return ((const unsigned char *)filep->access.membuf)[offset];
  10494. } else /* else block below */
  10495. #endif
  10496. if (filep->access.fp != NULL) {
  10497. return fgetc(filep->access.fp);
  10498. } else {
  10499. return EOF;
  10500. }
  10501. }
  10502. static void
  10503. send_ssi_file(struct mg_connection *conn,
  10504. const char *path,
  10505. struct mg_file *filep,
  10506. int include_level)
  10507. {
  10508. char buf[MG_BUF_LEN];
  10509. int ch, offset, len, in_tag, in_ssi_tag;
  10510. if (include_level > 10) {
  10511. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10512. return;
  10513. }
  10514. in_tag = in_ssi_tag = len = offset = 0;
  10515. /* Read file, byte by byte, and look for SSI include tags */
  10516. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10517. if (in_tag) {
  10518. /* We are in a tag, either SSI tag or html tag */
  10519. if (ch == '>') {
  10520. /* Tag is closing */
  10521. buf[len++] = '>';
  10522. if (in_ssi_tag) {
  10523. /* Handle SSI tag */
  10524. buf[len] = 0;
  10525. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10526. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10527. #if !defined(NO_POPEN)
  10528. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10529. do_ssi_exec(conn, buf + 9);
  10530. #endif /* !NO_POPEN */
  10531. } else {
  10532. mg_cry_internal(conn,
  10533. "%s: unknown SSI "
  10534. "command: \"%s\"",
  10535. path,
  10536. buf);
  10537. }
  10538. len = 0;
  10539. in_ssi_tag = in_tag = 0;
  10540. } else {
  10541. /* Not an SSI tag */
  10542. /* Flush buffer */
  10543. (void)mg_write(conn, buf, (size_t)len);
  10544. len = 0;
  10545. in_tag = 0;
  10546. }
  10547. } else {
  10548. /* Tag is still open */
  10549. buf[len++] = (char)(ch & 0xff);
  10550. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10551. /* All SSI tags start with <!--# */
  10552. in_ssi_tag = 1;
  10553. }
  10554. if ((len + 2) > (int)sizeof(buf)) {
  10555. /* Tag to long for buffer */
  10556. mg_cry_internal(conn, "%s: tag is too large", path);
  10557. return;
  10558. }
  10559. }
  10560. } else {
  10561. /* We are not in a tag yet. */
  10562. if (ch == '<') {
  10563. /* Tag is opening */
  10564. in_tag = 1;
  10565. if (len > 0) {
  10566. /* Flush current buffer.
  10567. * Buffer is filled with "len" bytes. */
  10568. (void)mg_write(conn, buf, (size_t)len);
  10569. }
  10570. /* Store the < */
  10571. len = 1;
  10572. buf[0] = '<';
  10573. } else {
  10574. /* No Tag */
  10575. /* Add data to buffer */
  10576. buf[len++] = (char)(ch & 0xff);
  10577. /* Flush if buffer is full */
  10578. if (len == (int)sizeof(buf)) {
  10579. mg_write(conn, buf, (size_t)len);
  10580. len = 0;
  10581. }
  10582. }
  10583. }
  10584. }
  10585. /* Send the rest of buffered data */
  10586. if (len > 0) {
  10587. mg_write(conn, buf, (size_t)len);
  10588. }
  10589. }
  10590. static void
  10591. handle_ssi_file_request(struct mg_connection *conn,
  10592. const char *path,
  10593. struct mg_file *filep)
  10594. {
  10595. char date[64];
  10596. time_t curtime = time(NULL);
  10597. const char *cors_orig_cfg;
  10598. const char *cors1, *cors2, *cors3;
  10599. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10600. return;
  10601. }
  10602. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10603. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10604. /* Cross-origin resource sharing (CORS). */
  10605. cors1 = "Access-Control-Allow-Origin: ";
  10606. cors2 = cors_orig_cfg;
  10607. cors3 = "\r\n";
  10608. } else {
  10609. cors1 = cors2 = cors3 = "";
  10610. }
  10611. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10612. /* File exists (precondition for calling this function),
  10613. * but can not be opened by the server. */
  10614. mg_send_http_error(conn,
  10615. 500,
  10616. "Error: Cannot read file\nfopen(%s): %s",
  10617. path,
  10618. strerror(ERRNO));
  10619. } else {
  10620. conn->must_close = 1;
  10621. gmt_time_string(date, sizeof(date), &curtime);
  10622. fclose_on_exec(&filep->access, conn);
  10623. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10624. send_no_cache_header(conn);
  10625. send_additional_header(conn);
  10626. mg_printf(conn,
  10627. "%s%s%s"
  10628. "Date: %s\r\n"
  10629. "Content-Type: text/html\r\n"
  10630. "Connection: %s\r\n\r\n",
  10631. cors1,
  10632. cors2,
  10633. cors3,
  10634. date,
  10635. suggest_connection_header(conn));
  10636. send_ssi_file(conn, path, filep, 0);
  10637. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10638. }
  10639. }
  10640. #endif /* NO_FILESYSTEMS */
  10641. #if !defined(NO_FILES)
  10642. static void
  10643. send_options(struct mg_connection *conn)
  10644. {
  10645. char date[64];
  10646. time_t curtime = time(NULL);
  10647. if (!conn) {
  10648. return;
  10649. }
  10650. conn->status_code = 200;
  10651. conn->must_close = 1;
  10652. gmt_time_string(date, sizeof(date), &curtime);
  10653. /* We do not set a "Cache-Control" header here, but leave the default.
  10654. * Since browsers do not send an OPTIONS request, we can not test the
  10655. * effect anyway. */
  10656. mg_printf(conn,
  10657. "HTTP/1.1 200 OK\r\n"
  10658. "Date: %s\r\n"
  10659. "Connection: %s\r\n"
  10660. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10661. "PROPFIND, MKCOL\r\n"
  10662. "DAV: 1\r\n",
  10663. date,
  10664. suggest_connection_header(conn));
  10665. send_additional_header(conn);
  10666. mg_printf(conn, "\r\n");
  10667. }
  10668. /* Writes PROPFIND properties for a collection element */
  10669. static int
  10670. print_props(struct mg_connection *conn,
  10671. const char *uri,
  10672. const char *name,
  10673. struct mg_file_stat *filep)
  10674. {
  10675. size_t href_size, i, j;
  10676. int len;
  10677. char *href, mtime[64];
  10678. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10679. return 0;
  10680. }
  10681. /* Estimate worst case size for encoding */
  10682. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10683. href = (char *)mg_malloc(href_size);
  10684. if (href == NULL) {
  10685. return 0;
  10686. }
  10687. len = mg_url_encode(uri, href, href_size);
  10688. if (len >= 0) {
  10689. /* Append an extra string */
  10690. mg_url_encode(name, href + len, href_size - (size_t)len);
  10691. }
  10692. /* Directory separator should be preserved. */
  10693. for (i = j = 0; href[i]; j++) {
  10694. if (!strncmp(href + i, "%2f", 3)) {
  10695. href[j] = '/';
  10696. i += 3;
  10697. } else {
  10698. href[j] = href[i++];
  10699. }
  10700. }
  10701. href[j] = '\0';
  10702. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10703. mg_printf(conn,
  10704. "<d:response>"
  10705. "<d:href>%s</d:href>"
  10706. "<d:propstat>"
  10707. "<d:prop>"
  10708. "<d:resourcetype>%s</d:resourcetype>"
  10709. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10710. "<d:getlastmodified>%s</d:getlastmodified>"
  10711. "</d:prop>"
  10712. "<d:status>HTTP/1.1 200 OK</d:status>"
  10713. "</d:propstat>"
  10714. "</d:response>\n",
  10715. href,
  10716. filep->is_directory ? "<d:collection/>" : "",
  10717. filep->size,
  10718. mtime);
  10719. mg_free(href);
  10720. return 1;
  10721. }
  10722. static int
  10723. print_dav_dir_entry(struct de *de, void *data)
  10724. {
  10725. struct mg_connection *conn = (struct mg_connection *)data;
  10726. if (!de || !conn
  10727. || !print_props(
  10728. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10729. /* stop scan */
  10730. return 1;
  10731. }
  10732. return 0;
  10733. }
  10734. static void
  10735. handle_propfind(struct mg_connection *conn,
  10736. const char *path,
  10737. struct mg_file_stat *filep)
  10738. {
  10739. const char *depth = mg_get_header(conn, "Depth");
  10740. char date[64];
  10741. time_t curtime = time(NULL);
  10742. gmt_time_string(date, sizeof(date), &curtime);
  10743. if (!conn || !path || !filep || !conn->dom_ctx) {
  10744. return;
  10745. }
  10746. conn->must_close = 1;
  10747. conn->status_code = 207;
  10748. mg_printf(conn,
  10749. "HTTP/1.1 207 Multi-Status\r\n"
  10750. "Date: %s\r\n",
  10751. date);
  10752. send_static_cache_header(conn);
  10753. send_additional_header(conn);
  10754. mg_printf(conn,
  10755. "Connection: %s\r\n"
  10756. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10757. suggest_connection_header(conn));
  10758. mg_printf(conn,
  10759. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10760. "<d:multistatus xmlns:d='DAV:'>\n");
  10761. /* Print properties for the requested resource itself */
  10762. print_props(conn, conn->request_info.local_uri, "", filep);
  10763. /* If it is a directory, print directory entries too if Depth is not 0
  10764. */
  10765. if (filep->is_directory
  10766. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10767. "yes")
  10768. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10769. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10770. }
  10771. mg_printf(conn, "%s\n", "</d:multistatus>");
  10772. }
  10773. #endif
  10774. void
  10775. mg_lock_connection(struct mg_connection *conn)
  10776. {
  10777. if (conn) {
  10778. (void)pthread_mutex_lock(&conn->mutex);
  10779. }
  10780. }
  10781. void
  10782. mg_unlock_connection(struct mg_connection *conn)
  10783. {
  10784. if (conn) {
  10785. (void)pthread_mutex_unlock(&conn->mutex);
  10786. }
  10787. }
  10788. void
  10789. mg_lock_context(struct mg_context *ctx)
  10790. {
  10791. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10792. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10793. }
  10794. }
  10795. void
  10796. mg_unlock_context(struct mg_context *ctx)
  10797. {
  10798. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10799. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10800. }
  10801. }
  10802. #if defined(USE_LUA)
  10803. #include "mod_lua.inl"
  10804. #endif /* USE_LUA */
  10805. #if defined(USE_DUKTAPE)
  10806. #include "mod_duktape.inl"
  10807. #endif /* USE_DUKTAPE */
  10808. #if defined(USE_WEBSOCKET)
  10809. #if !defined(NO_SSL_DL)
  10810. #define SHA_API static
  10811. #include "sha1.inl"
  10812. #endif
  10813. static int
  10814. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10815. {
  10816. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10817. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10818. SHA_CTX sha_ctx;
  10819. int truncated;
  10820. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10821. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10822. if (truncated) {
  10823. conn->must_close = 1;
  10824. return 0;
  10825. }
  10826. DEBUG_TRACE("%s", "Send websocket handshake");
  10827. SHA1_Init(&sha_ctx);
  10828. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10829. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10830. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10831. mg_printf(conn,
  10832. "HTTP/1.1 101 Switching Protocols\r\n"
  10833. "Upgrade: websocket\r\n"
  10834. "Connection: Upgrade\r\n"
  10835. "Sec-WebSocket-Accept: %s\r\n",
  10836. b64_sha);
  10837. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10838. mg_printf(conn,
  10839. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10840. conn->request_info.acceptedWebSocketSubprotocol);
  10841. } else {
  10842. mg_printf(conn, "%s", "\r\n");
  10843. }
  10844. return 1;
  10845. }
  10846. #if !defined(MG_MAX_UNANSWERED_PING)
  10847. /* Configuration of the maximum number of websocket PINGs that might
  10848. * stay unanswered before the connection is considered broken.
  10849. * Note: The name of this define may still change (until it is
  10850. * defined as a compile parameter in a documentation).
  10851. */
  10852. #define MG_MAX_UNANSWERED_PING (5)
  10853. #endif
  10854. static void
  10855. read_websocket(struct mg_connection *conn,
  10856. mg_websocket_data_handler ws_data_handler,
  10857. void *callback_data)
  10858. {
  10859. /* Pointer to the beginning of the portion of the incoming websocket
  10860. * message queue.
  10861. * The original websocket upgrade request is never removed, so the queue
  10862. * begins after it. */
  10863. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10864. int n, error, exit_by_callback;
  10865. int ret;
  10866. /* body_len is the length of the entire queue in bytes
  10867. * len is the length of the current message
  10868. * data_len is the length of the current message's data payload
  10869. * header_len is the length of the current message's header */
  10870. size_t i, len, mask_len = 0, header_len, body_len;
  10871. uint64_t data_len = 0;
  10872. /* "The masking key is a 32-bit value chosen at random by the client."
  10873. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10874. */
  10875. unsigned char mask[4];
  10876. /* data points to the place where the message is stored when passed to
  10877. * the websocket_data callback. This is either mem on the stack, or a
  10878. * dynamically allocated buffer if it is too large. */
  10879. unsigned char mem[4096];
  10880. unsigned char mop; /* mask flag and opcode */
  10881. /* Variables used for connection monitoring */
  10882. double timeout = -1.0;
  10883. int enable_ping_pong = 0;
  10884. int ping_count = 0;
  10885. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10886. enable_ping_pong =
  10887. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10888. "yes");
  10889. }
  10890. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10891. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10892. }
  10893. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10894. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10895. }
  10896. /* Enter data processing loop */
  10897. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10898. conn->request_info.remote_addr,
  10899. conn->request_info.remote_port);
  10900. conn->in_websocket_handling = 1;
  10901. mg_set_thread_name("wsock");
  10902. /* Loop continuously, reading messages from the socket, invoking the
  10903. * callback, and waiting repeatedly until an error occurs. */
  10904. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10905. && (!conn->must_close)) {
  10906. header_len = 0;
  10907. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10908. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10909. len = buf[1] & 127;
  10910. mask_len = (buf[1] & 128) ? 4 : 0;
  10911. if ((len < 126) && (body_len >= mask_len)) {
  10912. /* inline 7-bit length field */
  10913. data_len = len;
  10914. header_len = 2 + mask_len;
  10915. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10916. /* 16-bit length field */
  10917. header_len = 4 + mask_len;
  10918. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10919. } else if (body_len >= (10 + mask_len)) {
  10920. /* 64-bit length field */
  10921. uint32_t l1, l2;
  10922. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10923. memcpy(&l2, &buf[6], 4);
  10924. header_len = 10 + mask_len;
  10925. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10926. if (data_len > (uint64_t)0x7FFF0000ul) {
  10927. /* no can do */
  10928. mg_cry_internal(
  10929. conn,
  10930. "%s",
  10931. "websocket out of memory; closing connection");
  10932. break;
  10933. }
  10934. }
  10935. }
  10936. if ((header_len > 0) && (body_len >= header_len)) {
  10937. /* Allocate space to hold websocket payload */
  10938. unsigned char *data = mem;
  10939. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10940. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10941. conn->phys_ctx);
  10942. if (data == NULL) {
  10943. /* Allocation failed, exit the loop and then close the
  10944. * connection */
  10945. mg_cry_internal(
  10946. conn,
  10947. "%s",
  10948. "websocket out of memory; closing connection");
  10949. break;
  10950. }
  10951. }
  10952. /* Copy the mask before we shift the queue and destroy it */
  10953. if (mask_len > 0) {
  10954. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10955. } else {
  10956. memset(mask, 0, sizeof(mask));
  10957. }
  10958. /* Read frame payload from the first message in the queue into
  10959. * data and advance the queue by moving the memory in place. */
  10960. DEBUG_ASSERT(body_len >= header_len);
  10961. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10962. mop = buf[0]; /* current mask and opcode */
  10963. /* Overflow case */
  10964. len = body_len - header_len;
  10965. memcpy(data, buf + header_len, len);
  10966. error = 0;
  10967. while ((uint64_t)len < data_len) {
  10968. n = pull_inner(NULL,
  10969. conn,
  10970. (char *)(data + len),
  10971. (int)(data_len - len),
  10972. timeout);
  10973. if (n <= -2) {
  10974. error = 1;
  10975. break;
  10976. } else if (n > 0) {
  10977. len += (size_t)n;
  10978. } else {
  10979. /* Timeout: should retry */
  10980. /* TODO: retry condition */
  10981. }
  10982. }
  10983. if (error) {
  10984. mg_cry_internal(
  10985. conn,
  10986. "%s",
  10987. "Websocket pull failed; closing connection");
  10988. if (data != mem) {
  10989. mg_free(data);
  10990. }
  10991. break;
  10992. }
  10993. conn->data_len = conn->request_len;
  10994. } else {
  10995. mop = buf[0]; /* current mask and opcode, overwritten by
  10996. * memmove() */
  10997. /* Length of the message being read at the front of the
  10998. * queue. Cast to 31 bit is OK, since we limited
  10999. * data_len before. */
  11000. len = (size_t)data_len + header_len;
  11001. /* Copy the data payload into the data pointer for the
  11002. * callback. Cast to 31 bit is OK, since we
  11003. * limited data_len */
  11004. memcpy(data, buf + header_len, (size_t)data_len);
  11005. /* Move the queue forward len bytes */
  11006. memmove(buf, buf + len, body_len - len);
  11007. /* Mark the queue as advanced */
  11008. conn->data_len -= (int)len;
  11009. }
  11010. /* Apply mask if necessary */
  11011. if (mask_len > 0) {
  11012. for (i = 0; i < (size_t)data_len; i++) {
  11013. data[i] ^= mask[i & 3];
  11014. }
  11015. }
  11016. exit_by_callback = 0;
  11017. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11018. /* filter PONG messages */
  11019. DEBUG_TRACE("PONG from %s:%u",
  11020. conn->request_info.remote_addr,
  11021. conn->request_info.remote_port);
  11022. /* No unanwered PINGs left */
  11023. ping_count = 0;
  11024. } else if (enable_ping_pong
  11025. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11026. /* reply PING messages */
  11027. DEBUG_TRACE("Reply PING from %s:%u",
  11028. conn->request_info.remote_addr,
  11029. conn->request_info.remote_port);
  11030. ret = mg_websocket_write(conn,
  11031. MG_WEBSOCKET_OPCODE_PONG,
  11032. (char *)data,
  11033. (size_t)data_len);
  11034. if (ret <= 0) {
  11035. /* Error: send failed */
  11036. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11037. break;
  11038. }
  11039. } else {
  11040. /* Exit the loop if callback signals to exit (server side),
  11041. * or "connection close" opcode received (client side). */
  11042. if ((ws_data_handler != NULL)
  11043. && !ws_data_handler(conn,
  11044. mop,
  11045. (char *)data,
  11046. (size_t)data_len,
  11047. callback_data)) {
  11048. exit_by_callback = 1;
  11049. }
  11050. }
  11051. /* It a buffer has been allocated, free it again */
  11052. if (data != mem) {
  11053. mg_free(data);
  11054. }
  11055. if (exit_by_callback) {
  11056. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11057. conn->request_info.remote_addr,
  11058. conn->request_info.remote_port);
  11059. break;
  11060. }
  11061. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11062. /* Opcode == 8, connection close */
  11063. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11064. conn->request_info.remote_addr,
  11065. conn->request_info.remote_port);
  11066. break;
  11067. }
  11068. /* Not breaking the loop, process next websocket frame. */
  11069. } else {
  11070. /* Read from the socket into the next available location in the
  11071. * message queue. */
  11072. n = pull_inner(NULL,
  11073. conn,
  11074. conn->buf + conn->data_len,
  11075. conn->buf_size - conn->data_len,
  11076. timeout);
  11077. if (n <= -2) {
  11078. /* Error, no bytes read */
  11079. DEBUG_TRACE("PULL from %s:%u failed",
  11080. conn->request_info.remote_addr,
  11081. conn->request_info.remote_port);
  11082. break;
  11083. }
  11084. if (n > 0) {
  11085. conn->data_len += n;
  11086. /* Reset open PING count */
  11087. ping_count = 0;
  11088. } else {
  11089. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11090. && (!conn->must_close)) {
  11091. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11092. /* Stop sending PING */
  11093. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11094. "- closing connection",
  11095. ping_count,
  11096. conn->request_info.remote_addr,
  11097. conn->request_info.remote_port);
  11098. break;
  11099. }
  11100. if (enable_ping_pong) {
  11101. /* Send Websocket PING message */
  11102. DEBUG_TRACE("PING to %s:%u",
  11103. conn->request_info.remote_addr,
  11104. conn->request_info.remote_port);
  11105. ret = mg_websocket_write(conn,
  11106. MG_WEBSOCKET_OPCODE_PING,
  11107. NULL,
  11108. 0);
  11109. if (ret <= 0) {
  11110. /* Error: send failed */
  11111. DEBUG_TRACE("Send PING failed (%i)", ret);
  11112. break;
  11113. }
  11114. ping_count++;
  11115. }
  11116. }
  11117. /* Timeout: should retry */
  11118. /* TODO: get timeout def */
  11119. }
  11120. }
  11121. }
  11122. /* Leave data processing loop */
  11123. mg_set_thread_name("worker");
  11124. conn->in_websocket_handling = 0;
  11125. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11126. conn->request_info.remote_addr,
  11127. conn->request_info.remote_port);
  11128. }
  11129. static int
  11130. mg_websocket_write_exec(struct mg_connection *conn,
  11131. int opcode,
  11132. const char *data,
  11133. size_t dataLen,
  11134. uint32_t masking_key)
  11135. {
  11136. unsigned char header[14];
  11137. size_t headerLen;
  11138. int retval;
  11139. #if defined(GCC_DIAGNOSTIC)
  11140. /* Disable spurious conversion warning for GCC */
  11141. #pragma GCC diagnostic push
  11142. #pragma GCC diagnostic ignored "-Wconversion"
  11143. #endif
  11144. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11145. #if defined(GCC_DIAGNOSTIC)
  11146. #pragma GCC diagnostic pop
  11147. #endif
  11148. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11149. if (dataLen < 126) {
  11150. /* inline 7-bit length field */
  11151. header[1] = (unsigned char)dataLen;
  11152. headerLen = 2;
  11153. } else if (dataLen <= 0xFFFF) {
  11154. /* 16-bit length field */
  11155. uint16_t len = htons((uint16_t)dataLen);
  11156. header[1] = 126;
  11157. memcpy(header + 2, &len, 2);
  11158. headerLen = 4;
  11159. } else {
  11160. /* 64-bit length field */
  11161. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11162. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11163. header[1] = 127;
  11164. memcpy(header + 2, &len1, 4);
  11165. memcpy(header + 6, &len2, 4);
  11166. headerLen = 10;
  11167. }
  11168. if (masking_key) {
  11169. /* add mask */
  11170. header[1] |= 0x80;
  11171. memcpy(header + headerLen, &masking_key, 4);
  11172. headerLen += 4;
  11173. }
  11174. /* Note that POSIX/Winsock's send() is threadsafe
  11175. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11176. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11177. * push(), although that is only a problem if the packet is large or
  11178. * outgoing buffer is full). */
  11179. /* TODO: Check if this lock should be moved to user land.
  11180. * Currently the server sets this lock for websockets, but
  11181. * not for any other connection. It must be set for every
  11182. * conn read/written by more than one thread, no matter if
  11183. * it is a websocket or regular connection. */
  11184. (void)mg_lock_connection(conn);
  11185. retval = mg_write(conn, header, headerLen);
  11186. if (retval != (int)headerLen) {
  11187. /* Did not send complete header */
  11188. retval = -1;
  11189. } else {
  11190. if (dataLen > 0) {
  11191. retval = mg_write(conn, data, dataLen);
  11192. }
  11193. /* if dataLen == 0, the header length (2) is returned */
  11194. }
  11195. /* TODO: Remove this unlock as well, when lock is removed. */
  11196. mg_unlock_connection(conn);
  11197. return retval;
  11198. }
  11199. int
  11200. mg_websocket_write(struct mg_connection *conn,
  11201. int opcode,
  11202. const char *data,
  11203. size_t dataLen)
  11204. {
  11205. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11206. }
  11207. static void
  11208. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11209. {
  11210. size_t i = 0;
  11211. i = 0;
  11212. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11213. /* Convert in 32 bit words, if data is 4 byte aligned */
  11214. while (i < (in_len - 3)) {
  11215. *(uint32_t *)(void *)(out + i) =
  11216. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11217. i += 4;
  11218. }
  11219. }
  11220. if (i != in_len) {
  11221. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11222. while (i < in_len) {
  11223. *(uint8_t *)(void *)(out + i) =
  11224. *(uint8_t *)(void *)(in + i)
  11225. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11226. i++;
  11227. }
  11228. }
  11229. }
  11230. int
  11231. mg_websocket_client_write(struct mg_connection *conn,
  11232. int opcode,
  11233. const char *data,
  11234. size_t dataLen)
  11235. {
  11236. int retval = -1;
  11237. char *masked_data =
  11238. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11239. uint32_t masking_key = 0;
  11240. if (masked_data == NULL) {
  11241. /* Return -1 in an error case */
  11242. mg_cry_internal(conn,
  11243. "%s",
  11244. "Cannot allocate buffer for masked websocket response: "
  11245. "Out of memory");
  11246. return -1;
  11247. }
  11248. do {
  11249. /* Get a masking key - but not 0 */
  11250. masking_key = (uint32_t)get_random();
  11251. } while (masking_key == 0);
  11252. mask_data(data, dataLen, masking_key, masked_data);
  11253. retval = mg_websocket_write_exec(
  11254. conn, opcode, masked_data, dataLen, masking_key);
  11255. mg_free(masked_data);
  11256. return retval;
  11257. }
  11258. static void
  11259. handle_websocket_request(struct mg_connection *conn,
  11260. const char *path,
  11261. int is_callback_resource,
  11262. struct mg_websocket_subprotocols *subprotocols,
  11263. mg_websocket_connect_handler ws_connect_handler,
  11264. mg_websocket_ready_handler ws_ready_handler,
  11265. mg_websocket_data_handler ws_data_handler,
  11266. mg_websocket_close_handler ws_close_handler,
  11267. void *cbData)
  11268. {
  11269. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11270. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11271. ptrdiff_t lua_websock = 0;
  11272. #if !defined(USE_LUA)
  11273. (void)path;
  11274. #endif
  11275. /* Step 1: Check websocket protocol version. */
  11276. /* Step 1.1: Check Sec-WebSocket-Key. */
  11277. if (!websock_key) {
  11278. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11279. * requires a Sec-WebSocket-Key header.
  11280. */
  11281. /* It could be the hixie draft version
  11282. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11283. */
  11284. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11285. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11286. char key3[8];
  11287. if ((key1 != NULL) && (key2 != NULL)) {
  11288. /* This version uses 8 byte body data in a GET request */
  11289. conn->content_len = 8;
  11290. if (8 == mg_read(conn, key3, 8)) {
  11291. /* This is the hixie version */
  11292. mg_send_http_error(conn,
  11293. 426,
  11294. "%s",
  11295. "Protocol upgrade to RFC 6455 required");
  11296. return;
  11297. }
  11298. }
  11299. /* This is an unknown version */
  11300. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11301. return;
  11302. }
  11303. /* Step 1.2: Check websocket protocol version. */
  11304. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11305. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11306. /* Reject wrong versions */
  11307. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11308. return;
  11309. }
  11310. /* Step 1.3: Could check for "Host", but we do not really nead this
  11311. * value for anything, so just ignore it. */
  11312. /* Step 2: If a callback is responsible, call it. */
  11313. if (is_callback_resource) {
  11314. /* Step 2.1 check and select subprotocol */
  11315. const char *protocols[64]; // max 64 headers
  11316. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11317. "Sec-WebSocket-Protocol",
  11318. protocols,
  11319. 64);
  11320. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11321. int cnt = 0;
  11322. int idx;
  11323. unsigned long len;
  11324. const char *sep, *curSubProtocol,
  11325. *acceptedWebSocketSubprotocol = NULL;
  11326. /* look for matching subprotocol */
  11327. do {
  11328. const char *protocol = protocols[cnt];
  11329. do {
  11330. sep = strchr(protocol, ',');
  11331. curSubProtocol = protocol;
  11332. len = sep ? (unsigned long)(sep - protocol)
  11333. : (unsigned long)strlen(protocol);
  11334. while (sep && isspace((unsigned char)*++sep))
  11335. ; // ignore leading whitespaces
  11336. protocol = sep;
  11337. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11338. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11339. && (strncmp(curSubProtocol,
  11340. subprotocols->subprotocols[idx],
  11341. len)
  11342. == 0)) {
  11343. acceptedWebSocketSubprotocol =
  11344. subprotocols->subprotocols[idx];
  11345. break;
  11346. }
  11347. }
  11348. } while (sep && !acceptedWebSocketSubprotocol);
  11349. } while (++cnt < nbSubprotocolHeader
  11350. && !acceptedWebSocketSubprotocol);
  11351. conn->request_info.acceptedWebSocketSubprotocol =
  11352. acceptedWebSocketSubprotocol;
  11353. } else if (nbSubprotocolHeader > 0) {
  11354. /* keep legacy behavior */
  11355. const char *protocol = protocols[0];
  11356. /* The protocol is a comma separated list of names. */
  11357. /* The server must only return one value from this list. */
  11358. /* First check if it is a list or just a single value. */
  11359. const char *sep = strrchr(protocol, ',');
  11360. if (sep == NULL) {
  11361. /* Just a single protocol -> accept it. */
  11362. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11363. } else {
  11364. /* Multiple protocols -> accept the last one. */
  11365. /* This is just a quick fix if the client offers multiple
  11366. * protocols. The handler should have a list of accepted
  11367. * protocols on his own
  11368. * and use it to select one protocol among those the client
  11369. * has
  11370. * offered.
  11371. */
  11372. while (isspace((unsigned char)*++sep)) {
  11373. ; /* ignore leading whitespaces */
  11374. }
  11375. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11376. }
  11377. }
  11378. if ((ws_connect_handler != NULL)
  11379. && (ws_connect_handler(conn, cbData) != 0)) {
  11380. /* C callback has returned non-zero, do not proceed with
  11381. * handshake.
  11382. */
  11383. /* Note that C callbacks are no longer called when Lua is
  11384. * responsible, so C can no longer filter callbacks for Lua. */
  11385. return;
  11386. }
  11387. }
  11388. #if defined(USE_LUA)
  11389. /* Step 3: No callback. Check if Lua is responsible. */
  11390. else {
  11391. /* Step 3.1: Check if Lua is responsible. */
  11392. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11393. lua_websock = match_prefix(
  11394. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11395. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11396. path);
  11397. }
  11398. if (lua_websock) {
  11399. /* Step 3.2: Lua is responsible: call it. */
  11400. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11401. if (!conn->lua_websocket_state) {
  11402. /* Lua rejected the new client */
  11403. return;
  11404. }
  11405. }
  11406. }
  11407. #endif
  11408. /* Step 4: Check if there is a responsible websocket handler. */
  11409. if (!is_callback_resource && !lua_websock) {
  11410. /* There is no callback, and Lua is not responsible either. */
  11411. /* Reply with a 404 Not Found. We are still at a standard
  11412. * HTTP request here, before the websocket handshake, so
  11413. * we can still send standard HTTP error replies. */
  11414. mg_send_http_error(conn, 404, "%s", "Not found");
  11415. return;
  11416. }
  11417. /* Step 5: The websocket connection has been accepted */
  11418. if (!send_websocket_handshake(conn, websock_key)) {
  11419. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11420. return;
  11421. }
  11422. /* Step 6: Call the ready handler */
  11423. if (is_callback_resource) {
  11424. if (ws_ready_handler != NULL) {
  11425. ws_ready_handler(conn, cbData);
  11426. }
  11427. #if defined(USE_LUA)
  11428. } else if (lua_websock) {
  11429. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11430. /* the ready handler returned false */
  11431. return;
  11432. }
  11433. #endif
  11434. }
  11435. /* Step 7: Enter the read loop */
  11436. if (is_callback_resource) {
  11437. read_websocket(conn, ws_data_handler, cbData);
  11438. #if defined(USE_LUA)
  11439. } else if (lua_websock) {
  11440. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11441. #endif
  11442. }
  11443. /* Step 8: Call the close handler */
  11444. if (ws_close_handler) {
  11445. ws_close_handler(conn, cbData);
  11446. }
  11447. }
  11448. #endif /* !USE_WEBSOCKET */
  11449. /* Is upgrade request:
  11450. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11451. * 1 = upgrade to websocket
  11452. * 2 = upgrade to HTTP/2
  11453. * -1 = upgrade to unknown protocol
  11454. */
  11455. static int
  11456. should_switch_to_protocol(const struct mg_connection *conn)
  11457. {
  11458. const char *upgrade, *connection;
  11459. /* A websocket protocoll has the following HTTP headers:
  11460. *
  11461. * Connection: Upgrade
  11462. * Upgrade: Websocket
  11463. */
  11464. connection = mg_get_header(conn, "Connection");
  11465. if (connection == NULL) {
  11466. return PROTOCOL_TYPE_HTTP1;
  11467. }
  11468. if (!mg_strcasestr(connection, "upgrade")) {
  11469. return PROTOCOL_TYPE_HTTP1;
  11470. }
  11471. upgrade = mg_get_header(conn, "Upgrade");
  11472. if (upgrade == NULL) {
  11473. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11474. return -1;
  11475. }
  11476. /* Upgrade to ... */
  11477. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11478. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11479. * "Sec-WebSocket-Version" are also required.
  11480. * Don't check them here, since even an unsupported websocket protocol
  11481. * request still IS a websocket request (in contrast to a standard HTTP
  11482. * request). It will fail later in handle_websocket_request.
  11483. */
  11484. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11485. }
  11486. if (0 != mg_strcasestr(upgrade, "h2")) {
  11487. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11488. }
  11489. /* Upgrade to another protocol */
  11490. return -1;
  11491. }
  11492. static int
  11493. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11494. {
  11495. int n;
  11496. unsigned int a, b, c, d, slash;
  11497. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11498. slash = 32;
  11499. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11500. n = 0;
  11501. }
  11502. }
  11503. if ((n > 0) && ((size_t)n == vec->len)) {
  11504. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11505. /* IPv4 format */
  11506. if (sa->sa.sa_family == AF_INET) {
  11507. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11508. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11509. | ((uint32_t)c << 8) | (uint32_t)d;
  11510. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11511. return (ip & mask) == net;
  11512. }
  11513. return 0;
  11514. }
  11515. }
  11516. #if defined(USE_IPV6)
  11517. else {
  11518. char ad[50];
  11519. const char *p;
  11520. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11521. slash = 128;
  11522. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11523. n = 0;
  11524. }
  11525. }
  11526. if ((n <= 0) && no_strict) {
  11527. /* no square brackets? */
  11528. p = strchr(vec->ptr, '/');
  11529. if (p && (p < (vec->ptr + vec->len))) {
  11530. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11531. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11532. n += (int)(p - vec->ptr);
  11533. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11534. } else {
  11535. n = 0;
  11536. }
  11537. } else if (vec->len < sizeof(ad)) {
  11538. n = (int)vec->len;
  11539. slash = 128;
  11540. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11541. }
  11542. }
  11543. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11544. p = ad;
  11545. c = 0;
  11546. /* zone indexes are unsupported, at least two colons are needed */
  11547. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11548. if (*(p++) == ':') {
  11549. c++;
  11550. }
  11551. }
  11552. if ((*p == '\0') && (c >= 2)) {
  11553. struct sockaddr_in6 sin6;
  11554. unsigned int i;
  11555. /* for strict validation, an actual IPv6 argument is needed */
  11556. if (sa->sa.sa_family != AF_INET6) {
  11557. return 0;
  11558. }
  11559. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11560. /* IPv6 format */
  11561. for (i = 0; i < 16; i++) {
  11562. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11563. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11564. uint8_t mask = 0;
  11565. if (8 * i + 8 < slash) {
  11566. mask = 0xFFu;
  11567. } else if (8 * i < slash) {
  11568. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11569. }
  11570. if ((ip & mask) != net) {
  11571. return 0;
  11572. }
  11573. }
  11574. return 1;
  11575. }
  11576. }
  11577. }
  11578. }
  11579. #else
  11580. (void)no_strict;
  11581. #endif
  11582. /* malformed */
  11583. return -1;
  11584. }
  11585. static int
  11586. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11587. {
  11588. int throttle = 0;
  11589. struct vec vec, val;
  11590. char mult;
  11591. double v;
  11592. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11593. mult = ',';
  11594. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11595. || (v < 0)
  11596. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11597. && (mult != ','))) {
  11598. continue;
  11599. }
  11600. v *= (lowercase(&mult) == 'k')
  11601. ? 1024
  11602. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11603. if (vec.len == 1 && vec.ptr[0] == '*') {
  11604. throttle = (int)v;
  11605. } else {
  11606. int matched = parse_match_net(&vec, rsa, 0);
  11607. if (matched >= 0) {
  11608. /* a valid IP subnet */
  11609. if (matched) {
  11610. throttle = (int)v;
  11611. }
  11612. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11613. throttle = (int)v;
  11614. }
  11615. }
  11616. }
  11617. return throttle;
  11618. }
  11619. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11620. #include "handle_form.inl"
  11621. #if defined(MG_LEGACY_INTERFACE)
  11622. /* Implement the deprecated mg_upload function by calling the new
  11623. * mg_handle_form_request function. While mg_upload could only handle
  11624. * HTML forms sent as POST request in multipart/form-data format
  11625. * containing only file input elements, mg_handle_form_request can
  11626. * handle all form input elements and all standard request methods. */
  11627. struct mg_upload_user_data {
  11628. struct mg_connection *conn;
  11629. const char *destination_dir;
  11630. int num_uploaded_files;
  11631. };
  11632. /* Helper function for deprecated mg_upload. */
  11633. static int
  11634. mg_upload_field_found(const char *key,
  11635. const char *filename,
  11636. char *path,
  11637. size_t pathlen,
  11638. void *user_data)
  11639. {
  11640. int truncated = 0;
  11641. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11642. (void)key;
  11643. if (!filename) {
  11644. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11645. return FORM_FIELD_STORAGE_ABORT;
  11646. }
  11647. mg_snprintf(fud->conn,
  11648. &truncated,
  11649. path,
  11650. pathlen - 1,
  11651. "%s/%s",
  11652. fud->destination_dir,
  11653. filename);
  11654. if (truncated) {
  11655. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11656. return FORM_FIELD_STORAGE_ABORT;
  11657. }
  11658. return FORM_FIELD_STORAGE_STORE;
  11659. }
  11660. /* Helper function for deprecated mg_upload. */
  11661. static int
  11662. mg_upload_field_get(const char *key,
  11663. const char *value,
  11664. size_t value_size,
  11665. void *user_data)
  11666. {
  11667. /* Function should never be called */
  11668. (void)key;
  11669. (void)value;
  11670. (void)value_size;
  11671. (void)user_data;
  11672. return 0;
  11673. }
  11674. /* Helper function for deprecated mg_upload. */
  11675. static int
  11676. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11677. {
  11678. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11679. (void)file_size;
  11680. fud->num_uploaded_files++;
  11681. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11682. return 0;
  11683. }
  11684. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11685. int
  11686. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11687. {
  11688. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11689. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11690. mg_upload_field_get,
  11691. mg_upload_field_stored,
  11692. 0};
  11693. int ret;
  11694. fdh.user_data = (void *)&fud;
  11695. ret = mg_handle_form_request(conn, &fdh);
  11696. if (ret < 0) {
  11697. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11698. }
  11699. return fud.num_uploaded_files;
  11700. }
  11701. #endif
  11702. static int
  11703. get_first_ssl_listener_index(const struct mg_context *ctx)
  11704. {
  11705. unsigned int i;
  11706. int idx = -1;
  11707. if (ctx) {
  11708. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11709. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11710. }
  11711. }
  11712. return idx;
  11713. }
  11714. /* Return host (without port) */
  11715. static void
  11716. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11717. {
  11718. const char *host_header =
  11719. get_header(ri->http_headers, ri->num_headers, "Host");
  11720. host->ptr = NULL;
  11721. host->len = 0;
  11722. if (host_header != NULL) {
  11723. char *pos;
  11724. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11725. * is found. */
  11726. if (*host_header == '[') {
  11727. pos = strchr(host_header, ']');
  11728. if (!pos) {
  11729. /* Malformed hostname starts with '[', but no ']' found */
  11730. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11731. return;
  11732. }
  11733. /* terminate after ']' */
  11734. host->ptr = host_header;
  11735. host->len = (size_t)(pos + 1 - host_header);
  11736. } else {
  11737. /* Otherwise, a ':' separates hostname and port number */
  11738. pos = strchr(host_header, ':');
  11739. if (pos != NULL) {
  11740. host->len = (size_t)(pos - host_header);
  11741. } else {
  11742. host->len = strlen(host_header);
  11743. }
  11744. host->ptr = host_header;
  11745. }
  11746. }
  11747. }
  11748. static int
  11749. switch_domain_context(struct mg_connection *conn)
  11750. {
  11751. struct vec host;
  11752. get_host_from_request_info(&host, &conn->request_info);
  11753. if (host.ptr) {
  11754. if (conn->ssl) {
  11755. /* This is a HTTPS connection, maybe we have a hostname
  11756. * from SNI (set in ssl_servername_callback). */
  11757. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11758. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11759. /* We are not using the default domain */
  11760. if ((strlen(sslhost) != host.len)
  11761. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11762. /* Mismatch between SNI domain and HTTP domain */
  11763. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11764. sslhost,
  11765. (int)host.len,
  11766. host.ptr);
  11767. return 0;
  11768. }
  11769. }
  11770. } else {
  11771. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11772. while (dom) {
  11773. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11774. && !mg_strncasecmp(host.ptr,
  11775. dom->config[AUTHENTICATION_DOMAIN],
  11776. host.len)) {
  11777. /* Found matching domain */
  11778. DEBUG_TRACE("HTTP domain %s found",
  11779. dom->config[AUTHENTICATION_DOMAIN]);
  11780. /* TODO: Check if this is a HTTP or HTTPS domain */
  11781. conn->dom_ctx = dom;
  11782. break;
  11783. }
  11784. mg_lock_context(conn->phys_ctx);
  11785. dom = dom->next;
  11786. mg_unlock_context(conn->phys_ctx);
  11787. }
  11788. }
  11789. } else {
  11790. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11791. return 1;
  11792. }
  11793. DEBUG_TRACE("HTTP%s Host: %.*s",
  11794. conn->ssl ? "S" : "",
  11795. (int)host.len,
  11796. host.ptr);
  11797. return 1;
  11798. }
  11799. static void
  11800. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11801. {
  11802. struct vec host;
  11803. char target_url[MG_BUF_LEN];
  11804. int truncated = 0;
  11805. conn->must_close = 1;
  11806. /* Send host, port, uri and (if it exists) ?query_string */
  11807. get_host_from_request_info(&host, &conn->request_info);
  11808. if (host.ptr) {
  11809. /* Use "308 Permanent Redirect" */
  11810. int redirect_code = 308;
  11811. /* Create target URL */
  11812. mg_snprintf(conn,
  11813. &truncated,
  11814. target_url,
  11815. sizeof(target_url),
  11816. "https://%.*s:%d%s%s%s",
  11817. (int)host.len,
  11818. host.ptr,
  11819. (int)ntohs(USA_IN_PORT_UNSAFE(
  11820. &(conn->phys_ctx->listening_sockets[ssl_index].lsa))),
  11821. conn->request_info.local_uri,
  11822. (conn->request_info.query_string == NULL) ? "" : "?",
  11823. (conn->request_info.query_string == NULL)
  11824. ? ""
  11825. : conn->request_info.query_string);
  11826. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11827. * is used as buffer size) */
  11828. if (truncated) {
  11829. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11830. return;
  11831. }
  11832. /* Use redirect helper function */
  11833. mg_send_http_redirect(conn, target_url, redirect_code);
  11834. } else {
  11835. mg_send_http_error(conn, 400, "%s", "Bad Request");
  11836. }
  11837. }
  11838. static void
  11839. mg_set_handler_type(struct mg_context *phys_ctx,
  11840. struct mg_domain_context *dom_ctx,
  11841. const char *uri,
  11842. int handler_type,
  11843. int is_delete_request,
  11844. mg_request_handler handler,
  11845. struct mg_websocket_subprotocols *subprotocols,
  11846. mg_websocket_connect_handler connect_handler,
  11847. mg_websocket_ready_handler ready_handler,
  11848. mg_websocket_data_handler data_handler,
  11849. mg_websocket_close_handler close_handler,
  11850. mg_authorization_handler auth_handler,
  11851. void *cbdata)
  11852. {
  11853. struct mg_handler_info *tmp_rh, **lastref;
  11854. size_t urilen = strlen(uri);
  11855. if (handler_type == WEBSOCKET_HANDLER) {
  11856. DEBUG_ASSERT(handler == NULL);
  11857. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11858. || ready_handler != NULL || data_handler != NULL
  11859. || close_handler != NULL);
  11860. DEBUG_ASSERT(auth_handler == NULL);
  11861. if (handler != NULL) {
  11862. return;
  11863. }
  11864. if (!is_delete_request && (connect_handler == NULL)
  11865. && (ready_handler == NULL) && (data_handler == NULL)
  11866. && (close_handler == NULL)) {
  11867. return;
  11868. }
  11869. if (auth_handler != NULL) {
  11870. return;
  11871. }
  11872. } else if (handler_type == REQUEST_HANDLER) {
  11873. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11874. && data_handler == NULL && close_handler == NULL);
  11875. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11876. DEBUG_ASSERT(auth_handler == NULL);
  11877. if ((connect_handler != NULL) || (ready_handler != NULL)
  11878. || (data_handler != NULL) || (close_handler != NULL)) {
  11879. return;
  11880. }
  11881. if (!is_delete_request && (handler == NULL)) {
  11882. return;
  11883. }
  11884. if (auth_handler != NULL) {
  11885. return;
  11886. }
  11887. } else { /* AUTH_HANDLER */
  11888. DEBUG_ASSERT(handler == NULL);
  11889. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11890. && data_handler == NULL && close_handler == NULL);
  11891. DEBUG_ASSERT(auth_handler != NULL);
  11892. if (handler != NULL) {
  11893. return;
  11894. }
  11895. if ((connect_handler != NULL) || (ready_handler != NULL)
  11896. || (data_handler != NULL) || (close_handler != NULL)) {
  11897. return;
  11898. }
  11899. if (!is_delete_request && (auth_handler == NULL)) {
  11900. return;
  11901. }
  11902. }
  11903. if (!phys_ctx || !dom_ctx) {
  11904. return;
  11905. }
  11906. mg_lock_context(phys_ctx);
  11907. /* first try to find an existing handler */
  11908. do {
  11909. lastref = &(dom_ctx->handlers);
  11910. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11911. tmp_rh = tmp_rh->next) {
  11912. if (tmp_rh->handler_type == handler_type
  11913. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11914. if (!is_delete_request) {
  11915. /* update existing handler */
  11916. if (handler_type == REQUEST_HANDLER) {
  11917. /* Wait for end of use before updating */
  11918. if (tmp_rh->refcount) {
  11919. mg_unlock_context(phys_ctx);
  11920. mg_sleep(1);
  11921. mg_lock_context(phys_ctx);
  11922. /* tmp_rh might have been freed, search again. */
  11923. break;
  11924. }
  11925. /* Ok, the handler is no more use -> Update it */
  11926. tmp_rh->handler = handler;
  11927. } else if (handler_type == WEBSOCKET_HANDLER) {
  11928. tmp_rh->subprotocols = subprotocols;
  11929. tmp_rh->connect_handler = connect_handler;
  11930. tmp_rh->ready_handler = ready_handler;
  11931. tmp_rh->data_handler = data_handler;
  11932. tmp_rh->close_handler = close_handler;
  11933. } else { /* AUTH_HANDLER */
  11934. tmp_rh->auth_handler = auth_handler;
  11935. }
  11936. tmp_rh->cbdata = cbdata;
  11937. } else {
  11938. /* remove existing handler */
  11939. if (handler_type == REQUEST_HANDLER) {
  11940. /* Wait for end of use before removing */
  11941. if (tmp_rh->refcount) {
  11942. tmp_rh->removing = 1;
  11943. mg_unlock_context(phys_ctx);
  11944. mg_sleep(1);
  11945. mg_lock_context(phys_ctx);
  11946. /* tmp_rh might have been freed, search again. */
  11947. break;
  11948. }
  11949. /* Ok, the handler is no more used */
  11950. }
  11951. *lastref = tmp_rh->next;
  11952. mg_free(tmp_rh->uri);
  11953. mg_free(tmp_rh);
  11954. }
  11955. mg_unlock_context(phys_ctx);
  11956. return;
  11957. }
  11958. lastref = &(tmp_rh->next);
  11959. }
  11960. } while (tmp_rh != NULL);
  11961. if (is_delete_request) {
  11962. /* no handler to set, this was a remove request to a non-existing
  11963. * handler */
  11964. mg_unlock_context(phys_ctx);
  11965. return;
  11966. }
  11967. tmp_rh =
  11968. (struct mg_handler_info *)mg_calloc_ctx(1,
  11969. sizeof(struct mg_handler_info),
  11970. phys_ctx);
  11971. if (tmp_rh == NULL) {
  11972. mg_unlock_context(phys_ctx);
  11973. mg_cry_ctx_internal(phys_ctx,
  11974. "%s",
  11975. "Cannot create new request handler struct, OOM");
  11976. return;
  11977. }
  11978. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11979. if (!tmp_rh->uri) {
  11980. mg_unlock_context(phys_ctx);
  11981. mg_free(tmp_rh);
  11982. mg_cry_ctx_internal(phys_ctx,
  11983. "%s",
  11984. "Cannot create new request handler struct, OOM");
  11985. return;
  11986. }
  11987. tmp_rh->uri_len = urilen;
  11988. if (handler_type == REQUEST_HANDLER) {
  11989. tmp_rh->refcount = 0;
  11990. tmp_rh->removing = 0;
  11991. tmp_rh->handler = handler;
  11992. } else if (handler_type == WEBSOCKET_HANDLER) {
  11993. tmp_rh->subprotocols = subprotocols;
  11994. tmp_rh->connect_handler = connect_handler;
  11995. tmp_rh->ready_handler = ready_handler;
  11996. tmp_rh->data_handler = data_handler;
  11997. tmp_rh->close_handler = close_handler;
  11998. } else { /* AUTH_HANDLER */
  11999. tmp_rh->auth_handler = auth_handler;
  12000. }
  12001. tmp_rh->cbdata = cbdata;
  12002. tmp_rh->handler_type = handler_type;
  12003. tmp_rh->next = NULL;
  12004. *lastref = tmp_rh;
  12005. mg_unlock_context(phys_ctx);
  12006. }
  12007. void
  12008. mg_set_request_handler(struct mg_context *ctx,
  12009. const char *uri,
  12010. mg_request_handler handler,
  12011. void *cbdata)
  12012. {
  12013. mg_set_handler_type(ctx,
  12014. &(ctx->dd),
  12015. uri,
  12016. REQUEST_HANDLER,
  12017. handler == NULL,
  12018. handler,
  12019. NULL,
  12020. NULL,
  12021. NULL,
  12022. NULL,
  12023. NULL,
  12024. NULL,
  12025. cbdata);
  12026. }
  12027. void
  12028. mg_set_websocket_handler(struct mg_context *ctx,
  12029. const char *uri,
  12030. mg_websocket_connect_handler connect_handler,
  12031. mg_websocket_ready_handler ready_handler,
  12032. mg_websocket_data_handler data_handler,
  12033. mg_websocket_close_handler close_handler,
  12034. void *cbdata)
  12035. {
  12036. mg_set_websocket_handler_with_subprotocols(ctx,
  12037. uri,
  12038. NULL,
  12039. connect_handler,
  12040. ready_handler,
  12041. data_handler,
  12042. close_handler,
  12043. cbdata);
  12044. }
  12045. void
  12046. mg_set_websocket_handler_with_subprotocols(
  12047. struct mg_context *ctx,
  12048. const char *uri,
  12049. struct mg_websocket_subprotocols *subprotocols,
  12050. mg_websocket_connect_handler connect_handler,
  12051. mg_websocket_ready_handler ready_handler,
  12052. mg_websocket_data_handler data_handler,
  12053. mg_websocket_close_handler close_handler,
  12054. void *cbdata)
  12055. {
  12056. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12057. && (data_handler == NULL)
  12058. && (close_handler == NULL);
  12059. mg_set_handler_type(ctx,
  12060. &(ctx->dd),
  12061. uri,
  12062. WEBSOCKET_HANDLER,
  12063. is_delete_request,
  12064. NULL,
  12065. subprotocols,
  12066. connect_handler,
  12067. ready_handler,
  12068. data_handler,
  12069. close_handler,
  12070. NULL,
  12071. cbdata);
  12072. }
  12073. void
  12074. mg_set_auth_handler(struct mg_context *ctx,
  12075. const char *uri,
  12076. mg_authorization_handler handler,
  12077. void *cbdata)
  12078. {
  12079. mg_set_handler_type(ctx,
  12080. &(ctx->dd),
  12081. uri,
  12082. AUTH_HANDLER,
  12083. handler == NULL,
  12084. NULL,
  12085. NULL,
  12086. NULL,
  12087. NULL,
  12088. NULL,
  12089. NULL,
  12090. handler,
  12091. cbdata);
  12092. }
  12093. static int
  12094. get_request_handler(struct mg_connection *conn,
  12095. int handler_type,
  12096. mg_request_handler *handler,
  12097. struct mg_websocket_subprotocols **subprotocols,
  12098. mg_websocket_connect_handler *connect_handler,
  12099. mg_websocket_ready_handler *ready_handler,
  12100. mg_websocket_data_handler *data_handler,
  12101. mg_websocket_close_handler *close_handler,
  12102. mg_authorization_handler *auth_handler,
  12103. void **cbdata,
  12104. struct mg_handler_info **handler_info)
  12105. {
  12106. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12107. if (request_info) {
  12108. const char *uri = request_info->local_uri;
  12109. size_t urilen = strlen(uri);
  12110. struct mg_handler_info *tmp_rh;
  12111. int step, matched;
  12112. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12113. return 0;
  12114. }
  12115. mg_lock_context(conn->phys_ctx);
  12116. for (step = 0; step < 3; step++) {
  12117. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12118. tmp_rh = tmp_rh->next) {
  12119. if (tmp_rh->handler_type != handler_type) {
  12120. continue;
  12121. }
  12122. if (step == 0) {
  12123. /* first try for an exact match */
  12124. matched = (tmp_rh->uri_len == urilen)
  12125. && (strcmp(tmp_rh->uri, uri) == 0);
  12126. } else if (step == 1) {
  12127. /* next try for a partial match, we will accept
  12128. uri/something */
  12129. matched =
  12130. (tmp_rh->uri_len < urilen)
  12131. && (uri[tmp_rh->uri_len] == '/')
  12132. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12133. } else {
  12134. /* finally try for pattern match */
  12135. matched =
  12136. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12137. }
  12138. if (matched) {
  12139. if (handler_type == WEBSOCKET_HANDLER) {
  12140. *subprotocols = tmp_rh->subprotocols;
  12141. *connect_handler = tmp_rh->connect_handler;
  12142. *ready_handler = tmp_rh->ready_handler;
  12143. *data_handler = tmp_rh->data_handler;
  12144. *close_handler = tmp_rh->close_handler;
  12145. } else if (handler_type == REQUEST_HANDLER) {
  12146. if (tmp_rh->removing) {
  12147. /* Treat as none found */
  12148. step = 2;
  12149. break;
  12150. }
  12151. *handler = tmp_rh->handler;
  12152. /* Acquire handler and give it back */
  12153. tmp_rh->refcount++;
  12154. *handler_info = tmp_rh;
  12155. } else { /* AUTH_HANDLER */
  12156. *auth_handler = tmp_rh->auth_handler;
  12157. }
  12158. *cbdata = tmp_rh->cbdata;
  12159. mg_unlock_context(conn->phys_ctx);
  12160. return 1;
  12161. }
  12162. }
  12163. }
  12164. mg_unlock_context(conn->phys_ctx);
  12165. }
  12166. return 0; /* none found */
  12167. }
  12168. /* Check if the script file is in a path, allowed for script files.
  12169. * This can be used if uploading files is possible not only for the server
  12170. * admin, and the upload mechanism does not check the file extension.
  12171. */
  12172. static int
  12173. is_in_script_path(const struct mg_connection *conn, const char *path)
  12174. {
  12175. /* TODO (Feature): Add config value for allowed script path.
  12176. * Default: All allowed. */
  12177. (void)conn;
  12178. (void)path;
  12179. return 1;
  12180. }
  12181. #if defined(USE_WEBSOCKET) \
  12182. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12183. static int
  12184. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12185. void *cbdata)
  12186. {
  12187. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12188. if (pcallbacks->websocket_connect) {
  12189. return pcallbacks->websocket_connect(conn);
  12190. }
  12191. /* No handler set - assume "OK" */
  12192. return 0;
  12193. }
  12194. static void
  12195. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12196. {
  12197. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12198. if (pcallbacks->websocket_ready) {
  12199. pcallbacks->websocket_ready(conn);
  12200. }
  12201. }
  12202. static int
  12203. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12204. int bits,
  12205. char *data,
  12206. size_t len,
  12207. void *cbdata)
  12208. {
  12209. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12210. if (pcallbacks->websocket_data) {
  12211. return pcallbacks->websocket_data(conn, bits, data, len);
  12212. }
  12213. /* No handler set - assume "OK" */
  12214. return 1;
  12215. }
  12216. static void
  12217. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12218. void *cbdata)
  12219. {
  12220. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12221. if (pcallbacks->connection_close) {
  12222. pcallbacks->connection_close(conn);
  12223. }
  12224. }
  12225. #endif
  12226. /* This is the heart of the Civetweb's logic.
  12227. * This function is called when the request is read, parsed and validated,
  12228. * and Civetweb must decide what action to take: serve a file, or
  12229. * a directory, or call embedded function, etcetera. */
  12230. static void
  12231. handle_request(struct mg_connection *conn)
  12232. {
  12233. struct mg_request_info *ri = &conn->request_info;
  12234. char path[PATH_MAX];
  12235. int uri_len, ssl_index;
  12236. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12237. is_put_or_delete_request = 0, is_callback_resource = 0;
  12238. int i;
  12239. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12240. mg_request_handler callback_handler = NULL;
  12241. struct mg_handler_info *handler_info = NULL;
  12242. struct mg_websocket_subprotocols *subprotocols;
  12243. mg_websocket_connect_handler ws_connect_handler = NULL;
  12244. mg_websocket_ready_handler ws_ready_handler = NULL;
  12245. mg_websocket_data_handler ws_data_handler = NULL;
  12246. mg_websocket_close_handler ws_close_handler = NULL;
  12247. void *callback_data = NULL;
  12248. mg_authorization_handler auth_handler = NULL;
  12249. void *auth_callback_data = NULL;
  12250. int handler_type;
  12251. time_t curtime = time(NULL);
  12252. char date[64];
  12253. path[0] = 0;
  12254. /* 1. get the request url */
  12255. /* 1.1. split into url and query string */
  12256. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12257. != NULL) {
  12258. *((char *)conn->request_info.query_string++) = '\0';
  12259. }
  12260. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12261. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12262. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12263. if (ssl_index >= 0) {
  12264. redirect_to_https_port(conn, ssl_index);
  12265. } else {
  12266. /* A http to https forward port has been specified,
  12267. * but no https port to forward to. */
  12268. mg_send_http_error(conn,
  12269. 503,
  12270. "%s",
  12271. "Error: SSL forward not configured properly");
  12272. mg_cry_internal(conn,
  12273. "%s",
  12274. "Can not redirect to SSL, no SSL port available");
  12275. }
  12276. return;
  12277. }
  12278. uri_len = (int)strlen(ri->local_uri);
  12279. /* 1.3. decode url (if config says so) */
  12280. if (should_decode_url(conn)) {
  12281. mg_url_decode(
  12282. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12283. }
  12284. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12285. * not possible */
  12286. remove_dot_segments((char *)ri->local_uri);
  12287. /* step 1. completed, the url is known now */
  12288. uri_len = (int)strlen(ri->local_uri);
  12289. DEBUG_TRACE("URL: %s", ri->local_uri);
  12290. /* 2. if this ip has limited speed, set it for this connection */
  12291. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12292. &conn->client.rsa,
  12293. ri->local_uri);
  12294. /* 3. call a "handle everything" callback, if registered */
  12295. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12296. /* Note that since V1.7 the "begin_request" function is called
  12297. * before an authorization check. If an authorization check is
  12298. * required, use a request_handler instead. */
  12299. i = conn->phys_ctx->callbacks.begin_request(conn);
  12300. if (i > 0) {
  12301. /* callback already processed the request. Store the
  12302. return value as a status code for the access log. */
  12303. conn->status_code = i;
  12304. if (!conn->must_close) {
  12305. discard_unread_request_data(conn);
  12306. }
  12307. return;
  12308. } else if (i == 0) {
  12309. /* civetweb should process the request */
  12310. } else {
  12311. /* unspecified - may change with the next version */
  12312. return;
  12313. }
  12314. }
  12315. /* request not yet handled by a handler or redirect, so the request
  12316. * is processed here */
  12317. /* 4. Check for CORS preflight requests and handle them (if configured).
  12318. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12319. */
  12320. if (!strcmp(ri->request_method, "OPTIONS")) {
  12321. /* Send a response to CORS preflights only if
  12322. * access_control_allow_methods is not NULL and not an empty string.
  12323. * In this case, scripts can still handle CORS. */
  12324. const char *cors_meth_cfg =
  12325. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12326. const char *cors_orig_cfg =
  12327. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12328. const char *cors_origin =
  12329. get_header(ri->http_headers, ri->num_headers, "Origin");
  12330. const char *cors_acrm = get_header(ri->http_headers,
  12331. ri->num_headers,
  12332. "Access-Control-Request-Method");
  12333. /* Todo: check if cors_origin is in cors_orig_cfg.
  12334. * Or, let the client check this. */
  12335. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12336. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12337. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12338. /* This is a valid CORS preflight, and the server is configured
  12339. * to
  12340. * handle it automatically. */
  12341. const char *cors_acrh =
  12342. get_header(ri->http_headers,
  12343. ri->num_headers,
  12344. "Access-Control-Request-Headers");
  12345. gmt_time_string(date, sizeof(date), &curtime);
  12346. mg_printf(conn,
  12347. "HTTP/1.1 200 OK\r\n"
  12348. "Date: %s\r\n"
  12349. "Access-Control-Allow-Origin: %s\r\n"
  12350. "Access-Control-Allow-Methods: %s\r\n"
  12351. "Content-Length: 0\r\n"
  12352. "Connection: %s\r\n",
  12353. date,
  12354. cors_orig_cfg,
  12355. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12356. suggest_connection_header(conn));
  12357. if (cors_acrh != NULL) {
  12358. /* CORS request is asking for additional headers */
  12359. const char *cors_hdr_cfg =
  12360. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12361. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12362. /* Allow only if access_control_allow_headers is
  12363. * not NULL and not an empty string. If this
  12364. * configuration is set to *, allow everything.
  12365. * Otherwise this configuration must be a list
  12366. * of allowed HTTP header names. */
  12367. mg_printf(conn,
  12368. "Access-Control-Allow-Headers: %s\r\n",
  12369. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12370. : cors_hdr_cfg));
  12371. }
  12372. }
  12373. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12374. mg_printf(conn, "\r\n");
  12375. return;
  12376. }
  12377. }
  12378. /* 5. interpret the url to find out how the request must be handled
  12379. */
  12380. /* 5.1. first test, if the request targets the regular http(s)://
  12381. * protocol namespace or the websocket ws(s):// protocol namespace.
  12382. */
  12383. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12384. #if defined(USE_WEBSOCKET)
  12385. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12386. #else
  12387. handler_type = REQUEST_HANDLER;
  12388. #endif /* defined(USE_WEBSOCKET) */
  12389. /* 5.2. check if the request will be handled by a callback */
  12390. if (get_request_handler(conn,
  12391. handler_type,
  12392. &callback_handler,
  12393. &subprotocols,
  12394. &ws_connect_handler,
  12395. &ws_ready_handler,
  12396. &ws_data_handler,
  12397. &ws_close_handler,
  12398. NULL,
  12399. &callback_data,
  12400. &handler_info)) {
  12401. /* 5.2.1. A callback will handle this request. All requests
  12402. * handled
  12403. * by a callback have to be considered as requests to a script
  12404. * resource. */
  12405. is_callback_resource = 1;
  12406. is_script_resource = 1;
  12407. is_put_or_delete_request = is_put_or_delete_method(conn);
  12408. } else {
  12409. no_callback_resource:
  12410. /* 5.2.2. No callback is responsible for this request. The URI
  12411. * addresses a file based resource (static content or Lua/cgi
  12412. * scripts in the file system). */
  12413. is_callback_resource = 0;
  12414. interpret_uri(conn,
  12415. path,
  12416. sizeof(path),
  12417. &file.stat,
  12418. &is_found,
  12419. &is_script_resource,
  12420. &is_websocket_request,
  12421. &is_put_or_delete_request);
  12422. }
  12423. /* 6. authorization check */
  12424. /* 6.1. a custom authorization handler is installed */
  12425. if (get_request_handler(conn,
  12426. AUTH_HANDLER,
  12427. NULL,
  12428. NULL,
  12429. NULL,
  12430. NULL,
  12431. NULL,
  12432. NULL,
  12433. &auth_handler,
  12434. &auth_callback_data,
  12435. NULL)) {
  12436. if (!auth_handler(conn, auth_callback_data)) {
  12437. return;
  12438. }
  12439. } else if (is_put_or_delete_request && !is_script_resource
  12440. && !is_callback_resource) {
  12441. /* 6.2. this request is a PUT/DELETE to a real file */
  12442. /* 6.2.1. thus, the server must have real files */
  12443. #if defined(NO_FILES)
  12444. if (1) {
  12445. #else
  12446. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12447. #endif
  12448. /* This server does not have any real files, thus the
  12449. * PUT/DELETE methods are not valid. */
  12450. mg_send_http_error(conn,
  12451. 405,
  12452. "%s method not allowed",
  12453. conn->request_info.request_method);
  12454. return;
  12455. }
  12456. #if !defined(NO_FILES)
  12457. /* 6.2.2. Check if put authorization for static files is
  12458. * available.
  12459. */
  12460. if (!is_authorized_for_put(conn)) {
  12461. send_authorization_request(conn, NULL);
  12462. return;
  12463. }
  12464. #endif
  12465. } else {
  12466. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12467. * or it is a PUT or DELETE request to a resource that does not
  12468. * correspond to a file. Check authorization. */
  12469. if (!check_authorization(conn, path)) {
  12470. send_authorization_request(conn, NULL);
  12471. return;
  12472. }
  12473. }
  12474. /* request is authorized or does not need authorization */
  12475. /* 7. check if there are request handlers for this uri */
  12476. if (is_callback_resource) {
  12477. if (!is_websocket_request) {
  12478. i = callback_handler(conn, callback_data);
  12479. /* Callback handler will not be used anymore. Release it */
  12480. mg_lock_context(conn->phys_ctx);
  12481. handler_info->refcount--;
  12482. mg_unlock_context(conn->phys_ctx);
  12483. if (i > 0) {
  12484. /* Do nothing, callback has served the request. Store
  12485. * then return value as status code for the log and discard
  12486. * all data from the client not used by the callback. */
  12487. conn->status_code = i;
  12488. if (!conn->must_close) {
  12489. discard_unread_request_data(conn);
  12490. }
  12491. } else {
  12492. /* The handler did NOT handle the request. */
  12493. /* Some proper reactions would be:
  12494. * a) close the connections without sending anything
  12495. * b) send a 404 not found
  12496. * c) try if there is a file matching the URI
  12497. * It would be possible to do a, b or c in the callback
  12498. * implementation, and return 1 - we cannot do anything
  12499. * here, that is not possible in the callback.
  12500. *
  12501. * TODO: What would be the best reaction here?
  12502. * (Note: The reaction may change, if there is a better
  12503. *idea.)
  12504. */
  12505. /* For the moment, use option c: We look for a proper file,
  12506. * but since a file request is not always a script resource,
  12507. * the authorization check might be different. */
  12508. interpret_uri(conn,
  12509. path,
  12510. sizeof(path),
  12511. &file.stat,
  12512. &is_found,
  12513. &is_script_resource,
  12514. &is_websocket_request,
  12515. &is_put_or_delete_request);
  12516. callback_handler = NULL;
  12517. /* Here we are at a dead end:
  12518. * According to URI matching, a callback should be
  12519. * responsible for handling the request,
  12520. * we called it, but the callback declared itself
  12521. * not responsible.
  12522. * We use a goto here, to get out of this dead end,
  12523. * and continue with the default handling.
  12524. * A goto here is simpler and better to understand
  12525. * than some curious loop. */
  12526. goto no_callback_resource;
  12527. }
  12528. } else {
  12529. #if defined(USE_WEBSOCKET)
  12530. handle_websocket_request(conn,
  12531. path,
  12532. is_callback_resource,
  12533. subprotocols,
  12534. ws_connect_handler,
  12535. ws_ready_handler,
  12536. ws_data_handler,
  12537. ws_close_handler,
  12538. callback_data);
  12539. #endif
  12540. }
  12541. return;
  12542. }
  12543. /* 8. handle websocket requests */
  12544. #if defined(USE_WEBSOCKET)
  12545. if (is_websocket_request) {
  12546. if (is_script_resource) {
  12547. if (is_in_script_path(conn, path)) {
  12548. /* Websocket Lua script */
  12549. handle_websocket_request(conn,
  12550. path,
  12551. 0 /* Lua Script */,
  12552. NULL,
  12553. NULL,
  12554. NULL,
  12555. NULL,
  12556. NULL,
  12557. conn->phys_ctx->user_data);
  12558. } else {
  12559. /* Script was in an illegal path */
  12560. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12561. }
  12562. } else {
  12563. #if defined(MG_LEGACY_INTERFACE)
  12564. handle_websocket_request(
  12565. conn,
  12566. path,
  12567. !is_script_resource /* could be deprecated global callback
  12568. */
  12569. ,
  12570. NULL,
  12571. deprecated_websocket_connect_wrapper,
  12572. deprecated_websocket_ready_wrapper,
  12573. deprecated_websocket_data_wrapper,
  12574. NULL,
  12575. conn->phys_ctx->callbacks);
  12576. #else
  12577. mg_send_http_error(conn, 404, "%s", "Not found");
  12578. #endif
  12579. }
  12580. return;
  12581. } else
  12582. #endif
  12583. #if defined(NO_FILES)
  12584. /* 9a. In case the server uses only callbacks, this uri is
  12585. * unknown.
  12586. * Then, all request handling ends here. */
  12587. mg_send_http_error(conn, 404, "%s", "Not Found");
  12588. #else
  12589. /* 9b. This request is either for a static file or resource handled
  12590. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12591. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12592. mg_send_http_error(conn, 404, "%s", "Not Found");
  12593. return;
  12594. }
  12595. /* 10. Request is handled by a script */
  12596. if (is_script_resource) {
  12597. handle_file_based_request(conn, path, &file);
  12598. return;
  12599. }
  12600. /* 11. Handle put/delete/mkcol requests */
  12601. if (is_put_or_delete_request) {
  12602. /* 11.1. PUT method */
  12603. if (!strcmp(ri->request_method, "PUT")) {
  12604. put_file(conn, path);
  12605. return;
  12606. }
  12607. /* 11.2. DELETE method */
  12608. if (!strcmp(ri->request_method, "DELETE")) {
  12609. delete_file(conn, path);
  12610. return;
  12611. }
  12612. /* 11.3. MKCOL method */
  12613. if (!strcmp(ri->request_method, "MKCOL")) {
  12614. mkcol(conn, path);
  12615. return;
  12616. }
  12617. /* 11.4. PATCH method
  12618. * This method is not supported for static resources,
  12619. * only for scripts (Lua, CGI) and callbacks. */
  12620. mg_send_http_error(conn,
  12621. 405,
  12622. "%s method not allowed",
  12623. conn->request_info.request_method);
  12624. return;
  12625. }
  12626. /* 11. File does not exist, or it was configured that it should be
  12627. * hidden */
  12628. if (!is_found || (must_hide_file(conn, path))) {
  12629. mg_send_http_error(conn, 404, "%s", "Not found");
  12630. return;
  12631. }
  12632. /* 12. Directory uris should end with a slash */
  12633. if (file.stat.is_directory && (uri_len > 0)
  12634. && (ri->local_uri[uri_len - 1] != '/')) {
  12635. gmt_time_string(date, sizeof(date), &curtime);
  12636. mg_printf(conn,
  12637. "HTTP/1.1 301 Moved Permanently\r\n"
  12638. "Location: %s/\r\n"
  12639. "Date: %s\r\n"
  12640. /* "Cache-Control: private\r\n" (= default) */
  12641. "Content-Length: 0\r\n"
  12642. "Connection: %s\r\n",
  12643. ri->request_uri,
  12644. date,
  12645. suggest_connection_header(conn));
  12646. send_additional_header(conn);
  12647. mg_printf(conn, "\r\n");
  12648. return;
  12649. }
  12650. /* 13. Handle other methods than GET/HEAD */
  12651. /* 13.1. Handle PROPFIND */
  12652. if (!strcmp(ri->request_method, "PROPFIND")) {
  12653. handle_propfind(conn, path, &file.stat);
  12654. return;
  12655. }
  12656. /* 13.2. Handle OPTIONS for files */
  12657. if (!strcmp(ri->request_method, "OPTIONS")) {
  12658. /* This standard handler is only used for real files.
  12659. * Scripts should support the OPTIONS method themselves, to allow a
  12660. * maximum flexibility.
  12661. * Lua and CGI scripts may fully support CORS this way (including
  12662. * preflights). */
  12663. send_options(conn);
  12664. return;
  12665. }
  12666. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12667. if ((0 != strcmp(ri->request_method, "GET"))
  12668. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12669. mg_send_http_error(conn,
  12670. 405,
  12671. "%s method not allowed",
  12672. conn->request_info.request_method);
  12673. return;
  12674. }
  12675. /* 14. directories */
  12676. if (file.stat.is_directory) {
  12677. /* Substitute files have already been handled above. */
  12678. /* Here we can either generate and send a directory listing,
  12679. * or send an "access denied" error. */
  12680. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12681. "yes")) {
  12682. handle_directory_request(conn, path);
  12683. } else {
  12684. mg_send_http_error(conn,
  12685. 403,
  12686. "%s",
  12687. "Error: Directory listing denied");
  12688. }
  12689. return;
  12690. }
  12691. /* 15. read a normal file with GET or HEAD */
  12692. handle_file_based_request(conn, path, &file);
  12693. #endif /* !defined(NO_FILES) */
  12694. }
  12695. /* Include HTTP/2 modules */
  12696. #ifdef USE_HTTP2
  12697. #if defined(NO_SSL)
  12698. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12699. #endif
  12700. #include "mod_http2.inl"
  12701. #endif
  12702. #if !defined(NO_FILESYSTEMS)
  12703. static void
  12704. handle_file_based_request(struct mg_connection *conn,
  12705. const char *path,
  12706. struct mg_file *file)
  12707. {
  12708. if (!conn || !conn->dom_ctx) {
  12709. return;
  12710. }
  12711. if (0) {
  12712. #if defined(USE_LUA)
  12713. } else if (match_prefix(
  12714. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12715. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12716. path)
  12717. > 0) {
  12718. if (is_in_script_path(conn, path)) {
  12719. /* Lua server page: an SSI like page containing mostly plain
  12720. * html
  12721. * code
  12722. * plus some tags with server generated contents. */
  12723. handle_lsp_request(conn, path, file, NULL);
  12724. } else {
  12725. /* Script was in an illegal path */
  12726. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12727. }
  12728. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12729. strlen(
  12730. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12731. path)
  12732. > 0) {
  12733. if (is_in_script_path(conn, path)) {
  12734. /* Lua in-server module script: a CGI like script used to
  12735. * generate
  12736. * the
  12737. * entire reply. */
  12738. mg_exec_lua_script(conn, path, NULL);
  12739. } else {
  12740. /* Script was in an illegal path */
  12741. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12742. }
  12743. #endif
  12744. #if defined(USE_DUKTAPE)
  12745. } else if (match_prefix(
  12746. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12747. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12748. path)
  12749. > 0) {
  12750. if (is_in_script_path(conn, path)) {
  12751. /* Call duktape to generate the page */
  12752. mg_exec_duktape_script(conn, path);
  12753. } else {
  12754. /* Script was in an illegal path */
  12755. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12756. }
  12757. #endif
  12758. #if !defined(NO_CGI)
  12759. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12760. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12761. path)
  12762. > 0) {
  12763. if (is_in_script_path(conn, path)) {
  12764. /* CGI scripts may support all HTTP methods */
  12765. handle_cgi_request(conn, path);
  12766. } else {
  12767. /* Script was in an illegal path */
  12768. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12769. }
  12770. #endif /* !NO_CGI */
  12771. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12772. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12773. path)
  12774. > 0) {
  12775. if (is_in_script_path(conn, path)) {
  12776. handle_ssi_file_request(conn, path, file);
  12777. } else {
  12778. /* Script was in an illegal path */
  12779. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12780. }
  12781. #if !defined(NO_CACHING)
  12782. } else if ((!conn->in_error_handler)
  12783. && is_not_modified(conn, &file->stat)) {
  12784. /* Send 304 "Not Modified" - this must not send any body data */
  12785. handle_not_modified_static_file_request(conn, file);
  12786. #endif /* !NO_CACHING */
  12787. } else {
  12788. handle_static_file_request(conn, path, file, NULL, NULL);
  12789. }
  12790. }
  12791. #endif /* NO_FILESYSTEMS */
  12792. static void
  12793. close_all_listening_sockets(struct mg_context *ctx)
  12794. {
  12795. unsigned int i;
  12796. if (!ctx) {
  12797. return;
  12798. }
  12799. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12800. closesocket(ctx->listening_sockets[i].sock);
  12801. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12802. }
  12803. mg_free(ctx->listening_sockets);
  12804. ctx->listening_sockets = NULL;
  12805. mg_free(ctx->listening_socket_fds);
  12806. ctx->listening_socket_fds = NULL;
  12807. }
  12808. /* Valid listening port specification is: [ip_address:]port[s]
  12809. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12810. * Examples for IPv6: [::]:80, [::1]:80,
  12811. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12812. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12813. * In order to bind to both, IPv4 and IPv6, you can either add
  12814. * both ports using 8080,[::]:8080, or the short form +8080.
  12815. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12816. * one only accepting IPv4 the other only IPv6. +8080 creates
  12817. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12818. * environment, they might work differently, or might not work
  12819. * at all - it must be tested what options work best in the
  12820. * relevant network environment.
  12821. */
  12822. static int
  12823. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12824. {
  12825. unsigned int a, b, c, d;
  12826. unsigned port;
  12827. unsigned long portUL;
  12828. int ch, len;
  12829. const char *cb;
  12830. char *endptr;
  12831. #if defined(USE_IPV6)
  12832. char buf[100] = {0};
  12833. #endif
  12834. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12835. * Also, all-zeroes in the socket address means binding to all addresses
  12836. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12837. memset(so, 0, sizeof(*so));
  12838. so->lsa.sin.sin_family = AF_INET;
  12839. *ip_version = 0;
  12840. /* Initialize len as invalid. */
  12841. port = 0;
  12842. len = 0;
  12843. /* Test for different ways to format this string */
  12844. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12845. == 5) {
  12846. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12847. so->lsa.sin.sin_addr.s_addr =
  12848. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12849. so->lsa.sin.sin_port = htons((uint16_t)port);
  12850. *ip_version = 4;
  12851. #if defined(USE_IPV6)
  12852. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12853. && ((size_t)len <= vec->len)
  12854. && mg_inet_pton(
  12855. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12856. /* IPv6 address, examples: see above */
  12857. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12858. */
  12859. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12860. *ip_version = 6;
  12861. #endif
  12862. } else if ((vec->ptr[0] == '+')
  12863. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12864. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12865. /* Add 1 to len for the + character we skipped before */
  12866. len++;
  12867. #if defined(USE_IPV6)
  12868. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12869. so->lsa.sin6.sin6_family = AF_INET6;
  12870. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12871. *ip_version = 4 + 6;
  12872. #else
  12873. /* Bind to IPv4 only, since IPv6 is not built in. */
  12874. so->lsa.sin.sin_port = htons((uint16_t)port);
  12875. *ip_version = 4;
  12876. #endif
  12877. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12878. && (vec->ptr != endptr)) {
  12879. len = (int)(endptr - vec->ptr);
  12880. port = (uint16_t)portUL;
  12881. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12882. so->lsa.sin.sin_port = htons((uint16_t)port);
  12883. *ip_version = 4;
  12884. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12885. /* String could be a hostname. This check algotithm
  12886. * will only work for RFC 952 compliant hostnames,
  12887. * starting with a letter, containing only letters,
  12888. * digits and hyphen ('-'). Newer specs may allow
  12889. * more, but this is not guaranteed here, since it
  12890. * may interfere with rules for port option lists. */
  12891. /* According to RFC 1035, hostnames are restricted to 255 characters
  12892. * in total (63 between two dots). */
  12893. char hostname[256];
  12894. size_t hostnlen = (size_t)(cb - vec->ptr);
  12895. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12896. /* This would be invalid in any case */
  12897. *ip_version = 0;
  12898. return 0;
  12899. }
  12900. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12901. if (mg_inet_pton(
  12902. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12903. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12904. *ip_version = 4;
  12905. so->lsa.sin.sin_port = htons((uint16_t)port);
  12906. len += (int)(hostnlen + 1);
  12907. } else {
  12908. len = 0;
  12909. }
  12910. #if defined(USE_IPV6)
  12911. } else if (mg_inet_pton(AF_INET6,
  12912. hostname,
  12913. &so->lsa.sin6,
  12914. sizeof(so->lsa.sin6),
  12915. 1)) {
  12916. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12917. *ip_version = 6;
  12918. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12919. len += (int)(hostnlen + 1);
  12920. } else {
  12921. len = 0;
  12922. }
  12923. #endif
  12924. } else {
  12925. len = 0;
  12926. }
  12927. } else {
  12928. /* Parsing failure. */
  12929. len = 0;
  12930. }
  12931. /* sscanf and the option splitting code ensure the following condition
  12932. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12933. if ((len > 0) && is_valid_port(port)
  12934. && (((size_t)len == vec->len) || ((size_t)(len + 1) == vec->len))) {
  12935. /* Next character after the port number */
  12936. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12937. so->is_ssl = (ch == 's');
  12938. so->ssl_redir = (ch == 'r');
  12939. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12940. return 1;
  12941. }
  12942. }
  12943. /* Reset ip_version to 0 if there is an error */
  12944. *ip_version = 0;
  12945. return 0;
  12946. }
  12947. /* Is there any SSL port in use? */
  12948. static int
  12949. is_ssl_port_used(const char *ports)
  12950. {
  12951. if (ports) {
  12952. /* There are several different allowed syntax variants:
  12953. * - "80" for a single port using every network interface
  12954. * - "localhost:80" for a single port using only localhost
  12955. * - "80,localhost:8080" for two ports, one bound to localhost
  12956. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12957. * to IPv4 localhost, one to IPv6 localhost
  12958. * - "+80" use port 80 for IPv4 and IPv6
  12959. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12960. * for both: IPv4 and IPv4
  12961. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12962. * additionally port 8080 bound to localhost connections
  12963. *
  12964. * If we just look for 's' anywhere in the string, "localhost:80"
  12965. * will be detected as SSL (false positive).
  12966. * Looking for 's' after a digit may cause false positives in
  12967. * "my24service:8080".
  12968. * Looking from 's' backward if there are only ':' and numbers
  12969. * before will not work for "24service:8080" (non SSL, port 8080)
  12970. * or "24s" (SSL, port 24).
  12971. *
  12972. * Remark: Initially hostnames were not allowed to start with a
  12973. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12974. * Section 2.1).
  12975. *
  12976. * To get this correct, the entire string must be parsed as a whole,
  12977. * reading it as a list element for element and parsing with an
  12978. * algorithm equivalent to parse_port_string.
  12979. *
  12980. * In fact, we use local interface names here, not arbitrary
  12981. * hostnames, so in most cases the only name will be "localhost".
  12982. *
  12983. * So, for now, we use this simple algorithm, that may still return
  12984. * a false positive in bizarre cases.
  12985. */
  12986. int i;
  12987. int portslen = (int)strlen(ports);
  12988. char prevIsNumber = 0;
  12989. for (i = 0; i < portslen; i++) {
  12990. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12991. return 1;
  12992. }
  12993. if (ports[i] >= '0' && ports[i] <= '9') {
  12994. prevIsNumber = 1;
  12995. } else {
  12996. prevIsNumber = 0;
  12997. }
  12998. }
  12999. }
  13000. return 0;
  13001. }
  13002. static int
  13003. set_ports_option(struct mg_context *phys_ctx)
  13004. {
  13005. const char *list;
  13006. int on = 1;
  13007. #if defined(USE_IPV6)
  13008. int off = 0;
  13009. #endif
  13010. struct vec vec;
  13011. struct socket so, *ptr;
  13012. struct mg_pollfd *pfd;
  13013. union usa usa;
  13014. socklen_t len;
  13015. int ip_version;
  13016. int portsTotal = 0;
  13017. int portsOk = 0;
  13018. const char *opt_txt;
  13019. long opt_listen_backlog;
  13020. if (!phys_ctx) {
  13021. return 0;
  13022. }
  13023. memset(&so, 0, sizeof(so));
  13024. memset(&usa, 0, sizeof(usa));
  13025. len = sizeof(usa);
  13026. list = phys_ctx->dd.config[LISTENING_PORTS];
  13027. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13028. portsTotal++;
  13029. if (!parse_port_string(&vec, &so, &ip_version)) {
  13030. mg_cry_ctx_internal(
  13031. phys_ctx,
  13032. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13033. (int)vec.len,
  13034. vec.ptr,
  13035. portsTotal,
  13036. "[IP_ADDRESS:]PORT[s|r]");
  13037. continue;
  13038. }
  13039. #if !defined(NO_SSL)
  13040. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13041. mg_cry_ctx_internal(phys_ctx,
  13042. "Cannot add SSL socket (entry %i)",
  13043. portsTotal);
  13044. continue;
  13045. }
  13046. #endif
  13047. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13048. == INVALID_SOCKET) {
  13049. mg_cry_ctx_internal(phys_ctx,
  13050. "cannot create socket (entry %i)",
  13051. portsTotal);
  13052. continue;
  13053. }
  13054. #if defined(_WIN32)
  13055. /* Windows SO_REUSEADDR lets many procs binds to a
  13056. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13057. * if someone already has the socket -- DTL */
  13058. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13059. * Windows might need a few seconds before
  13060. * the same port can be used again in the
  13061. * same process, so a short Sleep may be
  13062. * required between mg_stop and mg_start.
  13063. */
  13064. if (setsockopt(so.sock,
  13065. SOL_SOCKET,
  13066. SO_EXCLUSIVEADDRUSE,
  13067. (SOCK_OPT_TYPE)&on,
  13068. sizeof(on))
  13069. != 0) {
  13070. /* Set reuse option, but don't abort on errors. */
  13071. mg_cry_ctx_internal(
  13072. phys_ctx,
  13073. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13074. portsTotal);
  13075. }
  13076. #else
  13077. if (setsockopt(so.sock,
  13078. SOL_SOCKET,
  13079. SO_REUSEADDR,
  13080. (SOCK_OPT_TYPE)&on,
  13081. sizeof(on))
  13082. != 0) {
  13083. /* Set reuse option, but don't abort on errors. */
  13084. mg_cry_ctx_internal(
  13085. phys_ctx,
  13086. "cannot set socket option SO_REUSEADDR (entry %i)",
  13087. portsTotal);
  13088. }
  13089. #endif
  13090. if (ip_version > 4) {
  13091. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13092. #if defined(USE_IPV6)
  13093. if (ip_version > 6) {
  13094. if (so.lsa.sa.sa_family == AF_INET6
  13095. && setsockopt(so.sock,
  13096. IPPROTO_IPV6,
  13097. IPV6_V6ONLY,
  13098. (void *)&off,
  13099. sizeof(off))
  13100. != 0) {
  13101. /* Set IPv6 only option, but don't abort on errors. */
  13102. mg_cry_ctx_internal(phys_ctx,
  13103. "cannot set socket option "
  13104. "IPV6_V6ONLY=off (entry %i)",
  13105. portsTotal);
  13106. }
  13107. } else {
  13108. if (so.lsa.sa.sa_family == AF_INET6
  13109. && setsockopt(so.sock,
  13110. IPPROTO_IPV6,
  13111. IPV6_V6ONLY,
  13112. (void *)&on,
  13113. sizeof(on))
  13114. != 0) {
  13115. /* Set IPv6 only option, but don't abort on errors. */
  13116. mg_cry_ctx_internal(phys_ctx,
  13117. "cannot set socket option "
  13118. "IPV6_V6ONLY=on (entry %i)",
  13119. portsTotal);
  13120. }
  13121. }
  13122. #else
  13123. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13124. closesocket(so.sock);
  13125. so.sock = INVALID_SOCKET;
  13126. continue;
  13127. #endif
  13128. }
  13129. if (so.lsa.sa.sa_family == AF_INET) {
  13130. len = sizeof(so.lsa.sin);
  13131. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13132. mg_cry_ctx_internal(phys_ctx,
  13133. "cannot bind to %.*s: %d (%s)",
  13134. (int)vec.len,
  13135. vec.ptr,
  13136. (int)ERRNO,
  13137. strerror(errno));
  13138. closesocket(so.sock);
  13139. so.sock = INVALID_SOCKET;
  13140. continue;
  13141. }
  13142. }
  13143. #if defined(USE_IPV6)
  13144. else if (so.lsa.sa.sa_family == AF_INET6) {
  13145. len = sizeof(so.lsa.sin6);
  13146. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13147. mg_cry_ctx_internal(phys_ctx,
  13148. "cannot bind to IPv6 %.*s: %d (%s)",
  13149. (int)vec.len,
  13150. vec.ptr,
  13151. (int)ERRNO,
  13152. strerror(errno));
  13153. closesocket(so.sock);
  13154. so.sock = INVALID_SOCKET;
  13155. continue;
  13156. }
  13157. }
  13158. #endif
  13159. else {
  13160. mg_cry_ctx_internal(
  13161. phys_ctx,
  13162. "cannot bind: address family not supported (entry %i)",
  13163. portsTotal);
  13164. closesocket(so.sock);
  13165. so.sock = INVALID_SOCKET;
  13166. continue;
  13167. }
  13168. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13169. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13170. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13171. mg_cry_ctx_internal(phys_ctx,
  13172. "%s value \"%s\" is invalid",
  13173. config_options[LISTEN_BACKLOG_SIZE].name,
  13174. opt_txt);
  13175. closesocket(so.sock);
  13176. so.sock = INVALID_SOCKET;
  13177. continue;
  13178. }
  13179. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13180. mg_cry_ctx_internal(phys_ctx,
  13181. "cannot listen to %.*s: %d (%s)",
  13182. (int)vec.len,
  13183. vec.ptr,
  13184. (int)ERRNO,
  13185. strerror(errno));
  13186. closesocket(so.sock);
  13187. so.sock = INVALID_SOCKET;
  13188. continue;
  13189. }
  13190. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13191. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13192. int err = (int)ERRNO;
  13193. mg_cry_ctx_internal(phys_ctx,
  13194. "call to getsockname failed %.*s: %d (%s)",
  13195. (int)vec.len,
  13196. vec.ptr,
  13197. err,
  13198. strerror(errno));
  13199. closesocket(so.sock);
  13200. so.sock = INVALID_SOCKET;
  13201. continue;
  13202. }
  13203. /* Update lsa port in case of random free ports */
  13204. #if defined(USE_IPV6)
  13205. if (so.lsa.sa.sa_family == AF_INET6) {
  13206. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13207. } else
  13208. #endif
  13209. {
  13210. so.lsa.sin.sin_port = usa.sin.sin_port;
  13211. }
  13212. if ((ptr = (struct socket *)
  13213. mg_realloc_ctx(phys_ctx->listening_sockets,
  13214. (phys_ctx->num_listening_sockets + 1)
  13215. * sizeof(phys_ctx->listening_sockets[0]),
  13216. phys_ctx))
  13217. == NULL) {
  13218. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13219. closesocket(so.sock);
  13220. so.sock = INVALID_SOCKET;
  13221. continue;
  13222. }
  13223. if ((pfd = (struct mg_pollfd *)
  13224. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13225. (phys_ctx->num_listening_sockets + 1)
  13226. * sizeof(phys_ctx->listening_socket_fds[0]),
  13227. phys_ctx))
  13228. == NULL) {
  13229. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13230. closesocket(so.sock);
  13231. so.sock = INVALID_SOCKET;
  13232. mg_free(ptr);
  13233. continue;
  13234. }
  13235. set_close_on_exec(so.sock, NULL, phys_ctx);
  13236. phys_ctx->listening_sockets = ptr;
  13237. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13238. phys_ctx->listening_socket_fds = pfd;
  13239. phys_ctx->num_listening_sockets++;
  13240. portsOk++;
  13241. }
  13242. if (portsOk != portsTotal) {
  13243. close_all_listening_sockets(phys_ctx);
  13244. portsOk = 0;
  13245. }
  13246. return portsOk;
  13247. }
  13248. static const char *
  13249. header_val(const struct mg_connection *conn, const char *header)
  13250. {
  13251. const char *header_value;
  13252. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13253. return "-";
  13254. } else {
  13255. return header_value;
  13256. }
  13257. }
  13258. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13259. static void log_access(const struct mg_connection *conn);
  13260. #include "external_log_access.inl"
  13261. #elif !defined(NO_FILESYSTEMS)
  13262. static void
  13263. log_access(const struct mg_connection *conn)
  13264. {
  13265. const struct mg_request_info *ri;
  13266. struct mg_file fi;
  13267. char date[64], src_addr[IP_ADDR_STR_LEN];
  13268. struct tm *tm;
  13269. const char *referer;
  13270. const char *user_agent;
  13271. char buf[4096];
  13272. if (!conn || !conn->dom_ctx) {
  13273. return;
  13274. }
  13275. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13276. if (mg_fopen(conn,
  13277. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13278. MG_FOPEN_MODE_APPEND,
  13279. &fi)
  13280. == 0) {
  13281. fi.access.fp = NULL;
  13282. }
  13283. } else {
  13284. fi.access.fp = NULL;
  13285. }
  13286. /* Log is written to a file and/or a callback. If both are not set,
  13287. * executing the rest of the function is pointless. */
  13288. if ((fi.access.fp == NULL)
  13289. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13290. return;
  13291. }
  13292. tm = localtime(&conn->conn_birth_time);
  13293. if (tm != NULL) {
  13294. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13295. } else {
  13296. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13297. date[sizeof(date) - 1] = '\0';
  13298. }
  13299. ri = &conn->request_info;
  13300. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13301. referer = header_val(conn, "Referer");
  13302. user_agent = header_val(conn, "User-Agent");
  13303. mg_snprintf(conn,
  13304. NULL, /* Ignore truncation in access log */
  13305. buf,
  13306. sizeof(buf),
  13307. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13308. src_addr,
  13309. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13310. date,
  13311. ri->request_method ? ri->request_method : "-",
  13312. ri->request_uri ? ri->request_uri : "-",
  13313. ri->query_string ? "?" : "",
  13314. ri->query_string ? ri->query_string : "",
  13315. ri->http_version,
  13316. conn->status_code,
  13317. conn->num_bytes_sent,
  13318. referer,
  13319. user_agent);
  13320. if (conn->phys_ctx->callbacks.log_access) {
  13321. conn->phys_ctx->callbacks.log_access(conn, buf);
  13322. }
  13323. if (fi.access.fp) {
  13324. int ok = 1;
  13325. flockfile(fi.access.fp);
  13326. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13327. ok = 0;
  13328. }
  13329. if (fflush(fi.access.fp) != 0) {
  13330. ok = 0;
  13331. }
  13332. funlockfile(fi.access.fp);
  13333. if (mg_fclose(&fi.access) != 0) {
  13334. ok = 0;
  13335. }
  13336. if (!ok) {
  13337. mg_cry_internal(conn,
  13338. "Error writing log file %s",
  13339. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13340. }
  13341. }
  13342. }
  13343. #else
  13344. #error Must either enable filesystems or provide a custom log_access implementation
  13345. #endif /* Externally provided function */
  13346. /* Verify given socket address against the ACL.
  13347. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13348. */
  13349. static int
  13350. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13351. {
  13352. int allowed, flag, matched;
  13353. struct vec vec;
  13354. if (phys_ctx) {
  13355. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13356. /* If any ACL is set, deny by default */
  13357. allowed = (list == NULL) ? '+' : '-';
  13358. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13359. flag = vec.ptr[0];
  13360. matched = -1;
  13361. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13362. vec.ptr++;
  13363. vec.len--;
  13364. matched = parse_match_net(&vec, sa, 1);
  13365. }
  13366. if (matched < 0) {
  13367. mg_cry_ctx_internal(phys_ctx,
  13368. "%s: subnet must be [+|-]IP-addr[/x]",
  13369. __func__);
  13370. return -1;
  13371. }
  13372. if (matched) {
  13373. allowed = flag;
  13374. }
  13375. }
  13376. return allowed == '+';
  13377. }
  13378. return -1;
  13379. }
  13380. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13381. static int
  13382. set_uid_option(struct mg_context *phys_ctx)
  13383. {
  13384. int success = 0;
  13385. if (phys_ctx) {
  13386. /* We are currently running as curr_uid. */
  13387. const uid_t curr_uid = getuid();
  13388. /* If set, we want to run as run_as_user. */
  13389. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13390. const struct passwd *to_pw = NULL;
  13391. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13392. /* run_as_user does not exist on the system. We can't proceed
  13393. * further. */
  13394. mg_cry_ctx_internal(phys_ctx,
  13395. "%s: unknown user [%s]",
  13396. __func__,
  13397. run_as_user);
  13398. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13399. /* There was either no request to change user, or we're already
  13400. * running as run_as_user. Nothing else to do.
  13401. */
  13402. success = 1;
  13403. } else {
  13404. /* Valid change request. */
  13405. if (setgid(to_pw->pw_gid) == -1) {
  13406. mg_cry_ctx_internal(phys_ctx,
  13407. "%s: setgid(%s): %s",
  13408. __func__,
  13409. run_as_user,
  13410. strerror(errno));
  13411. } else if (setgroups(0, NULL) == -1) {
  13412. mg_cry_ctx_internal(phys_ctx,
  13413. "%s: setgroups(): %s",
  13414. __func__,
  13415. strerror(errno));
  13416. } else if (setuid(to_pw->pw_uid) == -1) {
  13417. mg_cry_ctx_internal(phys_ctx,
  13418. "%s: setuid(%s): %s",
  13419. __func__,
  13420. run_as_user,
  13421. strerror(errno));
  13422. } else {
  13423. success = 1;
  13424. }
  13425. }
  13426. }
  13427. return success;
  13428. }
  13429. #endif /* !_WIN32 */
  13430. static void
  13431. tls_dtor(void *key)
  13432. {
  13433. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13434. /* key == pthread_getspecific(sTlsKey); */
  13435. if (tls) {
  13436. if (tls->is_master == 2) {
  13437. tls->is_master = -3; /* Mark memory as dead */
  13438. mg_free(tls);
  13439. }
  13440. }
  13441. pthread_setspecific(sTlsKey, NULL);
  13442. }
  13443. #if !defined(NO_SSL)
  13444. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13445. struct mg_domain_context *dom_ctx,
  13446. const char *pem,
  13447. const char *chain);
  13448. static const char *ssl_error(void);
  13449. static int
  13450. refresh_trust(struct mg_connection *conn)
  13451. {
  13452. struct stat cert_buf;
  13453. int64_t t = 0;
  13454. const char *pem;
  13455. const char *chain;
  13456. int should_verify_peer;
  13457. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13458. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13459. * refresh_trust still can not work. */
  13460. return 0;
  13461. }
  13462. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13463. if (chain == NULL) {
  13464. /* pem is not NULL here */
  13465. chain = pem;
  13466. }
  13467. if (*chain == 0) {
  13468. chain = NULL;
  13469. }
  13470. if (stat(pem, &cert_buf) != -1) {
  13471. t = (int64_t)cert_buf.st_mtime;
  13472. }
  13473. mg_lock_context(conn->phys_ctx);
  13474. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13475. conn->dom_ctx->ssl_cert_last_mtime = t;
  13476. should_verify_peer = 0;
  13477. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13478. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13479. == 0) {
  13480. should_verify_peer = 1;
  13481. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13482. "optional")
  13483. == 0) {
  13484. should_verify_peer = 1;
  13485. }
  13486. }
  13487. if (should_verify_peer) {
  13488. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13489. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13490. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13491. ca_file,
  13492. ca_path)
  13493. != 1) {
  13494. mg_unlock_context(conn->phys_ctx);
  13495. mg_cry_ctx_internal(
  13496. conn->phys_ctx,
  13497. "SSL_CTX_load_verify_locations error: %s "
  13498. "ssl_verify_peer requires setting "
  13499. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13500. "present in "
  13501. "the .conf file?",
  13502. ssl_error());
  13503. return 0;
  13504. }
  13505. }
  13506. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13507. mg_unlock_context(conn->phys_ctx);
  13508. return 0;
  13509. }
  13510. }
  13511. mg_unlock_context(conn->phys_ctx);
  13512. return 1;
  13513. }
  13514. #if defined(OPENSSL_API_1_1)
  13515. #else
  13516. static pthread_mutex_t *ssl_mutexes;
  13517. #endif /* OPENSSL_API_1_1 */
  13518. static int
  13519. sslize(struct mg_connection *conn,
  13520. int (*func)(SSL *),
  13521. const struct mg_client_options *client_options)
  13522. {
  13523. int ret, err;
  13524. int short_trust;
  13525. unsigned timeout = 1024;
  13526. unsigned i;
  13527. if (!conn) {
  13528. return 0;
  13529. }
  13530. short_trust =
  13531. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13532. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13533. if (short_trust) {
  13534. int trust_ret = refresh_trust(conn);
  13535. if (!trust_ret) {
  13536. return trust_ret;
  13537. }
  13538. }
  13539. mg_lock_context(conn->phys_ctx);
  13540. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13541. mg_unlock_context(conn->phys_ctx);
  13542. if (conn->ssl == NULL) {
  13543. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13544. OPENSSL_REMOVE_THREAD_STATE();
  13545. return 0;
  13546. }
  13547. SSL_set_app_data(conn->ssl, (char *)conn);
  13548. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13549. if (ret != 1) {
  13550. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13551. SSL_free(conn->ssl);
  13552. conn->ssl = NULL;
  13553. OPENSSL_REMOVE_THREAD_STATE();
  13554. return 0;
  13555. }
  13556. if (client_options) {
  13557. if (client_options->host_name) {
  13558. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13559. }
  13560. }
  13561. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13562. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13563. /* NOTE: The loop below acts as a back-off, so we can end
  13564. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13565. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13566. if (to >= 0) {
  13567. timeout = (unsigned)to;
  13568. }
  13569. }
  13570. /* SSL functions may fail and require to be called again:
  13571. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13572. * Here "func" could be SSL_connect or SSL_accept. */
  13573. for (i = 0; i <= timeout; i += 50) {
  13574. ERR_clear_error();
  13575. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13576. ret = func(conn->ssl);
  13577. if (ret != 1) {
  13578. err = SSL_get_error(conn->ssl, ret);
  13579. if ((err == SSL_ERROR_WANT_CONNECT)
  13580. || (err == SSL_ERROR_WANT_ACCEPT)
  13581. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13582. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13583. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13584. /* Don't wait if the server is going to be stopped. */
  13585. break;
  13586. }
  13587. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13588. /* Simply retry the function call. */
  13589. mg_sleep(50);
  13590. } else {
  13591. /* Need to retry the function call "later".
  13592. * See https://linux.die.net/man/3/ssl_get_error
  13593. * This is typical for non-blocking sockets. */
  13594. struct mg_pollfd pfd;
  13595. int pollres;
  13596. pfd.fd = conn->client.sock;
  13597. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13598. || (err == SSL_ERROR_WANT_WRITE))
  13599. ? POLLOUT
  13600. : POLLIN;
  13601. pollres =
  13602. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13603. if (pollres < 0) {
  13604. /* Break if error occured (-1)
  13605. * or server shutdown (-2) */
  13606. break;
  13607. }
  13608. }
  13609. } else if (err == SSL_ERROR_SYSCALL) {
  13610. /* This is an IO error. Look at errno. */
  13611. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13612. break;
  13613. } else {
  13614. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13615. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13616. break;
  13617. }
  13618. } else {
  13619. /* success */
  13620. break;
  13621. }
  13622. }
  13623. ERR_clear_error();
  13624. if (ret != 1) {
  13625. SSL_free(conn->ssl);
  13626. conn->ssl = NULL;
  13627. OPENSSL_REMOVE_THREAD_STATE();
  13628. return 0;
  13629. }
  13630. return 1;
  13631. }
  13632. /* Return OpenSSL error message (from CRYPTO lib) */
  13633. static const char *
  13634. ssl_error(void)
  13635. {
  13636. unsigned long err;
  13637. err = ERR_get_error();
  13638. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13639. }
  13640. static int
  13641. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13642. {
  13643. int i;
  13644. const char hexdigit[] = "0123456789abcdef";
  13645. if ((memlen <= 0) || (buflen <= 0)) {
  13646. return 0;
  13647. }
  13648. if (buflen < (3 * memlen)) {
  13649. return 0;
  13650. }
  13651. for (i = 0; i < memlen; i++) {
  13652. if (i > 0) {
  13653. buf[3 * i - 1] = ' ';
  13654. }
  13655. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13656. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13657. }
  13658. buf[3 * memlen - 1] = 0;
  13659. return 1;
  13660. }
  13661. static int
  13662. ssl_get_client_cert_info(const struct mg_connection *conn,
  13663. struct mg_client_cert *client_cert)
  13664. {
  13665. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13666. if (cert) {
  13667. char str_buf[1024];
  13668. unsigned char buf[256];
  13669. char *str_serial = NULL;
  13670. unsigned int ulen;
  13671. int ilen;
  13672. unsigned char *tmp_buf;
  13673. unsigned char *tmp_p;
  13674. /* Handle to algorithm used for fingerprint */
  13675. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13676. /* Get Subject and issuer */
  13677. X509_NAME *subj = X509_get_subject_name(cert);
  13678. X509_NAME *iss = X509_get_issuer_name(cert);
  13679. /* Get serial number */
  13680. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13681. /* Translate serial number to a hex string */
  13682. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13683. if (serial_bn) {
  13684. str_serial = BN_bn2hex(serial_bn);
  13685. BN_free(serial_bn);
  13686. }
  13687. client_cert->serial =
  13688. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13689. /* Translate subject and issuer to a string */
  13690. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13691. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13692. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13693. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13694. /* Calculate SHA1 fingerprint and store as a hex string */
  13695. ulen = 0;
  13696. /* ASN1_digest is deprecated. Do the calculation manually,
  13697. * using EVP_Digest. */
  13698. ilen = i2d_X509(cert, NULL);
  13699. tmp_buf = (ilen > 0)
  13700. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13701. conn->phys_ctx)
  13702. : NULL;
  13703. if (tmp_buf) {
  13704. tmp_p = tmp_buf;
  13705. (void)i2d_X509(cert, &tmp_p);
  13706. if (!EVP_Digest(
  13707. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13708. ulen = 0;
  13709. }
  13710. mg_free(tmp_buf);
  13711. }
  13712. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13713. *str_buf = 0;
  13714. }
  13715. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13716. client_cert->peer_cert = (void *)cert;
  13717. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13718. * see https://linux.die.net/man/3/bn_bn2hex */
  13719. OPENSSL_free(str_serial);
  13720. return 1;
  13721. }
  13722. return 0;
  13723. }
  13724. #if defined(OPENSSL_API_1_1)
  13725. #else
  13726. static void
  13727. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13728. {
  13729. (void)line;
  13730. (void)file;
  13731. if (mode & 1) {
  13732. /* 1 is CRYPTO_LOCK */
  13733. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13734. } else {
  13735. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13736. }
  13737. }
  13738. #endif /* OPENSSL_API_1_1 */
  13739. #if !defined(NO_SSL_DL)
  13740. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13741. static void *
  13742. load_tls_dll(char *ebuf,
  13743. size_t ebuf_len,
  13744. const char *dll_name,
  13745. struct ssl_func *sw,
  13746. int *feature_missing)
  13747. {
  13748. union {
  13749. void *p;
  13750. void (*fp)(void);
  13751. } u;
  13752. void *dll_handle;
  13753. struct ssl_func *fp;
  13754. int ok;
  13755. int truncated = 0;
  13756. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13757. mg_snprintf(NULL,
  13758. NULL, /* No truncation check for ebuf */
  13759. ebuf,
  13760. ebuf_len,
  13761. "%s: cannot load %s",
  13762. __func__,
  13763. dll_name);
  13764. return NULL;
  13765. }
  13766. ok = 1;
  13767. for (fp = sw; fp->name != NULL; fp++) {
  13768. #if defined(_WIN32)
  13769. /* GetProcAddress() returns pointer to function */
  13770. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13771. #else
  13772. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13773. * pointers to function pointers. We need to use a union to make a
  13774. * cast. */
  13775. u.p = dlsym(dll_handle, fp->name);
  13776. #endif /* _WIN32 */
  13777. /* Set pointer (might be NULL) */
  13778. fp->ptr = u.fp;
  13779. if (u.fp == NULL) {
  13780. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13781. if (feature_missing) {
  13782. feature_missing[fp->required]++;
  13783. }
  13784. if (fp->required == TLS_Mandatory) {
  13785. /* Mandatory function is missing */
  13786. if (ok) {
  13787. /* This is the first missing function.
  13788. * Create a new error message. */
  13789. mg_snprintf(NULL,
  13790. &truncated,
  13791. ebuf,
  13792. ebuf_len,
  13793. "%s: %s: cannot find %s",
  13794. __func__,
  13795. dll_name,
  13796. fp->name);
  13797. ok = 0;
  13798. } else {
  13799. /* This is yet anothermissing function.
  13800. * Append existing error message. */
  13801. size_t cur_len = strlen(ebuf);
  13802. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13803. mg_snprintf(NULL,
  13804. &truncated,
  13805. ebuf + cur_len,
  13806. ebuf_len - cur_len - 3,
  13807. ", %s",
  13808. fp->name);
  13809. if (truncated) {
  13810. /* If truncated, add "..." */
  13811. strcat(ebuf, "...");
  13812. }
  13813. }
  13814. }
  13815. }
  13816. }
  13817. }
  13818. if (!ok) {
  13819. (void)dlclose(dll_handle);
  13820. return NULL;
  13821. }
  13822. return dll_handle;
  13823. }
  13824. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13825. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13826. #endif /* NO_SSL_DL */
  13827. #if defined(SSL_ALREADY_INITIALIZED)
  13828. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13829. #else
  13830. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13831. #endif
  13832. static int
  13833. initialize_ssl(char *ebuf, size_t ebuf_len)
  13834. {
  13835. #if !defined(OPENSSL_API_1_1)
  13836. int i, num_locks;
  13837. size_t size;
  13838. #endif
  13839. if (ebuf_len > 0) {
  13840. ebuf[0] = 0;
  13841. }
  13842. #if !defined(NO_SSL_DL)
  13843. if (!cryptolib_dll_handle) {
  13844. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13845. cryptolib_dll_handle = load_tls_dll(
  13846. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13847. if (!cryptolib_dll_handle) {
  13848. mg_snprintf(NULL,
  13849. NULL, /* No truncation check for ebuf */
  13850. ebuf,
  13851. ebuf_len,
  13852. "%s: error loading library %s",
  13853. __func__,
  13854. CRYPTO_LIB);
  13855. DEBUG_TRACE("%s", ebuf);
  13856. return 0;
  13857. }
  13858. }
  13859. #endif /* NO_SSL_DL */
  13860. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13861. return 1;
  13862. }
  13863. #if !defined(OPENSSL_API_1_1)
  13864. /* Initialize locking callbacks, needed for thread safety.
  13865. * http://www.openssl.org/support/faq.html#PROG1
  13866. */
  13867. num_locks = CRYPTO_num_locks();
  13868. if (num_locks < 0) {
  13869. num_locks = 0;
  13870. }
  13871. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13872. /* allocate mutex array, if required */
  13873. if (num_locks == 0) {
  13874. /* No mutex array required */
  13875. ssl_mutexes = NULL;
  13876. } else {
  13877. /* Mutex array required - allocate it */
  13878. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13879. /* Check OOM */
  13880. if (ssl_mutexes == NULL) {
  13881. mg_snprintf(NULL,
  13882. NULL, /* No truncation check for ebuf */
  13883. ebuf,
  13884. ebuf_len,
  13885. "%s: cannot allocate mutexes: %s",
  13886. __func__,
  13887. ssl_error());
  13888. DEBUG_TRACE("%s", ebuf);
  13889. return 0;
  13890. }
  13891. /* initialize mutex array */
  13892. for (i = 0; i < num_locks; i++) {
  13893. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13894. mg_snprintf(NULL,
  13895. NULL, /* No truncation check for ebuf */
  13896. ebuf,
  13897. ebuf_len,
  13898. "%s: error initializing mutex %i of %i",
  13899. __func__,
  13900. i,
  13901. num_locks);
  13902. DEBUG_TRACE("%s", ebuf);
  13903. mg_free(ssl_mutexes);
  13904. return 0;
  13905. }
  13906. }
  13907. }
  13908. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13909. CRYPTO_set_id_callback(&mg_current_thread_id);
  13910. #endif /* OPENSSL_API_1_1 */
  13911. #if !defined(NO_SSL_DL)
  13912. if (!ssllib_dll_handle) {
  13913. ssllib_dll_handle =
  13914. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13915. if (!ssllib_dll_handle) {
  13916. #if !defined(OPENSSL_API_1_1)
  13917. mg_free(ssl_mutexes);
  13918. #endif
  13919. DEBUG_TRACE("%s", ebuf);
  13920. return 0;
  13921. }
  13922. }
  13923. #endif /* NO_SSL_DL */
  13924. #if defined(OPENSSL_API_1_1)
  13925. /* Initialize SSL library */
  13926. OPENSSL_init_ssl(0, NULL);
  13927. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13928. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13929. NULL);
  13930. #else
  13931. /* Initialize SSL library */
  13932. SSL_library_init();
  13933. SSL_load_error_strings();
  13934. #endif
  13935. return 1;
  13936. }
  13937. static int
  13938. ssl_use_pem_file(struct mg_context *phys_ctx,
  13939. struct mg_domain_context *dom_ctx,
  13940. const char *pem,
  13941. const char *chain)
  13942. {
  13943. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13944. mg_cry_ctx_internal(phys_ctx,
  13945. "%s: cannot open certificate file %s: %s",
  13946. __func__,
  13947. pem,
  13948. ssl_error());
  13949. return 0;
  13950. }
  13951. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13952. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13953. mg_cry_ctx_internal(phys_ctx,
  13954. "%s: cannot open private key file %s: %s",
  13955. __func__,
  13956. pem,
  13957. ssl_error());
  13958. return 0;
  13959. }
  13960. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13961. mg_cry_ctx_internal(phys_ctx,
  13962. "%s: certificate and private key do not match: %s",
  13963. __func__,
  13964. pem);
  13965. return 0;
  13966. }
  13967. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13968. * chain files that contain private keys and certificates in
  13969. * SSL_CTX_use_certificate_chain_file.
  13970. * The CivetWeb-Server used pem-Files that contained both information.
  13971. * In order to make wolfSSL work, it is split in two files.
  13972. * One file that contains key and certificate used by the server and
  13973. * an optional chain file for the ssl stack.
  13974. */
  13975. if (chain) {
  13976. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13977. mg_cry_ctx_internal(phys_ctx,
  13978. "%s: cannot use certificate chain file %s: %s",
  13979. __func__,
  13980. chain,
  13981. ssl_error());
  13982. return 0;
  13983. }
  13984. }
  13985. return 1;
  13986. }
  13987. #if defined(OPENSSL_API_1_1)
  13988. static unsigned long
  13989. ssl_get_protocol(int version_id)
  13990. {
  13991. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13992. if (version_id > 0)
  13993. ret |= SSL_OP_NO_SSLv2;
  13994. if (version_id > 1)
  13995. ret |= SSL_OP_NO_SSLv3;
  13996. if (version_id > 2)
  13997. ret |= SSL_OP_NO_TLSv1;
  13998. if (version_id > 3)
  13999. ret |= SSL_OP_NO_TLSv1_1;
  14000. if (version_id > 4)
  14001. ret |= SSL_OP_NO_TLSv1_2;
  14002. #if defined(SSL_OP_NO_TLSv1_3)
  14003. if (version_id > 5)
  14004. ret |= SSL_OP_NO_TLSv1_3;
  14005. #endif
  14006. return ret;
  14007. }
  14008. #else
  14009. static long
  14010. ssl_get_protocol(int version_id)
  14011. {
  14012. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14013. if (version_id > 0)
  14014. ret |= SSL_OP_NO_SSLv2;
  14015. if (version_id > 1)
  14016. ret |= SSL_OP_NO_SSLv3;
  14017. if (version_id > 2)
  14018. ret |= SSL_OP_NO_TLSv1;
  14019. if (version_id > 3)
  14020. ret |= SSL_OP_NO_TLSv1_1;
  14021. if (version_id > 4)
  14022. ret |= SSL_OP_NO_TLSv1_2;
  14023. #if defined(SSL_OP_NO_TLSv1_3)
  14024. if (version_id > 5)
  14025. ret |= SSL_OP_NO_TLSv1_3;
  14026. #endif
  14027. return (long)ret;
  14028. }
  14029. #endif /* OPENSSL_API_1_1 */
  14030. /* SSL callback documentation:
  14031. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14032. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14033. * https://linux.die.net/man/3/ssl_set_info_callback */
  14034. /* Note: There is no "const" for the first argument in the documentation
  14035. * examples, however some (maybe most, but not all) headers of OpenSSL
  14036. * versions / OpenSSL compatibility layers have it. Having a different
  14037. * definition will cause a warning in C and an error in C++. Use "const SSL
  14038. * *", while automatical conversion from "SSL *" works for all compilers,
  14039. * but not other way around */
  14040. static void
  14041. ssl_info_callback(const SSL *ssl, int what, int ret)
  14042. {
  14043. (void)ret;
  14044. if (what & SSL_CB_HANDSHAKE_START) {
  14045. SSL_get_app_data(ssl);
  14046. }
  14047. if (what & SSL_CB_HANDSHAKE_DONE) {
  14048. /* TODO: check for openSSL 1.1 */
  14049. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14050. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14051. }
  14052. }
  14053. static int
  14054. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14055. {
  14056. #if defined(GCC_DIAGNOSTIC)
  14057. #pragma GCC diagnostic push
  14058. #pragma GCC diagnostic ignored "-Wcast-align"
  14059. #endif /* defined(GCC_DIAGNOSTIC) */
  14060. /* We used an aligned pointer in SSL_set_app_data */
  14061. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14062. #if defined(GCC_DIAGNOSTIC)
  14063. #pragma GCC diagnostic pop
  14064. #endif /* defined(GCC_DIAGNOSTIC) */
  14065. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14066. (void)ad;
  14067. (void)arg;
  14068. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14069. DEBUG_ASSERT(0);
  14070. return SSL_TLSEXT_ERR_NOACK;
  14071. }
  14072. conn->dom_ctx = &(conn->phys_ctx->dd);
  14073. /* Old clients (Win XP) will not support SNI. Then, there
  14074. * is no server name available in the request - we can
  14075. * only work with the default certificate.
  14076. * Multiple HTTPS hosts on one IP+port are only possible
  14077. * with a certificate containing all alternative names.
  14078. */
  14079. if ((servername == NULL) || (*servername == 0)) {
  14080. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14081. mg_lock_context(conn->phys_ctx);
  14082. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14083. mg_unlock_context(conn->phys_ctx);
  14084. return SSL_TLSEXT_ERR_NOACK;
  14085. }
  14086. DEBUG_TRACE("TLS connection to host %s", servername);
  14087. while (conn->dom_ctx) {
  14088. if (!mg_strcasecmp(servername,
  14089. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14090. /* Found matching domain */
  14091. DEBUG_TRACE("TLS domain %s found",
  14092. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14093. break;
  14094. }
  14095. mg_lock_context(conn->phys_ctx);
  14096. conn->dom_ctx = conn->dom_ctx->next;
  14097. mg_unlock_context(conn->phys_ctx);
  14098. }
  14099. if (conn->dom_ctx == NULL) {
  14100. /* Default domain */
  14101. DEBUG_TRACE("TLS default domain %s used",
  14102. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14103. conn->dom_ctx = &(conn->phys_ctx->dd);
  14104. }
  14105. mg_lock_context(conn->phys_ctx);
  14106. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14107. mg_unlock_context(conn->phys_ctx);
  14108. return SSL_TLSEXT_ERR_OK;
  14109. }
  14110. #if defined(USE_HTTP2)
  14111. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14112. static const char *alpn_proto_order[] = {alpn_proto_list,
  14113. alpn_proto_list + 3,
  14114. alpn_proto_list + 3 + 8,
  14115. NULL};
  14116. #else
  14117. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14118. static const char *alpn_proto_order[] = {alpn_proto_list,
  14119. alpn_proto_list + 8,
  14120. NULL};
  14121. #endif
  14122. static int
  14123. alpn_select_cb(SSL *ssl,
  14124. const unsigned char **out,
  14125. unsigned char *outlen,
  14126. const unsigned char *in,
  14127. unsigned int inlen,
  14128. void *arg)
  14129. {
  14130. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14131. unsigned int i, j;
  14132. struct mg_workerTLS *tls =
  14133. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14134. (void)ssl;
  14135. (void)dom_ctx;
  14136. if (tls == NULL) {
  14137. /* Need to store protocol in Thread Local Storage */
  14138. /* If there is no Thread Local Storage, don't use ALPN */
  14139. return SSL_TLSEXT_ERR_NOACK;
  14140. }
  14141. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14142. /* check all accepted protocols in this order */
  14143. const char *alpn_proto = alpn_proto_order[j];
  14144. /* search input for matching protocol */
  14145. for (i = 0; i < inlen; i++) {
  14146. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14147. *out = in + i + 1;
  14148. *outlen = in[i];
  14149. tls->alpn_proto = alpn_proto;
  14150. return SSL_TLSEXT_ERR_OK;
  14151. }
  14152. }
  14153. }
  14154. /* Nothing found */
  14155. return SSL_TLSEXT_ERR_NOACK;
  14156. }
  14157. static int
  14158. next_protos_advertised_cb(SSL *ssl,
  14159. const unsigned char **data,
  14160. unsigned int *len,
  14161. void *arg)
  14162. {
  14163. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14164. *data = (const unsigned char *)alpn_proto_list;
  14165. *len = (unsigned int)strlen((const char *)data);
  14166. (void)ssl;
  14167. (void)dom_ctx;
  14168. return SSL_TLSEXT_ERR_OK;
  14169. }
  14170. static int
  14171. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14172. {
  14173. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14174. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14175. (const unsigned char *)alpn_proto_list,
  14176. alpn_len);
  14177. if (ret != 0) {
  14178. mg_cry_ctx_internal(phys_ctx,
  14179. "SSL_CTX_set_alpn_protos error: %s",
  14180. ssl_error());
  14181. }
  14182. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14183. alpn_select_cb,
  14184. (void *)dom_ctx);
  14185. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14186. next_protos_advertised_cb,
  14187. (void *)dom_ctx);
  14188. return ret;
  14189. }
  14190. /* Setup SSL CTX as required by CivetWeb */
  14191. static int
  14192. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14193. struct mg_domain_context *dom_ctx,
  14194. const char *pem,
  14195. const char *chain)
  14196. {
  14197. int callback_ret;
  14198. int should_verify_peer;
  14199. int peer_certificate_optional;
  14200. const char *ca_path;
  14201. const char *ca_file;
  14202. int use_default_verify_paths;
  14203. int verify_depth;
  14204. struct timespec now_mt;
  14205. md5_byte_t ssl_context_id[16];
  14206. md5_state_t md5state;
  14207. int protocol_ver;
  14208. #if defined(OPENSSL_API_1_1)
  14209. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14210. mg_cry_ctx_internal(phys_ctx,
  14211. "SSL_CTX_new (server) error: %s",
  14212. ssl_error());
  14213. return 0;
  14214. }
  14215. #else
  14216. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14217. mg_cry_ctx_internal(phys_ctx,
  14218. "SSL_CTX_new (server) error: %s",
  14219. ssl_error());
  14220. return 0;
  14221. }
  14222. #endif /* OPENSSL_API_1_1 */
  14223. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14224. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14225. | SSL_OP_NO_TLSv1_1);
  14226. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14227. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14228. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14229. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14230. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14231. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14232. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14233. #if defined(SSL_OP_NO_RENEGOTIATION)
  14234. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14235. #endif
  14236. #if !defined(NO_SSL_DL)
  14237. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14238. #endif /* NO_SSL_DL */
  14239. /* In SSL documentation examples callback defined without const
  14240. * specifier 'void (*)(SSL *, int, int)' See:
  14241. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14242. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14243. * But in the source code const SSL is used:
  14244. * 'void (*)(const SSL *, int, int)' See:
  14245. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14246. * Problem about wrong documentation described, but not resolved:
  14247. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14248. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14249. * But when compiled with modern C++ compiler, correct const should be
  14250. * provided
  14251. */
  14252. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14253. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14254. ssl_servername_callback);
  14255. /* If a callback has been specified, call it. */
  14256. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14257. ? 0
  14258. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14259. phys_ctx->user_data));
  14260. /* If callback returns 0, civetweb sets up the SSL certificate.
  14261. * If it returns 1, civetweb assumes the calback already did this.
  14262. * If it returns -1, initializing ssl fails. */
  14263. if (callback_ret < 0) {
  14264. mg_cry_ctx_internal(phys_ctx,
  14265. "SSL callback returned error: %i",
  14266. callback_ret);
  14267. return 0;
  14268. }
  14269. if (callback_ret > 0) {
  14270. /* Callback did everything. */
  14271. return 1;
  14272. }
  14273. /* If a domain callback has been specified, call it. */
  14274. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14275. ? 0
  14276. : (phys_ctx->callbacks.init_ssl_domain(
  14277. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14278. dom_ctx->ssl_ctx,
  14279. phys_ctx->user_data));
  14280. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14281. * If it returns 1, civetweb assumes the calback already did this.
  14282. * If it returns -1, initializing ssl fails. */
  14283. if (callback_ret < 0) {
  14284. mg_cry_ctx_internal(phys_ctx,
  14285. "Domain SSL callback returned error: %i",
  14286. callback_ret);
  14287. return 0;
  14288. }
  14289. if (callback_ret > 0) {
  14290. /* Domain callback did everything. */
  14291. return 1;
  14292. }
  14293. /* Use some combination of start time, domain and port as a SSL
  14294. * context ID. This should be unique on the current machine. */
  14295. md5_init(&md5state);
  14296. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14297. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14298. md5_append(&md5state,
  14299. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14300. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14301. md5_append(&md5state,
  14302. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14303. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14304. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14305. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14306. md5_finish(&md5state, ssl_context_id);
  14307. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14308. (unsigned char *)ssl_context_id,
  14309. sizeof(ssl_context_id));
  14310. if (pem != NULL) {
  14311. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14312. return 0;
  14313. }
  14314. }
  14315. /* Should we support client certificates? */
  14316. /* Default is "no". */
  14317. should_verify_peer = 0;
  14318. peer_certificate_optional = 0;
  14319. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14320. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14321. /* Yes, they are mandatory */
  14322. should_verify_peer = 1;
  14323. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14324. "optional")
  14325. == 0) {
  14326. /* Yes, they are optional */
  14327. should_verify_peer = 1;
  14328. peer_certificate_optional = 1;
  14329. }
  14330. }
  14331. use_default_verify_paths =
  14332. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14333. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14334. == 0);
  14335. if (should_verify_peer) {
  14336. ca_path = dom_ctx->config[SSL_CA_PATH];
  14337. ca_file = dom_ctx->config[SSL_CA_FILE];
  14338. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14339. != 1) {
  14340. mg_cry_ctx_internal(phys_ctx,
  14341. "SSL_CTX_load_verify_locations error: %s "
  14342. "ssl_verify_peer requires setting "
  14343. "either ssl_ca_path or ssl_ca_file. "
  14344. "Is any of them present in the "
  14345. ".conf file?",
  14346. ssl_error());
  14347. return 0;
  14348. }
  14349. if (peer_certificate_optional) {
  14350. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14351. } else {
  14352. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14353. SSL_VERIFY_PEER
  14354. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14355. NULL);
  14356. }
  14357. if (use_default_verify_paths
  14358. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14359. mg_cry_ctx_internal(phys_ctx,
  14360. "SSL_CTX_set_default_verify_paths error: %s",
  14361. ssl_error());
  14362. return 0;
  14363. }
  14364. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14365. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14366. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14367. }
  14368. }
  14369. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14370. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14371. dom_ctx->config[SSL_CIPHER_LIST])
  14372. != 1) {
  14373. mg_cry_ctx_internal(phys_ctx,
  14374. "SSL_CTX_set_cipher_list error: %s",
  14375. ssl_error());
  14376. }
  14377. }
  14378. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14379. #if !defined(NO_SSL_DL)
  14380. if (!tls_feature_missing[TLS_ALPN])
  14381. #endif
  14382. {
  14383. init_alpn(phys_ctx, dom_ctx);
  14384. }
  14385. return 1;
  14386. }
  14387. /* Check if SSL is required.
  14388. * If so, dynamically load SSL library
  14389. * and set up ctx->ssl_ctx pointer. */
  14390. static int
  14391. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14392. {
  14393. void *ssl_ctx = 0;
  14394. int callback_ret;
  14395. const char *pem;
  14396. const char *chain;
  14397. char ebuf[128];
  14398. if (!phys_ctx) {
  14399. return 0;
  14400. }
  14401. if (!dom_ctx) {
  14402. dom_ctx = &(phys_ctx->dd);
  14403. }
  14404. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14405. /* No SSL port is set. No need to setup SSL. */
  14406. return 1;
  14407. }
  14408. /* Check for external SSL_CTX */
  14409. callback_ret =
  14410. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14411. ? 0
  14412. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14413. phys_ctx->user_data));
  14414. if (callback_ret < 0) {
  14415. mg_cry_ctx_internal(phys_ctx,
  14416. "external_ssl_ctx callback returned error: %i",
  14417. callback_ret);
  14418. return 0;
  14419. } else if (callback_ret > 0) {
  14420. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14421. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14422. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14423. return 0;
  14424. }
  14425. return 1;
  14426. }
  14427. /* Check for external domain SSL_CTX */
  14428. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14429. ? 0
  14430. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14431. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14432. &ssl_ctx,
  14433. phys_ctx->user_data));
  14434. if (callback_ret < 0) {
  14435. mg_cry_ctx_internal(
  14436. phys_ctx,
  14437. "external_ssl_ctx_domain callback returned error: %i",
  14438. callback_ret);
  14439. return 0;
  14440. } else if (callback_ret > 0) {
  14441. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14442. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14443. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14444. return 0;
  14445. }
  14446. return 1;
  14447. }
  14448. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14449. * 0, CivetWeb should continue initializing SSL */
  14450. /* If PEM file is not specified and the init_ssl callbacks
  14451. * are not specified, setup will fail. */
  14452. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14453. && (phys_ctx->callbacks.init_ssl == NULL)
  14454. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14455. /* No certificate and no init_ssl callbacks:
  14456. * Essential data to set up TLS is missing.
  14457. */
  14458. mg_cry_ctx_internal(phys_ctx,
  14459. "Initializing SSL failed: -%s is not set",
  14460. config_options[SSL_CERTIFICATE].name);
  14461. return 0;
  14462. }
  14463. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14464. if (chain == NULL) {
  14465. chain = pem;
  14466. }
  14467. if ((chain != NULL) && (*chain == 0)) {
  14468. chain = NULL;
  14469. }
  14470. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14471. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14472. return 0;
  14473. }
  14474. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14475. }
  14476. static void
  14477. uninitialize_ssl(void)
  14478. {
  14479. #if defined(OPENSSL_API_1_1)
  14480. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14481. /* Shutdown according to
  14482. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14483. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14484. */
  14485. CONF_modules_unload(1);
  14486. #else
  14487. int i;
  14488. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14489. /* Shutdown according to
  14490. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14491. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14492. */
  14493. CRYPTO_set_locking_callback(NULL);
  14494. CRYPTO_set_id_callback(NULL);
  14495. ENGINE_cleanup();
  14496. CONF_modules_unload(1);
  14497. ERR_free_strings();
  14498. EVP_cleanup();
  14499. CRYPTO_cleanup_all_ex_data();
  14500. OPENSSL_REMOVE_THREAD_STATE();
  14501. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14502. pthread_mutex_destroy(&ssl_mutexes[i]);
  14503. }
  14504. mg_free(ssl_mutexes);
  14505. ssl_mutexes = NULL;
  14506. #endif /* OPENSSL_API_1_1 */
  14507. }
  14508. }
  14509. #endif /* !NO_SSL */
  14510. #if !defined(NO_FILESYSTEMS)
  14511. static int
  14512. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14513. {
  14514. if (phys_ctx) {
  14515. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14516. const char *path;
  14517. struct mg_connection fc;
  14518. if (!dom_ctx) {
  14519. dom_ctx = &(phys_ctx->dd);
  14520. }
  14521. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14522. if ((path != NULL)
  14523. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14524. mg_cry_ctx_internal(phys_ctx,
  14525. "Cannot open %s: %s",
  14526. path,
  14527. strerror(ERRNO));
  14528. return 0;
  14529. }
  14530. return 1;
  14531. }
  14532. return 0;
  14533. }
  14534. #endif /* NO_FILESYSTEMS */
  14535. static int
  14536. set_acl_option(struct mg_context *phys_ctx)
  14537. {
  14538. union usa sa;
  14539. memset(&sa, 0, sizeof(sa));
  14540. #if defined(USE_IPV6)
  14541. sa.sin6.sin6_family = AF_INET6;
  14542. #else
  14543. sa.sin.sin_family = AF_INET;
  14544. #endif
  14545. return check_acl(phys_ctx, &sa) != -1;
  14546. }
  14547. static void
  14548. reset_per_request_attributes(struct mg_connection *conn)
  14549. {
  14550. if (!conn) {
  14551. return;
  14552. }
  14553. conn->connection_type =
  14554. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14555. conn->num_bytes_sent = conn->consumed_content = 0;
  14556. conn->path_info = NULL;
  14557. conn->status_code = -1;
  14558. conn->content_len = -1;
  14559. conn->is_chunked = 0;
  14560. conn->must_close = 0;
  14561. conn->request_len = 0;
  14562. conn->throttle = 0;
  14563. conn->accept_gzip = 0;
  14564. conn->response_info.content_length = conn->request_info.content_length = -1;
  14565. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14566. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14567. conn->response_info.status_text = NULL;
  14568. conn->response_info.status_code = 0;
  14569. conn->request_info.remote_user = NULL;
  14570. conn->request_info.request_method = NULL;
  14571. conn->request_info.request_uri = NULL;
  14572. conn->request_info.local_uri = NULL;
  14573. #if defined(MG_LEGACY_INTERFACE)
  14574. /* Legacy before split into local_uri and request_uri */
  14575. conn->request_info.uri = NULL;
  14576. #endif
  14577. }
  14578. static int
  14579. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14580. {
  14581. if (setsockopt(sock,
  14582. IPPROTO_TCP,
  14583. TCP_NODELAY,
  14584. (SOCK_OPT_TYPE)&nodelay_on,
  14585. sizeof(nodelay_on))
  14586. != 0) {
  14587. /* Error */
  14588. return 1;
  14589. }
  14590. /* OK */
  14591. return 0;
  14592. }
  14593. #if !defined(__ZEPHYR__)
  14594. static void
  14595. close_socket_gracefully(struct mg_connection *conn)
  14596. {
  14597. #if defined(_WIN32)
  14598. char buf[MG_BUF_LEN];
  14599. int n;
  14600. #endif
  14601. struct linger linger;
  14602. int error_code = 0;
  14603. int linger_timeout = -2;
  14604. socklen_t opt_len = sizeof(error_code);
  14605. if (!conn) {
  14606. return;
  14607. }
  14608. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14609. * "Note that enabling a nonzero timeout on a nonblocking socket
  14610. * is not recommended.", so set it to blocking now */
  14611. set_blocking_mode(conn->client.sock);
  14612. /* Send FIN to the client */
  14613. shutdown(conn->client.sock, SHUTDOWN_WR);
  14614. #if defined(_WIN32)
  14615. /* Read and discard pending incoming data. If we do not do that and
  14616. * close
  14617. * the socket, the data in the send buffer may be discarded. This
  14618. * behaviour is seen on Windows, when client keeps sending data
  14619. * when server decides to close the connection; then when client
  14620. * does recv() it gets no data back. */
  14621. do {
  14622. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14623. } while (n > 0);
  14624. #endif
  14625. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14626. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14627. }
  14628. /* Set linger option according to configuration */
  14629. if (linger_timeout >= 0) {
  14630. /* Set linger option to avoid socket hanging out after close. This
  14631. * prevent ephemeral port exhaust problem under high QPS. */
  14632. linger.l_onoff = 1;
  14633. #if defined(_MSC_VER)
  14634. #pragma warning(push)
  14635. #pragma warning(disable : 4244)
  14636. #endif
  14637. #if defined(GCC_DIAGNOSTIC)
  14638. #pragma GCC diagnostic push
  14639. #pragma GCC diagnostic ignored "-Wconversion"
  14640. #endif
  14641. /* Data type of linger structure elements may differ,
  14642. * so we don't know what cast we need here.
  14643. * Disable type conversion warnings. */
  14644. linger.l_linger = (linger_timeout + 999) / 1000;
  14645. #if defined(GCC_DIAGNOSTIC)
  14646. #pragma GCC diagnostic pop
  14647. #endif
  14648. #if defined(_MSC_VER)
  14649. #pragma warning(pop)
  14650. #endif
  14651. } else {
  14652. linger.l_onoff = 0;
  14653. linger.l_linger = 0;
  14654. }
  14655. if (linger_timeout < -1) {
  14656. /* Default: don't configure any linger */
  14657. } else if (getsockopt(conn->client.sock,
  14658. SOL_SOCKET,
  14659. SO_ERROR,
  14660. #if defined(_WIN32) /* WinSock uses different data type here */
  14661. (char *)&error_code,
  14662. #else
  14663. &error_code,
  14664. #endif
  14665. &opt_len)
  14666. != 0) {
  14667. /* Cannot determine if socket is already closed. This should
  14668. * not occur and never did in a test. Log an error message
  14669. * and continue. */
  14670. mg_cry_internal(conn,
  14671. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14672. __func__,
  14673. strerror(ERRNO));
  14674. #if defined(_WIN32)
  14675. } else if (error_code == WSAECONNRESET) {
  14676. #else
  14677. } else if (error_code == ECONNRESET) {
  14678. #endif
  14679. /* Socket already closed by client/peer, close socket without linger
  14680. */
  14681. } else {
  14682. /* Set linger timeout */
  14683. if (setsockopt(conn->client.sock,
  14684. SOL_SOCKET,
  14685. SO_LINGER,
  14686. (char *)&linger,
  14687. sizeof(linger))
  14688. != 0) {
  14689. mg_cry_internal(
  14690. conn,
  14691. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14692. __func__,
  14693. linger.l_onoff,
  14694. linger.l_linger,
  14695. strerror(ERRNO));
  14696. }
  14697. }
  14698. /* Now we know that our FIN is ACK-ed, safe to close */
  14699. closesocket(conn->client.sock);
  14700. conn->client.sock = INVALID_SOCKET;
  14701. }
  14702. #endif
  14703. static void
  14704. close_connection(struct mg_connection *conn)
  14705. {
  14706. #if defined(USE_SERVER_STATS)
  14707. conn->conn_state = 6; /* to close */
  14708. #endif
  14709. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14710. if (conn->lua_websocket_state) {
  14711. lua_websocket_close(conn, conn->lua_websocket_state);
  14712. conn->lua_websocket_state = NULL;
  14713. }
  14714. #endif
  14715. mg_lock_connection(conn);
  14716. /* Set close flag, so keep-alive loops will stop */
  14717. conn->must_close = 1;
  14718. /* call the connection_close callback if assigned */
  14719. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14720. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14721. conn->phys_ctx->callbacks.connection_close(conn);
  14722. }
  14723. }
  14724. /* Reset user data, after close callback is called.
  14725. * Do not reuse it. If the user needs a destructor,
  14726. * it must be done in the connection_close callback. */
  14727. mg_set_user_connection_data(conn, NULL);
  14728. #if defined(USE_SERVER_STATS)
  14729. conn->conn_state = 7; /* closing */
  14730. #endif
  14731. #if !defined(NO_SSL)
  14732. if (conn->ssl != NULL) {
  14733. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14734. */
  14735. SSL_shutdown(conn->ssl);
  14736. SSL_free(conn->ssl);
  14737. OPENSSL_REMOVE_THREAD_STATE();
  14738. conn->ssl = NULL;
  14739. }
  14740. #endif
  14741. if (conn->client.sock != INVALID_SOCKET) {
  14742. #if defined(__ZEPHYR__)
  14743. closesocket(conn->client.sock);
  14744. #else
  14745. close_socket_gracefully(conn);
  14746. #endif
  14747. conn->client.sock = INVALID_SOCKET;
  14748. }
  14749. mg_unlock_connection(conn);
  14750. #if defined(USE_SERVER_STATS)
  14751. conn->conn_state = 8; /* closed */
  14752. #endif
  14753. }
  14754. void
  14755. mg_close_connection(struct mg_connection *conn)
  14756. {
  14757. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14758. return;
  14759. }
  14760. #if defined(USE_WEBSOCKET)
  14761. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14762. if (conn->in_websocket_handling) {
  14763. /* Set close flag, so the server thread can exit. */
  14764. conn->must_close = 1;
  14765. return;
  14766. }
  14767. }
  14768. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14769. unsigned int i;
  14770. /* client context: loops must end */
  14771. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14772. conn->must_close = 1;
  14773. /* We need to get the client thread out of the select/recv call
  14774. * here. */
  14775. /* Since we use a sleep quantum of some seconds to check for recv
  14776. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14777. /* join worker thread */
  14778. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14779. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14780. }
  14781. }
  14782. #endif /* defined(USE_WEBSOCKET) */
  14783. close_connection(conn);
  14784. #if !defined(NO_SSL)
  14785. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14786. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14787. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14788. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14789. }
  14790. #endif
  14791. #if defined(USE_WEBSOCKET)
  14792. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14793. mg_free(conn->phys_ctx->worker_threadids);
  14794. (void)pthread_mutex_destroy(&conn->mutex);
  14795. mg_free(conn);
  14796. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14797. (void)pthread_mutex_destroy(&conn->mutex);
  14798. mg_free(conn);
  14799. }
  14800. #else
  14801. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14802. (void)pthread_mutex_destroy(&conn->mutex);
  14803. mg_free(conn);
  14804. }
  14805. #endif /* defined(USE_WEBSOCKET) */
  14806. }
  14807. static struct mg_connection *
  14808. mg_connect_client_impl(const struct mg_client_options *client_options,
  14809. int use_ssl,
  14810. char *ebuf,
  14811. size_t ebuf_len)
  14812. {
  14813. struct mg_connection *conn = NULL;
  14814. SOCKET sock;
  14815. union usa sa;
  14816. struct sockaddr *psa;
  14817. socklen_t len;
  14818. unsigned max_req_size =
  14819. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14820. /* Size of structures, aligned to 8 bytes */
  14821. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14822. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14823. conn =
  14824. (struct mg_connection *)mg_calloc(1,
  14825. conn_size + ctx_size + max_req_size);
  14826. if (conn == NULL) {
  14827. mg_snprintf(NULL,
  14828. NULL, /* No truncation check for ebuf */
  14829. ebuf,
  14830. ebuf_len,
  14831. "calloc(): %s",
  14832. strerror(ERRNO));
  14833. return NULL;
  14834. }
  14835. #if defined(GCC_DIAGNOSTIC)
  14836. #pragma GCC diagnostic push
  14837. #pragma GCC diagnostic ignored "-Wcast-align"
  14838. #endif /* defined(GCC_DIAGNOSTIC) */
  14839. /* conn_size is aligned to 8 bytes */
  14840. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14841. #if defined(GCC_DIAGNOSTIC)
  14842. #pragma GCC diagnostic pop
  14843. #endif /* defined(GCC_DIAGNOSTIC) */
  14844. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14845. conn->buf_size = (int)max_req_size;
  14846. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14847. conn->dom_ctx = &(conn->phys_ctx->dd);
  14848. if (!connect_socket(conn->phys_ctx,
  14849. client_options->host,
  14850. client_options->port,
  14851. use_ssl,
  14852. ebuf,
  14853. ebuf_len,
  14854. &sock,
  14855. &sa)) {
  14856. /* ebuf is set by connect_socket,
  14857. * free all memory and return NULL; */
  14858. mg_free(conn);
  14859. return NULL;
  14860. }
  14861. #if !defined(NO_SSL)
  14862. #if defined(OPENSSL_API_1_1)
  14863. if (use_ssl
  14864. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14865. == NULL) {
  14866. mg_snprintf(NULL,
  14867. NULL, /* No truncation check for ebuf */
  14868. ebuf,
  14869. ebuf_len,
  14870. "SSL_CTX_new error: %s",
  14871. ssl_error());
  14872. closesocket(sock);
  14873. mg_free(conn);
  14874. return NULL;
  14875. }
  14876. #else
  14877. if (use_ssl
  14878. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14879. == NULL) {
  14880. mg_snprintf(NULL,
  14881. NULL, /* No truncation check for ebuf */
  14882. ebuf,
  14883. ebuf_len,
  14884. "SSL_CTX_new error: %s",
  14885. ssl_error());
  14886. closesocket(sock);
  14887. mg_free(conn);
  14888. return NULL;
  14889. }
  14890. #endif /* OPENSSL_API_1_1 */
  14891. #endif /* NO_SSL */
  14892. #if defined(USE_IPV6)
  14893. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14894. : sizeof(conn->client.rsa.sin6);
  14895. psa = (sa.sa.sa_family == AF_INET)
  14896. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14897. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14898. #else
  14899. len = sizeof(conn->client.rsa.sin);
  14900. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14901. #endif
  14902. conn->client.sock = sock;
  14903. conn->client.lsa = sa;
  14904. if (getsockname(sock, psa, &len) != 0) {
  14905. mg_cry_internal(conn,
  14906. "%s: getsockname() failed: %s",
  14907. __func__,
  14908. strerror(ERRNO));
  14909. }
  14910. conn->client.is_ssl = use_ssl ? 1 : 0;
  14911. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14912. mg_snprintf(NULL,
  14913. NULL, /* No truncation check for ebuf */
  14914. ebuf,
  14915. ebuf_len,
  14916. "Can not create mutex");
  14917. #if !defined(NO_SSL)
  14918. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14919. #endif
  14920. closesocket(sock);
  14921. mg_free(conn);
  14922. return NULL;
  14923. }
  14924. #if !defined(NO_SSL)
  14925. if (use_ssl) {
  14926. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14927. * SSL_CTX_set_verify call is needed to switch off server
  14928. * certificate checking, which is off by default in OpenSSL and
  14929. * on in yaSSL. */
  14930. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14931. * SSL_VERIFY_PEER, verify_ssl_server); */
  14932. if (client_options->client_cert) {
  14933. if (!ssl_use_pem_file(conn->phys_ctx,
  14934. conn->dom_ctx,
  14935. client_options->client_cert,
  14936. NULL)) {
  14937. mg_snprintf(NULL,
  14938. NULL, /* No truncation check for ebuf */
  14939. ebuf,
  14940. ebuf_len,
  14941. "Can not use SSL client certificate");
  14942. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14943. closesocket(sock);
  14944. mg_free(conn);
  14945. return NULL;
  14946. }
  14947. }
  14948. if (client_options->server_cert) {
  14949. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14950. client_options->server_cert,
  14951. NULL)
  14952. != 1) {
  14953. mg_cry_internal(conn,
  14954. "SSL_CTX_load_verify_locations error: %s ",
  14955. ssl_error());
  14956. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14957. closesocket(sock);
  14958. mg_free(conn);
  14959. return NULL;
  14960. }
  14961. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14962. } else {
  14963. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14964. }
  14965. if (!sslize(conn, SSL_connect, client_options)) {
  14966. mg_snprintf(NULL,
  14967. NULL, /* No truncation check for ebuf */
  14968. ebuf,
  14969. ebuf_len,
  14970. "SSL connection error");
  14971. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14972. closesocket(sock);
  14973. mg_free(conn);
  14974. return NULL;
  14975. }
  14976. }
  14977. #endif
  14978. return conn;
  14979. }
  14980. CIVETWEB_API struct mg_connection *
  14981. mg_connect_client_secure(const struct mg_client_options *client_options,
  14982. char *error_buffer,
  14983. size_t error_buffer_size)
  14984. {
  14985. return mg_connect_client_impl(client_options,
  14986. 1,
  14987. error_buffer,
  14988. error_buffer_size);
  14989. }
  14990. struct mg_connection *
  14991. mg_connect_client(const char *host,
  14992. int port,
  14993. int use_ssl,
  14994. char *error_buffer,
  14995. size_t error_buffer_size)
  14996. {
  14997. struct mg_client_options opts;
  14998. memset(&opts, 0, sizeof(opts));
  14999. opts.host = host;
  15000. opts.port = port;
  15001. return mg_connect_client_impl(&opts,
  15002. use_ssl,
  15003. error_buffer,
  15004. error_buffer_size);
  15005. }
  15006. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15007. struct mg_connection *
  15008. mg_connect_client2(const char *host,
  15009. const char *protocol,
  15010. int port,
  15011. const char *path,
  15012. struct mg_init_data *init,
  15013. struct mg_error_data *error)
  15014. {
  15015. int is_ssl, is_ws;
  15016. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15017. if (error != NULL) {
  15018. error->code = 0;
  15019. if (error->text_buffer_size > 0) {
  15020. *error->text = 0;
  15021. }
  15022. }
  15023. if ((host == NULL) || (protocol == NULL)) {
  15024. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15025. mg_snprintf(NULL,
  15026. NULL, /* No truncation check for error buffers */
  15027. error->text,
  15028. error->text_buffer_size,
  15029. "%s",
  15030. "Invalid parameters");
  15031. }
  15032. return NULL;
  15033. }
  15034. /* check all known protocolls */
  15035. if (!mg_strcasecmp(protocol, "http")) {
  15036. is_ssl = 0;
  15037. is_ws = 0;
  15038. } else if (!mg_strcasecmp(protocol, "https")) {
  15039. is_ssl = 1;
  15040. is_ws = 0;
  15041. #if defined(USE_WEBSOCKET)
  15042. } else if (!mg_strcasecmp(protocol, "ws")) {
  15043. is_ssl = 0;
  15044. is_ws = 1;
  15045. } else if (!mg_strcasecmp(protocol, "wss")) {
  15046. is_ssl = 1;
  15047. is_ws = 1;
  15048. #endif
  15049. } else {
  15050. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15051. mg_snprintf(NULL,
  15052. NULL, /* No truncation check for error buffers */
  15053. error->text,
  15054. error->text_buffer_size,
  15055. "Protocol %s not supported",
  15056. protocol);
  15057. }
  15058. return NULL;
  15059. }
  15060. /* TODO: The current implementation here just calls the old
  15061. * implementations, without using any new options. This is just a first
  15062. * step to test the new interfaces. */
  15063. #if defined(USE_WEBSOCKET)
  15064. if (is_ws) {
  15065. /* TODO: implement all options */
  15066. return mg_connect_websocket_client(
  15067. host,
  15068. port,
  15069. is_ssl,
  15070. ((error != NULL) ? error->text : NULL),
  15071. ((error != NULL) ? error->text_buffer_size : 0),
  15072. (path ? path : ""),
  15073. NULL /* TODO: origin */,
  15074. deprecated_websocket_data_wrapper,
  15075. deprecated_websocket_close_wrapper,
  15076. (void *)init->callbacks);
  15077. }
  15078. #endif
  15079. /* TODO: all additional options */
  15080. struct mg_client_options opts;
  15081. memset(&opts, 0, sizeof(opts));
  15082. opts.host = host;
  15083. opts.port = port;
  15084. return mg_connect_client_impl(&opts,
  15085. is_ssl,
  15086. ((error != NULL) ? error->text : NULL),
  15087. ((error != NULL) ? error->text_buffer_size
  15088. : 0));
  15089. }
  15090. #endif
  15091. static const struct {
  15092. const char *proto;
  15093. size_t proto_len;
  15094. unsigned default_port;
  15095. } abs_uri_protocols[] = {{"http://", 7, 80},
  15096. {"https://", 8, 443},
  15097. {"ws://", 5, 80},
  15098. {"wss://", 6, 443},
  15099. {NULL, 0, 0}};
  15100. /* Check if the uri is valid.
  15101. * return 0 for invalid uri,
  15102. * return 1 for *,
  15103. * return 2 for relative uri,
  15104. * return 3 for absolute uri without port,
  15105. * return 4 for absolute uri with port */
  15106. static int
  15107. get_uri_type(const char *uri)
  15108. {
  15109. int i;
  15110. const char *hostend, *portbegin;
  15111. char *portend;
  15112. unsigned long port;
  15113. /* According to the HTTP standard
  15114. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15115. * URI can be an asterisk (*) or should start with slash (relative uri),
  15116. * or it should start with the protocol (absolute uri). */
  15117. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15118. /* asterisk */
  15119. return 1;
  15120. }
  15121. /* Valid URIs according to RFC 3986
  15122. * (https://www.ietf.org/rfc/rfc3986.txt)
  15123. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15124. * and unreserved characters A-Z a-z 0-9 and -._~
  15125. * and % encoded symbols.
  15126. */
  15127. for (i = 0; uri[i] != 0; i++) {
  15128. if (uri[i] < 33) {
  15129. /* control characters and spaces are invalid */
  15130. return 0;
  15131. }
  15132. if (uri[i] > 126) {
  15133. /* non-ascii characters must be % encoded */
  15134. return 0;
  15135. } else {
  15136. switch (uri[i]) {
  15137. case '"': /* 34 */
  15138. case '<': /* 60 */
  15139. case '>': /* 62 */
  15140. case '\\': /* 92 */
  15141. case '^': /* 94 */
  15142. case '`': /* 96 */
  15143. case '{': /* 123 */
  15144. case '|': /* 124 */
  15145. case '}': /* 125 */
  15146. return 0;
  15147. default:
  15148. /* character is ok */
  15149. break;
  15150. }
  15151. }
  15152. }
  15153. /* A relative uri starts with a / character */
  15154. if (uri[0] == '/') {
  15155. /* relative uri */
  15156. return 2;
  15157. }
  15158. /* It could be an absolute uri: */
  15159. /* This function only checks if the uri is valid, not if it is
  15160. * addressing the current server. So civetweb can also be used
  15161. * as a proxy server. */
  15162. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15163. if (mg_strncasecmp(uri,
  15164. abs_uri_protocols[i].proto,
  15165. abs_uri_protocols[i].proto_len)
  15166. == 0) {
  15167. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15168. if (!hostend) {
  15169. return 0;
  15170. }
  15171. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15172. if (!portbegin) {
  15173. return 3;
  15174. }
  15175. port = strtoul(portbegin + 1, &portend, 10);
  15176. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15177. return 0;
  15178. }
  15179. return 4;
  15180. }
  15181. }
  15182. return 0;
  15183. }
  15184. /* Return NULL or the relative uri at the current server */
  15185. static const char *
  15186. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15187. {
  15188. const char *server_domain;
  15189. size_t server_domain_len;
  15190. size_t request_domain_len = 0;
  15191. unsigned long port = 0;
  15192. int i, auth_domain_check_enabled;
  15193. const char *hostbegin = NULL;
  15194. const char *hostend = NULL;
  15195. const char *portbegin;
  15196. char *portend;
  15197. auth_domain_check_enabled =
  15198. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15199. /* DNS is case insensitive, so use case insensitive string compare here
  15200. */
  15201. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15202. if (mg_strncasecmp(uri,
  15203. abs_uri_protocols[i].proto,
  15204. abs_uri_protocols[i].proto_len)
  15205. == 0) {
  15206. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15207. hostend = strchr(hostbegin, '/');
  15208. if (!hostend) {
  15209. return 0;
  15210. }
  15211. portbegin = strchr(hostbegin, ':');
  15212. if ((!portbegin) || (portbegin > hostend)) {
  15213. port = abs_uri_protocols[i].default_port;
  15214. request_domain_len = (size_t)(hostend - hostbegin);
  15215. } else {
  15216. port = strtoul(portbegin + 1, &portend, 10);
  15217. if ((portend != hostend) || (port <= 0)
  15218. || !is_valid_port(port)) {
  15219. return 0;
  15220. }
  15221. request_domain_len = (size_t)(portbegin - hostbegin);
  15222. }
  15223. /* protocol found, port set */
  15224. break;
  15225. }
  15226. }
  15227. if (!port) {
  15228. /* port remains 0 if the protocol is not found */
  15229. return 0;
  15230. }
  15231. /* Check if the request is directed to a different server. */
  15232. /* First check if the port is the same. */
  15233. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15234. /* Request is directed to a different port */
  15235. return 0;
  15236. }
  15237. /* Finally check if the server corresponds to the authentication
  15238. * domain of the server (the server domain).
  15239. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15240. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15241. * but do not allow substrings (like
  15242. * http://notmydomain.com/path/file.ext
  15243. * or http://mydomain.com.fake/path/file.ext).
  15244. */
  15245. if (auth_domain_check_enabled) {
  15246. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15247. server_domain_len = strlen(server_domain);
  15248. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15249. return 0;
  15250. }
  15251. if ((request_domain_len == server_domain_len)
  15252. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15253. /* Request is directed to this server - full name match. */
  15254. } else {
  15255. if (request_domain_len < (server_domain_len + 2)) {
  15256. /* Request is directed to another server: The server name
  15257. * is longer than the request name.
  15258. * Drop this case here to avoid overflows in the
  15259. * following checks. */
  15260. return 0;
  15261. }
  15262. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15263. /* Request is directed to another server: It could be a
  15264. * substring
  15265. * like notmyserver.com */
  15266. return 0;
  15267. }
  15268. if (0
  15269. != memcmp(server_domain,
  15270. hostbegin + request_domain_len - server_domain_len,
  15271. server_domain_len)) {
  15272. /* Request is directed to another server:
  15273. * The server name is different. */
  15274. return 0;
  15275. }
  15276. }
  15277. }
  15278. return hostend;
  15279. }
  15280. static int
  15281. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15282. {
  15283. if (ebuf_len > 0) {
  15284. ebuf[0] = '\0';
  15285. }
  15286. *err = 0;
  15287. reset_per_request_attributes(conn);
  15288. if (!conn) {
  15289. mg_snprintf(conn,
  15290. NULL, /* No truncation check for ebuf */
  15291. ebuf,
  15292. ebuf_len,
  15293. "%s",
  15294. "Internal error");
  15295. *err = 500;
  15296. return 0;
  15297. }
  15298. /* Set the time the request was received. This value should be used for
  15299. * timeouts. */
  15300. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15301. conn->request_len =
  15302. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15303. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15304. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15305. mg_snprintf(conn,
  15306. NULL, /* No truncation check for ebuf */
  15307. ebuf,
  15308. ebuf_len,
  15309. "%s",
  15310. "Invalid message size");
  15311. *err = 500;
  15312. return 0;
  15313. }
  15314. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15315. mg_snprintf(conn,
  15316. NULL, /* No truncation check for ebuf */
  15317. ebuf,
  15318. ebuf_len,
  15319. "%s",
  15320. "Message too large");
  15321. *err = 413;
  15322. return 0;
  15323. }
  15324. if (conn->request_len <= 0) {
  15325. if (conn->data_len > 0) {
  15326. mg_snprintf(conn,
  15327. NULL, /* No truncation check for ebuf */
  15328. ebuf,
  15329. ebuf_len,
  15330. "%s",
  15331. "Malformed message");
  15332. *err = 400;
  15333. } else {
  15334. /* Server did not recv anything -> just close the connection */
  15335. conn->must_close = 1;
  15336. mg_snprintf(conn,
  15337. NULL, /* No truncation check for ebuf */
  15338. ebuf,
  15339. ebuf_len,
  15340. "%s",
  15341. "No data received");
  15342. *err = 0;
  15343. }
  15344. return 0;
  15345. }
  15346. return 1;
  15347. }
  15348. static int
  15349. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15350. {
  15351. const char *cl;
  15352. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15353. return 0;
  15354. }
  15355. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15356. <= 0) {
  15357. mg_snprintf(conn,
  15358. NULL, /* No truncation check for ebuf */
  15359. ebuf,
  15360. ebuf_len,
  15361. "%s",
  15362. "Bad request");
  15363. *err = 400;
  15364. return 0;
  15365. }
  15366. /* Message is a valid request */
  15367. if (!switch_domain_context(conn)) {
  15368. mg_snprintf(conn,
  15369. NULL, /* No truncation check for ebuf */
  15370. ebuf,
  15371. ebuf_len,
  15372. "%s",
  15373. "Bad request: Host mismatch");
  15374. *err = 400;
  15375. return 0;
  15376. }
  15377. if (((cl = get_header(conn->request_info.http_headers,
  15378. conn->request_info.num_headers,
  15379. "Transfer-Encoding"))
  15380. != NULL)
  15381. && mg_strcasecmp(cl, "identity")) {
  15382. if (mg_strcasecmp(cl, "chunked")) {
  15383. mg_snprintf(conn,
  15384. NULL, /* No truncation check for ebuf */
  15385. ebuf,
  15386. ebuf_len,
  15387. "%s",
  15388. "Bad request");
  15389. *err = 400;
  15390. return 0;
  15391. }
  15392. conn->is_chunked = 1;
  15393. conn->content_len = 0; /* not yet read */
  15394. } else if ((cl = get_header(conn->request_info.http_headers,
  15395. conn->request_info.num_headers,
  15396. "Content-Length"))
  15397. != NULL) {
  15398. /* Request has content length set */
  15399. char *endptr = NULL;
  15400. conn->content_len = strtoll(cl, &endptr, 10);
  15401. if ((endptr == cl) || (conn->content_len < 0)) {
  15402. mg_snprintf(conn,
  15403. NULL, /* No truncation check for ebuf */
  15404. ebuf,
  15405. ebuf_len,
  15406. "%s",
  15407. "Bad request");
  15408. *err = 411;
  15409. return 0;
  15410. }
  15411. /* Publish the content length back to the request info. */
  15412. conn->request_info.content_length = conn->content_len;
  15413. } else {
  15414. /* There is no exception, see RFC7230. */
  15415. conn->content_len = 0;
  15416. }
  15417. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15418. return 1;
  15419. }
  15420. /* conn is assumed to be valid in this internal function */
  15421. static int
  15422. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15423. {
  15424. const char *cl;
  15425. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15426. return 0;
  15427. }
  15428. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15429. <= 0) {
  15430. mg_snprintf(conn,
  15431. NULL, /* No truncation check for ebuf */
  15432. ebuf,
  15433. ebuf_len,
  15434. "%s",
  15435. "Bad response");
  15436. *err = 400;
  15437. return 0;
  15438. }
  15439. /* Message is a valid response */
  15440. if (((cl = get_header(conn->response_info.http_headers,
  15441. conn->response_info.num_headers,
  15442. "Transfer-Encoding"))
  15443. != NULL)
  15444. && mg_strcasecmp(cl, "identity")) {
  15445. if (mg_strcasecmp(cl, "chunked")) {
  15446. mg_snprintf(conn,
  15447. NULL, /* No truncation check for ebuf */
  15448. ebuf,
  15449. ebuf_len,
  15450. "%s",
  15451. "Bad request");
  15452. *err = 400;
  15453. return 0;
  15454. }
  15455. conn->is_chunked = 1;
  15456. conn->content_len = 0; /* not yet read */
  15457. } else if ((cl = get_header(conn->response_info.http_headers,
  15458. conn->response_info.num_headers,
  15459. "Content-Length"))
  15460. != NULL) {
  15461. char *endptr = NULL;
  15462. conn->content_len = strtoll(cl, &endptr, 10);
  15463. if ((endptr == cl) || (conn->content_len < 0)) {
  15464. mg_snprintf(conn,
  15465. NULL, /* No truncation check for ebuf */
  15466. ebuf,
  15467. ebuf_len,
  15468. "%s",
  15469. "Bad request");
  15470. *err = 411;
  15471. return 0;
  15472. }
  15473. /* Publish the content length back to the response info. */
  15474. conn->response_info.content_length = conn->content_len;
  15475. /* TODO: check if it is still used in response_info */
  15476. conn->request_info.content_length = conn->content_len;
  15477. /* TODO: we should also consider HEAD method */
  15478. if (conn->response_info.status_code == 304) {
  15479. conn->content_len = 0;
  15480. }
  15481. } else {
  15482. /* TODO: we should also consider HEAD method */
  15483. if (((conn->response_info.status_code >= 100)
  15484. && (conn->response_info.status_code <= 199))
  15485. || (conn->response_info.status_code == 204)
  15486. || (conn->response_info.status_code == 304)) {
  15487. conn->content_len = 0;
  15488. } else {
  15489. conn->content_len = -1; /* unknown content length */
  15490. }
  15491. }
  15492. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15493. return 1;
  15494. }
  15495. int
  15496. mg_get_response(struct mg_connection *conn,
  15497. char *ebuf,
  15498. size_t ebuf_len,
  15499. int timeout)
  15500. {
  15501. int err, ret;
  15502. char txt[32]; /* will not overflow */
  15503. char *save_timeout;
  15504. char *new_timeout;
  15505. if (ebuf_len > 0) {
  15506. ebuf[0] = '\0';
  15507. }
  15508. if (!conn) {
  15509. mg_snprintf(conn,
  15510. NULL, /* No truncation check for ebuf */
  15511. ebuf,
  15512. ebuf_len,
  15513. "%s",
  15514. "Parameter error");
  15515. return -1;
  15516. }
  15517. /* Reset the previous responses */
  15518. conn->data_len = 0;
  15519. /* Implementation of API function for HTTP clients */
  15520. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15521. if (timeout >= 0) {
  15522. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15523. new_timeout = txt;
  15524. } else {
  15525. new_timeout = NULL;
  15526. }
  15527. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15528. ret = get_response(conn, ebuf, ebuf_len, &err);
  15529. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15530. #if defined(MG_LEGACY_INTERFACE)
  15531. /* TODO: 1) uri is deprecated;
  15532. * 2) here, ri.uri is the http response code */
  15533. conn->request_info.uri = conn->request_info.request_uri;
  15534. #endif
  15535. conn->request_info.local_uri = conn->request_info.request_uri;
  15536. /* TODO (mid): Define proper return values - maybe return length?
  15537. * For the first test use <0 for error and >0 for OK */
  15538. return (ret == 0) ? -1 : +1;
  15539. }
  15540. struct mg_connection *
  15541. mg_download(const char *host,
  15542. int port,
  15543. int use_ssl,
  15544. char *ebuf,
  15545. size_t ebuf_len,
  15546. const char *fmt,
  15547. ...)
  15548. {
  15549. struct mg_connection *conn;
  15550. va_list ap;
  15551. int i;
  15552. int reqerr;
  15553. if (ebuf_len > 0) {
  15554. ebuf[0] = '\0';
  15555. }
  15556. va_start(ap, fmt);
  15557. /* open a connection */
  15558. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15559. if (conn != NULL) {
  15560. i = mg_vprintf(conn, fmt, ap);
  15561. if (i <= 0) {
  15562. mg_snprintf(conn,
  15563. NULL, /* No truncation check for ebuf */
  15564. ebuf,
  15565. ebuf_len,
  15566. "%s",
  15567. "Error sending request");
  15568. } else {
  15569. /* make sure the buffer is clear */
  15570. conn->data_len = 0;
  15571. get_response(conn, ebuf, ebuf_len, &reqerr);
  15572. #if defined(MG_LEGACY_INTERFACE)
  15573. /* TODO: 1) uri is deprecated;
  15574. * 2) here, ri.uri is the http response code */
  15575. conn->request_info.uri = conn->request_info.request_uri;
  15576. #endif
  15577. conn->request_info.local_uri = conn->request_info.request_uri;
  15578. }
  15579. }
  15580. /* if an error occurred, close the connection */
  15581. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15582. mg_close_connection(conn);
  15583. conn = NULL;
  15584. }
  15585. va_end(ap);
  15586. return conn;
  15587. }
  15588. struct websocket_client_thread_data {
  15589. struct mg_connection *conn;
  15590. mg_websocket_data_handler data_handler;
  15591. mg_websocket_close_handler close_handler;
  15592. void *callback_data;
  15593. };
  15594. #if defined(USE_WEBSOCKET)
  15595. #if defined(_WIN32)
  15596. static unsigned __stdcall websocket_client_thread(void *data)
  15597. #else
  15598. static void *
  15599. websocket_client_thread(void *data)
  15600. #endif
  15601. {
  15602. struct websocket_client_thread_data *cdata =
  15603. (struct websocket_client_thread_data *)data;
  15604. void *user_thread_ptr = NULL;
  15605. #if !defined(_WIN32)
  15606. struct sigaction sa;
  15607. /* Ignore SIGPIPE */
  15608. memset(&sa, 0, sizeof(sa));
  15609. sa.sa_handler = SIG_IGN;
  15610. sigaction(SIGPIPE, &sa, NULL);
  15611. #endif
  15612. mg_set_thread_name("ws-clnt");
  15613. if (cdata->conn->phys_ctx) {
  15614. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15615. /* 3 indicates a websocket client thread */
  15616. /* TODO: check if conn->phys_ctx can be set */
  15617. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15618. cdata->conn->phys_ctx, 3);
  15619. }
  15620. }
  15621. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15622. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15623. if (cdata->close_handler != NULL) {
  15624. cdata->close_handler(cdata->conn, cdata->callback_data);
  15625. }
  15626. /* The websocket_client context has only this thread. If it runs out,
  15627. set the stop_flag to 2 (= "stopped"). */
  15628. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15629. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15630. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15631. 3,
  15632. user_thread_ptr);
  15633. }
  15634. mg_free((void *)cdata);
  15635. #if defined(_WIN32)
  15636. return 0;
  15637. #else
  15638. return NULL;
  15639. #endif
  15640. }
  15641. #endif
  15642. static struct mg_connection *
  15643. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15644. int use_ssl,
  15645. char *error_buffer,
  15646. size_t error_buffer_size,
  15647. const char *path,
  15648. const char *origin,
  15649. mg_websocket_data_handler data_func,
  15650. mg_websocket_close_handler close_func,
  15651. void *user_data)
  15652. {
  15653. struct mg_connection *conn = NULL;
  15654. #if defined(USE_WEBSOCKET)
  15655. struct websocket_client_thread_data *thread_data;
  15656. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15657. const char *handshake_req;
  15658. int port = client_options->port;
  15659. const char *host = client_options->host;
  15660. int i;
  15661. if (origin != NULL) {
  15662. handshake_req = "GET %s HTTP/1.1\r\n"
  15663. "Host: %s\r\n"
  15664. "Upgrade: websocket\r\n"
  15665. "Connection: Upgrade\r\n"
  15666. "Sec-WebSocket-Key: %s\r\n"
  15667. "Sec-WebSocket-Version: 13\r\n"
  15668. "Origin: %s\r\n"
  15669. "\r\n";
  15670. } else {
  15671. handshake_req = "GET %s HTTP/1.1\r\n"
  15672. "Host: %s\r\n"
  15673. "Upgrade: websocket\r\n"
  15674. "Connection: Upgrade\r\n"
  15675. "Sec-WebSocket-Key: %s\r\n"
  15676. "Sec-WebSocket-Version: 13\r\n"
  15677. "\r\n";
  15678. }
  15679. #if defined(__clang__)
  15680. #pragma clang diagnostic push
  15681. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15682. #endif
  15683. /* Establish the client connection and request upgrade */
  15684. conn =
  15685. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15686. if (conn == NULL) {
  15687. /* error_buffer already filled */
  15688. return NULL;
  15689. }
  15690. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15691. if (i <= 0) {
  15692. mg_snprintf(conn,
  15693. NULL, /* No truncation check for ebuf */
  15694. error_buffer,
  15695. error_buffer_size,
  15696. "%s",
  15697. "Error sending request");
  15698. mg_close_connection(conn);
  15699. return NULL;
  15700. }
  15701. conn->data_len = 0;
  15702. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15703. mg_close_connection(conn);
  15704. return NULL;
  15705. }
  15706. conn->request_info.local_uri = conn->request_info.request_uri;
  15707. #if defined(__clang__)
  15708. #pragma clang diagnostic pop
  15709. #endif
  15710. /* Connection object will be null if something goes wrong */
  15711. if (conn == NULL) {
  15712. if (!*error_buffer) {
  15713. /* There should be already an error message */
  15714. mg_snprintf(conn,
  15715. NULL, /* No truncation check for ebuf */
  15716. error_buffer,
  15717. error_buffer_size,
  15718. "Unexpected error");
  15719. }
  15720. return NULL;
  15721. }
  15722. if (conn->response_info.status_code != 101) {
  15723. /* We sent an "upgrade" request. For a correct websocket
  15724. * protocol handshake, we expect a "101 Continue" response.
  15725. * Otherwise it is a protocol violation. Maybe the HTTP
  15726. * Server does not know websockets. */
  15727. if (!*error_buffer) {
  15728. /* set an error, if not yet set */
  15729. mg_snprintf(conn,
  15730. NULL, /* No truncation check for ebuf */
  15731. error_buffer,
  15732. error_buffer_size,
  15733. "Unexpected server reply");
  15734. }
  15735. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15736. mg_close_connection(conn);
  15737. return NULL;
  15738. }
  15739. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15740. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15741. if (!thread_data) {
  15742. DEBUG_TRACE("%s\r\n", "Out of memory");
  15743. mg_close_connection(conn);
  15744. return NULL;
  15745. }
  15746. thread_data->conn = conn;
  15747. thread_data->data_handler = data_func;
  15748. thread_data->close_handler = close_func;
  15749. thread_data->callback_data = user_data;
  15750. conn->phys_ctx->worker_threadids =
  15751. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15752. if (!conn->phys_ctx->worker_threadids) {
  15753. DEBUG_TRACE("%s\r\n", "Out of memory");
  15754. mg_free(thread_data);
  15755. mg_close_connection(conn);
  15756. return NULL;
  15757. }
  15758. /* Now upgrade to ws/wss client context */
  15759. conn->phys_ctx->user_data = user_data;
  15760. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15761. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15762. /* Start a thread to read the websocket client connection
  15763. * This thread will automatically stop when mg_disconnect is
  15764. * called on the client connection */
  15765. if (mg_start_thread_with_id(websocket_client_thread,
  15766. thread_data,
  15767. conn->phys_ctx->worker_threadids)
  15768. != 0) {
  15769. conn->phys_ctx->cfg_worker_threads = 0;
  15770. mg_free(thread_data);
  15771. mg_close_connection(conn);
  15772. conn = NULL;
  15773. DEBUG_TRACE("%s",
  15774. "Websocket client connect thread could not be started\r\n");
  15775. }
  15776. #else
  15777. /* Appease "unused parameter" warnings */
  15778. (void)client_options;
  15779. (void)use_ssl;
  15780. (void)error_buffer;
  15781. (void)error_buffer_size;
  15782. (void)path;
  15783. (void)origin;
  15784. (void)user_data;
  15785. (void)data_func;
  15786. (void)close_func;
  15787. #endif
  15788. return conn;
  15789. }
  15790. struct mg_connection *
  15791. mg_connect_websocket_client(const char *host,
  15792. int port,
  15793. int use_ssl,
  15794. char *error_buffer,
  15795. size_t error_buffer_size,
  15796. const char *path,
  15797. const char *origin,
  15798. mg_websocket_data_handler data_func,
  15799. mg_websocket_close_handler close_func,
  15800. void *user_data)
  15801. {
  15802. struct mg_client_options client_options;
  15803. memset(&client_options, 0, sizeof(client_options));
  15804. client_options.host = host;
  15805. client_options.port = port;
  15806. return mg_connect_websocket_client_impl(&client_options,
  15807. use_ssl,
  15808. error_buffer,
  15809. error_buffer_size,
  15810. path,
  15811. origin,
  15812. data_func,
  15813. close_func,
  15814. user_data);
  15815. }
  15816. struct mg_connection *
  15817. mg_connect_websocket_client_secure(
  15818. const struct mg_client_options *client_options,
  15819. char *error_buffer,
  15820. size_t error_buffer_size,
  15821. const char *path,
  15822. const char *origin,
  15823. mg_websocket_data_handler data_func,
  15824. mg_websocket_close_handler close_func,
  15825. void *user_data)
  15826. {
  15827. if (!client_options) {
  15828. return NULL;
  15829. }
  15830. return mg_connect_websocket_client_impl(client_options,
  15831. 1,
  15832. error_buffer,
  15833. error_buffer_size,
  15834. path,
  15835. origin,
  15836. data_func,
  15837. close_func,
  15838. user_data);
  15839. }
  15840. /* Prepare connection data structure */
  15841. static void
  15842. init_connection(struct mg_connection *conn)
  15843. {
  15844. /* Is keep alive allowed by the server */
  15845. int keep_alive_enabled =
  15846. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15847. if (!keep_alive_enabled) {
  15848. conn->must_close = 1;
  15849. }
  15850. /* Important: on new connection, reset the receiving buffer. Credit
  15851. * goes to crule42. */
  15852. conn->data_len = 0;
  15853. conn->handled_requests = 0;
  15854. mg_set_user_connection_data(conn, NULL);
  15855. #if defined(USE_SERVER_STATS)
  15856. conn->conn_state = 2; /* init */
  15857. #endif
  15858. /* call the init_connection callback if assigned */
  15859. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15860. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15861. void *conn_data = NULL;
  15862. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15863. mg_set_user_connection_data(conn, conn_data);
  15864. }
  15865. }
  15866. }
  15867. /* Process a connection - may handle multiple requests
  15868. * using the same connection.
  15869. * Must be called with a valid connection (conn and
  15870. * conn->phys_ctx must be valid).
  15871. */
  15872. static void
  15873. process_new_connection(struct mg_connection *conn)
  15874. {
  15875. struct mg_request_info *ri = &conn->request_info;
  15876. int keep_alive, discard_len;
  15877. char ebuf[100];
  15878. const char *hostend;
  15879. int reqerr, uri_type;
  15880. #if defined(USE_SERVER_STATS)
  15881. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15882. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15883. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15884. /* could use atomic compare exchange, but this
  15885. * seems overkill for statistics data */
  15886. conn->phys_ctx->max_active_connections = mcon;
  15887. }
  15888. #endif
  15889. init_connection(conn);
  15890. DEBUG_TRACE("Start processing connection from %s",
  15891. conn->request_info.remote_addr);
  15892. /* Loop over multiple requests sent using the same connection
  15893. * (while "keep alive"). */
  15894. do {
  15895. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15896. conn->handled_requests + 1);
  15897. #if defined(USE_SERVER_STATS)
  15898. conn->conn_state = 3; /* ready */
  15899. #endif
  15900. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15901. /* The request sent by the client could not be understood by
  15902. * the server, or it was incomplete or a timeout. Send an
  15903. * error message and close the connection. */
  15904. if (reqerr > 0) {
  15905. DEBUG_ASSERT(ebuf[0] != '\0');
  15906. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15907. }
  15908. } else if (strcmp(ri->http_version, "1.0")
  15909. && strcmp(ri->http_version, "1.1")) {
  15910. /* HTTP/2 is not allowed here */
  15911. mg_snprintf(conn,
  15912. NULL, /* No truncation check for ebuf */
  15913. ebuf,
  15914. sizeof(ebuf),
  15915. "Bad HTTP version: [%s]",
  15916. ri->http_version);
  15917. mg_send_http_error(conn, 505, "%s", ebuf);
  15918. }
  15919. if (ebuf[0] == '\0') {
  15920. uri_type = get_uri_type(conn->request_info.request_uri);
  15921. switch (uri_type) {
  15922. case 1:
  15923. /* Asterisk */
  15924. conn->request_info.local_uri = 0;
  15925. /* TODO: Deal with '*'. */
  15926. break;
  15927. case 2:
  15928. /* relative uri */
  15929. conn->request_info.local_uri = conn->request_info.request_uri;
  15930. break;
  15931. case 3:
  15932. case 4:
  15933. /* absolute uri (with/without port) */
  15934. hostend = get_rel_url_at_current_server(
  15935. conn->request_info.request_uri, conn);
  15936. if (hostend) {
  15937. conn->request_info.local_uri = hostend;
  15938. } else {
  15939. conn->request_info.local_uri = NULL;
  15940. }
  15941. break;
  15942. default:
  15943. mg_snprintf(conn,
  15944. NULL, /* No truncation check for ebuf */
  15945. ebuf,
  15946. sizeof(ebuf),
  15947. "Invalid URI");
  15948. mg_send_http_error(conn, 400, "%s", ebuf);
  15949. conn->request_info.local_uri = NULL;
  15950. break;
  15951. }
  15952. #if defined(MG_LEGACY_INTERFACE)
  15953. /* Legacy before split into local_uri and request_uri */
  15954. conn->request_info.uri = conn->request_info.local_uri;
  15955. #endif
  15956. }
  15957. if (ebuf[0] != '\0') {
  15958. conn->protocol_type = -1;
  15959. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15960. /* HTTP/1 allows protocol upgrade */
  15961. conn->protocol_type = should_switch_to_protocol(conn);
  15962. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15963. /* This will occur, if a HTTP/1.1 request should be upgraded
  15964. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15965. * Since most (all?) major browsers only support HTTP/2 using
  15966. * ALPN, this is hard to test and very low priority.
  15967. * Deactivate it (at least for now).
  15968. */
  15969. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15970. }
  15971. }
  15972. DEBUG_TRACE("http: %s, error: %s",
  15973. (ri->http_version ? ri->http_version : "none"),
  15974. (ebuf[0] ? ebuf : "none"));
  15975. if (ebuf[0] == '\0') {
  15976. if (conn->request_info.local_uri) {
  15977. /* handle request to local server */
  15978. #if defined(USE_SERVER_STATS)
  15979. conn->conn_state = 4; /* processing */
  15980. #endif
  15981. handle_request(conn);
  15982. #if defined(USE_SERVER_STATS)
  15983. conn->conn_state = 5; /* processed */
  15984. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15985. conn->consumed_content);
  15986. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15987. conn->num_bytes_sent);
  15988. #endif
  15989. DEBUG_TRACE("%s", "handle_request done");
  15990. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15991. conn->phys_ctx->callbacks.end_request(conn,
  15992. conn->status_code);
  15993. DEBUG_TRACE("%s", "end_request callback done");
  15994. }
  15995. log_access(conn);
  15996. } else {
  15997. /* TODO: handle non-local request (PROXY) */
  15998. conn->must_close = 1;
  15999. }
  16000. } else {
  16001. conn->must_close = 1;
  16002. }
  16003. if (ri->remote_user != NULL) {
  16004. mg_free((void *)ri->remote_user);
  16005. /* Important! When having connections with and without auth
  16006. * would cause double free and then crash */
  16007. ri->remote_user = NULL;
  16008. }
  16009. /* NOTE(lsm): order is important here. should_keep_alive() call
  16010. * is using parsed request, which will be invalid after
  16011. * memmove's below.
  16012. * Therefore, memorize should_keep_alive() result now for later
  16013. * use in loop exit condition. */
  16014. /* Enable it only if this request is completely discardable. */
  16015. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16016. && should_keep_alive(conn) && (conn->content_len >= 0)
  16017. && (conn->request_len > 0)
  16018. && ((conn->is_chunked == 4)
  16019. || (!conn->is_chunked
  16020. && ((conn->consumed_content == conn->content_len)
  16021. || ((conn->request_len + conn->content_len)
  16022. <= conn->data_len))))
  16023. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16024. if (keep_alive) {
  16025. /* Discard all buffered data for this request */
  16026. discard_len =
  16027. ((conn->request_len + conn->content_len) < conn->data_len)
  16028. ? (int)(conn->request_len + conn->content_len)
  16029. : conn->data_len;
  16030. conn->data_len -= discard_len;
  16031. if (conn->data_len > 0) {
  16032. DEBUG_TRACE("discard_len = %d", discard_len);
  16033. memmove(conn->buf,
  16034. conn->buf + discard_len,
  16035. (size_t)conn->data_len);
  16036. }
  16037. }
  16038. DEBUG_ASSERT(conn->data_len >= 0);
  16039. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16040. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16041. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16042. (long int)conn->data_len,
  16043. (long int)conn->buf_size);
  16044. break;
  16045. }
  16046. conn->handled_requests++;
  16047. } while (keep_alive);
  16048. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16049. conn->request_info.remote_addr,
  16050. difftime(time(NULL), conn->conn_birth_time));
  16051. close_connection(conn);
  16052. #if defined(USE_SERVER_STATS)
  16053. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16054. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16055. #endif
  16056. }
  16057. #if defined(ALTERNATIVE_QUEUE)
  16058. static void
  16059. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16060. {
  16061. unsigned int i;
  16062. while (!ctx->stop_flag) {
  16063. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16064. /* find a free worker slot and signal it */
  16065. if (ctx->client_socks[i].in_use == 2) {
  16066. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16067. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16068. ctx->client_socks[i] = *sp;
  16069. ctx->client_socks[i].in_use = 1;
  16070. /* socket has been moved to the consumer */
  16071. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16072. (void)event_signal(ctx->client_wait_events[i]);
  16073. return;
  16074. }
  16075. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16076. }
  16077. }
  16078. /* queue is full */
  16079. mg_sleep(1);
  16080. }
  16081. /* must consume */
  16082. set_blocking_mode(sp->sock);
  16083. closesocket(sp->sock);
  16084. }
  16085. static int
  16086. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16087. {
  16088. DEBUG_TRACE("%s", "going idle");
  16089. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16090. ctx->client_socks[thread_index].in_use = 2;
  16091. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16092. event_wait(ctx->client_wait_events[thread_index]);
  16093. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16094. *sp = ctx->client_socks[thread_index];
  16095. if (ctx->stop_flag) {
  16096. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16097. if (sp->in_use == 1) {
  16098. /* must consume */
  16099. set_blocking_mode(sp->sock);
  16100. closesocket(sp->sock);
  16101. }
  16102. return 0;
  16103. }
  16104. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16105. if (sp->in_use == 1) {
  16106. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16107. return 1;
  16108. }
  16109. /* must not reach here */
  16110. DEBUG_ASSERT(0);
  16111. return 0;
  16112. }
  16113. #else /* ALTERNATIVE_QUEUE */
  16114. /* Worker threads take accepted socket from the queue */
  16115. static int
  16116. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16117. {
  16118. (void)thread_index;
  16119. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16120. DEBUG_TRACE("%s", "going idle");
  16121. /* If the queue is empty, wait. We're idle at this point. */
  16122. while ((ctx->sq_head == ctx->sq_tail)
  16123. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16124. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16125. }
  16126. /* If we're stopping, sq_head may be equal to sq_tail. */
  16127. if (ctx->sq_head > ctx->sq_tail) {
  16128. /* Copy socket from the queue and increment tail */
  16129. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16130. ctx->sq_tail++;
  16131. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16132. /* Wrap pointers if needed */
  16133. while (ctx->sq_tail > ctx->sq_size) {
  16134. ctx->sq_tail -= ctx->sq_size;
  16135. ctx->sq_head -= ctx->sq_size;
  16136. }
  16137. }
  16138. (void)pthread_cond_signal(&ctx->sq_empty);
  16139. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16140. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16141. }
  16142. /* Master thread adds accepted socket to a queue */
  16143. static void
  16144. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16145. {
  16146. int queue_filled;
  16147. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16148. queue_filled = ctx->sq_head - ctx->sq_tail;
  16149. /* If the queue is full, wait */
  16150. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16151. && (queue_filled >= ctx->sq_size)) {
  16152. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16153. #if defined(USE_SERVER_STATS)
  16154. if (queue_filled > ctx->sq_max_fill) {
  16155. ctx->sq_max_fill = queue_filled;
  16156. }
  16157. #endif
  16158. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16159. ctx->sq_blocked = 0; /* Not blocked now */
  16160. queue_filled = ctx->sq_head - ctx->sq_tail;
  16161. }
  16162. if (queue_filled < ctx->sq_size) {
  16163. /* Copy socket to the queue and increment head */
  16164. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16165. ctx->sq_head++;
  16166. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16167. }
  16168. queue_filled = ctx->sq_head - ctx->sq_tail;
  16169. #if defined(USE_SERVER_STATS)
  16170. if (queue_filled > ctx->sq_max_fill) {
  16171. ctx->sq_max_fill = queue_filled;
  16172. }
  16173. #endif
  16174. (void)pthread_cond_signal(&ctx->sq_full);
  16175. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16176. }
  16177. #endif /* ALTERNATIVE_QUEUE */
  16178. static void
  16179. worker_thread_run(struct mg_connection *conn)
  16180. {
  16181. struct mg_context *ctx = conn->phys_ctx;
  16182. int thread_index;
  16183. struct mg_workerTLS tls;
  16184. #if defined(MG_LEGACY_INTERFACE)
  16185. uint32_t addr;
  16186. #endif
  16187. mg_set_thread_name("worker");
  16188. tls.is_master = 0;
  16189. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16190. #if defined(_WIN32)
  16191. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16192. #endif
  16193. /* Initialize thread local storage before calling any callback */
  16194. pthread_setspecific(sTlsKey, &tls);
  16195. /* Check if there is a user callback */
  16196. if (ctx->callbacks.init_thread) {
  16197. /* call init_thread for a worker thread (type 1), and store the
  16198. * return value */
  16199. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16200. } else {
  16201. /* No callback: set user pointer to NULL */
  16202. tls.user_ptr = NULL;
  16203. }
  16204. /* Connection structure has been pre-allocated */
  16205. thread_index = (int)(conn - ctx->worker_connections);
  16206. if ((thread_index < 0)
  16207. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16208. mg_cry_ctx_internal(ctx,
  16209. "Internal error: Invalid worker index %i",
  16210. thread_index);
  16211. return;
  16212. }
  16213. /* Request buffers are not pre-allocated. They are private to the
  16214. * request and do not contain any state information that might be
  16215. * of interest to anyone observing a server status. */
  16216. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16217. if (conn->buf == NULL) {
  16218. mg_cry_ctx_internal(
  16219. ctx,
  16220. "Out of memory: Cannot allocate buffer for worker %i",
  16221. thread_index);
  16222. return;
  16223. }
  16224. conn->buf_size = (int)ctx->max_request_size;
  16225. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16226. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16227. conn->request_info.user_data = ctx->user_data;
  16228. /* Allocate a mutex for this connection to allow communication both
  16229. * within the request handler and from elsewhere in the application
  16230. */
  16231. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16232. mg_free(conn->buf);
  16233. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16234. return;
  16235. }
  16236. #if defined(USE_SERVER_STATS)
  16237. conn->conn_state = 1; /* not consumed */
  16238. #endif
  16239. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16240. * signal sq_empty condvar to wake up the master waiting in
  16241. * produce_socket() */
  16242. while (consume_socket(ctx, &conn->client, thread_index)) {
  16243. /* New connections must start with new protocol negotiation */
  16244. tls.alpn_proto = NULL;
  16245. #if defined(USE_SERVER_STATS)
  16246. conn->conn_close_time = 0;
  16247. #endif
  16248. conn->conn_birth_time = time(NULL);
  16249. /* Fill in IP, port info early so even if SSL setup below fails,
  16250. * error handler would have the corresponding info.
  16251. * Thanks to Johannes Winkelmann for the patch.
  16252. */
  16253. conn->request_info.remote_port =
  16254. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16255. sockaddr_to_string(conn->request_info.remote_addr,
  16256. sizeof(conn->request_info.remote_addr),
  16257. &conn->client.rsa);
  16258. DEBUG_TRACE("Start processing connection from %s",
  16259. conn->request_info.remote_addr);
  16260. conn->request_info.is_ssl = conn->client.is_ssl;
  16261. if (conn->client.is_ssl) {
  16262. #if !defined(NO_SSL)
  16263. /* HTTPS connection */
  16264. if (sslize(conn, SSL_accept, NULL)) {
  16265. /* conn->dom_ctx is set in get_request */
  16266. /* Get SSL client certificate information (if set) */
  16267. struct mg_client_cert client_cert;
  16268. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16269. conn->request_info.client_cert = &client_cert;
  16270. }
  16271. /* process HTTPS connection */
  16272. #if defined(USE_HTTP2)
  16273. if ((tls.alpn_proto != NULL)
  16274. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16275. /* process HTTPS/2 connection */
  16276. init_connection(conn);
  16277. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16278. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16279. conn->content_len = -1;
  16280. conn->is_chunked = 0;
  16281. process_new_http2_connection(conn);
  16282. } else
  16283. #endif
  16284. {
  16285. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16286. process_new_connection(conn);
  16287. }
  16288. /* Free client certificate info */
  16289. if (conn->request_info.client_cert) {
  16290. mg_free((void *)(conn->request_info.client_cert->subject));
  16291. mg_free((void *)(conn->request_info.client_cert->issuer));
  16292. mg_free((void *)(conn->request_info.client_cert->serial));
  16293. mg_free((void *)(conn->request_info.client_cert->finger));
  16294. /* Free certificate memory */
  16295. X509_free(
  16296. (X509 *)conn->request_info.client_cert->peer_cert);
  16297. conn->request_info.client_cert->peer_cert = 0;
  16298. conn->request_info.client_cert->subject = 0;
  16299. conn->request_info.client_cert->issuer = 0;
  16300. conn->request_info.client_cert->serial = 0;
  16301. conn->request_info.client_cert->finger = 0;
  16302. conn->request_info.client_cert = 0;
  16303. }
  16304. } else {
  16305. /* make sure the connection is cleaned up on SSL failure */
  16306. close_connection(conn);
  16307. }
  16308. #endif
  16309. } else {
  16310. /* process HTTP connection */
  16311. process_new_connection(conn);
  16312. }
  16313. DEBUG_TRACE("%s", "Connection closed");
  16314. #if defined(USE_SERVER_STATS)
  16315. conn->conn_close_time = time(NULL);
  16316. #endif
  16317. }
  16318. /* Call exit thread user callback */
  16319. if (ctx->callbacks.exit_thread) {
  16320. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16321. }
  16322. /* delete thread local storage objects */
  16323. pthread_setspecific(sTlsKey, NULL);
  16324. #if defined(_WIN32)
  16325. CloseHandle(tls.pthread_cond_helper_mutex);
  16326. #endif
  16327. pthread_mutex_destroy(&conn->mutex);
  16328. /* Free the request buffer. */
  16329. conn->buf_size = 0;
  16330. mg_free(conn->buf);
  16331. conn->buf = NULL;
  16332. #if defined(USE_SERVER_STATS)
  16333. conn->conn_state = 9; /* done */
  16334. #endif
  16335. DEBUG_TRACE("%s", "exiting");
  16336. }
  16337. /* Threads have different return types on Windows and Unix. */
  16338. #if defined(_WIN32)
  16339. static unsigned __stdcall worker_thread(void *thread_func_param)
  16340. {
  16341. worker_thread_run((struct mg_connection *)thread_func_param);
  16342. return 0;
  16343. }
  16344. #else
  16345. static void *
  16346. worker_thread(void *thread_func_param)
  16347. {
  16348. #if !defined(__ZEPHYR__)
  16349. struct sigaction sa;
  16350. /* Ignore SIGPIPE */
  16351. memset(&sa, 0, sizeof(sa));
  16352. sa.sa_handler = SIG_IGN;
  16353. sigaction(SIGPIPE, &sa, NULL);
  16354. #endif
  16355. worker_thread_run((struct mg_connection *)thread_func_param);
  16356. return NULL;
  16357. }
  16358. #endif /* _WIN32 */
  16359. /* This is an internal function, thus all arguments are expected to be
  16360. * valid - a NULL check is not required. */
  16361. static void
  16362. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16363. {
  16364. struct socket so;
  16365. char src_addr[IP_ADDR_STR_LEN];
  16366. socklen_t len = sizeof(so.rsa);
  16367. #if !defined(__ZEPHYR__)
  16368. int on = 1;
  16369. #endif
  16370. memset(&so, 0, sizeof(so));
  16371. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16372. == INVALID_SOCKET) {
  16373. } else if (check_acl(ctx, &so.rsa) != 1) {
  16374. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16375. mg_cry_ctx_internal(ctx,
  16376. "%s: %s is not allowed to connect",
  16377. __func__,
  16378. src_addr);
  16379. closesocket(so.sock);
  16380. } else {
  16381. /* Put so socket structure into the queue */
  16382. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16383. set_close_on_exec(so.sock, NULL, ctx);
  16384. so.is_ssl = listener->is_ssl;
  16385. so.ssl_redir = listener->ssl_redir;
  16386. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16387. mg_cry_ctx_internal(ctx,
  16388. "%s: getsockname() failed: %s",
  16389. __func__,
  16390. strerror(ERRNO));
  16391. }
  16392. #if !defined(__ZEPHYR__)
  16393. /* Set TCP keep-alive. This is needed because if HTTP-level
  16394. * keep-alive
  16395. * is enabled, and client resets the connection, server won't get
  16396. * TCP FIN or RST and will keep the connection open forever. With
  16397. * TCP keep-alive, next keep-alive handshake will figure out that
  16398. * the client is down and will close the server end.
  16399. * Thanks to Igor Klopov who suggested the patch. */
  16400. if (setsockopt(so.sock,
  16401. SOL_SOCKET,
  16402. SO_KEEPALIVE,
  16403. (SOCK_OPT_TYPE)&on,
  16404. sizeof(on))
  16405. != 0) {
  16406. mg_cry_ctx_internal(
  16407. ctx,
  16408. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16409. __func__,
  16410. strerror(ERRNO));
  16411. }
  16412. #endif
  16413. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16414. * to effectively fill up the underlying IP packet payload and
  16415. * reduce the overhead of sending lots of small buffers. However
  16416. * this hurts the server's throughput (ie. operations per second)
  16417. * when HTTP 1.1 persistent connections are used and the responses
  16418. * are relatively small (eg. less than 1400 bytes).
  16419. */
  16420. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16421. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16422. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16423. mg_cry_ctx_internal(
  16424. ctx,
  16425. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16426. __func__,
  16427. strerror(ERRNO));
  16428. }
  16429. }
  16430. /* The "non blocking" property should already be
  16431. * inherited from the parent socket. Set it for
  16432. * non-compliant socket implementations. */
  16433. set_non_blocking_mode(so.sock);
  16434. so.in_use = 0;
  16435. produce_socket(ctx, &so);
  16436. }
  16437. }
  16438. static void
  16439. master_thread_run(struct mg_context *ctx)
  16440. {
  16441. struct mg_workerTLS tls;
  16442. struct mg_pollfd *pfd;
  16443. unsigned int i;
  16444. unsigned int workerthreadcount;
  16445. if (!ctx) {
  16446. return;
  16447. }
  16448. mg_set_thread_name("master");
  16449. /* Increase priority of the master thread */
  16450. #if defined(_WIN32)
  16451. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16452. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16453. int min_prio = sched_get_priority_min(SCHED_RR);
  16454. int max_prio = sched_get_priority_max(SCHED_RR);
  16455. if ((min_prio >= 0) && (max_prio >= 0)
  16456. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16457. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16458. struct sched_param sched_param = {0};
  16459. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16460. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16461. }
  16462. #endif
  16463. /* Initialize thread local storage */
  16464. #if defined(_WIN32)
  16465. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16466. #endif
  16467. tls.is_master = 1;
  16468. pthread_setspecific(sTlsKey, &tls);
  16469. if (ctx->callbacks.init_thread) {
  16470. /* Callback for the master thread (type 0) */
  16471. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16472. } else {
  16473. tls.user_ptr = NULL;
  16474. }
  16475. /* Server starts *now* */
  16476. ctx->start_time = time(NULL);
  16477. /* Start the server */
  16478. pfd = ctx->listening_socket_fds;
  16479. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16480. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16481. pfd[i].fd = ctx->listening_sockets[i].sock;
  16482. pfd[i].events = POLLIN;
  16483. }
  16484. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16485. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16486. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16487. * successful poll, and POLLIN is defined as
  16488. * (POLLRDNORM | POLLRDBAND)
  16489. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16490. * pfd[i].revents == POLLIN. */
  16491. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16492. && (pfd[i].revents & POLLIN)) {
  16493. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16494. }
  16495. }
  16496. }
  16497. }
  16498. /* Here stop_flag is 1 - Initiate shutdown. */
  16499. DEBUG_TRACE("%s", "stopping workers");
  16500. /* Stop signal received: somebody called mg_stop. Quit. */
  16501. close_all_listening_sockets(ctx);
  16502. /* Wakeup workers that are waiting for connections to handle. */
  16503. #if defined(ALTERNATIVE_QUEUE)
  16504. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16505. event_signal(ctx->client_wait_events[i]);
  16506. }
  16507. #else
  16508. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16509. pthread_cond_broadcast(&ctx->sq_full);
  16510. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16511. #endif
  16512. /* Join all worker threads to avoid leaking threads. */
  16513. workerthreadcount = ctx->cfg_worker_threads;
  16514. for (i = 0; i < workerthreadcount; i++) {
  16515. if (ctx->worker_threadids[i] != 0) {
  16516. mg_join_thread(ctx->worker_threadids[i]);
  16517. }
  16518. }
  16519. #if defined(USE_LUA)
  16520. /* Free Lua state of lua background task */
  16521. if (ctx->lua_background_state) {
  16522. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16523. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16524. if (lua_istable(lstate, -1)) {
  16525. reg_boolean(lstate, "shutdown", 1);
  16526. lua_pop(lstate, 1);
  16527. mg_sleep(2);
  16528. }
  16529. lua_close(lstate);
  16530. ctx->lua_background_state = 0;
  16531. }
  16532. #endif
  16533. DEBUG_TRACE("%s", "exiting");
  16534. /* call exit thread callback */
  16535. if (ctx->callbacks.exit_thread) {
  16536. /* Callback for the master thread (type 0) */
  16537. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16538. }
  16539. #if defined(_WIN32)
  16540. CloseHandle(tls.pthread_cond_helper_mutex);
  16541. #endif
  16542. pthread_setspecific(sTlsKey, NULL);
  16543. /* Signal mg_stop() that we're done.
  16544. * WARNING: This must be the very last thing this
  16545. * thread does, as ctx becomes invalid after this line. */
  16546. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16547. }
  16548. /* Threads have different return types on Windows and Unix. */
  16549. #if defined(_WIN32)
  16550. static unsigned __stdcall master_thread(void *thread_func_param)
  16551. {
  16552. master_thread_run((struct mg_context *)thread_func_param);
  16553. return 0;
  16554. }
  16555. #else
  16556. static void *
  16557. master_thread(void *thread_func_param)
  16558. {
  16559. #if !defined(__ZEPHYR__)
  16560. struct sigaction sa;
  16561. /* Ignore SIGPIPE */
  16562. memset(&sa, 0, sizeof(sa));
  16563. sa.sa_handler = SIG_IGN;
  16564. sigaction(SIGPIPE, &sa, NULL);
  16565. #endif
  16566. master_thread_run((struct mg_context *)thread_func_param);
  16567. return NULL;
  16568. }
  16569. #endif /* _WIN32 */
  16570. static void
  16571. free_context(struct mg_context *ctx)
  16572. {
  16573. int i;
  16574. struct mg_handler_info *tmp_rh;
  16575. if (ctx == NULL) {
  16576. return;
  16577. }
  16578. if (ctx->callbacks.exit_context) {
  16579. ctx->callbacks.exit_context(ctx);
  16580. }
  16581. /* All threads exited, no sync is needed. Destroy thread mutex and
  16582. * condvars
  16583. */
  16584. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16585. #if defined(ALTERNATIVE_QUEUE)
  16586. mg_free(ctx->client_socks);
  16587. if (ctx->client_wait_events != NULL) {
  16588. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16589. event_destroy(ctx->client_wait_events[i]);
  16590. }
  16591. mg_free(ctx->client_wait_events);
  16592. }
  16593. #else
  16594. (void)pthread_cond_destroy(&ctx->sq_empty);
  16595. (void)pthread_cond_destroy(&ctx->sq_full);
  16596. mg_free(ctx->squeue);
  16597. #endif
  16598. /* Destroy other context global data structures mutex */
  16599. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16600. #if defined(USE_TIMERS)
  16601. timers_exit(ctx);
  16602. #endif
  16603. /* Deallocate config parameters */
  16604. for (i = 0; i < NUM_OPTIONS; i++) {
  16605. if (ctx->dd.config[i] != NULL) {
  16606. #if defined(_MSC_VER)
  16607. #pragma warning(suppress : 6001)
  16608. #endif
  16609. mg_free(ctx->dd.config[i]);
  16610. }
  16611. }
  16612. /* Deallocate request handlers */
  16613. while (ctx->dd.handlers) {
  16614. tmp_rh = ctx->dd.handlers;
  16615. ctx->dd.handlers = tmp_rh->next;
  16616. mg_free(tmp_rh->uri);
  16617. mg_free(tmp_rh);
  16618. }
  16619. #if !defined(NO_SSL)
  16620. /* Deallocate SSL context */
  16621. if (ctx->dd.ssl_ctx != NULL) {
  16622. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16623. int callback_ret =
  16624. (ctx->callbacks.external_ssl_ctx == NULL)
  16625. ? 0
  16626. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16627. if (callback_ret == 0) {
  16628. SSL_CTX_free(ctx->dd.ssl_ctx);
  16629. }
  16630. /* else: ignore error and ommit SSL_CTX_free in case
  16631. * callback_ret is 1 */
  16632. }
  16633. #endif /* !NO_SSL */
  16634. /* Deallocate worker thread ID array */
  16635. mg_free(ctx->worker_threadids);
  16636. /* Deallocate worker thread ID array */
  16637. mg_free(ctx->worker_connections);
  16638. /* deallocate system name string */
  16639. mg_free(ctx->systemName);
  16640. /* Deallocate context itself */
  16641. mg_free(ctx);
  16642. }
  16643. void
  16644. mg_stop(struct mg_context *ctx)
  16645. {
  16646. pthread_t mt;
  16647. if (!ctx) {
  16648. return;
  16649. }
  16650. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16651. * two threads is not allowed. */
  16652. mt = ctx->masterthreadid;
  16653. if (mt == 0) {
  16654. return;
  16655. }
  16656. ctx->masterthreadid = 0;
  16657. /* Set stop flag, so all threads know they have to exit. */
  16658. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16659. /* Wait until everything has stopped. */
  16660. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16661. (void)mg_sleep(10);
  16662. }
  16663. mg_join_thread(mt);
  16664. free_context(ctx);
  16665. }
  16666. static void
  16667. get_system_name(char **sysName)
  16668. {
  16669. #if defined(_WIN32)
  16670. #if defined(_WIN32_WCE)
  16671. *sysName = mg_strdup("WinCE");
  16672. #else
  16673. char name[128];
  16674. DWORD dwVersion = 0;
  16675. DWORD dwMajorVersion = 0;
  16676. DWORD dwMinorVersion = 0;
  16677. DWORD dwBuild = 0;
  16678. BOOL wowRet, isWoW = FALSE;
  16679. #if defined(_MSC_VER)
  16680. #pragma warning(push)
  16681. /* GetVersion was declared deprecated */
  16682. #pragma warning(disable : 4996)
  16683. #endif
  16684. dwVersion = GetVersion();
  16685. #if defined(_MSC_VER)
  16686. #pragma warning(pop)
  16687. #endif
  16688. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16689. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16690. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16691. (void)dwBuild;
  16692. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16693. sprintf(name,
  16694. "Windows %u.%u%s",
  16695. (unsigned)dwMajorVersion,
  16696. (unsigned)dwMinorVersion,
  16697. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16698. *sysName = mg_strdup(name);
  16699. #endif
  16700. #elif defined(__ZEPHYR__)
  16701. *sysName = mg_strdup("Zephyr OS");
  16702. #else
  16703. struct utsname name;
  16704. memset(&name, 0, sizeof(name));
  16705. uname(&name);
  16706. *sysName = mg_strdup(name.sysname);
  16707. #endif
  16708. }
  16709. static void
  16710. legacy_init(const char **options)
  16711. {
  16712. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16713. if (options) {
  16714. const char **run_options = options;
  16715. const char *optname = config_options[LISTENING_PORTS].name;
  16716. /* Try to find the "listening_ports" option */
  16717. while (*run_options) {
  16718. if (!strcmp(*run_options, optname)) {
  16719. ports_option = run_options[1];
  16720. }
  16721. run_options += 2;
  16722. }
  16723. }
  16724. if (is_ssl_port_used(ports_option)) {
  16725. /* Initialize with SSL support */
  16726. mg_init_library(MG_FEATURES_TLS);
  16727. } else {
  16728. /* Initialize without SSL support */
  16729. mg_init_library(MG_FEATURES_DEFAULT);
  16730. }
  16731. }
  16732. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16733. static
  16734. #endif
  16735. struct mg_context *
  16736. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16737. {
  16738. struct mg_context *ctx;
  16739. const char *name, *value, *default_value;
  16740. int idx, ok, workerthreadcount;
  16741. unsigned int i;
  16742. int itmp;
  16743. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16744. const char **options =
  16745. ((init != NULL) ? (init->configuration_options) : (NULL));
  16746. struct mg_workerTLS tls;
  16747. if (error != NULL) {
  16748. error->code = 0;
  16749. if (error->text_buffer_size > 0) {
  16750. *error->text = 0;
  16751. }
  16752. }
  16753. if (mg_init_library_called == 0) {
  16754. /* Legacy INIT, if mg_start is called without mg_init_library.
  16755. * Note: This will cause a memory leak when unloading the library.
  16756. */
  16757. legacy_init(options);
  16758. }
  16759. if (mg_init_library_called == 0) {
  16760. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16761. mg_snprintf(NULL,
  16762. NULL, /* No truncation check for error buffers */
  16763. error->text,
  16764. error->text_buffer_size,
  16765. "%s",
  16766. "Library uninitialized");
  16767. }
  16768. return NULL;
  16769. }
  16770. /* Allocate context and initialize reasonable general case defaults. */
  16771. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16772. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16773. mg_snprintf(NULL,
  16774. NULL, /* No truncation check for error buffers */
  16775. error->text,
  16776. error->text_buffer_size,
  16777. "%s",
  16778. "Out of memory");
  16779. }
  16780. return NULL;
  16781. }
  16782. /* Random number generator will initialize at the first call */
  16783. ctx->dd.auth_nonce_mask =
  16784. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16785. /* Save started thread index to reuse in other external API calls
  16786. * For the sake of thread synchronization all non-civetweb threads
  16787. * can be considered as single external thread */
  16788. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16789. tls.is_master = -1; /* Thread calling mg_start */
  16790. tls.thread_idx = ctx->starter_thread_idx;
  16791. #if defined(_WIN32)
  16792. tls.pthread_cond_helper_mutex = NULL;
  16793. #endif
  16794. pthread_setspecific(sTlsKey, &tls);
  16795. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16796. #if !defined(ALTERNATIVE_QUEUE)
  16797. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16798. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16799. ctx->sq_blocked = 0;
  16800. #endif
  16801. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16802. if (!ok) {
  16803. const char *err_msg =
  16804. "Cannot initialize thread synchronization objects";
  16805. /* Fatal error - abort start. However, this situation should never
  16806. * occur in practice. */
  16807. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16808. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16809. mg_snprintf(NULL,
  16810. NULL, /* No truncation check for error buffers */
  16811. error->text,
  16812. error->text_buffer_size,
  16813. "%s",
  16814. err_msg);
  16815. }
  16816. mg_free(ctx);
  16817. pthread_setspecific(sTlsKey, NULL);
  16818. return NULL;
  16819. }
  16820. if ((init != NULL) && (init->callbacks != NULL)) {
  16821. /* Set all callbacks except exit_context. */
  16822. ctx->callbacks = *init->callbacks;
  16823. exit_callback = init->callbacks->exit_context;
  16824. /* The exit callback is activated once the context is successfully
  16825. * created. It should not be called, if an incomplete context object
  16826. * is deleted during a failed initialization. */
  16827. ctx->callbacks.exit_context = 0;
  16828. }
  16829. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16830. ctx->dd.handlers = NULL;
  16831. ctx->dd.next = NULL;
  16832. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16833. ctx->dd.shared_lua_websockets = NULL;
  16834. #endif
  16835. /* Store options */
  16836. while (options && (name = *options++) != NULL) {
  16837. if ((idx = get_option_index(name)) == -1) {
  16838. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16839. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16840. mg_snprintf(NULL,
  16841. NULL, /* No truncation check for error buffers */
  16842. error->text,
  16843. error->text_buffer_size,
  16844. "Invalid configuration option: %s",
  16845. name);
  16846. }
  16847. free_context(ctx);
  16848. pthread_setspecific(sTlsKey, NULL);
  16849. return NULL;
  16850. } else if ((value = *options++) == NULL) {
  16851. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16852. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16853. mg_snprintf(NULL,
  16854. NULL, /* No truncation check for error buffers */
  16855. error->text,
  16856. error->text_buffer_size,
  16857. "Invalid configuration option value: %s",
  16858. name);
  16859. }
  16860. free_context(ctx);
  16861. pthread_setspecific(sTlsKey, NULL);
  16862. return NULL;
  16863. }
  16864. if (ctx->dd.config[idx] != NULL) {
  16865. /* A duplicate configuration option is not an error - the last
  16866. * option value will be used. */
  16867. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16868. mg_free(ctx->dd.config[idx]);
  16869. }
  16870. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16871. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16872. }
  16873. /* Set default value if needed */
  16874. for (i = 0; config_options[i].name != NULL; i++) {
  16875. default_value = config_options[i].default_value;
  16876. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16877. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16878. }
  16879. }
  16880. /* Request size option */
  16881. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16882. if (itmp < 1024) {
  16883. mg_cry_ctx_internal(ctx,
  16884. "%s too small",
  16885. config_options[MAX_REQUEST_SIZE].name);
  16886. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16887. mg_snprintf(NULL,
  16888. NULL, /* No truncation check for error buffers */
  16889. error->text,
  16890. error->text_buffer_size,
  16891. "Invalid configuration option value: %s",
  16892. config_options[MAX_REQUEST_SIZE].name);
  16893. }
  16894. free_context(ctx);
  16895. pthread_setspecific(sTlsKey, NULL);
  16896. return NULL;
  16897. }
  16898. ctx->max_request_size = (unsigned)itmp;
  16899. /* Queue length */
  16900. #if !defined(ALTERNATIVE_QUEUE)
  16901. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16902. if (itmp < 1) {
  16903. mg_cry_ctx_internal(ctx,
  16904. "%s too small",
  16905. config_options[CONNECTION_QUEUE_SIZE].name);
  16906. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16907. mg_snprintf(NULL,
  16908. NULL, /* No truncation check for error buffers */
  16909. error->text,
  16910. error->text_buffer_size,
  16911. "Invalid configuration option value: %s",
  16912. config_options[CONNECTION_QUEUE_SIZE].name);
  16913. }
  16914. free_context(ctx);
  16915. pthread_setspecific(sTlsKey, NULL);
  16916. return NULL;
  16917. }
  16918. ctx->squeue =
  16919. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16920. if (ctx->squeue == NULL) {
  16921. mg_cry_ctx_internal(ctx,
  16922. "Out of memory: Cannot allocate %s",
  16923. config_options[CONNECTION_QUEUE_SIZE].name);
  16924. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16925. mg_snprintf(NULL,
  16926. NULL, /* No truncation check for error buffers */
  16927. error->text,
  16928. error->text_buffer_size,
  16929. "Out of memory: Cannot allocate %s",
  16930. config_options[CONNECTION_QUEUE_SIZE].name);
  16931. }
  16932. free_context(ctx);
  16933. pthread_setspecific(sTlsKey, NULL);
  16934. return NULL;
  16935. }
  16936. ctx->sq_size = itmp;
  16937. #endif
  16938. /* Worker thread count option */
  16939. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16940. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16941. if (workerthreadcount <= 0) {
  16942. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16943. } else {
  16944. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16945. }
  16946. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16947. mg_snprintf(NULL,
  16948. NULL, /* No truncation check for error buffers */
  16949. error->text,
  16950. error->text_buffer_size,
  16951. "Invalid configuration option value: %s",
  16952. config_options[NUM_THREADS].name);
  16953. }
  16954. free_context(ctx);
  16955. pthread_setspecific(sTlsKey, NULL);
  16956. return NULL;
  16957. }
  16958. /* Document root */
  16959. #if defined(NO_FILES)
  16960. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16961. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16962. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16963. mg_snprintf(NULL,
  16964. NULL, /* No truncation check for error buffers */
  16965. error->text,
  16966. error->text_buffer_size,
  16967. "Invalid configuration option value: %s",
  16968. config_options[DOCUMENT_ROOT].name);
  16969. }
  16970. free_context(ctx);
  16971. pthread_setspecific(sTlsKey, NULL);
  16972. return NULL;
  16973. }
  16974. #endif
  16975. get_system_name(&ctx->systemName);
  16976. #if defined(USE_LUA)
  16977. /* If a Lua background script has been configured, start it. */
  16978. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16979. char ebuf[256];
  16980. struct vec opt_vec;
  16981. struct vec eq_vec;
  16982. const char *sparams;
  16983. lua_State *state = mg_prepare_lua_context_script(
  16984. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16985. if (!state) {
  16986. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16987. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16988. mg_snprintf(NULL,
  16989. NULL, /* No truncation check for error buffers */
  16990. error->text,
  16991. error->text_buffer_size,
  16992. "Error in script %s: %s",
  16993. config_options[DOCUMENT_ROOT].name,
  16994. ebuf);
  16995. }
  16996. free_context(ctx);
  16997. pthread_setspecific(sTlsKey, NULL);
  16998. return NULL;
  16999. }
  17000. ctx->lua_background_state = (void *)state;
  17001. lua_newtable(state);
  17002. reg_boolean(state, "shutdown", 0);
  17003. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17004. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17005. reg_llstring(
  17006. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17007. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17008. break;
  17009. }
  17010. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17011. } else {
  17012. ctx->lua_background_state = 0;
  17013. }
  17014. #endif
  17015. /* Step by step initialization of ctx - depending on build options */
  17016. #if !defined(NO_FILESYSTEMS)
  17017. if (!set_gpass_option(ctx, NULL)) {
  17018. const char *err_msg = "Invalid global password file";
  17019. /* Fatal error - abort start. */
  17020. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17021. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17022. mg_snprintf(NULL,
  17023. NULL, /* No truncation check for error buffers */
  17024. error->text,
  17025. error->text_buffer_size,
  17026. "%s",
  17027. err_msg);
  17028. }
  17029. free_context(ctx);
  17030. pthread_setspecific(sTlsKey, NULL);
  17031. return NULL;
  17032. }
  17033. #endif
  17034. #if !defined(NO_SSL)
  17035. if (!init_ssl_ctx(ctx, NULL)) {
  17036. const char *err_msg = "Error initializing SSL context";
  17037. /* Fatal error - abort start. */
  17038. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17039. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17040. mg_snprintf(NULL,
  17041. NULL, /* No truncation check for error buffers */
  17042. error->text,
  17043. error->text_buffer_size,
  17044. "%s",
  17045. err_msg);
  17046. }
  17047. free_context(ctx);
  17048. pthread_setspecific(sTlsKey, NULL);
  17049. return NULL;
  17050. }
  17051. #endif
  17052. if (!set_ports_option(ctx)) {
  17053. const char *err_msg = "Failed to setup server ports";
  17054. /* Fatal error - abort start. */
  17055. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17056. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17057. mg_snprintf(NULL,
  17058. NULL, /* No truncation check for error buffers */
  17059. error->text,
  17060. error->text_buffer_size,
  17061. "%s",
  17062. err_msg);
  17063. }
  17064. free_context(ctx);
  17065. pthread_setspecific(sTlsKey, NULL);
  17066. return NULL;
  17067. }
  17068. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17069. if (!set_uid_option(ctx)) {
  17070. const char *err_msg = "Failed to run as configured user";
  17071. /* Fatal error - abort start. */
  17072. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17073. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17074. mg_snprintf(NULL,
  17075. NULL, /* No truncation check for error buffers */
  17076. error->text,
  17077. error->text_buffer_size,
  17078. "%s",
  17079. err_msg);
  17080. }
  17081. free_context(ctx);
  17082. pthread_setspecific(sTlsKey, NULL);
  17083. return NULL;
  17084. }
  17085. #endif
  17086. if (!set_acl_option(ctx)) {
  17087. const char *err_msg = "Failed to setup access control list";
  17088. /* Fatal error - abort start. */
  17089. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17090. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17091. mg_snprintf(NULL,
  17092. NULL, /* No truncation check for error buffers */
  17093. error->text,
  17094. error->text_buffer_size,
  17095. "%s",
  17096. err_msg);
  17097. }
  17098. free_context(ctx);
  17099. pthread_setspecific(sTlsKey, NULL);
  17100. return NULL;
  17101. }
  17102. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17103. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17104. sizeof(pthread_t),
  17105. ctx);
  17106. if (ctx->worker_threadids == NULL) {
  17107. const char *err_msg = "Not enough memory for worker thread ID array";
  17108. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17109. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17110. mg_snprintf(NULL,
  17111. NULL, /* No truncation check for error buffers */
  17112. error->text,
  17113. error->text_buffer_size,
  17114. "%s",
  17115. err_msg);
  17116. }
  17117. free_context(ctx);
  17118. pthread_setspecific(sTlsKey, NULL);
  17119. return NULL;
  17120. }
  17121. ctx->worker_connections =
  17122. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17123. sizeof(struct mg_connection),
  17124. ctx);
  17125. if (ctx->worker_connections == NULL) {
  17126. const char *err_msg =
  17127. "Not enough memory for worker thread connection array";
  17128. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17129. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17130. mg_snprintf(NULL,
  17131. NULL, /* No truncation check for error buffers */
  17132. error->text,
  17133. error->text_buffer_size,
  17134. "%s",
  17135. err_msg);
  17136. }
  17137. free_context(ctx);
  17138. pthread_setspecific(sTlsKey, NULL);
  17139. return NULL;
  17140. }
  17141. #if defined(ALTERNATIVE_QUEUE)
  17142. ctx->client_wait_events =
  17143. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17144. sizeof(ctx->client_wait_events[0]),
  17145. ctx);
  17146. if (ctx->client_wait_events == NULL) {
  17147. const char *err_msg = "Not enough memory for worker event array";
  17148. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17149. mg_free(ctx->worker_threadids);
  17150. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17151. mg_snprintf(NULL,
  17152. NULL, /* No truncation check for error buffers */
  17153. error->text,
  17154. error->text_buffer_size,
  17155. "%s",
  17156. err_msg);
  17157. }
  17158. free_context(ctx);
  17159. pthread_setspecific(sTlsKey, NULL);
  17160. return NULL;
  17161. }
  17162. ctx->client_socks =
  17163. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17164. sizeof(ctx->client_socks[0]),
  17165. ctx);
  17166. if (ctx->client_socks == NULL) {
  17167. const char *err_msg = "Not enough memory for worker socket array";
  17168. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17169. mg_free(ctx->client_wait_events);
  17170. mg_free(ctx->worker_threadids);
  17171. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17172. mg_snprintf(NULL,
  17173. NULL, /* No truncation check for error buffers */
  17174. error->text,
  17175. error->text_buffer_size,
  17176. "%s",
  17177. err_msg);
  17178. }
  17179. free_context(ctx);
  17180. pthread_setspecific(sTlsKey, NULL);
  17181. return NULL;
  17182. }
  17183. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17184. ctx->client_wait_events[i] = event_create();
  17185. if (ctx->client_wait_events[i] == 0) {
  17186. const char *err_msg = "Error creating worker event %i";
  17187. mg_cry_ctx_internal(ctx, err_msg, i);
  17188. while (i > 0) {
  17189. i--;
  17190. event_destroy(ctx->client_wait_events[i]);
  17191. }
  17192. mg_free(ctx->client_socks);
  17193. mg_free(ctx->client_wait_events);
  17194. mg_free(ctx->worker_threadids);
  17195. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17196. mg_snprintf(NULL,
  17197. NULL, /* No truncation check for error buffers */
  17198. error->text,
  17199. error->text_buffer_size,
  17200. err_msg,
  17201. i);
  17202. }
  17203. free_context(ctx);
  17204. pthread_setspecific(sTlsKey, NULL);
  17205. return NULL;
  17206. }
  17207. }
  17208. #endif
  17209. #if defined(USE_TIMERS)
  17210. if (timers_init(ctx) != 0) {
  17211. const char *err_msg = "Error creating timers";
  17212. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17213. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17214. mg_snprintf(NULL,
  17215. NULL, /* No truncation check for error buffers */
  17216. error->text,
  17217. error->text_buffer_size,
  17218. "%s",
  17219. err_msg);
  17220. }
  17221. free_context(ctx);
  17222. pthread_setspecific(sTlsKey, NULL);
  17223. return NULL;
  17224. }
  17225. #endif
  17226. /* Context has been created - init user libraries */
  17227. if (ctx->callbacks.init_context) {
  17228. ctx->callbacks.init_context(ctx);
  17229. }
  17230. /* From now, the context is successfully created.
  17231. * When it is destroyed, the exit callback should be called. */
  17232. ctx->callbacks.exit_context = exit_callback;
  17233. ctx->context_type = CONTEXT_SERVER; /* server context */
  17234. /* Start worker threads */
  17235. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17236. /* worker_thread sets up the other fields */
  17237. ctx->worker_connections[i].phys_ctx = ctx;
  17238. if (mg_start_thread_with_id(worker_thread,
  17239. &ctx->worker_connections[i],
  17240. &ctx->worker_threadids[i])
  17241. != 0) {
  17242. long error_no = (long)ERRNO;
  17243. /* thread was not created */
  17244. if (i > 0) {
  17245. /* If the second, third, ... thread cannot be created, set a
  17246. * warning, but keep running. */
  17247. mg_cry_ctx_internal(ctx,
  17248. "Cannot start worker thread %i: error %ld",
  17249. i + 1,
  17250. error_no);
  17251. /* If the server initialization should stop here, all
  17252. * threads that have already been created must be stopped
  17253. * first, before any free_context(ctx) call.
  17254. */
  17255. } else {
  17256. /* If the first worker thread cannot be created, stop
  17257. * initialization and free the entire server context. */
  17258. mg_cry_ctx_internal(ctx,
  17259. "Cannot create threads: error %ld",
  17260. error_no);
  17261. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17262. mg_snprintf(
  17263. NULL,
  17264. NULL, /* No truncation check for error buffers */
  17265. error->text,
  17266. error->text_buffer_size,
  17267. "Cannot create first worker thread: error %ld",
  17268. error_no);
  17269. }
  17270. free_context(ctx);
  17271. pthread_setspecific(sTlsKey, NULL);
  17272. return NULL;
  17273. }
  17274. break;
  17275. }
  17276. }
  17277. /* Start master (listening) thread */
  17278. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17279. pthread_setspecific(sTlsKey, NULL);
  17280. return ctx;
  17281. }
  17282. struct mg_context *
  17283. mg_start(const struct mg_callbacks *callbacks,
  17284. void *user_data,
  17285. const char **options)
  17286. {
  17287. struct mg_init_data init = {0};
  17288. init.callbacks = callbacks;
  17289. init.user_data = user_data;
  17290. init.configuration_options = options;
  17291. return mg_start2(&init, NULL);
  17292. }
  17293. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17294. /* Add an additional domain to an already running web server. */
  17295. int
  17296. mg_start_domain2(struct mg_context *ctx,
  17297. const char **options,
  17298. struct mg_error_data *error)
  17299. {
  17300. const char *name;
  17301. const char *value;
  17302. const char *default_value;
  17303. struct mg_domain_context *new_dom;
  17304. struct mg_domain_context *dom;
  17305. int idx, i;
  17306. if (error != NULL) {
  17307. error->code = 0;
  17308. if (error->text_buffer_size > 0) {
  17309. *error->text = 0;
  17310. }
  17311. }
  17312. if ((ctx == NULL) || (options == NULL)) {
  17313. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17314. mg_snprintf(NULL,
  17315. NULL, /* No truncation check for error buffers */
  17316. error->text,
  17317. error->text_buffer_size,
  17318. "%s",
  17319. "Invalid parameters");
  17320. }
  17321. return -1;
  17322. }
  17323. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17324. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17325. mg_snprintf(NULL,
  17326. NULL, /* No truncation check for error buffers */
  17327. error->text,
  17328. error->text_buffer_size,
  17329. "%s",
  17330. "Server already stopped");
  17331. }
  17332. return -1;
  17333. }
  17334. new_dom = (struct mg_domain_context *)
  17335. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17336. if (!new_dom) {
  17337. /* Out of memory */
  17338. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17339. mg_snprintf(NULL,
  17340. NULL, /* No truncation check for error buffers */
  17341. error->text,
  17342. error->text_buffer_size,
  17343. "%s",
  17344. "Out or memory");
  17345. }
  17346. return -6;
  17347. }
  17348. /* Store options - TODO: unite duplicate code */
  17349. while (options && (name = *options++) != NULL) {
  17350. if ((idx = get_option_index(name)) == -1) {
  17351. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17352. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17353. mg_snprintf(NULL,
  17354. NULL, /* No truncation check for error buffers */
  17355. error->text,
  17356. error->text_buffer_size,
  17357. "Invalid option: %s",
  17358. name);
  17359. }
  17360. mg_free(new_dom);
  17361. return -2;
  17362. } else if ((value = *options++) == NULL) {
  17363. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17364. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17365. mg_snprintf(NULL,
  17366. NULL, /* No truncation check for error buffers */
  17367. error->text,
  17368. error->text_buffer_size,
  17369. "Invalid option value: %s",
  17370. name);
  17371. }
  17372. mg_free(new_dom);
  17373. return -2;
  17374. }
  17375. if (new_dom->config[idx] != NULL) {
  17376. /* Duplicate option: Later values overwrite earlier ones. */
  17377. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17378. mg_free(new_dom->config[idx]);
  17379. }
  17380. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17381. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17382. }
  17383. /* Authentication domain is mandatory */
  17384. /* TODO: Maybe use a new option hostname? */
  17385. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17386. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17387. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17388. mg_snprintf(NULL,
  17389. NULL, /* No truncation check for error buffers */
  17390. error->text,
  17391. error->text_buffer_size,
  17392. "Mandatory option %s missing",
  17393. config_options[AUTHENTICATION_DOMAIN].name);
  17394. }
  17395. mg_free(new_dom);
  17396. return -4;
  17397. }
  17398. /* Set default value if needed. Take the config value from
  17399. * ctx as a default value. */
  17400. for (i = 0; config_options[i].name != NULL; i++) {
  17401. default_value = ctx->dd.config[i];
  17402. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17403. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17404. }
  17405. }
  17406. new_dom->handlers = NULL;
  17407. new_dom->next = NULL;
  17408. new_dom->nonce_count = 0;
  17409. new_dom->auth_nonce_mask =
  17410. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17411. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17412. new_dom->shared_lua_websockets = NULL;
  17413. #endif
  17414. #if !defined(NO_SSL)
  17415. if (!init_ssl_ctx(ctx, new_dom)) {
  17416. /* Init SSL failed */
  17417. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17418. mg_snprintf(NULL,
  17419. NULL, /* No truncation check for error buffers */
  17420. error->text,
  17421. error->text_buffer_size,
  17422. "%s",
  17423. "Initializing SSL context failed");
  17424. }
  17425. mg_free(new_dom);
  17426. return -3;
  17427. }
  17428. #endif
  17429. /* Add element to linked list. */
  17430. mg_lock_context(ctx);
  17431. idx = 0;
  17432. dom = &(ctx->dd);
  17433. for (;;) {
  17434. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17435. dom->config[AUTHENTICATION_DOMAIN])) {
  17436. /* Domain collision */
  17437. mg_cry_ctx_internal(ctx,
  17438. "domain %s already in use",
  17439. new_dom->config[AUTHENTICATION_DOMAIN]);
  17440. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17441. mg_snprintf(NULL,
  17442. NULL, /* No truncation check for error buffers */
  17443. error->text,
  17444. error->text_buffer_size,
  17445. "Domain %s specified by %s is already in use",
  17446. new_dom->config[AUTHENTICATION_DOMAIN],
  17447. config_options[AUTHENTICATION_DOMAIN].name);
  17448. }
  17449. mg_free(new_dom);
  17450. mg_unlock_context(ctx);
  17451. return -5;
  17452. }
  17453. /* Count number of domains */
  17454. idx++;
  17455. if (dom->next == NULL) {
  17456. dom->next = new_dom;
  17457. break;
  17458. }
  17459. dom = dom->next;
  17460. }
  17461. mg_unlock_context(ctx);
  17462. /* Return domain number */
  17463. return idx;
  17464. }
  17465. int
  17466. mg_start_domain(struct mg_context *ctx, const char **options)
  17467. {
  17468. return mg_start_domain2(ctx, options, NULL);
  17469. }
  17470. #endif
  17471. /* Feature check API function */
  17472. unsigned
  17473. mg_check_feature(unsigned feature)
  17474. {
  17475. static const unsigned feature_set = 0
  17476. /* Set bits for available features according to API documentation.
  17477. * This bit mask is created at compile time, according to the active
  17478. * preprocessor defines. It is a single const value at runtime. */
  17479. #if !defined(NO_FILES)
  17480. | MG_FEATURES_FILES
  17481. #endif
  17482. #if !defined(NO_SSL)
  17483. | MG_FEATURES_SSL
  17484. #endif
  17485. #if !defined(NO_CGI)
  17486. | MG_FEATURES_CGI
  17487. #endif
  17488. #if defined(USE_IPV6)
  17489. | MG_FEATURES_IPV6
  17490. #endif
  17491. #if defined(USE_WEBSOCKET)
  17492. | MG_FEATURES_WEBSOCKET
  17493. #endif
  17494. #if defined(USE_LUA)
  17495. | MG_FEATURES_LUA
  17496. #endif
  17497. #if defined(USE_DUKTAPE)
  17498. | MG_FEATURES_SSJS
  17499. #endif
  17500. #if !defined(NO_CACHING)
  17501. | MG_FEATURES_CACHE
  17502. #endif
  17503. #if defined(USE_SERVER_STATS)
  17504. | MG_FEATURES_STATS
  17505. #endif
  17506. #if defined(USE_ZLIB)
  17507. | MG_FEATURES_COMPRESSION
  17508. #endif
  17509. /* Set some extra bits not defined in the API documentation.
  17510. * These bits may change without further notice. */
  17511. #if defined(MG_LEGACY_INTERFACE)
  17512. | 0x00008000u
  17513. #endif
  17514. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17515. | 0x00004000u
  17516. #endif
  17517. #if defined(MEMORY_DEBUGGING)
  17518. | 0x00001000u
  17519. #endif
  17520. #if defined(USE_TIMERS)
  17521. | 0x00020000u
  17522. #endif
  17523. #if !defined(NO_NONCE_CHECK)
  17524. | 0x00040000u
  17525. #endif
  17526. #if !defined(NO_POPEN)
  17527. | 0x00080000u
  17528. #endif
  17529. ;
  17530. return (feature & feature_set);
  17531. }
  17532. static size_t
  17533. mg_str_append(char **dst, char *end, const char *src)
  17534. {
  17535. size_t len = strlen(src);
  17536. if (*dst != end) {
  17537. /* Append src if enough space, or close dst. */
  17538. if ((size_t)(end - *dst) > len) {
  17539. strcpy(*dst, src);
  17540. *dst += len;
  17541. } else {
  17542. *dst = end;
  17543. }
  17544. }
  17545. return len;
  17546. }
  17547. /* Get system information. It can be printed or stored by the caller.
  17548. * Return the size of available information. */
  17549. int
  17550. mg_get_system_info(char *buffer, int buflen)
  17551. {
  17552. char *end, *append_eoobj = NULL, block[256];
  17553. size_t system_info_length = 0;
  17554. #if defined(_WIN32)
  17555. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17556. #else
  17557. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17558. #endif
  17559. if ((buffer == NULL) || (buflen < 1)) {
  17560. buflen = 0;
  17561. end = buffer;
  17562. } else {
  17563. *buffer = 0;
  17564. end = buffer + buflen;
  17565. }
  17566. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17567. /* has enough space to append eoobj */
  17568. append_eoobj = buffer;
  17569. if (end) {
  17570. end -= sizeof(eoobj) - 1;
  17571. }
  17572. }
  17573. system_info_length += mg_str_append(&buffer, end, "{");
  17574. /* Server version */
  17575. {
  17576. const char *version = mg_version();
  17577. mg_snprintf(NULL,
  17578. NULL,
  17579. block,
  17580. sizeof(block),
  17581. "%s\"version\" : \"%s\"",
  17582. eol,
  17583. version);
  17584. system_info_length += mg_str_append(&buffer, end, block);
  17585. }
  17586. /* System info */
  17587. {
  17588. #if defined(_WIN32)
  17589. DWORD dwVersion = 0;
  17590. DWORD dwMajorVersion = 0;
  17591. DWORD dwMinorVersion = 0;
  17592. SYSTEM_INFO si;
  17593. GetSystemInfo(&si);
  17594. #if defined(_MSC_VER)
  17595. #pragma warning(push)
  17596. /* GetVersion was declared deprecated */
  17597. #pragma warning(disable : 4996)
  17598. #endif
  17599. dwVersion = GetVersion();
  17600. #if defined(_MSC_VER)
  17601. #pragma warning(pop)
  17602. #endif
  17603. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17604. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17605. mg_snprintf(NULL,
  17606. NULL,
  17607. block,
  17608. sizeof(block),
  17609. ",%s\"os\" : \"Windows %u.%u\"",
  17610. eol,
  17611. (unsigned)dwMajorVersion,
  17612. (unsigned)dwMinorVersion);
  17613. system_info_length += mg_str_append(&buffer, end, block);
  17614. mg_snprintf(NULL,
  17615. NULL,
  17616. block,
  17617. sizeof(block),
  17618. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17619. eol,
  17620. (unsigned)si.wProcessorArchitecture,
  17621. (unsigned)si.dwNumberOfProcessors,
  17622. (unsigned)si.dwActiveProcessorMask);
  17623. system_info_length += mg_str_append(&buffer, end, block);
  17624. #elif defined(__ZEPHYR__)
  17625. mg_snprintf(NULL,
  17626. NULL,
  17627. block,
  17628. sizeof(block),
  17629. ",%s\"os\" : \"%s %s\"",
  17630. eol,
  17631. "Zephyr OS",
  17632. ZEPHYR_VERSION);
  17633. system_info_length += mg_str_append(&buffer, end, block);
  17634. #else
  17635. struct utsname name;
  17636. memset(&name, 0, sizeof(name));
  17637. uname(&name);
  17638. mg_snprintf(NULL,
  17639. NULL,
  17640. block,
  17641. sizeof(block),
  17642. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17643. eol,
  17644. name.sysname,
  17645. name.version,
  17646. name.release,
  17647. name.machine);
  17648. system_info_length += mg_str_append(&buffer, end, block);
  17649. #endif
  17650. }
  17651. /* Features */
  17652. {
  17653. mg_snprintf(NULL,
  17654. NULL,
  17655. block,
  17656. sizeof(block),
  17657. ",%s\"features\" : %lu"
  17658. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17659. eol,
  17660. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17661. eol,
  17662. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17663. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17664. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17665. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17666. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17667. : "",
  17668. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17669. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17670. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17671. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17672. system_info_length += mg_str_append(&buffer, end, block);
  17673. #if defined(USE_LUA)
  17674. mg_snprintf(NULL,
  17675. NULL,
  17676. block,
  17677. sizeof(block),
  17678. ",%s\"lua_version\" : \"%u (%s)\"",
  17679. eol,
  17680. (unsigned)LUA_VERSION_NUM,
  17681. LUA_RELEASE);
  17682. system_info_length += mg_str_append(&buffer, end, block);
  17683. #endif
  17684. #if defined(USE_DUKTAPE)
  17685. mg_snprintf(NULL,
  17686. NULL,
  17687. block,
  17688. sizeof(block),
  17689. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17690. eol,
  17691. (unsigned)DUK_VERSION / 10000,
  17692. ((unsigned)DUK_VERSION / 100) % 100,
  17693. (unsigned)DUK_VERSION % 100);
  17694. system_info_length += mg_str_append(&buffer, end, block);
  17695. #endif
  17696. }
  17697. /* Build date */
  17698. {
  17699. #if defined(GCC_DIAGNOSTIC)
  17700. #if GCC_VERSION >= 40900
  17701. #pragma GCC diagnostic push
  17702. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17703. #pragma GCC diagnostic ignored "-Wdate-time"
  17704. #endif
  17705. #endif
  17706. mg_snprintf(NULL,
  17707. NULL,
  17708. block,
  17709. sizeof(block),
  17710. ",%s\"build\" : \"%s\"",
  17711. eol,
  17712. __DATE__);
  17713. #if defined(GCC_DIAGNOSTIC)
  17714. #if GCC_VERSION >= 40900
  17715. #pragma GCC diagnostic pop
  17716. #endif
  17717. #endif
  17718. system_info_length += mg_str_append(&buffer, end, block);
  17719. }
  17720. /* Compiler information */
  17721. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17722. {
  17723. #if defined(_MSC_VER)
  17724. mg_snprintf(NULL,
  17725. NULL,
  17726. block,
  17727. sizeof(block),
  17728. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17729. eol,
  17730. (unsigned)_MSC_VER,
  17731. (unsigned)_MSC_FULL_VER);
  17732. system_info_length += mg_str_append(&buffer, end, block);
  17733. #elif defined(__MINGW64__)
  17734. mg_snprintf(NULL,
  17735. NULL,
  17736. block,
  17737. sizeof(block),
  17738. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17739. eol,
  17740. (unsigned)__MINGW64_VERSION_MAJOR,
  17741. (unsigned)__MINGW64_VERSION_MINOR);
  17742. system_info_length += mg_str_append(&buffer, end, block);
  17743. mg_snprintf(NULL,
  17744. NULL,
  17745. block,
  17746. sizeof(block),
  17747. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17748. eol,
  17749. (unsigned)__MINGW32_MAJOR_VERSION,
  17750. (unsigned)__MINGW32_MINOR_VERSION);
  17751. system_info_length += mg_str_append(&buffer, end, block);
  17752. #elif defined(__MINGW32__)
  17753. mg_snprintf(NULL,
  17754. NULL,
  17755. block,
  17756. sizeof(block),
  17757. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17758. eol,
  17759. (unsigned)__MINGW32_MAJOR_VERSION,
  17760. (unsigned)__MINGW32_MINOR_VERSION);
  17761. system_info_length += mg_str_append(&buffer, end, block);
  17762. #elif defined(__clang__)
  17763. mg_snprintf(NULL,
  17764. NULL,
  17765. block,
  17766. sizeof(block),
  17767. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17768. eol,
  17769. __clang_major__,
  17770. __clang_minor__,
  17771. __clang_patchlevel__,
  17772. __clang_version__);
  17773. system_info_length += mg_str_append(&buffer, end, block);
  17774. #elif defined(__GNUC__)
  17775. mg_snprintf(NULL,
  17776. NULL,
  17777. block,
  17778. sizeof(block),
  17779. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17780. eol,
  17781. (unsigned)__GNUC__,
  17782. (unsigned)__GNUC_MINOR__,
  17783. (unsigned)__GNUC_PATCHLEVEL__);
  17784. system_info_length += mg_str_append(&buffer, end, block);
  17785. #elif defined(__INTEL_COMPILER)
  17786. mg_snprintf(NULL,
  17787. NULL,
  17788. block,
  17789. sizeof(block),
  17790. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17791. eol,
  17792. (unsigned)__INTEL_COMPILER);
  17793. system_info_length += mg_str_append(&buffer, end, block);
  17794. #elif defined(__BORLANDC__)
  17795. mg_snprintf(NULL,
  17796. NULL,
  17797. block,
  17798. sizeof(block),
  17799. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17800. eol,
  17801. (unsigned)__BORLANDC__);
  17802. system_info_length += mg_str_append(&buffer, end, block);
  17803. #elif defined(__SUNPRO_C)
  17804. mg_snprintf(NULL,
  17805. NULL,
  17806. block,
  17807. sizeof(block),
  17808. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17809. eol,
  17810. (unsigned)__SUNPRO_C);
  17811. system_info_length += mg_str_append(&buffer, end, block);
  17812. #else
  17813. mg_snprintf(NULL,
  17814. NULL,
  17815. block,
  17816. sizeof(block),
  17817. ",%s\"compiler\" : \"other\"",
  17818. eol);
  17819. system_info_length += mg_str_append(&buffer, end, block);
  17820. #endif
  17821. }
  17822. /* Determine 32/64 bit data mode.
  17823. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17824. {
  17825. mg_snprintf(NULL,
  17826. NULL,
  17827. block,
  17828. sizeof(block),
  17829. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17830. "char:%u/%u, "
  17831. "ptr:%u, size:%u, time:%u\"",
  17832. eol,
  17833. (unsigned)sizeof(short),
  17834. (unsigned)sizeof(int),
  17835. (unsigned)sizeof(long),
  17836. (unsigned)sizeof(long long),
  17837. (unsigned)sizeof(float),
  17838. (unsigned)sizeof(double),
  17839. (unsigned)sizeof(long double),
  17840. (unsigned)sizeof(char),
  17841. (unsigned)sizeof(wchar_t),
  17842. (unsigned)sizeof(void *),
  17843. (unsigned)sizeof(size_t),
  17844. (unsigned)sizeof(time_t));
  17845. system_info_length += mg_str_append(&buffer, end, block);
  17846. }
  17847. /* Terminate string */
  17848. if (append_eoobj) {
  17849. strcat(append_eoobj, eoobj);
  17850. }
  17851. system_info_length += sizeof(eoobj) - 1;
  17852. return (int)system_info_length;
  17853. }
  17854. /* Get context information. It can be printed or stored by the caller.
  17855. * Return the size of available information. */
  17856. int
  17857. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17858. {
  17859. #if defined(USE_SERVER_STATS)
  17860. char *end, *append_eoobj = NULL, block[256];
  17861. size_t context_info_length = 0;
  17862. #if defined(_WIN32)
  17863. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17864. #else
  17865. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17866. #endif
  17867. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17868. if ((buffer == NULL) || (buflen < 1)) {
  17869. buflen = 0;
  17870. end = buffer;
  17871. } else {
  17872. *buffer = 0;
  17873. end = buffer + buflen;
  17874. }
  17875. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17876. /* has enough space to append eoobj */
  17877. append_eoobj = buffer;
  17878. end -= sizeof(eoobj) - 1;
  17879. }
  17880. context_info_length += mg_str_append(&buffer, end, "{");
  17881. if (ms) { /* <-- should be always true */
  17882. /* Memory information */
  17883. mg_snprintf(NULL,
  17884. NULL,
  17885. block,
  17886. sizeof(block),
  17887. "%s\"memory\" : {%s"
  17888. "\"blocks\" : %i,%s"
  17889. "\"used\" : %" INT64_FMT ",%s"
  17890. "\"maxUsed\" : %" INT64_FMT "%s"
  17891. "}",
  17892. eol,
  17893. eol,
  17894. ms->blockCount,
  17895. eol,
  17896. ms->totalMemUsed,
  17897. eol,
  17898. ms->maxMemUsed,
  17899. eol);
  17900. context_info_length += mg_str_append(&buffer, end, block);
  17901. }
  17902. if (ctx) {
  17903. /* Declare all variables at begin of the block, to comply
  17904. * with old C standards. */
  17905. char start_time_str[64] = {0};
  17906. char now_str[64] = {0};
  17907. time_t start_time = ctx->start_time;
  17908. time_t now = time(NULL);
  17909. /* Connections information */
  17910. mg_snprintf(NULL,
  17911. NULL,
  17912. block,
  17913. sizeof(block),
  17914. ",%s\"connections\" : {%s"
  17915. "\"active\" : %i,%s"
  17916. "\"maxActive\" : %i,%s"
  17917. "\"total\" : %" INT64_FMT "%s"
  17918. "}",
  17919. eol,
  17920. eol,
  17921. ctx->active_connections,
  17922. eol,
  17923. ctx->max_active_connections,
  17924. eol,
  17925. ctx->total_connections,
  17926. eol);
  17927. context_info_length += mg_str_append(&buffer, end, block);
  17928. /* Queue information */
  17929. #if !defined(ALTERNATIVE_QUEUE)
  17930. mg_snprintf(NULL,
  17931. NULL,
  17932. block,
  17933. sizeof(block),
  17934. ",%s\"queue\" : {%s"
  17935. "\"length\" : %i,%s"
  17936. "\"filled\" : %i,%s"
  17937. "\"maxFilled\" : %i,%s"
  17938. "\"full\" : %s%s"
  17939. "}",
  17940. eol,
  17941. eol,
  17942. ctx->sq_size,
  17943. eol,
  17944. ctx->sq_head - ctx->sq_tail,
  17945. eol,
  17946. ctx->sq_max_fill,
  17947. eol,
  17948. (ctx->sq_blocked ? "true" : "false"),
  17949. eol);
  17950. context_info_length += mg_str_append(&buffer, end, block);
  17951. #endif
  17952. /* Requests information */
  17953. mg_snprintf(NULL,
  17954. NULL,
  17955. block,
  17956. sizeof(block),
  17957. ",%s\"requests\" : {%s"
  17958. "\"total\" : %" INT64_FMT "%s"
  17959. "}",
  17960. eol,
  17961. eol,
  17962. ctx->total_requests,
  17963. eol);
  17964. context_info_length += mg_str_append(&buffer, end, block);
  17965. /* Data information */
  17966. mg_snprintf(NULL,
  17967. NULL,
  17968. block,
  17969. sizeof(block),
  17970. ",%s\"data\" : {%s"
  17971. "\"read\" : %" INT64_FMT ",%s"
  17972. "\"written\" : %" INT64_FMT "%s"
  17973. "}",
  17974. eol,
  17975. eol,
  17976. ctx->total_data_read,
  17977. eol,
  17978. ctx->total_data_written,
  17979. eol);
  17980. context_info_length += mg_str_append(&buffer, end, block);
  17981. /* Execution time information */
  17982. gmt_time_string(start_time_str,
  17983. sizeof(start_time_str) - 1,
  17984. &start_time);
  17985. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17986. mg_snprintf(NULL,
  17987. NULL,
  17988. block,
  17989. sizeof(block),
  17990. ",%s\"time\" : {%s"
  17991. "\"uptime\" : %.0f,%s"
  17992. "\"start\" : \"%s\",%s"
  17993. "\"now\" : \"%s\"%s"
  17994. "}",
  17995. eol,
  17996. eol,
  17997. difftime(now, start_time),
  17998. eol,
  17999. start_time_str,
  18000. eol,
  18001. now_str,
  18002. eol);
  18003. context_info_length += mg_str_append(&buffer, end, block);
  18004. }
  18005. /* Terminate string */
  18006. if (append_eoobj) {
  18007. strcat(append_eoobj, eoobj);
  18008. }
  18009. context_info_length += sizeof(eoobj) - 1;
  18010. return (int)context_info_length;
  18011. #else
  18012. (void)ctx;
  18013. if ((buffer != NULL) && (buflen > 0)) {
  18014. *buffer = 0;
  18015. }
  18016. return 0;
  18017. #endif
  18018. }
  18019. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18020. /* Get connection information. It can be printed or stored by the caller.
  18021. * Return the size of available information. */
  18022. int
  18023. mg_get_connection_info(const struct mg_context *ctx,
  18024. int idx,
  18025. char *buffer,
  18026. int buflen)
  18027. {
  18028. const struct mg_connection *conn;
  18029. const struct mg_request_info *ri;
  18030. char *end, *append_eoobj = NULL, block[256];
  18031. size_t connection_info_length = 0;
  18032. int state = 0;
  18033. const char *state_str = "unknown";
  18034. #if defined(_WIN32)
  18035. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18036. #else
  18037. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18038. #endif
  18039. if ((buffer == NULL) || (buflen < 1)) {
  18040. buflen = 0;
  18041. end = buffer;
  18042. } else {
  18043. *buffer = 0;
  18044. end = buffer + buflen;
  18045. }
  18046. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18047. /* has enough space to append eoobj */
  18048. append_eoobj = buffer;
  18049. end -= sizeof(eoobj) - 1;
  18050. }
  18051. if ((ctx == NULL) || (idx < 0)) {
  18052. /* Parameter error */
  18053. return 0;
  18054. }
  18055. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18056. /* Out of range */
  18057. return 0;
  18058. }
  18059. /* Take connection [idx]. This connection is not locked in
  18060. * any way, so some other thread might use it. */
  18061. conn = (ctx->worker_connections) + idx;
  18062. /* Initialize output string */
  18063. connection_info_length += mg_str_append(&buffer, end, "{");
  18064. /* Init variables */
  18065. ri = &(conn->request_info);
  18066. #if defined(USE_SERVER_STATS)
  18067. state = conn->conn_state;
  18068. /* State as string */
  18069. switch (state) {
  18070. case 0:
  18071. state_str = "undefined";
  18072. break;
  18073. case 1:
  18074. state_str = "not used";
  18075. break;
  18076. case 2:
  18077. state_str = "init";
  18078. break;
  18079. case 3:
  18080. state_str = "ready";
  18081. break;
  18082. case 4:
  18083. state_str = "processing";
  18084. break;
  18085. case 5:
  18086. state_str = "processed";
  18087. break;
  18088. case 6:
  18089. state_str = "to close";
  18090. break;
  18091. case 7:
  18092. state_str = "closing";
  18093. break;
  18094. case 8:
  18095. state_str = "closed";
  18096. break;
  18097. case 9:
  18098. state_str = "done";
  18099. break;
  18100. }
  18101. #endif
  18102. /* Connection info */
  18103. if ((state >= 3) && (state < 9)) {
  18104. mg_snprintf(NULL,
  18105. NULL,
  18106. block,
  18107. sizeof(block),
  18108. "%s\"connection\" : {%s"
  18109. "\"remote\" : {%s"
  18110. "\"protocol\" : \"%s\",%s"
  18111. "\"addr\" : \"%s\",%s"
  18112. "\"port\" : %u%s"
  18113. "},%s"
  18114. "\"handled_requests\" : %u%s"
  18115. "}",
  18116. eol,
  18117. eol,
  18118. eol,
  18119. get_proto_name(conn),
  18120. eol,
  18121. ri->remote_addr,
  18122. eol,
  18123. ri->remote_port,
  18124. eol,
  18125. eol,
  18126. conn->handled_requests,
  18127. eol);
  18128. connection_info_length += mg_str_append(&buffer, end, block);
  18129. }
  18130. /* Request info */
  18131. if ((state >= 4) && (state < 6)) {
  18132. mg_snprintf(NULL,
  18133. NULL,
  18134. block,
  18135. sizeof(block),
  18136. "%s%s\"request_info\" : {%s"
  18137. "\"method\" : \"%s\",%s"
  18138. "\"uri\" : \"%s\",%s"
  18139. "\"query\" : %s%s%s%s"
  18140. "}",
  18141. (connection_info_length > 1 ? "," : ""),
  18142. eol,
  18143. eol,
  18144. ri->request_method,
  18145. eol,
  18146. ri->request_uri,
  18147. eol,
  18148. ri->query_string ? "\"" : "",
  18149. ri->query_string ? ri->query_string : "null",
  18150. ri->query_string ? "\"" : "",
  18151. eol);
  18152. connection_info_length += mg_str_append(&buffer, end, block);
  18153. }
  18154. /* Execution time information */
  18155. if ((state >= 2) && (state < 9)) {
  18156. char start_time_str[64] = {0};
  18157. char close_time_str[64] = {0};
  18158. time_t start_time = conn->conn_birth_time;
  18159. time_t close_time = 0;
  18160. double time_diff;
  18161. gmt_time_string(start_time_str,
  18162. sizeof(start_time_str) - 1,
  18163. &start_time);
  18164. #if defined(USE_SERVER_STATS)
  18165. close_time = conn->conn_close_time;
  18166. #endif
  18167. if (close_time != 0) {
  18168. time_diff = difftime(close_time, start_time);
  18169. gmt_time_string(close_time_str,
  18170. sizeof(close_time_str) - 1,
  18171. &close_time);
  18172. } else {
  18173. time_t now = time(NULL);
  18174. time_diff = difftime(now, start_time);
  18175. close_time_str[0] = 0; /* or use "now" ? */
  18176. }
  18177. mg_snprintf(NULL,
  18178. NULL,
  18179. block,
  18180. sizeof(block),
  18181. "%s%s\"time\" : {%s"
  18182. "\"uptime\" : %.0f,%s"
  18183. "\"start\" : \"%s\",%s"
  18184. "\"closed\" : \"%s\"%s"
  18185. "}",
  18186. (connection_info_length > 1 ? "," : ""),
  18187. eol,
  18188. eol,
  18189. time_diff,
  18190. eol,
  18191. start_time_str,
  18192. eol,
  18193. close_time_str,
  18194. eol);
  18195. connection_info_length += mg_str_append(&buffer, end, block);
  18196. }
  18197. /* Remote user name */
  18198. if ((ri->remote_user) && (state < 9)) {
  18199. mg_snprintf(NULL,
  18200. NULL,
  18201. block,
  18202. sizeof(block),
  18203. "%s%s\"user\" : {%s"
  18204. "\"name\" : \"%s\",%s"
  18205. "}",
  18206. (connection_info_length > 1 ? "," : ""),
  18207. eol,
  18208. eol,
  18209. ri->remote_user,
  18210. eol);
  18211. connection_info_length += mg_str_append(&buffer, end, block);
  18212. }
  18213. /* Data block */
  18214. if (state >= 3) {
  18215. mg_snprintf(NULL,
  18216. NULL,
  18217. block,
  18218. sizeof(block),
  18219. "%s%s\"data\" : {%s"
  18220. "\"read\" : %" INT64_FMT ",%s"
  18221. "\"written\" : %" INT64_FMT "%s"
  18222. "}",
  18223. (connection_info_length > 1 ? "," : ""),
  18224. eol,
  18225. eol,
  18226. conn->consumed_content,
  18227. eol,
  18228. conn->num_bytes_sent,
  18229. eol);
  18230. connection_info_length += mg_str_append(&buffer, end, block);
  18231. }
  18232. /* State */
  18233. mg_snprintf(NULL,
  18234. NULL,
  18235. block,
  18236. sizeof(block),
  18237. "%s%s\"state\" : \"%s\"",
  18238. (connection_info_length > 1 ? "," : ""),
  18239. eol,
  18240. state_str);
  18241. connection_info_length += mg_str_append(&buffer, end, block);
  18242. /* Terminate string */
  18243. if (append_eoobj) {
  18244. strcat(append_eoobj, eoobj);
  18245. }
  18246. connection_info_length += sizeof(eoobj) - 1;
  18247. return (int)connection_info_length;
  18248. }
  18249. #endif
  18250. /* Initialize this library. This function does not need to be thread safe.
  18251. */
  18252. unsigned
  18253. mg_init_library(unsigned features)
  18254. {
  18255. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18256. unsigned features_inited = features_to_init;
  18257. if (mg_init_library_called <= 0) {
  18258. /* Not initialized yet */
  18259. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18260. return 0;
  18261. }
  18262. }
  18263. mg_global_lock();
  18264. if (mg_init_library_called <= 0) {
  18265. #if defined(_WIN32)
  18266. int file_mutex_init = 1;
  18267. int wsa = 1;
  18268. #else
  18269. int mutexattr_init = 1;
  18270. #endif
  18271. int failed = 1;
  18272. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18273. if (key_create == 0) {
  18274. #if defined(_WIN32)
  18275. file_mutex_init =
  18276. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18277. if (file_mutex_init == 0) {
  18278. /* Start WinSock */
  18279. WSADATA data;
  18280. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18281. }
  18282. #else
  18283. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18284. if (mutexattr_init == 0) {
  18285. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18286. PTHREAD_MUTEX_RECURSIVE);
  18287. }
  18288. #endif
  18289. }
  18290. if (failed) {
  18291. #if defined(_WIN32)
  18292. if (wsa == 0) {
  18293. (void)WSACleanup();
  18294. }
  18295. if (file_mutex_init == 0) {
  18296. (void)pthread_mutex_destroy(&global_log_file_lock);
  18297. }
  18298. #else
  18299. if (mutexattr_init == 0) {
  18300. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18301. }
  18302. #endif
  18303. if (key_create == 0) {
  18304. (void)pthread_key_delete(sTlsKey);
  18305. }
  18306. mg_global_unlock();
  18307. (void)pthread_mutex_destroy(&global_lock_mutex);
  18308. return 0;
  18309. }
  18310. #if defined(USE_LUA)
  18311. lua_init_optional_libraries();
  18312. #endif
  18313. }
  18314. mg_global_unlock();
  18315. #if !defined(NO_SSL)
  18316. if (features_to_init & MG_FEATURES_SSL) {
  18317. if (!mg_ssl_initialized) {
  18318. char ebuf[128];
  18319. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18320. mg_ssl_initialized = 1;
  18321. } else {
  18322. (void)ebuf;
  18323. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18324. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18325. }
  18326. } else {
  18327. /* ssl already initialized */
  18328. }
  18329. }
  18330. #endif
  18331. mg_global_lock();
  18332. if (mg_init_library_called <= 0) {
  18333. mg_init_library_called = 1;
  18334. } else {
  18335. mg_init_library_called++;
  18336. }
  18337. mg_global_unlock();
  18338. return features_inited;
  18339. }
  18340. /* Un-initialize this library. */
  18341. unsigned
  18342. mg_exit_library(void)
  18343. {
  18344. if (mg_init_library_called <= 0) {
  18345. return 0;
  18346. }
  18347. mg_global_lock();
  18348. mg_init_library_called--;
  18349. if (mg_init_library_called == 0) {
  18350. #if !defined(NO_SSL)
  18351. if (mg_ssl_initialized) {
  18352. uninitialize_ssl();
  18353. mg_ssl_initialized = 0;
  18354. }
  18355. #endif
  18356. #if defined(_WIN32)
  18357. (void)WSACleanup();
  18358. (void)pthread_mutex_destroy(&global_log_file_lock);
  18359. #else
  18360. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18361. #endif
  18362. (void)pthread_key_delete(sTlsKey);
  18363. #if defined(USE_LUA)
  18364. lua_exit_optional_libraries();
  18365. #endif
  18366. mg_global_unlock();
  18367. (void)pthread_mutex_destroy(&global_lock_mutex);
  18368. return 1;
  18369. }
  18370. mg_global_unlock();
  18371. return 1;
  18372. }
  18373. /* End of civetweb.c */