civetweb.c 567 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142
  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. const char *host = client_options->host;
  15659. int i;
  15660. if (origin != NULL) {
  15661. handshake_req = "GET %s HTTP/1.1\r\n"
  15662. "Host: %s\r\n"
  15663. "Upgrade: websocket\r\n"
  15664. "Connection: Upgrade\r\n"
  15665. "Sec-WebSocket-Key: %s\r\n"
  15666. "Sec-WebSocket-Version: 13\r\n"
  15667. "Origin: %s\r\n"
  15668. "\r\n";
  15669. } else {
  15670. handshake_req = "GET %s HTTP/1.1\r\n"
  15671. "Host: %s\r\n"
  15672. "Upgrade: websocket\r\n"
  15673. "Connection: Upgrade\r\n"
  15674. "Sec-WebSocket-Key: %s\r\n"
  15675. "Sec-WebSocket-Version: 13\r\n"
  15676. "\r\n";
  15677. }
  15678. #if defined(__clang__)
  15679. #pragma clang diagnostic push
  15680. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15681. #endif
  15682. /* Establish the client connection and request upgrade */
  15683. conn =
  15684. mg_connect_client_impl(client_options, use_ssl, error_buffer, error_buffer_size);
  15685. if (conn == NULL) {
  15686. /* error_buffer already filled */
  15687. return NULL;
  15688. }
  15689. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15690. if (i <= 0) {
  15691. mg_snprintf(conn,
  15692. NULL, /* No truncation check for ebuf */
  15693. error_buffer,
  15694. error_buffer_size,
  15695. "%s",
  15696. "Error sending request");
  15697. mg_close_connection(conn);
  15698. return NULL;
  15699. }
  15700. conn->data_len = 0;
  15701. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15702. mg_close_connection(conn);
  15703. return NULL;
  15704. }
  15705. conn->request_info.local_uri = conn->request_info.request_uri;
  15706. #if defined(__clang__)
  15707. #pragma clang diagnostic pop
  15708. #endif
  15709. /* Connection object will be null if something goes wrong */
  15710. if (conn == NULL) {
  15711. if (!*error_buffer) {
  15712. /* There should be already an error message */
  15713. mg_snprintf(conn,
  15714. NULL, /* No truncation check for ebuf */
  15715. error_buffer,
  15716. error_buffer_size,
  15717. "Unexpected error");
  15718. }
  15719. return NULL;
  15720. }
  15721. if (conn->response_info.status_code != 101) {
  15722. /* We sent an "upgrade" request. For a correct websocket
  15723. * protocol handshake, we expect a "101 Continue" response.
  15724. * Otherwise it is a protocol violation. Maybe the HTTP
  15725. * Server does not know websockets. */
  15726. if (!*error_buffer) {
  15727. /* set an error, if not yet set */
  15728. mg_snprintf(conn,
  15729. NULL, /* No truncation check for ebuf */
  15730. error_buffer,
  15731. error_buffer_size,
  15732. "Unexpected server reply");
  15733. }
  15734. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15735. mg_close_connection(conn);
  15736. return NULL;
  15737. }
  15738. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15739. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15740. if (!thread_data) {
  15741. DEBUG_TRACE("%s\r\n", "Out of memory");
  15742. mg_close_connection(conn);
  15743. return NULL;
  15744. }
  15745. thread_data->conn = conn;
  15746. thread_data->data_handler = data_func;
  15747. thread_data->close_handler = close_func;
  15748. thread_data->callback_data = user_data;
  15749. conn->phys_ctx->worker_threadids =
  15750. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15751. if (!conn->phys_ctx->worker_threadids) {
  15752. DEBUG_TRACE("%s\r\n", "Out of memory");
  15753. mg_free(thread_data);
  15754. mg_close_connection(conn);
  15755. return NULL;
  15756. }
  15757. /* Now upgrade to ws/wss client context */
  15758. conn->phys_ctx->user_data = user_data;
  15759. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15760. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15761. /* Start a thread to read the websocket client connection
  15762. * This thread will automatically stop when mg_disconnect is
  15763. * called on the client connection */
  15764. if (mg_start_thread_with_id(websocket_client_thread,
  15765. thread_data,
  15766. conn->phys_ctx->worker_threadids)
  15767. != 0) {
  15768. conn->phys_ctx->cfg_worker_threads = 0;
  15769. mg_free(thread_data);
  15770. mg_close_connection(conn);
  15771. conn = NULL;
  15772. DEBUG_TRACE("%s",
  15773. "Websocket client connect thread could not be started\r\n");
  15774. }
  15775. #else
  15776. /* Appease "unused parameter" warnings */
  15777. (void)client_options;
  15778. (void)use_ssl;
  15779. (void)error_buffer;
  15780. (void)error_buffer_size;
  15781. (void)path;
  15782. (void)origin;
  15783. (void)user_data;
  15784. (void)data_func;
  15785. (void)close_func;
  15786. #endif
  15787. return conn;
  15788. }
  15789. struct mg_connection *
  15790. mg_connect_websocket_client(const char *host,
  15791. int port,
  15792. int use_ssl,
  15793. char *error_buffer,
  15794. size_t error_buffer_size,
  15795. const char *path,
  15796. const char *origin,
  15797. mg_websocket_data_handler data_func,
  15798. mg_websocket_close_handler close_func,
  15799. void *user_data)
  15800. {
  15801. struct mg_client_options client_options;
  15802. memset(&client_options, 0, sizeof(client_options));
  15803. client_options.host = host;
  15804. client_options.port = port;
  15805. return mg_connect_websocket_client_impl(&client_options,
  15806. use_ssl,
  15807. error_buffer,
  15808. error_buffer_size,
  15809. path,
  15810. origin,
  15811. data_func,
  15812. close_func,
  15813. user_data);
  15814. }
  15815. struct mg_connection *
  15816. mg_connect_websocket_client_secure(
  15817. const struct mg_client_options *client_options,
  15818. char *error_buffer,
  15819. size_t error_buffer_size,
  15820. const char *path,
  15821. const char *origin,
  15822. mg_websocket_data_handler data_func,
  15823. mg_websocket_close_handler close_func,
  15824. void *user_data)
  15825. {
  15826. if (!client_options) {
  15827. return NULL;
  15828. }
  15829. return mg_connect_websocket_client_impl(client_options,
  15830. 1,
  15831. error_buffer,
  15832. error_buffer_size,
  15833. path,
  15834. origin,
  15835. data_func,
  15836. close_func,
  15837. user_data);
  15838. }
  15839. /* Prepare connection data structure */
  15840. static void
  15841. init_connection(struct mg_connection *conn)
  15842. {
  15843. /* Is keep alive allowed by the server */
  15844. int keep_alive_enabled =
  15845. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15846. if (!keep_alive_enabled) {
  15847. conn->must_close = 1;
  15848. }
  15849. /* Important: on new connection, reset the receiving buffer. Credit
  15850. * goes to crule42. */
  15851. conn->data_len = 0;
  15852. conn->handled_requests = 0;
  15853. mg_set_user_connection_data(conn, NULL);
  15854. #if defined(USE_SERVER_STATS)
  15855. conn->conn_state = 2; /* init */
  15856. #endif
  15857. /* call the init_connection callback if assigned */
  15858. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15859. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15860. void *conn_data = NULL;
  15861. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15862. mg_set_user_connection_data(conn, conn_data);
  15863. }
  15864. }
  15865. }
  15866. /* Process a connection - may handle multiple requests
  15867. * using the same connection.
  15868. * Must be called with a valid connection (conn and
  15869. * conn->phys_ctx must be valid).
  15870. */
  15871. static void
  15872. process_new_connection(struct mg_connection *conn)
  15873. {
  15874. struct mg_request_info *ri = &conn->request_info;
  15875. int keep_alive, discard_len;
  15876. char ebuf[100];
  15877. const char *hostend;
  15878. int reqerr, uri_type;
  15879. #if defined(USE_SERVER_STATS)
  15880. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15881. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15882. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15883. /* could use atomic compare exchange, but this
  15884. * seems overkill for statistics data */
  15885. conn->phys_ctx->max_active_connections = mcon;
  15886. }
  15887. #endif
  15888. init_connection(conn);
  15889. DEBUG_TRACE("Start processing connection from %s",
  15890. conn->request_info.remote_addr);
  15891. /* Loop over multiple requests sent using the same connection
  15892. * (while "keep alive"). */
  15893. do {
  15894. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15895. conn->handled_requests + 1);
  15896. #if defined(USE_SERVER_STATS)
  15897. conn->conn_state = 3; /* ready */
  15898. #endif
  15899. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15900. /* The request sent by the client could not be understood by
  15901. * the server, or it was incomplete or a timeout. Send an
  15902. * error message and close the connection. */
  15903. if (reqerr > 0) {
  15904. DEBUG_ASSERT(ebuf[0] != '\0');
  15905. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15906. }
  15907. } else if (strcmp(ri->http_version, "1.0")
  15908. && strcmp(ri->http_version, "1.1")) {
  15909. /* HTTP/2 is not allowed here */
  15910. mg_snprintf(conn,
  15911. NULL, /* No truncation check for ebuf */
  15912. ebuf,
  15913. sizeof(ebuf),
  15914. "Bad HTTP version: [%s]",
  15915. ri->http_version);
  15916. mg_send_http_error(conn, 505, "%s", ebuf);
  15917. }
  15918. if (ebuf[0] == '\0') {
  15919. uri_type = get_uri_type(conn->request_info.request_uri);
  15920. switch (uri_type) {
  15921. case 1:
  15922. /* Asterisk */
  15923. conn->request_info.local_uri = 0;
  15924. /* TODO: Deal with '*'. */
  15925. break;
  15926. case 2:
  15927. /* relative uri */
  15928. conn->request_info.local_uri = conn->request_info.request_uri;
  15929. break;
  15930. case 3:
  15931. case 4:
  15932. /* absolute uri (with/without port) */
  15933. hostend = get_rel_url_at_current_server(
  15934. conn->request_info.request_uri, conn);
  15935. if (hostend) {
  15936. conn->request_info.local_uri = hostend;
  15937. } else {
  15938. conn->request_info.local_uri = NULL;
  15939. }
  15940. break;
  15941. default:
  15942. mg_snprintf(conn,
  15943. NULL, /* No truncation check for ebuf */
  15944. ebuf,
  15945. sizeof(ebuf),
  15946. "Invalid URI");
  15947. mg_send_http_error(conn, 400, "%s", ebuf);
  15948. conn->request_info.local_uri = NULL;
  15949. break;
  15950. }
  15951. #if defined(MG_LEGACY_INTERFACE)
  15952. /* Legacy before split into local_uri and request_uri */
  15953. conn->request_info.uri = conn->request_info.local_uri;
  15954. #endif
  15955. }
  15956. if (ebuf[0] != '\0') {
  15957. conn->protocol_type = -1;
  15958. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15959. /* HTTP/1 allows protocol upgrade */
  15960. conn->protocol_type = should_switch_to_protocol(conn);
  15961. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15962. /* This will occur, if a HTTP/1.1 request should be upgraded
  15963. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15964. * Since most (all?) major browsers only support HTTP/2 using
  15965. * ALPN, this is hard to test and very low priority.
  15966. * Deactivate it (at least for now).
  15967. */
  15968. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15969. }
  15970. }
  15971. DEBUG_TRACE("http: %s, error: %s",
  15972. (ri->http_version ? ri->http_version : "none"),
  15973. (ebuf[0] ? ebuf : "none"));
  15974. if (ebuf[0] == '\0') {
  15975. if (conn->request_info.local_uri) {
  15976. /* handle request to local server */
  15977. #if defined(USE_SERVER_STATS)
  15978. conn->conn_state = 4; /* processing */
  15979. #endif
  15980. handle_request(conn);
  15981. #if defined(USE_SERVER_STATS)
  15982. conn->conn_state = 5; /* processed */
  15983. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15984. conn->consumed_content);
  15985. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15986. conn->num_bytes_sent);
  15987. #endif
  15988. DEBUG_TRACE("%s", "handle_request done");
  15989. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15990. conn->phys_ctx->callbacks.end_request(conn,
  15991. conn->status_code);
  15992. DEBUG_TRACE("%s", "end_request callback done");
  15993. }
  15994. log_access(conn);
  15995. } else {
  15996. /* TODO: handle non-local request (PROXY) */
  15997. conn->must_close = 1;
  15998. }
  15999. } else {
  16000. conn->must_close = 1;
  16001. }
  16002. if (ri->remote_user != NULL) {
  16003. mg_free((void *)ri->remote_user);
  16004. /* Important! When having connections with and without auth
  16005. * would cause double free and then crash */
  16006. ri->remote_user = NULL;
  16007. }
  16008. /* NOTE(lsm): order is important here. should_keep_alive() call
  16009. * is using parsed request, which will be invalid after
  16010. * memmove's below.
  16011. * Therefore, memorize should_keep_alive() result now for later
  16012. * use in loop exit condition. */
  16013. /* Enable it only if this request is completely discardable. */
  16014. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16015. && should_keep_alive(conn) && (conn->content_len >= 0)
  16016. && (conn->request_len > 0)
  16017. && ((conn->is_chunked == 4)
  16018. || (!conn->is_chunked
  16019. && ((conn->consumed_content == conn->content_len)
  16020. || ((conn->request_len + conn->content_len)
  16021. <= conn->data_len))))
  16022. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16023. if (keep_alive) {
  16024. /* Discard all buffered data for this request */
  16025. discard_len =
  16026. ((conn->request_len + conn->content_len) < conn->data_len)
  16027. ? (int)(conn->request_len + conn->content_len)
  16028. : conn->data_len;
  16029. conn->data_len -= discard_len;
  16030. if (conn->data_len > 0) {
  16031. DEBUG_TRACE("discard_len = %d", discard_len);
  16032. memmove(conn->buf,
  16033. conn->buf + discard_len,
  16034. (size_t)conn->data_len);
  16035. }
  16036. }
  16037. DEBUG_ASSERT(conn->data_len >= 0);
  16038. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16039. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16040. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16041. (long int)conn->data_len,
  16042. (long int)conn->buf_size);
  16043. break;
  16044. }
  16045. conn->handled_requests++;
  16046. } while (keep_alive);
  16047. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16048. conn->request_info.remote_addr,
  16049. difftime(time(NULL), conn->conn_birth_time));
  16050. close_connection(conn);
  16051. #if defined(USE_SERVER_STATS)
  16052. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16053. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16054. #endif
  16055. }
  16056. #if defined(ALTERNATIVE_QUEUE)
  16057. static void
  16058. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16059. {
  16060. unsigned int i;
  16061. while (!ctx->stop_flag) {
  16062. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16063. /* find a free worker slot and signal it */
  16064. if (ctx->client_socks[i].in_use == 2) {
  16065. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16066. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16067. ctx->client_socks[i] = *sp;
  16068. ctx->client_socks[i].in_use = 1;
  16069. /* socket has been moved to the consumer */
  16070. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16071. (void)event_signal(ctx->client_wait_events[i]);
  16072. return;
  16073. }
  16074. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16075. }
  16076. }
  16077. /* queue is full */
  16078. mg_sleep(1);
  16079. }
  16080. /* must consume */
  16081. set_blocking_mode(sp->sock);
  16082. closesocket(sp->sock);
  16083. }
  16084. static int
  16085. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16086. {
  16087. DEBUG_TRACE("%s", "going idle");
  16088. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16089. ctx->client_socks[thread_index].in_use = 2;
  16090. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16091. event_wait(ctx->client_wait_events[thread_index]);
  16092. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16093. *sp = ctx->client_socks[thread_index];
  16094. if (ctx->stop_flag) {
  16095. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16096. if (sp->in_use == 1) {
  16097. /* must consume */
  16098. set_blocking_mode(sp->sock);
  16099. closesocket(sp->sock);
  16100. }
  16101. return 0;
  16102. }
  16103. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16104. if (sp->in_use == 1) {
  16105. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16106. return 1;
  16107. }
  16108. /* must not reach here */
  16109. DEBUG_ASSERT(0);
  16110. return 0;
  16111. }
  16112. #else /* ALTERNATIVE_QUEUE */
  16113. /* Worker threads take accepted socket from the queue */
  16114. static int
  16115. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16116. {
  16117. (void)thread_index;
  16118. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16119. DEBUG_TRACE("%s", "going idle");
  16120. /* If the queue is empty, wait. We're idle at this point. */
  16121. while ((ctx->sq_head == ctx->sq_tail)
  16122. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16123. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16124. }
  16125. /* If we're stopping, sq_head may be equal to sq_tail. */
  16126. if (ctx->sq_head > ctx->sq_tail) {
  16127. /* Copy socket from the queue and increment tail */
  16128. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16129. ctx->sq_tail++;
  16130. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16131. /* Wrap pointers if needed */
  16132. while (ctx->sq_tail > ctx->sq_size) {
  16133. ctx->sq_tail -= ctx->sq_size;
  16134. ctx->sq_head -= ctx->sq_size;
  16135. }
  16136. }
  16137. (void)pthread_cond_signal(&ctx->sq_empty);
  16138. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16139. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16140. }
  16141. /* Master thread adds accepted socket to a queue */
  16142. static void
  16143. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16144. {
  16145. int queue_filled;
  16146. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16147. queue_filled = ctx->sq_head - ctx->sq_tail;
  16148. /* If the queue is full, wait */
  16149. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16150. && (queue_filled >= ctx->sq_size)) {
  16151. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16152. #if defined(USE_SERVER_STATS)
  16153. if (queue_filled > ctx->sq_max_fill) {
  16154. ctx->sq_max_fill = queue_filled;
  16155. }
  16156. #endif
  16157. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16158. ctx->sq_blocked = 0; /* Not blocked now */
  16159. queue_filled = ctx->sq_head - ctx->sq_tail;
  16160. }
  16161. if (queue_filled < ctx->sq_size) {
  16162. /* Copy socket to the queue and increment head */
  16163. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16164. ctx->sq_head++;
  16165. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16166. }
  16167. queue_filled = ctx->sq_head - ctx->sq_tail;
  16168. #if defined(USE_SERVER_STATS)
  16169. if (queue_filled > ctx->sq_max_fill) {
  16170. ctx->sq_max_fill = queue_filled;
  16171. }
  16172. #endif
  16173. (void)pthread_cond_signal(&ctx->sq_full);
  16174. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16175. }
  16176. #endif /* ALTERNATIVE_QUEUE */
  16177. static void
  16178. worker_thread_run(struct mg_connection *conn)
  16179. {
  16180. struct mg_context *ctx = conn->phys_ctx;
  16181. int thread_index;
  16182. struct mg_workerTLS tls;
  16183. #if defined(MG_LEGACY_INTERFACE)
  16184. uint32_t addr;
  16185. #endif
  16186. mg_set_thread_name("worker");
  16187. tls.is_master = 0;
  16188. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16189. #if defined(_WIN32)
  16190. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16191. #endif
  16192. /* Initialize thread local storage before calling any callback */
  16193. pthread_setspecific(sTlsKey, &tls);
  16194. /* Check if there is a user callback */
  16195. if (ctx->callbacks.init_thread) {
  16196. /* call init_thread for a worker thread (type 1), and store the
  16197. * return value */
  16198. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16199. } else {
  16200. /* No callback: set user pointer to NULL */
  16201. tls.user_ptr = NULL;
  16202. }
  16203. /* Connection structure has been pre-allocated */
  16204. thread_index = (int)(conn - ctx->worker_connections);
  16205. if ((thread_index < 0)
  16206. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16207. mg_cry_ctx_internal(ctx,
  16208. "Internal error: Invalid worker index %i",
  16209. thread_index);
  16210. return;
  16211. }
  16212. /* Request buffers are not pre-allocated. They are private to the
  16213. * request and do not contain any state information that might be
  16214. * of interest to anyone observing a server status. */
  16215. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16216. if (conn->buf == NULL) {
  16217. mg_cry_ctx_internal(
  16218. ctx,
  16219. "Out of memory: Cannot allocate buffer for worker %i",
  16220. thread_index);
  16221. return;
  16222. }
  16223. conn->buf_size = (int)ctx->max_request_size;
  16224. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16225. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16226. conn->request_info.user_data = ctx->user_data;
  16227. /* Allocate a mutex for this connection to allow communication both
  16228. * within the request handler and from elsewhere in the application
  16229. */
  16230. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16231. mg_free(conn->buf);
  16232. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16233. return;
  16234. }
  16235. #if defined(USE_SERVER_STATS)
  16236. conn->conn_state = 1; /* not consumed */
  16237. #endif
  16238. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16239. * signal sq_empty condvar to wake up the master waiting in
  16240. * produce_socket() */
  16241. while (consume_socket(ctx, &conn->client, thread_index)) {
  16242. /* New connections must start with new protocol negotiation */
  16243. tls.alpn_proto = NULL;
  16244. #if defined(USE_SERVER_STATS)
  16245. conn->conn_close_time = 0;
  16246. #endif
  16247. conn->conn_birth_time = time(NULL);
  16248. /* Fill in IP, port info early so even if SSL setup below fails,
  16249. * error handler would have the corresponding info.
  16250. * Thanks to Johannes Winkelmann for the patch.
  16251. */
  16252. conn->request_info.remote_port =
  16253. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16254. sockaddr_to_string(conn->request_info.remote_addr,
  16255. sizeof(conn->request_info.remote_addr),
  16256. &conn->client.rsa);
  16257. DEBUG_TRACE("Start processing connection from %s",
  16258. conn->request_info.remote_addr);
  16259. conn->request_info.is_ssl = conn->client.is_ssl;
  16260. if (conn->client.is_ssl) {
  16261. #if !defined(NO_SSL)
  16262. /* HTTPS connection */
  16263. if (sslize(conn, SSL_accept, NULL)) {
  16264. /* conn->dom_ctx is set in get_request */
  16265. /* Get SSL client certificate information (if set) */
  16266. struct mg_client_cert client_cert;
  16267. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16268. conn->request_info.client_cert = &client_cert;
  16269. }
  16270. /* process HTTPS connection */
  16271. #if defined(USE_HTTP2)
  16272. if ((tls.alpn_proto != NULL)
  16273. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16274. /* process HTTPS/2 connection */
  16275. init_connection(conn);
  16276. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16277. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16278. conn->content_len = -1;
  16279. conn->is_chunked = 0;
  16280. process_new_http2_connection(conn);
  16281. } else
  16282. #endif
  16283. {
  16284. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16285. process_new_connection(conn);
  16286. }
  16287. /* Free client certificate info */
  16288. if (conn->request_info.client_cert) {
  16289. mg_free((void *)(conn->request_info.client_cert->subject));
  16290. mg_free((void *)(conn->request_info.client_cert->issuer));
  16291. mg_free((void *)(conn->request_info.client_cert->serial));
  16292. mg_free((void *)(conn->request_info.client_cert->finger));
  16293. /* Free certificate memory */
  16294. X509_free(
  16295. (X509 *)conn->request_info.client_cert->peer_cert);
  16296. conn->request_info.client_cert->peer_cert = 0;
  16297. conn->request_info.client_cert->subject = 0;
  16298. conn->request_info.client_cert->issuer = 0;
  16299. conn->request_info.client_cert->serial = 0;
  16300. conn->request_info.client_cert->finger = 0;
  16301. conn->request_info.client_cert = 0;
  16302. }
  16303. } else {
  16304. /* make sure the connection is cleaned up on SSL failure */
  16305. close_connection(conn);
  16306. }
  16307. #endif
  16308. } else {
  16309. /* process HTTP connection */
  16310. process_new_connection(conn);
  16311. }
  16312. DEBUG_TRACE("%s", "Connection closed");
  16313. #if defined(USE_SERVER_STATS)
  16314. conn->conn_close_time = time(NULL);
  16315. #endif
  16316. }
  16317. /* Call exit thread user callback */
  16318. if (ctx->callbacks.exit_thread) {
  16319. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16320. }
  16321. /* delete thread local storage objects */
  16322. pthread_setspecific(sTlsKey, NULL);
  16323. #if defined(_WIN32)
  16324. CloseHandle(tls.pthread_cond_helper_mutex);
  16325. #endif
  16326. pthread_mutex_destroy(&conn->mutex);
  16327. /* Free the request buffer. */
  16328. conn->buf_size = 0;
  16329. mg_free(conn->buf);
  16330. conn->buf = NULL;
  16331. #if defined(USE_SERVER_STATS)
  16332. conn->conn_state = 9; /* done */
  16333. #endif
  16334. DEBUG_TRACE("%s", "exiting");
  16335. }
  16336. /* Threads have different return types on Windows and Unix. */
  16337. #if defined(_WIN32)
  16338. static unsigned __stdcall worker_thread(void *thread_func_param)
  16339. {
  16340. worker_thread_run((struct mg_connection *)thread_func_param);
  16341. return 0;
  16342. }
  16343. #else
  16344. static void *
  16345. worker_thread(void *thread_func_param)
  16346. {
  16347. #if !defined(__ZEPHYR__)
  16348. struct sigaction sa;
  16349. /* Ignore SIGPIPE */
  16350. memset(&sa, 0, sizeof(sa));
  16351. sa.sa_handler = SIG_IGN;
  16352. sigaction(SIGPIPE, &sa, NULL);
  16353. #endif
  16354. worker_thread_run((struct mg_connection *)thread_func_param);
  16355. return NULL;
  16356. }
  16357. #endif /* _WIN32 */
  16358. /* This is an internal function, thus all arguments are expected to be
  16359. * valid - a NULL check is not required. */
  16360. static void
  16361. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16362. {
  16363. struct socket so;
  16364. char src_addr[IP_ADDR_STR_LEN];
  16365. socklen_t len = sizeof(so.rsa);
  16366. #if !defined(__ZEPHYR__)
  16367. int on = 1;
  16368. #endif
  16369. memset(&so, 0, sizeof(so));
  16370. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16371. == INVALID_SOCKET) {
  16372. } else if (check_acl(ctx, &so.rsa) != 1) {
  16373. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16374. mg_cry_ctx_internal(ctx,
  16375. "%s: %s is not allowed to connect",
  16376. __func__,
  16377. src_addr);
  16378. closesocket(so.sock);
  16379. } else {
  16380. /* Put so socket structure into the queue */
  16381. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16382. set_close_on_exec(so.sock, NULL, ctx);
  16383. so.is_ssl = listener->is_ssl;
  16384. so.ssl_redir = listener->ssl_redir;
  16385. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16386. mg_cry_ctx_internal(ctx,
  16387. "%s: getsockname() failed: %s",
  16388. __func__,
  16389. strerror(ERRNO));
  16390. }
  16391. #if !defined(__ZEPHYR__)
  16392. /* Set TCP keep-alive. This is needed because if HTTP-level
  16393. * keep-alive
  16394. * is enabled, and client resets the connection, server won't get
  16395. * TCP FIN or RST and will keep the connection open forever. With
  16396. * TCP keep-alive, next keep-alive handshake will figure out that
  16397. * the client is down and will close the server end.
  16398. * Thanks to Igor Klopov who suggested the patch. */
  16399. if (setsockopt(so.sock,
  16400. SOL_SOCKET,
  16401. SO_KEEPALIVE,
  16402. (SOCK_OPT_TYPE)&on,
  16403. sizeof(on))
  16404. != 0) {
  16405. mg_cry_ctx_internal(
  16406. ctx,
  16407. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16408. __func__,
  16409. strerror(ERRNO));
  16410. }
  16411. #endif
  16412. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16413. * to effectively fill up the underlying IP packet payload and
  16414. * reduce the overhead of sending lots of small buffers. However
  16415. * this hurts the server's throughput (ie. operations per second)
  16416. * when HTTP 1.1 persistent connections are used and the responses
  16417. * are relatively small (eg. less than 1400 bytes).
  16418. */
  16419. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16420. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16421. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16422. mg_cry_ctx_internal(
  16423. ctx,
  16424. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16425. __func__,
  16426. strerror(ERRNO));
  16427. }
  16428. }
  16429. /* The "non blocking" property should already be
  16430. * inherited from the parent socket. Set it for
  16431. * non-compliant socket implementations. */
  16432. set_non_blocking_mode(so.sock);
  16433. so.in_use = 0;
  16434. produce_socket(ctx, &so);
  16435. }
  16436. }
  16437. static void
  16438. master_thread_run(struct mg_context *ctx)
  16439. {
  16440. struct mg_workerTLS tls;
  16441. struct mg_pollfd *pfd;
  16442. unsigned int i;
  16443. unsigned int workerthreadcount;
  16444. if (!ctx) {
  16445. return;
  16446. }
  16447. mg_set_thread_name("master");
  16448. /* Increase priority of the master thread */
  16449. #if defined(_WIN32)
  16450. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16451. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16452. int min_prio = sched_get_priority_min(SCHED_RR);
  16453. int max_prio = sched_get_priority_max(SCHED_RR);
  16454. if ((min_prio >= 0) && (max_prio >= 0)
  16455. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16456. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16457. struct sched_param sched_param = {0};
  16458. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16459. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16460. }
  16461. #endif
  16462. /* Initialize thread local storage */
  16463. #if defined(_WIN32)
  16464. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16465. #endif
  16466. tls.is_master = 1;
  16467. pthread_setspecific(sTlsKey, &tls);
  16468. if (ctx->callbacks.init_thread) {
  16469. /* Callback for the master thread (type 0) */
  16470. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16471. } else {
  16472. tls.user_ptr = NULL;
  16473. }
  16474. /* Server starts *now* */
  16475. ctx->start_time = time(NULL);
  16476. /* Start the server */
  16477. pfd = ctx->listening_socket_fds;
  16478. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16479. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16480. pfd[i].fd = ctx->listening_sockets[i].sock;
  16481. pfd[i].events = POLLIN;
  16482. }
  16483. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16484. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16485. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16486. * successful poll, and POLLIN is defined as
  16487. * (POLLRDNORM | POLLRDBAND)
  16488. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16489. * pfd[i].revents == POLLIN. */
  16490. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16491. && (pfd[i].revents & POLLIN)) {
  16492. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16493. }
  16494. }
  16495. }
  16496. }
  16497. /* Here stop_flag is 1 - Initiate shutdown. */
  16498. DEBUG_TRACE("%s", "stopping workers");
  16499. /* Stop signal received: somebody called mg_stop. Quit. */
  16500. close_all_listening_sockets(ctx);
  16501. /* Wakeup workers that are waiting for connections to handle. */
  16502. #if defined(ALTERNATIVE_QUEUE)
  16503. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16504. event_signal(ctx->client_wait_events[i]);
  16505. }
  16506. #else
  16507. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16508. pthread_cond_broadcast(&ctx->sq_full);
  16509. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16510. #endif
  16511. /* Join all worker threads to avoid leaking threads. */
  16512. workerthreadcount = ctx->cfg_worker_threads;
  16513. for (i = 0; i < workerthreadcount; i++) {
  16514. if (ctx->worker_threadids[i] != 0) {
  16515. mg_join_thread(ctx->worker_threadids[i]);
  16516. }
  16517. }
  16518. #if defined(USE_LUA)
  16519. /* Free Lua state of lua background task */
  16520. if (ctx->lua_background_state) {
  16521. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16522. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16523. if (lua_istable(lstate, -1)) {
  16524. reg_boolean(lstate, "shutdown", 1);
  16525. lua_pop(lstate, 1);
  16526. mg_sleep(2);
  16527. }
  16528. lua_close(lstate);
  16529. ctx->lua_background_state = 0;
  16530. }
  16531. #endif
  16532. DEBUG_TRACE("%s", "exiting");
  16533. /* call exit thread callback */
  16534. if (ctx->callbacks.exit_thread) {
  16535. /* Callback for the master thread (type 0) */
  16536. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16537. }
  16538. #if defined(_WIN32)
  16539. CloseHandle(tls.pthread_cond_helper_mutex);
  16540. #endif
  16541. pthread_setspecific(sTlsKey, NULL);
  16542. /* Signal mg_stop() that we're done.
  16543. * WARNING: This must be the very last thing this
  16544. * thread does, as ctx becomes invalid after this line. */
  16545. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16546. }
  16547. /* Threads have different return types on Windows and Unix. */
  16548. #if defined(_WIN32)
  16549. static unsigned __stdcall master_thread(void *thread_func_param)
  16550. {
  16551. master_thread_run((struct mg_context *)thread_func_param);
  16552. return 0;
  16553. }
  16554. #else
  16555. static void *
  16556. master_thread(void *thread_func_param)
  16557. {
  16558. #if !defined(__ZEPHYR__)
  16559. struct sigaction sa;
  16560. /* Ignore SIGPIPE */
  16561. memset(&sa, 0, sizeof(sa));
  16562. sa.sa_handler = SIG_IGN;
  16563. sigaction(SIGPIPE, &sa, NULL);
  16564. #endif
  16565. master_thread_run((struct mg_context *)thread_func_param);
  16566. return NULL;
  16567. }
  16568. #endif /* _WIN32 */
  16569. static void
  16570. free_context(struct mg_context *ctx)
  16571. {
  16572. int i;
  16573. struct mg_handler_info *tmp_rh;
  16574. if (ctx == NULL) {
  16575. return;
  16576. }
  16577. if (ctx->callbacks.exit_context) {
  16578. ctx->callbacks.exit_context(ctx);
  16579. }
  16580. /* All threads exited, no sync is needed. Destroy thread mutex and
  16581. * condvars
  16582. */
  16583. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16584. #if defined(ALTERNATIVE_QUEUE)
  16585. mg_free(ctx->client_socks);
  16586. if (ctx->client_wait_events != NULL) {
  16587. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16588. event_destroy(ctx->client_wait_events[i]);
  16589. }
  16590. mg_free(ctx->client_wait_events);
  16591. }
  16592. #else
  16593. (void)pthread_cond_destroy(&ctx->sq_empty);
  16594. (void)pthread_cond_destroy(&ctx->sq_full);
  16595. mg_free(ctx->squeue);
  16596. #endif
  16597. /* Destroy other context global data structures mutex */
  16598. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16599. #if defined(USE_TIMERS)
  16600. timers_exit(ctx);
  16601. #endif
  16602. /* Deallocate config parameters */
  16603. for (i = 0; i < NUM_OPTIONS; i++) {
  16604. if (ctx->dd.config[i] != NULL) {
  16605. #if defined(_MSC_VER)
  16606. #pragma warning(suppress : 6001)
  16607. #endif
  16608. mg_free(ctx->dd.config[i]);
  16609. }
  16610. }
  16611. /* Deallocate request handlers */
  16612. while (ctx->dd.handlers) {
  16613. tmp_rh = ctx->dd.handlers;
  16614. ctx->dd.handlers = tmp_rh->next;
  16615. mg_free(tmp_rh->uri);
  16616. mg_free(tmp_rh);
  16617. }
  16618. #if !defined(NO_SSL)
  16619. /* Deallocate SSL context */
  16620. if (ctx->dd.ssl_ctx != NULL) {
  16621. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16622. int callback_ret =
  16623. (ctx->callbacks.external_ssl_ctx == NULL)
  16624. ? 0
  16625. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16626. if (callback_ret == 0) {
  16627. SSL_CTX_free(ctx->dd.ssl_ctx);
  16628. }
  16629. /* else: ignore error and ommit SSL_CTX_free in case
  16630. * callback_ret is 1 */
  16631. }
  16632. #endif /* !NO_SSL */
  16633. /* Deallocate worker thread ID array */
  16634. mg_free(ctx->worker_threadids);
  16635. /* Deallocate worker thread ID array */
  16636. mg_free(ctx->worker_connections);
  16637. /* deallocate system name string */
  16638. mg_free(ctx->systemName);
  16639. /* Deallocate context itself */
  16640. mg_free(ctx);
  16641. }
  16642. void
  16643. mg_stop(struct mg_context *ctx)
  16644. {
  16645. pthread_t mt;
  16646. if (!ctx) {
  16647. return;
  16648. }
  16649. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16650. * two threads is not allowed. */
  16651. mt = ctx->masterthreadid;
  16652. if (mt == 0) {
  16653. return;
  16654. }
  16655. ctx->masterthreadid = 0;
  16656. /* Set stop flag, so all threads know they have to exit. */
  16657. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16658. /* Wait until everything has stopped. */
  16659. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16660. (void)mg_sleep(10);
  16661. }
  16662. mg_join_thread(mt);
  16663. free_context(ctx);
  16664. }
  16665. static void
  16666. get_system_name(char **sysName)
  16667. {
  16668. #if defined(_WIN32)
  16669. #if defined(_WIN32_WCE)
  16670. *sysName = mg_strdup("WinCE");
  16671. #else
  16672. char name[128];
  16673. DWORD dwVersion = 0;
  16674. DWORD dwMajorVersion = 0;
  16675. DWORD dwMinorVersion = 0;
  16676. DWORD dwBuild = 0;
  16677. BOOL wowRet, isWoW = FALSE;
  16678. #if defined(_MSC_VER)
  16679. #pragma warning(push)
  16680. /* GetVersion was declared deprecated */
  16681. #pragma warning(disable : 4996)
  16682. #endif
  16683. dwVersion = GetVersion();
  16684. #if defined(_MSC_VER)
  16685. #pragma warning(pop)
  16686. #endif
  16687. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16688. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16689. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16690. (void)dwBuild;
  16691. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16692. sprintf(name,
  16693. "Windows %u.%u%s",
  16694. (unsigned)dwMajorVersion,
  16695. (unsigned)dwMinorVersion,
  16696. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16697. *sysName = mg_strdup(name);
  16698. #endif
  16699. #elif defined(__ZEPHYR__)
  16700. *sysName = mg_strdup("Zephyr OS");
  16701. #else
  16702. struct utsname name;
  16703. memset(&name, 0, sizeof(name));
  16704. uname(&name);
  16705. *sysName = mg_strdup(name.sysname);
  16706. #endif
  16707. }
  16708. static void
  16709. legacy_init(const char **options)
  16710. {
  16711. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16712. if (options) {
  16713. const char **run_options = options;
  16714. const char *optname = config_options[LISTENING_PORTS].name;
  16715. /* Try to find the "listening_ports" option */
  16716. while (*run_options) {
  16717. if (!strcmp(*run_options, optname)) {
  16718. ports_option = run_options[1];
  16719. }
  16720. run_options += 2;
  16721. }
  16722. }
  16723. if (is_ssl_port_used(ports_option)) {
  16724. /* Initialize with SSL support */
  16725. mg_init_library(MG_FEATURES_TLS);
  16726. } else {
  16727. /* Initialize without SSL support */
  16728. mg_init_library(MG_FEATURES_DEFAULT);
  16729. }
  16730. }
  16731. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16732. static
  16733. #endif
  16734. struct mg_context *
  16735. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16736. {
  16737. struct mg_context *ctx;
  16738. const char *name, *value, *default_value;
  16739. int idx, ok, workerthreadcount;
  16740. unsigned int i;
  16741. int itmp;
  16742. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16743. const char **options =
  16744. ((init != NULL) ? (init->configuration_options) : (NULL));
  16745. struct mg_workerTLS tls;
  16746. if (error != NULL) {
  16747. error->code = 0;
  16748. if (error->text_buffer_size > 0) {
  16749. *error->text = 0;
  16750. }
  16751. }
  16752. if (mg_init_library_called == 0) {
  16753. /* Legacy INIT, if mg_start is called without mg_init_library.
  16754. * Note: This will cause a memory leak when unloading the library.
  16755. */
  16756. legacy_init(options);
  16757. }
  16758. if (mg_init_library_called == 0) {
  16759. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16760. mg_snprintf(NULL,
  16761. NULL, /* No truncation check for error buffers */
  16762. error->text,
  16763. error->text_buffer_size,
  16764. "%s",
  16765. "Library uninitialized");
  16766. }
  16767. return NULL;
  16768. }
  16769. /* Allocate context and initialize reasonable general case defaults. */
  16770. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16771. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16772. mg_snprintf(NULL,
  16773. NULL, /* No truncation check for error buffers */
  16774. error->text,
  16775. error->text_buffer_size,
  16776. "%s",
  16777. "Out of memory");
  16778. }
  16779. return NULL;
  16780. }
  16781. /* Random number generator will initialize at the first call */
  16782. ctx->dd.auth_nonce_mask =
  16783. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16784. /* Save started thread index to reuse in other external API calls
  16785. * For the sake of thread synchronization all non-civetweb threads
  16786. * can be considered as single external thread */
  16787. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16788. tls.is_master = -1; /* Thread calling mg_start */
  16789. tls.thread_idx = ctx->starter_thread_idx;
  16790. #if defined(_WIN32)
  16791. tls.pthread_cond_helper_mutex = NULL;
  16792. #endif
  16793. pthread_setspecific(sTlsKey, &tls);
  16794. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16795. #if !defined(ALTERNATIVE_QUEUE)
  16796. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16797. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16798. ctx->sq_blocked = 0;
  16799. #endif
  16800. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16801. if (!ok) {
  16802. const char *err_msg =
  16803. "Cannot initialize thread synchronization objects";
  16804. /* Fatal error - abort start. However, this situation should never
  16805. * occur in practice. */
  16806. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16807. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16808. mg_snprintf(NULL,
  16809. NULL, /* No truncation check for error buffers */
  16810. error->text,
  16811. error->text_buffer_size,
  16812. "%s",
  16813. err_msg);
  16814. }
  16815. mg_free(ctx);
  16816. pthread_setspecific(sTlsKey, NULL);
  16817. return NULL;
  16818. }
  16819. if ((init != NULL) && (init->callbacks != NULL)) {
  16820. /* Set all callbacks except exit_context. */
  16821. ctx->callbacks = *init->callbacks;
  16822. exit_callback = init->callbacks->exit_context;
  16823. /* The exit callback is activated once the context is successfully
  16824. * created. It should not be called, if an incomplete context object
  16825. * is deleted during a failed initialization. */
  16826. ctx->callbacks.exit_context = 0;
  16827. }
  16828. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16829. ctx->dd.handlers = NULL;
  16830. ctx->dd.next = NULL;
  16831. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16832. ctx->dd.shared_lua_websockets = NULL;
  16833. #endif
  16834. /* Store options */
  16835. while (options && (name = *options++) != NULL) {
  16836. if ((idx = get_option_index(name)) == -1) {
  16837. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16838. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16839. mg_snprintf(NULL,
  16840. NULL, /* No truncation check for error buffers */
  16841. error->text,
  16842. error->text_buffer_size,
  16843. "Invalid configuration option: %s",
  16844. name);
  16845. }
  16846. free_context(ctx);
  16847. pthread_setspecific(sTlsKey, NULL);
  16848. return NULL;
  16849. } else if ((value = *options++) == NULL) {
  16850. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16851. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16852. mg_snprintf(NULL,
  16853. NULL, /* No truncation check for error buffers */
  16854. error->text,
  16855. error->text_buffer_size,
  16856. "Invalid configuration option value: %s",
  16857. name);
  16858. }
  16859. free_context(ctx);
  16860. pthread_setspecific(sTlsKey, NULL);
  16861. return NULL;
  16862. }
  16863. if (ctx->dd.config[idx] != NULL) {
  16864. /* A duplicate configuration option is not an error - the last
  16865. * option value will be used. */
  16866. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16867. mg_free(ctx->dd.config[idx]);
  16868. }
  16869. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16870. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16871. }
  16872. /* Set default value if needed */
  16873. for (i = 0; config_options[i].name != NULL; i++) {
  16874. default_value = config_options[i].default_value;
  16875. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16876. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16877. }
  16878. }
  16879. /* Request size option */
  16880. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16881. if (itmp < 1024) {
  16882. mg_cry_ctx_internal(ctx,
  16883. "%s too small",
  16884. config_options[MAX_REQUEST_SIZE].name);
  16885. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16886. mg_snprintf(NULL,
  16887. NULL, /* No truncation check for error buffers */
  16888. error->text,
  16889. error->text_buffer_size,
  16890. "Invalid configuration option value: %s",
  16891. config_options[MAX_REQUEST_SIZE].name);
  16892. }
  16893. free_context(ctx);
  16894. pthread_setspecific(sTlsKey, NULL);
  16895. return NULL;
  16896. }
  16897. ctx->max_request_size = (unsigned)itmp;
  16898. /* Queue length */
  16899. #if !defined(ALTERNATIVE_QUEUE)
  16900. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16901. if (itmp < 1) {
  16902. mg_cry_ctx_internal(ctx,
  16903. "%s too small",
  16904. config_options[CONNECTION_QUEUE_SIZE].name);
  16905. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16906. mg_snprintf(NULL,
  16907. NULL, /* No truncation check for error buffers */
  16908. error->text,
  16909. error->text_buffer_size,
  16910. "Invalid configuration option value: %s",
  16911. config_options[CONNECTION_QUEUE_SIZE].name);
  16912. }
  16913. free_context(ctx);
  16914. pthread_setspecific(sTlsKey, NULL);
  16915. return NULL;
  16916. }
  16917. ctx->squeue =
  16918. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16919. if (ctx->squeue == NULL) {
  16920. mg_cry_ctx_internal(ctx,
  16921. "Out of memory: Cannot allocate %s",
  16922. config_options[CONNECTION_QUEUE_SIZE].name);
  16923. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16924. mg_snprintf(NULL,
  16925. NULL, /* No truncation check for error buffers */
  16926. error->text,
  16927. error->text_buffer_size,
  16928. "Out of memory: Cannot allocate %s",
  16929. config_options[CONNECTION_QUEUE_SIZE].name);
  16930. }
  16931. free_context(ctx);
  16932. pthread_setspecific(sTlsKey, NULL);
  16933. return NULL;
  16934. }
  16935. ctx->sq_size = itmp;
  16936. #endif
  16937. /* Worker thread count option */
  16938. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16939. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16940. if (workerthreadcount <= 0) {
  16941. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16942. } else {
  16943. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16944. }
  16945. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16946. mg_snprintf(NULL,
  16947. NULL, /* No truncation check for error buffers */
  16948. error->text,
  16949. error->text_buffer_size,
  16950. "Invalid configuration option value: %s",
  16951. config_options[NUM_THREADS].name);
  16952. }
  16953. free_context(ctx);
  16954. pthread_setspecific(sTlsKey, NULL);
  16955. return NULL;
  16956. }
  16957. /* Document root */
  16958. #if defined(NO_FILES)
  16959. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16960. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16961. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16962. mg_snprintf(NULL,
  16963. NULL, /* No truncation check for error buffers */
  16964. error->text,
  16965. error->text_buffer_size,
  16966. "Invalid configuration option value: %s",
  16967. config_options[DOCUMENT_ROOT].name);
  16968. }
  16969. free_context(ctx);
  16970. pthread_setspecific(sTlsKey, NULL);
  16971. return NULL;
  16972. }
  16973. #endif
  16974. get_system_name(&ctx->systemName);
  16975. #if defined(USE_LUA)
  16976. /* If a Lua background script has been configured, start it. */
  16977. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16978. char ebuf[256];
  16979. struct vec opt_vec;
  16980. struct vec eq_vec;
  16981. const char *sparams;
  16982. lua_State *state = mg_prepare_lua_context_script(
  16983. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16984. if (!state) {
  16985. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16986. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16987. mg_snprintf(NULL,
  16988. NULL, /* No truncation check for error buffers */
  16989. error->text,
  16990. error->text_buffer_size,
  16991. "Error in script %s: %s",
  16992. config_options[DOCUMENT_ROOT].name,
  16993. ebuf);
  16994. }
  16995. free_context(ctx);
  16996. pthread_setspecific(sTlsKey, NULL);
  16997. return NULL;
  16998. }
  16999. ctx->lua_background_state = (void *)state;
  17000. lua_newtable(state);
  17001. reg_boolean(state, "shutdown", 0);
  17002. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17003. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17004. reg_llstring(
  17005. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17006. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17007. break;
  17008. }
  17009. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17010. } else {
  17011. ctx->lua_background_state = 0;
  17012. }
  17013. #endif
  17014. /* Step by step initialization of ctx - depending on build options */
  17015. #if !defined(NO_FILESYSTEMS)
  17016. if (!set_gpass_option(ctx, NULL)) {
  17017. const char *err_msg = "Invalid global password file";
  17018. /* Fatal error - abort start. */
  17019. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17020. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17021. mg_snprintf(NULL,
  17022. NULL, /* No truncation check for error buffers */
  17023. error->text,
  17024. error->text_buffer_size,
  17025. "%s",
  17026. err_msg);
  17027. }
  17028. free_context(ctx);
  17029. pthread_setspecific(sTlsKey, NULL);
  17030. return NULL;
  17031. }
  17032. #endif
  17033. #if !defined(NO_SSL)
  17034. if (!init_ssl_ctx(ctx, NULL)) {
  17035. const char *err_msg = "Error initializing SSL context";
  17036. /* Fatal error - abort start. */
  17037. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17038. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17039. mg_snprintf(NULL,
  17040. NULL, /* No truncation check for error buffers */
  17041. error->text,
  17042. error->text_buffer_size,
  17043. "%s",
  17044. err_msg);
  17045. }
  17046. free_context(ctx);
  17047. pthread_setspecific(sTlsKey, NULL);
  17048. return NULL;
  17049. }
  17050. #endif
  17051. if (!set_ports_option(ctx)) {
  17052. const char *err_msg = "Failed to setup server ports";
  17053. /* Fatal error - abort start. */
  17054. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17055. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17056. mg_snprintf(NULL,
  17057. NULL, /* No truncation check for error buffers */
  17058. error->text,
  17059. error->text_buffer_size,
  17060. "%s",
  17061. err_msg);
  17062. }
  17063. free_context(ctx);
  17064. pthread_setspecific(sTlsKey, NULL);
  17065. return NULL;
  17066. }
  17067. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17068. if (!set_uid_option(ctx)) {
  17069. const char *err_msg = "Failed to run as configured user";
  17070. /* Fatal error - abort start. */
  17071. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17072. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17073. mg_snprintf(NULL,
  17074. NULL, /* No truncation check for error buffers */
  17075. error->text,
  17076. error->text_buffer_size,
  17077. "%s",
  17078. err_msg);
  17079. }
  17080. free_context(ctx);
  17081. pthread_setspecific(sTlsKey, NULL);
  17082. return NULL;
  17083. }
  17084. #endif
  17085. if (!set_acl_option(ctx)) {
  17086. const char *err_msg = "Failed to setup access control list";
  17087. /* Fatal error - abort start. */
  17088. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17089. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17090. mg_snprintf(NULL,
  17091. NULL, /* No truncation check for error buffers */
  17092. error->text,
  17093. error->text_buffer_size,
  17094. "%s",
  17095. err_msg);
  17096. }
  17097. free_context(ctx);
  17098. pthread_setspecific(sTlsKey, NULL);
  17099. return NULL;
  17100. }
  17101. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17102. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17103. sizeof(pthread_t),
  17104. ctx);
  17105. if (ctx->worker_threadids == NULL) {
  17106. const char *err_msg = "Not enough memory for worker thread ID array";
  17107. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17108. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17109. mg_snprintf(NULL,
  17110. NULL, /* No truncation check for error buffers */
  17111. error->text,
  17112. error->text_buffer_size,
  17113. "%s",
  17114. err_msg);
  17115. }
  17116. free_context(ctx);
  17117. pthread_setspecific(sTlsKey, NULL);
  17118. return NULL;
  17119. }
  17120. ctx->worker_connections =
  17121. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17122. sizeof(struct mg_connection),
  17123. ctx);
  17124. if (ctx->worker_connections == NULL) {
  17125. const char *err_msg =
  17126. "Not enough memory for worker thread connection array";
  17127. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17128. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17129. mg_snprintf(NULL,
  17130. NULL, /* No truncation check for error buffers */
  17131. error->text,
  17132. error->text_buffer_size,
  17133. "%s",
  17134. err_msg);
  17135. }
  17136. free_context(ctx);
  17137. pthread_setspecific(sTlsKey, NULL);
  17138. return NULL;
  17139. }
  17140. #if defined(ALTERNATIVE_QUEUE)
  17141. ctx->client_wait_events =
  17142. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17143. sizeof(ctx->client_wait_events[0]),
  17144. ctx);
  17145. if (ctx->client_wait_events == NULL) {
  17146. const char *err_msg = "Not enough memory for worker event array";
  17147. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17148. mg_free(ctx->worker_threadids);
  17149. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17150. mg_snprintf(NULL,
  17151. NULL, /* No truncation check for error buffers */
  17152. error->text,
  17153. error->text_buffer_size,
  17154. "%s",
  17155. err_msg);
  17156. }
  17157. free_context(ctx);
  17158. pthread_setspecific(sTlsKey, NULL);
  17159. return NULL;
  17160. }
  17161. ctx->client_socks =
  17162. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17163. sizeof(ctx->client_socks[0]),
  17164. ctx);
  17165. if (ctx->client_socks == NULL) {
  17166. const char *err_msg = "Not enough memory for worker socket array";
  17167. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17168. mg_free(ctx->client_wait_events);
  17169. mg_free(ctx->worker_threadids);
  17170. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17171. mg_snprintf(NULL,
  17172. NULL, /* No truncation check for error buffers */
  17173. error->text,
  17174. error->text_buffer_size,
  17175. "%s",
  17176. err_msg);
  17177. }
  17178. free_context(ctx);
  17179. pthread_setspecific(sTlsKey, NULL);
  17180. return NULL;
  17181. }
  17182. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17183. ctx->client_wait_events[i] = event_create();
  17184. if (ctx->client_wait_events[i] == 0) {
  17185. const char *err_msg = "Error creating worker event %i";
  17186. mg_cry_ctx_internal(ctx, err_msg, i);
  17187. while (i > 0) {
  17188. i--;
  17189. event_destroy(ctx->client_wait_events[i]);
  17190. }
  17191. mg_free(ctx->client_socks);
  17192. mg_free(ctx->client_wait_events);
  17193. mg_free(ctx->worker_threadids);
  17194. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17195. mg_snprintf(NULL,
  17196. NULL, /* No truncation check for error buffers */
  17197. error->text,
  17198. error->text_buffer_size,
  17199. err_msg,
  17200. i);
  17201. }
  17202. free_context(ctx);
  17203. pthread_setspecific(sTlsKey, NULL);
  17204. return NULL;
  17205. }
  17206. }
  17207. #endif
  17208. #if defined(USE_TIMERS)
  17209. if (timers_init(ctx) != 0) {
  17210. const char *err_msg = "Error creating timers";
  17211. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17212. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17213. mg_snprintf(NULL,
  17214. NULL, /* No truncation check for error buffers */
  17215. error->text,
  17216. error->text_buffer_size,
  17217. "%s",
  17218. err_msg);
  17219. }
  17220. free_context(ctx);
  17221. pthread_setspecific(sTlsKey, NULL);
  17222. return NULL;
  17223. }
  17224. #endif
  17225. /* Context has been created - init user libraries */
  17226. if (ctx->callbacks.init_context) {
  17227. ctx->callbacks.init_context(ctx);
  17228. }
  17229. /* From now, the context is successfully created.
  17230. * When it is destroyed, the exit callback should be called. */
  17231. ctx->callbacks.exit_context = exit_callback;
  17232. ctx->context_type = CONTEXT_SERVER; /* server context */
  17233. /* Start worker threads */
  17234. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17235. /* worker_thread sets up the other fields */
  17236. ctx->worker_connections[i].phys_ctx = ctx;
  17237. if (mg_start_thread_with_id(worker_thread,
  17238. &ctx->worker_connections[i],
  17239. &ctx->worker_threadids[i])
  17240. != 0) {
  17241. long error_no = (long)ERRNO;
  17242. /* thread was not created */
  17243. if (i > 0) {
  17244. /* If the second, third, ... thread cannot be created, set a
  17245. * warning, but keep running. */
  17246. mg_cry_ctx_internal(ctx,
  17247. "Cannot start worker thread %i: error %ld",
  17248. i + 1,
  17249. error_no);
  17250. /* If the server initialization should stop here, all
  17251. * threads that have already been created must be stopped
  17252. * first, before any free_context(ctx) call.
  17253. */
  17254. } else {
  17255. /* If the first worker thread cannot be created, stop
  17256. * initialization and free the entire server context. */
  17257. mg_cry_ctx_internal(ctx,
  17258. "Cannot create threads: error %ld",
  17259. error_no);
  17260. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17261. mg_snprintf(
  17262. NULL,
  17263. NULL, /* No truncation check for error buffers */
  17264. error->text,
  17265. error->text_buffer_size,
  17266. "Cannot create first worker thread: error %ld",
  17267. error_no);
  17268. }
  17269. free_context(ctx);
  17270. pthread_setspecific(sTlsKey, NULL);
  17271. return NULL;
  17272. }
  17273. break;
  17274. }
  17275. }
  17276. /* Start master (listening) thread */
  17277. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17278. pthread_setspecific(sTlsKey, NULL);
  17279. return ctx;
  17280. }
  17281. struct mg_context *
  17282. mg_start(const struct mg_callbacks *callbacks,
  17283. void *user_data,
  17284. const char **options)
  17285. {
  17286. struct mg_init_data init = {0};
  17287. init.callbacks = callbacks;
  17288. init.user_data = user_data;
  17289. init.configuration_options = options;
  17290. return mg_start2(&init, NULL);
  17291. }
  17292. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17293. /* Add an additional domain to an already running web server. */
  17294. int
  17295. mg_start_domain2(struct mg_context *ctx,
  17296. const char **options,
  17297. struct mg_error_data *error)
  17298. {
  17299. const char *name;
  17300. const char *value;
  17301. const char *default_value;
  17302. struct mg_domain_context *new_dom;
  17303. struct mg_domain_context *dom;
  17304. int idx, i;
  17305. if (error != NULL) {
  17306. error->code = 0;
  17307. if (error->text_buffer_size > 0) {
  17308. *error->text = 0;
  17309. }
  17310. }
  17311. if ((ctx == NULL) || (options == NULL)) {
  17312. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17313. mg_snprintf(NULL,
  17314. NULL, /* No truncation check for error buffers */
  17315. error->text,
  17316. error->text_buffer_size,
  17317. "%s",
  17318. "Invalid parameters");
  17319. }
  17320. return -1;
  17321. }
  17322. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17323. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17324. mg_snprintf(NULL,
  17325. NULL, /* No truncation check for error buffers */
  17326. error->text,
  17327. error->text_buffer_size,
  17328. "%s",
  17329. "Server already stopped");
  17330. }
  17331. return -1;
  17332. }
  17333. new_dom = (struct mg_domain_context *)
  17334. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17335. if (!new_dom) {
  17336. /* Out of memory */
  17337. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17338. mg_snprintf(NULL,
  17339. NULL, /* No truncation check for error buffers */
  17340. error->text,
  17341. error->text_buffer_size,
  17342. "%s",
  17343. "Out or memory");
  17344. }
  17345. return -6;
  17346. }
  17347. /* Store options - TODO: unite duplicate code */
  17348. while (options && (name = *options++) != NULL) {
  17349. if ((idx = get_option_index(name)) == -1) {
  17350. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17351. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17352. mg_snprintf(NULL,
  17353. NULL, /* No truncation check for error buffers */
  17354. error->text,
  17355. error->text_buffer_size,
  17356. "Invalid option: %s",
  17357. name);
  17358. }
  17359. mg_free(new_dom);
  17360. return -2;
  17361. } else if ((value = *options++) == NULL) {
  17362. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17363. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17364. mg_snprintf(NULL,
  17365. NULL, /* No truncation check for error buffers */
  17366. error->text,
  17367. error->text_buffer_size,
  17368. "Invalid option value: %s",
  17369. name);
  17370. }
  17371. mg_free(new_dom);
  17372. return -2;
  17373. }
  17374. if (new_dom->config[idx] != NULL) {
  17375. /* Duplicate option: Later values overwrite earlier ones. */
  17376. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17377. mg_free(new_dom->config[idx]);
  17378. }
  17379. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17380. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17381. }
  17382. /* Authentication domain is mandatory */
  17383. /* TODO: Maybe use a new option hostname? */
  17384. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17385. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17386. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17387. mg_snprintf(NULL,
  17388. NULL, /* No truncation check for error buffers */
  17389. error->text,
  17390. error->text_buffer_size,
  17391. "Mandatory option %s missing",
  17392. config_options[AUTHENTICATION_DOMAIN].name);
  17393. }
  17394. mg_free(new_dom);
  17395. return -4;
  17396. }
  17397. /* Set default value if needed. Take the config value from
  17398. * ctx as a default value. */
  17399. for (i = 0; config_options[i].name != NULL; i++) {
  17400. default_value = ctx->dd.config[i];
  17401. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17402. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17403. }
  17404. }
  17405. new_dom->handlers = NULL;
  17406. new_dom->next = NULL;
  17407. new_dom->nonce_count = 0;
  17408. new_dom->auth_nonce_mask =
  17409. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17410. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17411. new_dom->shared_lua_websockets = NULL;
  17412. #endif
  17413. #if !defined(NO_SSL)
  17414. if (!init_ssl_ctx(ctx, new_dom)) {
  17415. /* Init SSL failed */
  17416. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17417. mg_snprintf(NULL,
  17418. NULL, /* No truncation check for error buffers */
  17419. error->text,
  17420. error->text_buffer_size,
  17421. "%s",
  17422. "Initializing SSL context failed");
  17423. }
  17424. mg_free(new_dom);
  17425. return -3;
  17426. }
  17427. #endif
  17428. /* Add element to linked list. */
  17429. mg_lock_context(ctx);
  17430. idx = 0;
  17431. dom = &(ctx->dd);
  17432. for (;;) {
  17433. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17434. dom->config[AUTHENTICATION_DOMAIN])) {
  17435. /* Domain collision */
  17436. mg_cry_ctx_internal(ctx,
  17437. "domain %s already in use",
  17438. new_dom->config[AUTHENTICATION_DOMAIN]);
  17439. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17440. mg_snprintf(NULL,
  17441. NULL, /* No truncation check for error buffers */
  17442. error->text,
  17443. error->text_buffer_size,
  17444. "Domain %s specified by %s is already in use",
  17445. new_dom->config[AUTHENTICATION_DOMAIN],
  17446. config_options[AUTHENTICATION_DOMAIN].name);
  17447. }
  17448. mg_free(new_dom);
  17449. mg_unlock_context(ctx);
  17450. return -5;
  17451. }
  17452. /* Count number of domains */
  17453. idx++;
  17454. if (dom->next == NULL) {
  17455. dom->next = new_dom;
  17456. break;
  17457. }
  17458. dom = dom->next;
  17459. }
  17460. mg_unlock_context(ctx);
  17461. /* Return domain number */
  17462. return idx;
  17463. }
  17464. int
  17465. mg_start_domain(struct mg_context *ctx, const char **options)
  17466. {
  17467. return mg_start_domain2(ctx, options, NULL);
  17468. }
  17469. #endif
  17470. /* Feature check API function */
  17471. unsigned
  17472. mg_check_feature(unsigned feature)
  17473. {
  17474. static const unsigned feature_set = 0
  17475. /* Set bits for available features according to API documentation.
  17476. * This bit mask is created at compile time, according to the active
  17477. * preprocessor defines. It is a single const value at runtime. */
  17478. #if !defined(NO_FILES)
  17479. | MG_FEATURES_FILES
  17480. #endif
  17481. #if !defined(NO_SSL)
  17482. | MG_FEATURES_SSL
  17483. #endif
  17484. #if !defined(NO_CGI)
  17485. | MG_FEATURES_CGI
  17486. #endif
  17487. #if defined(USE_IPV6)
  17488. | MG_FEATURES_IPV6
  17489. #endif
  17490. #if defined(USE_WEBSOCKET)
  17491. | MG_FEATURES_WEBSOCKET
  17492. #endif
  17493. #if defined(USE_LUA)
  17494. | MG_FEATURES_LUA
  17495. #endif
  17496. #if defined(USE_DUKTAPE)
  17497. | MG_FEATURES_SSJS
  17498. #endif
  17499. #if !defined(NO_CACHING)
  17500. | MG_FEATURES_CACHE
  17501. #endif
  17502. #if defined(USE_SERVER_STATS)
  17503. | MG_FEATURES_STATS
  17504. #endif
  17505. #if defined(USE_ZLIB)
  17506. | MG_FEATURES_COMPRESSION
  17507. #endif
  17508. /* Set some extra bits not defined in the API documentation.
  17509. * These bits may change without further notice. */
  17510. #if defined(MG_LEGACY_INTERFACE)
  17511. | 0x00008000u
  17512. #endif
  17513. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17514. | 0x00004000u
  17515. #endif
  17516. #if defined(MEMORY_DEBUGGING)
  17517. | 0x00001000u
  17518. #endif
  17519. #if defined(USE_TIMERS)
  17520. | 0x00020000u
  17521. #endif
  17522. #if !defined(NO_NONCE_CHECK)
  17523. | 0x00040000u
  17524. #endif
  17525. #if !defined(NO_POPEN)
  17526. | 0x00080000u
  17527. #endif
  17528. ;
  17529. return (feature & feature_set);
  17530. }
  17531. static size_t
  17532. mg_str_append(char **dst, char *end, const char *src)
  17533. {
  17534. size_t len = strlen(src);
  17535. if (*dst != end) {
  17536. /* Append src if enough space, or close dst. */
  17537. if ((size_t)(end - *dst) > len) {
  17538. strcpy(*dst, src);
  17539. *dst += len;
  17540. } else {
  17541. *dst = end;
  17542. }
  17543. }
  17544. return len;
  17545. }
  17546. /* Get system information. It can be printed or stored by the caller.
  17547. * Return the size of available information. */
  17548. int
  17549. mg_get_system_info(char *buffer, int buflen)
  17550. {
  17551. char *end, *append_eoobj = NULL, block[256];
  17552. size_t system_info_length = 0;
  17553. #if defined(_WIN32)
  17554. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17555. #else
  17556. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17557. #endif
  17558. if ((buffer == NULL) || (buflen < 1)) {
  17559. buflen = 0;
  17560. end = buffer;
  17561. } else {
  17562. *buffer = 0;
  17563. end = buffer + buflen;
  17564. }
  17565. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17566. /* has enough space to append eoobj */
  17567. append_eoobj = buffer;
  17568. if (end) {
  17569. end -= sizeof(eoobj) - 1;
  17570. }
  17571. }
  17572. system_info_length += mg_str_append(&buffer, end, "{");
  17573. /* Server version */
  17574. {
  17575. const char *version = mg_version();
  17576. mg_snprintf(NULL,
  17577. NULL,
  17578. block,
  17579. sizeof(block),
  17580. "%s\"version\" : \"%s\"",
  17581. eol,
  17582. version);
  17583. system_info_length += mg_str_append(&buffer, end, block);
  17584. }
  17585. /* System info */
  17586. {
  17587. #if defined(_WIN32)
  17588. DWORD dwVersion = 0;
  17589. DWORD dwMajorVersion = 0;
  17590. DWORD dwMinorVersion = 0;
  17591. SYSTEM_INFO si;
  17592. GetSystemInfo(&si);
  17593. #if defined(_MSC_VER)
  17594. #pragma warning(push)
  17595. /* GetVersion was declared deprecated */
  17596. #pragma warning(disable : 4996)
  17597. #endif
  17598. dwVersion = GetVersion();
  17599. #if defined(_MSC_VER)
  17600. #pragma warning(pop)
  17601. #endif
  17602. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17603. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17604. mg_snprintf(NULL,
  17605. NULL,
  17606. block,
  17607. sizeof(block),
  17608. ",%s\"os\" : \"Windows %u.%u\"",
  17609. eol,
  17610. (unsigned)dwMajorVersion,
  17611. (unsigned)dwMinorVersion);
  17612. system_info_length += mg_str_append(&buffer, end, block);
  17613. mg_snprintf(NULL,
  17614. NULL,
  17615. block,
  17616. sizeof(block),
  17617. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17618. eol,
  17619. (unsigned)si.wProcessorArchitecture,
  17620. (unsigned)si.dwNumberOfProcessors,
  17621. (unsigned)si.dwActiveProcessorMask);
  17622. system_info_length += mg_str_append(&buffer, end, block);
  17623. #elif defined(__ZEPHYR__)
  17624. mg_snprintf(NULL,
  17625. NULL,
  17626. block,
  17627. sizeof(block),
  17628. ",%s\"os\" : \"%s %s\"",
  17629. eol,
  17630. "Zephyr OS",
  17631. ZEPHYR_VERSION);
  17632. system_info_length += mg_str_append(&buffer, end, block);
  17633. #else
  17634. struct utsname name;
  17635. memset(&name, 0, sizeof(name));
  17636. uname(&name);
  17637. mg_snprintf(NULL,
  17638. NULL,
  17639. block,
  17640. sizeof(block),
  17641. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17642. eol,
  17643. name.sysname,
  17644. name.version,
  17645. name.release,
  17646. name.machine);
  17647. system_info_length += mg_str_append(&buffer, end, block);
  17648. #endif
  17649. }
  17650. /* Features */
  17651. {
  17652. mg_snprintf(NULL,
  17653. NULL,
  17654. block,
  17655. sizeof(block),
  17656. ",%s\"features\" : %lu"
  17657. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17658. eol,
  17659. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17660. eol,
  17661. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17662. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17663. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17664. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17665. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17666. : "",
  17667. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17668. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17669. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17670. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17671. system_info_length += mg_str_append(&buffer, end, block);
  17672. #if defined(USE_LUA)
  17673. mg_snprintf(NULL,
  17674. NULL,
  17675. block,
  17676. sizeof(block),
  17677. ",%s\"lua_version\" : \"%u (%s)\"",
  17678. eol,
  17679. (unsigned)LUA_VERSION_NUM,
  17680. LUA_RELEASE);
  17681. system_info_length += mg_str_append(&buffer, end, block);
  17682. #endif
  17683. #if defined(USE_DUKTAPE)
  17684. mg_snprintf(NULL,
  17685. NULL,
  17686. block,
  17687. sizeof(block),
  17688. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17689. eol,
  17690. (unsigned)DUK_VERSION / 10000,
  17691. ((unsigned)DUK_VERSION / 100) % 100,
  17692. (unsigned)DUK_VERSION % 100);
  17693. system_info_length += mg_str_append(&buffer, end, block);
  17694. #endif
  17695. }
  17696. /* Build date */
  17697. {
  17698. #if defined(GCC_DIAGNOSTIC)
  17699. #if GCC_VERSION >= 40900
  17700. #pragma GCC diagnostic push
  17701. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17702. #pragma GCC diagnostic ignored "-Wdate-time"
  17703. #endif
  17704. #endif
  17705. mg_snprintf(NULL,
  17706. NULL,
  17707. block,
  17708. sizeof(block),
  17709. ",%s\"build\" : \"%s\"",
  17710. eol,
  17711. __DATE__);
  17712. #if defined(GCC_DIAGNOSTIC)
  17713. #if GCC_VERSION >= 40900
  17714. #pragma GCC diagnostic pop
  17715. #endif
  17716. #endif
  17717. system_info_length += mg_str_append(&buffer, end, block);
  17718. }
  17719. /* Compiler information */
  17720. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17721. {
  17722. #if defined(_MSC_VER)
  17723. mg_snprintf(NULL,
  17724. NULL,
  17725. block,
  17726. sizeof(block),
  17727. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17728. eol,
  17729. (unsigned)_MSC_VER,
  17730. (unsigned)_MSC_FULL_VER);
  17731. system_info_length += mg_str_append(&buffer, end, block);
  17732. #elif defined(__MINGW64__)
  17733. mg_snprintf(NULL,
  17734. NULL,
  17735. block,
  17736. sizeof(block),
  17737. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17738. eol,
  17739. (unsigned)__MINGW64_VERSION_MAJOR,
  17740. (unsigned)__MINGW64_VERSION_MINOR);
  17741. system_info_length += mg_str_append(&buffer, end, block);
  17742. mg_snprintf(NULL,
  17743. NULL,
  17744. block,
  17745. sizeof(block),
  17746. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17747. eol,
  17748. (unsigned)__MINGW32_MAJOR_VERSION,
  17749. (unsigned)__MINGW32_MINOR_VERSION);
  17750. system_info_length += mg_str_append(&buffer, end, block);
  17751. #elif defined(__MINGW32__)
  17752. mg_snprintf(NULL,
  17753. NULL,
  17754. block,
  17755. sizeof(block),
  17756. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17757. eol,
  17758. (unsigned)__MINGW32_MAJOR_VERSION,
  17759. (unsigned)__MINGW32_MINOR_VERSION);
  17760. system_info_length += mg_str_append(&buffer, end, block);
  17761. #elif defined(__clang__)
  17762. mg_snprintf(NULL,
  17763. NULL,
  17764. block,
  17765. sizeof(block),
  17766. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17767. eol,
  17768. __clang_major__,
  17769. __clang_minor__,
  17770. __clang_patchlevel__,
  17771. __clang_version__);
  17772. system_info_length += mg_str_append(&buffer, end, block);
  17773. #elif defined(__GNUC__)
  17774. mg_snprintf(NULL,
  17775. NULL,
  17776. block,
  17777. sizeof(block),
  17778. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17779. eol,
  17780. (unsigned)__GNUC__,
  17781. (unsigned)__GNUC_MINOR__,
  17782. (unsigned)__GNUC_PATCHLEVEL__);
  17783. system_info_length += mg_str_append(&buffer, end, block);
  17784. #elif defined(__INTEL_COMPILER)
  17785. mg_snprintf(NULL,
  17786. NULL,
  17787. block,
  17788. sizeof(block),
  17789. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17790. eol,
  17791. (unsigned)__INTEL_COMPILER);
  17792. system_info_length += mg_str_append(&buffer, end, block);
  17793. #elif defined(__BORLANDC__)
  17794. mg_snprintf(NULL,
  17795. NULL,
  17796. block,
  17797. sizeof(block),
  17798. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17799. eol,
  17800. (unsigned)__BORLANDC__);
  17801. system_info_length += mg_str_append(&buffer, end, block);
  17802. #elif defined(__SUNPRO_C)
  17803. mg_snprintf(NULL,
  17804. NULL,
  17805. block,
  17806. sizeof(block),
  17807. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17808. eol,
  17809. (unsigned)__SUNPRO_C);
  17810. system_info_length += mg_str_append(&buffer, end, block);
  17811. #else
  17812. mg_snprintf(NULL,
  17813. NULL,
  17814. block,
  17815. sizeof(block),
  17816. ",%s\"compiler\" : \"other\"",
  17817. eol);
  17818. system_info_length += mg_str_append(&buffer, end, block);
  17819. #endif
  17820. }
  17821. /* Determine 32/64 bit data mode.
  17822. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17823. {
  17824. mg_snprintf(NULL,
  17825. NULL,
  17826. block,
  17827. sizeof(block),
  17828. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17829. "char:%u/%u, "
  17830. "ptr:%u, size:%u, time:%u\"",
  17831. eol,
  17832. (unsigned)sizeof(short),
  17833. (unsigned)sizeof(int),
  17834. (unsigned)sizeof(long),
  17835. (unsigned)sizeof(long long),
  17836. (unsigned)sizeof(float),
  17837. (unsigned)sizeof(double),
  17838. (unsigned)sizeof(long double),
  17839. (unsigned)sizeof(char),
  17840. (unsigned)sizeof(wchar_t),
  17841. (unsigned)sizeof(void *),
  17842. (unsigned)sizeof(size_t),
  17843. (unsigned)sizeof(time_t));
  17844. system_info_length += mg_str_append(&buffer, end, block);
  17845. }
  17846. /* Terminate string */
  17847. if (append_eoobj) {
  17848. strcat(append_eoobj, eoobj);
  17849. }
  17850. system_info_length += sizeof(eoobj) - 1;
  17851. return (int)system_info_length;
  17852. }
  17853. /* Get context information. It can be printed or stored by the caller.
  17854. * Return the size of available information. */
  17855. int
  17856. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17857. {
  17858. #if defined(USE_SERVER_STATS)
  17859. char *end, *append_eoobj = NULL, block[256];
  17860. size_t context_info_length = 0;
  17861. #if defined(_WIN32)
  17862. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17863. #else
  17864. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17865. #endif
  17866. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17867. if ((buffer == NULL) || (buflen < 1)) {
  17868. buflen = 0;
  17869. end = buffer;
  17870. } else {
  17871. *buffer = 0;
  17872. end = buffer + buflen;
  17873. }
  17874. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17875. /* has enough space to append eoobj */
  17876. append_eoobj = buffer;
  17877. end -= sizeof(eoobj) - 1;
  17878. }
  17879. context_info_length += mg_str_append(&buffer, end, "{");
  17880. if (ms) { /* <-- should be always true */
  17881. /* Memory information */
  17882. mg_snprintf(NULL,
  17883. NULL,
  17884. block,
  17885. sizeof(block),
  17886. "%s\"memory\" : {%s"
  17887. "\"blocks\" : %i,%s"
  17888. "\"used\" : %" INT64_FMT ",%s"
  17889. "\"maxUsed\" : %" INT64_FMT "%s"
  17890. "}",
  17891. eol,
  17892. eol,
  17893. ms->blockCount,
  17894. eol,
  17895. ms->totalMemUsed,
  17896. eol,
  17897. ms->maxMemUsed,
  17898. eol);
  17899. context_info_length += mg_str_append(&buffer, end, block);
  17900. }
  17901. if (ctx) {
  17902. /* Declare all variables at begin of the block, to comply
  17903. * with old C standards. */
  17904. char start_time_str[64] = {0};
  17905. char now_str[64] = {0};
  17906. time_t start_time = ctx->start_time;
  17907. time_t now = time(NULL);
  17908. /* Connections information */
  17909. mg_snprintf(NULL,
  17910. NULL,
  17911. block,
  17912. sizeof(block),
  17913. ",%s\"connections\" : {%s"
  17914. "\"active\" : %i,%s"
  17915. "\"maxActive\" : %i,%s"
  17916. "\"total\" : %" INT64_FMT "%s"
  17917. "}",
  17918. eol,
  17919. eol,
  17920. ctx->active_connections,
  17921. eol,
  17922. ctx->max_active_connections,
  17923. eol,
  17924. ctx->total_connections,
  17925. eol);
  17926. context_info_length += mg_str_append(&buffer, end, block);
  17927. /* Queue information */
  17928. #if !defined(ALTERNATIVE_QUEUE)
  17929. mg_snprintf(NULL,
  17930. NULL,
  17931. block,
  17932. sizeof(block),
  17933. ",%s\"queue\" : {%s"
  17934. "\"length\" : %i,%s"
  17935. "\"filled\" : %i,%s"
  17936. "\"maxFilled\" : %i,%s"
  17937. "\"full\" : %s%s"
  17938. "}",
  17939. eol,
  17940. eol,
  17941. ctx->sq_size,
  17942. eol,
  17943. ctx->sq_head - ctx->sq_tail,
  17944. eol,
  17945. ctx->sq_max_fill,
  17946. eol,
  17947. (ctx->sq_blocked ? "true" : "false"),
  17948. eol);
  17949. context_info_length += mg_str_append(&buffer, end, block);
  17950. #endif
  17951. /* Requests information */
  17952. mg_snprintf(NULL,
  17953. NULL,
  17954. block,
  17955. sizeof(block),
  17956. ",%s\"requests\" : {%s"
  17957. "\"total\" : %" INT64_FMT "%s"
  17958. "}",
  17959. eol,
  17960. eol,
  17961. ctx->total_requests,
  17962. eol);
  17963. context_info_length += mg_str_append(&buffer, end, block);
  17964. /* Data information */
  17965. mg_snprintf(NULL,
  17966. NULL,
  17967. block,
  17968. sizeof(block),
  17969. ",%s\"data\" : {%s"
  17970. "\"read\" : %" INT64_FMT ",%s"
  17971. "\"written\" : %" INT64_FMT "%s"
  17972. "}",
  17973. eol,
  17974. eol,
  17975. ctx->total_data_read,
  17976. eol,
  17977. ctx->total_data_written,
  17978. eol);
  17979. context_info_length += mg_str_append(&buffer, end, block);
  17980. /* Execution time information */
  17981. gmt_time_string(start_time_str,
  17982. sizeof(start_time_str) - 1,
  17983. &start_time);
  17984. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17985. mg_snprintf(NULL,
  17986. NULL,
  17987. block,
  17988. sizeof(block),
  17989. ",%s\"time\" : {%s"
  17990. "\"uptime\" : %.0f,%s"
  17991. "\"start\" : \"%s\",%s"
  17992. "\"now\" : \"%s\"%s"
  17993. "}",
  17994. eol,
  17995. eol,
  17996. difftime(now, start_time),
  17997. eol,
  17998. start_time_str,
  17999. eol,
  18000. now_str,
  18001. eol);
  18002. context_info_length += mg_str_append(&buffer, end, block);
  18003. }
  18004. /* Terminate string */
  18005. if (append_eoobj) {
  18006. strcat(append_eoobj, eoobj);
  18007. }
  18008. context_info_length += sizeof(eoobj) - 1;
  18009. return (int)context_info_length;
  18010. #else
  18011. (void)ctx;
  18012. if ((buffer != NULL) && (buflen > 0)) {
  18013. *buffer = 0;
  18014. }
  18015. return 0;
  18016. #endif
  18017. }
  18018. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18019. /* Get connection information. It can be printed or stored by the caller.
  18020. * Return the size of available information. */
  18021. int
  18022. mg_get_connection_info(const struct mg_context *ctx,
  18023. int idx,
  18024. char *buffer,
  18025. int buflen)
  18026. {
  18027. const struct mg_connection *conn;
  18028. const struct mg_request_info *ri;
  18029. char *end, *append_eoobj = NULL, block[256];
  18030. size_t connection_info_length = 0;
  18031. int state = 0;
  18032. const char *state_str = "unknown";
  18033. #if defined(_WIN32)
  18034. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18035. #else
  18036. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18037. #endif
  18038. if ((buffer == NULL) || (buflen < 1)) {
  18039. buflen = 0;
  18040. end = buffer;
  18041. } else {
  18042. *buffer = 0;
  18043. end = buffer + buflen;
  18044. }
  18045. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18046. /* has enough space to append eoobj */
  18047. append_eoobj = buffer;
  18048. end -= sizeof(eoobj) - 1;
  18049. }
  18050. if ((ctx == NULL) || (idx < 0)) {
  18051. /* Parameter error */
  18052. return 0;
  18053. }
  18054. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18055. /* Out of range */
  18056. return 0;
  18057. }
  18058. /* Take connection [idx]. This connection is not locked in
  18059. * any way, so some other thread might use it. */
  18060. conn = (ctx->worker_connections) + idx;
  18061. /* Initialize output string */
  18062. connection_info_length += mg_str_append(&buffer, end, "{");
  18063. /* Init variables */
  18064. ri = &(conn->request_info);
  18065. #if defined(USE_SERVER_STATS)
  18066. state = conn->conn_state;
  18067. /* State as string */
  18068. switch (state) {
  18069. case 0:
  18070. state_str = "undefined";
  18071. break;
  18072. case 1:
  18073. state_str = "not used";
  18074. break;
  18075. case 2:
  18076. state_str = "init";
  18077. break;
  18078. case 3:
  18079. state_str = "ready";
  18080. break;
  18081. case 4:
  18082. state_str = "processing";
  18083. break;
  18084. case 5:
  18085. state_str = "processed";
  18086. break;
  18087. case 6:
  18088. state_str = "to close";
  18089. break;
  18090. case 7:
  18091. state_str = "closing";
  18092. break;
  18093. case 8:
  18094. state_str = "closed";
  18095. break;
  18096. case 9:
  18097. state_str = "done";
  18098. break;
  18099. }
  18100. #endif
  18101. /* Connection info */
  18102. if ((state >= 3) && (state < 9)) {
  18103. mg_snprintf(NULL,
  18104. NULL,
  18105. block,
  18106. sizeof(block),
  18107. "%s\"connection\" : {%s"
  18108. "\"remote\" : {%s"
  18109. "\"protocol\" : \"%s\",%s"
  18110. "\"addr\" : \"%s\",%s"
  18111. "\"port\" : %u%s"
  18112. "},%s"
  18113. "\"handled_requests\" : %u%s"
  18114. "}",
  18115. eol,
  18116. eol,
  18117. eol,
  18118. get_proto_name(conn),
  18119. eol,
  18120. ri->remote_addr,
  18121. eol,
  18122. ri->remote_port,
  18123. eol,
  18124. eol,
  18125. conn->handled_requests,
  18126. eol);
  18127. connection_info_length += mg_str_append(&buffer, end, block);
  18128. }
  18129. /* Request info */
  18130. if ((state >= 4) && (state < 6)) {
  18131. mg_snprintf(NULL,
  18132. NULL,
  18133. block,
  18134. sizeof(block),
  18135. "%s%s\"request_info\" : {%s"
  18136. "\"method\" : \"%s\",%s"
  18137. "\"uri\" : \"%s\",%s"
  18138. "\"query\" : %s%s%s%s"
  18139. "}",
  18140. (connection_info_length > 1 ? "," : ""),
  18141. eol,
  18142. eol,
  18143. ri->request_method,
  18144. eol,
  18145. ri->request_uri,
  18146. eol,
  18147. ri->query_string ? "\"" : "",
  18148. ri->query_string ? ri->query_string : "null",
  18149. ri->query_string ? "\"" : "",
  18150. eol);
  18151. connection_info_length += mg_str_append(&buffer, end, block);
  18152. }
  18153. /* Execution time information */
  18154. if ((state >= 2) && (state < 9)) {
  18155. char start_time_str[64] = {0};
  18156. char close_time_str[64] = {0};
  18157. time_t start_time = conn->conn_birth_time;
  18158. time_t close_time = 0;
  18159. double time_diff;
  18160. gmt_time_string(start_time_str,
  18161. sizeof(start_time_str) - 1,
  18162. &start_time);
  18163. #if defined(USE_SERVER_STATS)
  18164. close_time = conn->conn_close_time;
  18165. #endif
  18166. if (close_time != 0) {
  18167. time_diff = difftime(close_time, start_time);
  18168. gmt_time_string(close_time_str,
  18169. sizeof(close_time_str) - 1,
  18170. &close_time);
  18171. } else {
  18172. time_t now = time(NULL);
  18173. time_diff = difftime(now, start_time);
  18174. close_time_str[0] = 0; /* or use "now" ? */
  18175. }
  18176. mg_snprintf(NULL,
  18177. NULL,
  18178. block,
  18179. sizeof(block),
  18180. "%s%s\"time\" : {%s"
  18181. "\"uptime\" : %.0f,%s"
  18182. "\"start\" : \"%s\",%s"
  18183. "\"closed\" : \"%s\"%s"
  18184. "}",
  18185. (connection_info_length > 1 ? "," : ""),
  18186. eol,
  18187. eol,
  18188. time_diff,
  18189. eol,
  18190. start_time_str,
  18191. eol,
  18192. close_time_str,
  18193. eol);
  18194. connection_info_length += mg_str_append(&buffer, end, block);
  18195. }
  18196. /* Remote user name */
  18197. if ((ri->remote_user) && (state < 9)) {
  18198. mg_snprintf(NULL,
  18199. NULL,
  18200. block,
  18201. sizeof(block),
  18202. "%s%s\"user\" : {%s"
  18203. "\"name\" : \"%s\",%s"
  18204. "}",
  18205. (connection_info_length > 1 ? "," : ""),
  18206. eol,
  18207. eol,
  18208. ri->remote_user,
  18209. eol);
  18210. connection_info_length += mg_str_append(&buffer, end, block);
  18211. }
  18212. /* Data block */
  18213. if (state >= 3) {
  18214. mg_snprintf(NULL,
  18215. NULL,
  18216. block,
  18217. sizeof(block),
  18218. "%s%s\"data\" : {%s"
  18219. "\"read\" : %" INT64_FMT ",%s"
  18220. "\"written\" : %" INT64_FMT "%s"
  18221. "}",
  18222. (connection_info_length > 1 ? "," : ""),
  18223. eol,
  18224. eol,
  18225. conn->consumed_content,
  18226. eol,
  18227. conn->num_bytes_sent,
  18228. eol);
  18229. connection_info_length += mg_str_append(&buffer, end, block);
  18230. }
  18231. /* State */
  18232. mg_snprintf(NULL,
  18233. NULL,
  18234. block,
  18235. sizeof(block),
  18236. "%s%s\"state\" : \"%s\"",
  18237. (connection_info_length > 1 ? "," : ""),
  18238. eol,
  18239. state_str);
  18240. connection_info_length += mg_str_append(&buffer, end, block);
  18241. /* Terminate string */
  18242. if (append_eoobj) {
  18243. strcat(append_eoobj, eoobj);
  18244. }
  18245. connection_info_length += sizeof(eoobj) - 1;
  18246. return (int)connection_info_length;
  18247. }
  18248. #endif
  18249. /* Initialize this library. This function does not need to be thread safe.
  18250. */
  18251. unsigned
  18252. mg_init_library(unsigned features)
  18253. {
  18254. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18255. unsigned features_inited = features_to_init;
  18256. if (mg_init_library_called <= 0) {
  18257. /* Not initialized yet */
  18258. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18259. return 0;
  18260. }
  18261. }
  18262. mg_global_lock();
  18263. if (mg_init_library_called <= 0) {
  18264. #if defined(_WIN32)
  18265. int file_mutex_init = 1;
  18266. int wsa = 1;
  18267. #else
  18268. int mutexattr_init = 1;
  18269. #endif
  18270. int failed = 1;
  18271. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18272. if (key_create == 0) {
  18273. #if defined(_WIN32)
  18274. file_mutex_init =
  18275. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18276. if (file_mutex_init == 0) {
  18277. /* Start WinSock */
  18278. WSADATA data;
  18279. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18280. }
  18281. #else
  18282. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18283. if (mutexattr_init == 0) {
  18284. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18285. PTHREAD_MUTEX_RECURSIVE);
  18286. }
  18287. #endif
  18288. }
  18289. if (failed) {
  18290. #if defined(_WIN32)
  18291. if (wsa == 0) {
  18292. (void)WSACleanup();
  18293. }
  18294. if (file_mutex_init == 0) {
  18295. (void)pthread_mutex_destroy(&global_log_file_lock);
  18296. }
  18297. #else
  18298. if (mutexattr_init == 0) {
  18299. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18300. }
  18301. #endif
  18302. if (key_create == 0) {
  18303. (void)pthread_key_delete(sTlsKey);
  18304. }
  18305. mg_global_unlock();
  18306. (void)pthread_mutex_destroy(&global_lock_mutex);
  18307. return 0;
  18308. }
  18309. #if defined(USE_LUA)
  18310. lua_init_optional_libraries();
  18311. #endif
  18312. }
  18313. mg_global_unlock();
  18314. #if !defined(NO_SSL)
  18315. if (features_to_init & MG_FEATURES_SSL) {
  18316. if (!mg_ssl_initialized) {
  18317. char ebuf[128];
  18318. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18319. mg_ssl_initialized = 1;
  18320. } else {
  18321. (void)ebuf;
  18322. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18323. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18324. }
  18325. } else {
  18326. /* ssl already initialized */
  18327. }
  18328. }
  18329. #endif
  18330. mg_global_lock();
  18331. if (mg_init_library_called <= 0) {
  18332. mg_init_library_called = 1;
  18333. } else {
  18334. mg_init_library_called++;
  18335. }
  18336. mg_global_unlock();
  18337. return features_inited;
  18338. }
  18339. /* Un-initialize this library. */
  18340. unsigned
  18341. mg_exit_library(void)
  18342. {
  18343. if (mg_init_library_called <= 0) {
  18344. return 0;
  18345. }
  18346. mg_global_lock();
  18347. mg_init_library_called--;
  18348. if (mg_init_library_called == 0) {
  18349. #if !defined(NO_SSL)
  18350. if (mg_ssl_initialized) {
  18351. uninitialize_ssl();
  18352. mg_ssl_initialized = 0;
  18353. }
  18354. #endif
  18355. #if defined(_WIN32)
  18356. (void)WSACleanup();
  18357. (void)pthread_mutex_destroy(&global_log_file_lock);
  18358. #else
  18359. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18360. #endif
  18361. (void)pthread_key_delete(sTlsKey);
  18362. #if defined(USE_LUA)
  18363. lua_exit_optional_libraries();
  18364. #endif
  18365. mg_global_unlock();
  18366. (void)pthread_mutex_destroy(&global_lock_mutex);
  18367. return 1;
  18368. }
  18369. mg_global_unlock();
  18370. return 1;
  18371. }
  18372. /* End of civetweb.c */