civetweb.c 566 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132
  1. /* Copyright (c) 2013-2020 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE 8096
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #ifndef DEBUG_TRACE_STREAM
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. /********************************************************************/
  369. /* CivetWeb configuration defines */
  370. /********************************************************************/
  371. /* Maximum number of threads that can be configured.
  372. * The number of threads actually created depends on the "num_threads"
  373. * configuration parameter, but this is the upper limit. */
  374. #if !defined(MAX_WORKER_THREADS)
  375. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  376. #endif
  377. /* Timeout interval for select/poll calls.
  378. * The timeouts depend on "*_timeout_ms" configuration values, but long
  379. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  380. * This reduces the time required to stop the server. */
  381. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  382. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  383. #endif
  384. /* Do not try to compress files smaller than this limit. */
  385. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  386. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  387. #endif
  388. #if !defined(PASSWORDS_FILE_NAME)
  389. #define PASSWORDS_FILE_NAME ".htpasswd"
  390. #endif
  391. /* Initial buffer size for all CGI environment variables. In case there is
  392. * not enough space, another block is allocated. */
  393. #if !defined(CGI_ENVIRONMENT_SIZE)
  394. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  395. #endif
  396. /* Maximum number of environment variables. */
  397. #if !defined(MAX_CGI_ENVIR_VARS)
  398. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  399. #endif
  400. /* General purpose buffer size. */
  401. #if !defined(MG_BUF_LEN) /* in bytes */
  402. #define MG_BUF_LEN (1024 * 8)
  403. #endif
  404. /********************************************************************/
  405. /* Helper makros */
  406. #if !defined(ARRAY_SIZE)
  407. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  408. #endif
  409. #include <stdint.h>
  410. /* Standard defines */
  411. #if !defined(INT64_MAX)
  412. #define INT64_MAX (9223372036854775807)
  413. #endif
  414. #define SHUTDOWN_RD (0)
  415. #define SHUTDOWN_WR (1)
  416. #define SHUTDOWN_BOTH (2)
  417. mg_static_assert(MAX_WORKER_THREADS >= 1,
  418. "worker threads must be a positive number");
  419. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  420. "size_t data type size check");
  421. #if defined(_WIN32) /* WINDOWS include block */
  422. #include <malloc.h> /* *alloc( */
  423. #include <stdlib.h> /* *alloc( */
  424. #include <time.h> /* struct timespec */
  425. #include <windows.h>
  426. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  427. #include <ws2tcpip.h>
  428. typedef const char *SOCK_OPT_TYPE;
  429. #if !defined(PATH_MAX)
  430. #define W_PATH_MAX (MAX_PATH)
  431. /* at most three UTF-8 chars per wchar_t */
  432. #define PATH_MAX (W_PATH_MAX * 3)
  433. #else
  434. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  435. #endif
  436. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  437. #if !defined(_IN_PORT_T)
  438. #if !defined(in_port_t)
  439. #define in_port_t u_short
  440. #endif
  441. #endif
  442. #if !defined(_WIN32_WCE)
  443. #include <direct.h>
  444. #include <io.h>
  445. #include <process.h>
  446. #else /* _WIN32_WCE */
  447. #define NO_CGI /* WinCE has no pipes */
  448. #define NO_POPEN /* WinCE has no popen */
  449. typedef long off_t;
  450. #define errno ((int)(GetLastError()))
  451. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  452. #endif /* _WIN32_WCE */
  453. #define MAKEUQUAD(lo, hi) \
  454. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  455. #define RATE_DIFF (10000000) /* 100 nsecs */
  456. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  457. #define SYS2UNIX_TIME(lo, hi) \
  458. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  459. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  460. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  461. * Also use _strtoui64 on modern M$ compilers */
  462. #if defined(_MSC_VER)
  463. #if (_MSC_VER < 1300)
  464. #define STRX(x) #x
  465. #define STR(x) STRX(x)
  466. #define __func__ __FILE__ ":" STR(__LINE__)
  467. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  468. #define strtoll(x, y, z) (_atoi64(x))
  469. #else
  470. #define __func__ __FUNCTION__
  471. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  472. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  473. #endif
  474. #endif /* _MSC_VER */
  475. #define ERRNO ((int)(GetLastError()))
  476. #define NO_SOCKLEN_T
  477. #if defined(_WIN64) || defined(__MINGW64__)
  478. #if !defined(SSL_LIB)
  479. #if defined(OPENSSL_API_1_1)
  480. #define SSL_LIB "libssl-1_1-x64.dll"
  481. #else /* OPENSSL_API_1_1 */
  482. #define SSL_LIB "ssleay64.dll"
  483. #endif /* OPENSSL_API_1_1 */
  484. #endif /* SSL_LIB */
  485. #if !defined(CRYPTO_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  488. #else /* OPENSSL_API_1_1 */
  489. #define CRYPTO_LIB "libeay64.dll"
  490. #endif /* OPENSSL_API_1_1 */
  491. #endif /* CRYPTO_LIB */
  492. #else /* defined(_WIN64) || defined(__MINGW64__) */
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1.dll"
  496. #else
  497. #define SSL_LIB "ssleay32.dll"
  498. #endif
  499. #endif /* SSL_LIB */
  500. #if !defined(CRYPTO_LIB)
  501. #if defined(OPENSSL_API_1_1)
  502. #define CRYPTO_LIB "libcrypto-1_1.dll"
  503. #else
  504. #define CRYPTO_LIB "libeay32.dll"
  505. #endif
  506. #endif /* CRYPTO_LIB */
  507. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  508. #define O_NONBLOCK (0)
  509. #if !defined(W_OK)
  510. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  511. #endif
  512. #define _POSIX_
  513. #define INT64_FMT "I64d"
  514. #define UINT64_FMT "I64u"
  515. #define WINCDECL __cdecl
  516. #define vsnprintf_impl _vsnprintf
  517. #define access _access
  518. #define mg_sleep(x) (Sleep(x))
  519. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  520. #if !defined(popen)
  521. #define popen(x, y) (_popen(x, y))
  522. #endif
  523. #if !defined(pclose)
  524. #define pclose(x) (_pclose(x))
  525. #endif
  526. #define close(x) (_close(x))
  527. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  528. #define RTLD_LAZY (0)
  529. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  530. #define fdopen(x, y) (_fdopen((x), (y)))
  531. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  532. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  533. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  534. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  535. #define sleep(x) (Sleep((x)*1000))
  536. #define rmdir(x) (_rmdir(x))
  537. #if defined(_WIN64) || !defined(__MINGW32__)
  538. /* Only MinGW 32 bit is missing this function */
  539. #define timegm(x) (_mkgmtime(x))
  540. #else
  541. time_t timegm(struct tm *tm);
  542. #define NEED_TIMEGM
  543. #endif
  544. #if !defined(fileno)
  545. #define fileno(x) (_fileno(x))
  546. #endif /* !fileno MINGW #defines fileno */
  547. typedef struct {
  548. CRITICAL_SECTION sec; /* Immovable */
  549. } pthread_mutex_t;
  550. typedef DWORD pthread_key_t;
  551. typedef HANDLE pthread_t;
  552. typedef struct {
  553. pthread_mutex_t threadIdSec;
  554. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  555. } pthread_cond_t;
  556. #if !defined(__clockid_t_defined)
  557. typedef DWORD clockid_t;
  558. #endif
  559. #if !defined(CLOCK_MONOTONIC)
  560. #define CLOCK_MONOTONIC (1)
  561. #endif
  562. #if !defined(CLOCK_REALTIME)
  563. #define CLOCK_REALTIME (2)
  564. #endif
  565. #if !defined(CLOCK_THREAD)
  566. #define CLOCK_THREAD (3)
  567. #endif
  568. #if !defined(CLOCK_PROCESS)
  569. #define CLOCK_PROCESS (4)
  570. #endif
  571. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  572. #define _TIMESPEC_DEFINED
  573. #endif
  574. #if !defined(_TIMESPEC_DEFINED)
  575. struct timespec {
  576. time_t tv_sec; /* seconds */
  577. long tv_nsec; /* nanoseconds */
  578. };
  579. #endif
  580. #if !defined(WIN_PTHREADS_TIME_H)
  581. #define MUST_IMPLEMENT_CLOCK_GETTIME
  582. #endif
  583. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  584. #define clock_gettime mg_clock_gettime
  585. static int
  586. clock_gettime(clockid_t clk_id, struct timespec *tp)
  587. {
  588. FILETIME ft;
  589. ULARGE_INTEGER li, li2;
  590. BOOL ok = FALSE;
  591. double d;
  592. static double perfcnt_per_sec = 0.0;
  593. static BOOL initialized = FALSE;
  594. if (!initialized) {
  595. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  596. perfcnt_per_sec = 1.0 / li.QuadPart;
  597. initialized = TRUE;
  598. }
  599. if (tp) {
  600. memset(tp, 0, sizeof(*tp));
  601. if (clk_id == CLOCK_REALTIME) {
  602. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  603. GetSystemTimeAsFileTime(&ft);
  604. li.LowPart = ft.dwLowDateTime;
  605. li.HighPart = ft.dwHighDateTime;
  606. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  607. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  608. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  609. ok = TRUE;
  610. /* END: CLOCK_REALTIME */
  611. } else if (clk_id == CLOCK_MONOTONIC) {
  612. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  613. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  614. d = li.QuadPart * perfcnt_per_sec;
  615. tp->tv_sec = (time_t)d;
  616. d -= (double)tp->tv_sec;
  617. tp->tv_nsec = (long)(d * 1.0E9);
  618. ok = TRUE;
  619. /* END: CLOCK_MONOTONIC */
  620. } else if (clk_id == CLOCK_THREAD) {
  621. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  622. FILETIME t_create, t_exit, t_kernel, t_user;
  623. if (GetThreadTimes(GetCurrentThread(),
  624. &t_create,
  625. &t_exit,
  626. &t_kernel,
  627. &t_user)) {
  628. li.LowPart = t_user.dwLowDateTime;
  629. li.HighPart = t_user.dwHighDateTime;
  630. li2.LowPart = t_kernel.dwLowDateTime;
  631. li2.HighPart = t_kernel.dwHighDateTime;
  632. li.QuadPart += li2.QuadPart;
  633. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  634. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  635. ok = TRUE;
  636. }
  637. /* END: CLOCK_THREAD */
  638. } else if (clk_id == CLOCK_PROCESS) {
  639. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetProcessTimes(GetCurrentProcess(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_PROCESS */
  656. } else {
  657. /* BEGIN: unknown clock */
  658. /* ok = FALSE; already set by init */
  659. /* END: unknown clock */
  660. }
  661. }
  662. return ok ? 0 : -1;
  663. }
  664. #endif
  665. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  666. static int pthread_mutex_lock(pthread_mutex_t *);
  667. static int pthread_mutex_unlock(pthread_mutex_t *);
  668. static void path_to_unicode(const struct mg_connection *conn,
  669. const char *path,
  670. wchar_t *wbuf,
  671. size_t wbuf_len);
  672. /* All file operations need to be rewritten to solve #246. */
  673. struct mg_file;
  674. static const char *
  675. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  676. /* POSIX dirent interface */
  677. struct dirent {
  678. char d_name[PATH_MAX];
  679. };
  680. typedef struct DIR {
  681. HANDLE handle;
  682. WIN32_FIND_DATAW info;
  683. struct dirent result;
  684. } DIR;
  685. #if defined(HAVE_POLL)
  686. #define mg_pollfd pollfd
  687. #else
  688. struct mg_pollfd {
  689. SOCKET fd;
  690. short events;
  691. short revents;
  692. };
  693. #endif
  694. /* Mark required libraries */
  695. #if defined(_MSC_VER)
  696. #pragma comment(lib, "Ws2_32.lib")
  697. #endif
  698. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  699. #include <inttypes.h>
  700. typedef const void *SOCK_OPT_TYPE;
  701. #if defined(ANDROID)
  702. typedef unsigned short int in_port_t;
  703. #endif
  704. #if !defined(__ZEPHYR__)
  705. #include <arpa/inet.h>
  706. #include <ctype.h>
  707. #include <dirent.h>
  708. #include <grp.h>
  709. #include <limits.h>
  710. #include <netdb.h>
  711. #include <netinet/in.h>
  712. #include <netinet/tcp.h>
  713. #include <pthread.h>
  714. #include <pwd.h>
  715. #include <stdarg.h>
  716. #include <stddef.h>
  717. #include <stdio.h>
  718. #include <stdlib.h>
  719. #include <string.h>
  720. #include <sys/poll.h>
  721. #include <sys/socket.h>
  722. #include <sys/time.h>
  723. #include <sys/utsname.h>
  724. #include <sys/wait.h>
  725. #include <time.h>
  726. #include <unistd.h>
  727. #endif
  728. #define vsnprintf_impl vsnprintf
  729. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  730. #include <dlfcn.h>
  731. #endif
  732. #if defined(__MACH__)
  733. #define SSL_LIB "libssl.dylib"
  734. #define CRYPTO_LIB "libcrypto.dylib"
  735. #else
  736. #if !defined(SSL_LIB)
  737. #define SSL_LIB "libssl.so"
  738. #endif
  739. #if !defined(CRYPTO_LIB)
  740. #define CRYPTO_LIB "libcrypto.so"
  741. #endif
  742. #endif
  743. #if !defined(O_BINARY)
  744. #define O_BINARY (0)
  745. #endif /* O_BINARY */
  746. #define closesocket(a) (close(a))
  747. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  748. #define mg_remove(conn, x) (remove(x))
  749. #define mg_sleep(x) (usleep((x)*1000))
  750. #define mg_opendir(conn, x) (opendir(x))
  751. #define mg_closedir(x) (closedir(x))
  752. #define mg_readdir(x) (readdir(x))
  753. #define ERRNO (errno)
  754. #define INVALID_SOCKET (-1)
  755. #define INT64_FMT PRId64
  756. #define UINT64_FMT PRIu64
  757. typedef int SOCKET;
  758. #define WINCDECL
  759. #if defined(__hpux)
  760. /* HPUX 11 does not have monotonic, fall back to realtime */
  761. #if !defined(CLOCK_MONOTONIC)
  762. #define CLOCK_MONOTONIC CLOCK_REALTIME
  763. #endif
  764. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  765. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  766. * the prototypes use int* rather than socklen_t* which matches the
  767. * actual library expectation. When called with the wrong size arg
  768. * accept() returns a zero client inet addr and check_acl() always
  769. * fails. Since socklen_t is widely used below, just force replace
  770. * their typedef with int. - DTL
  771. */
  772. #define socklen_t int
  773. #endif /* hpux */
  774. #define mg_pollfd pollfd
  775. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  776. /* In case our C library is missing "timegm", provide an implementation */
  777. #if defined(NEED_TIMEGM)
  778. static inline int
  779. is_leap(int y)
  780. {
  781. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  782. }
  783. static inline int
  784. count_leap(int y)
  785. {
  786. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  787. }
  788. time_t
  789. timegm(struct tm *tm)
  790. {
  791. static const unsigned short ydays[] = {
  792. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  793. int year = tm->tm_year + 1900;
  794. int mon = tm->tm_mon;
  795. int mday = tm->tm_mday - 1;
  796. int hour = tm->tm_hour;
  797. int min = tm->tm_min;
  798. int sec = tm->tm_sec;
  799. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  800. || (mday >= ydays[mon + 1] - ydays[mon]
  801. + (mon == 1 && is_leap(year) ? 1 : 0))
  802. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  803. return -1;
  804. time_t res = year - 1970;
  805. res *= 365;
  806. res += mday;
  807. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  808. res += count_leap(year);
  809. res *= 24;
  810. res += hour;
  811. res *= 60;
  812. res += min;
  813. res *= 60;
  814. res += sec;
  815. return res;
  816. }
  817. #endif /* NEED_TIMEGM */
  818. /* va_copy should always be a macro, C99 and C++11 - DTL */
  819. #if !defined(va_copy)
  820. #define va_copy(x, y) ((x) = (y))
  821. #endif
  822. #if defined(_WIN32)
  823. /* Create substitutes for POSIX functions in Win32. */
  824. #if defined(GCC_DIAGNOSTIC)
  825. /* Show no warning in case system functions are not used. */
  826. #pragma GCC diagnostic push
  827. #pragma GCC diagnostic ignored "-Wunused-function"
  828. #endif
  829. static pthread_mutex_t global_log_file_lock;
  830. FUNCTION_MAY_BE_UNUSED
  831. static DWORD
  832. pthread_self(void)
  833. {
  834. return GetCurrentThreadId();
  835. }
  836. FUNCTION_MAY_BE_UNUSED
  837. static int
  838. pthread_key_create(
  839. pthread_key_t *key,
  840. void (*_ignored)(void *) /* destructor not supported for Windows */
  841. )
  842. {
  843. (void)_ignored;
  844. if ((key != 0)) {
  845. *key = TlsAlloc();
  846. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  847. }
  848. return -2;
  849. }
  850. FUNCTION_MAY_BE_UNUSED
  851. static int
  852. pthread_key_delete(pthread_key_t key)
  853. {
  854. return TlsFree(key) ? 0 : 1;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. pthread_setspecific(pthread_key_t key, void *value)
  859. {
  860. return TlsSetValue(key, value) ? 0 : 1;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static void *
  864. pthread_getspecific(pthread_key_t key)
  865. {
  866. return TlsGetValue(key);
  867. }
  868. #if defined(GCC_DIAGNOSTIC)
  869. /* Enable unused function warning again */
  870. #pragma GCC diagnostic pop
  871. #endif
  872. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  873. #else
  874. static pthread_mutexattr_t pthread_mutex_attr;
  875. #endif /* _WIN32 */
  876. #if defined(_WIN32_WCE)
  877. /* Create substitutes for POSIX functions in Win32. */
  878. #if defined(GCC_DIAGNOSTIC)
  879. /* Show no warning in case system functions are not used. */
  880. #pragma GCC diagnostic push
  881. #pragma GCC diagnostic ignored "-Wunused-function"
  882. #endif
  883. FUNCTION_MAY_BE_UNUSED
  884. static time_t
  885. time(time_t *ptime)
  886. {
  887. time_t t;
  888. SYSTEMTIME st;
  889. FILETIME ft;
  890. GetSystemTime(&st);
  891. SystemTimeToFileTime(&st, &ft);
  892. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  893. if (ptime != NULL) {
  894. *ptime = t;
  895. }
  896. return t;
  897. }
  898. FUNCTION_MAY_BE_UNUSED
  899. static struct tm *
  900. localtime_s(const time_t *ptime, struct tm *ptm)
  901. {
  902. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  903. FILETIME ft, lft;
  904. SYSTEMTIME st;
  905. TIME_ZONE_INFORMATION tzinfo;
  906. if (ptm == NULL) {
  907. return NULL;
  908. }
  909. *(int64_t *)&ft = t;
  910. FileTimeToLocalFileTime(&ft, &lft);
  911. FileTimeToSystemTime(&lft, &st);
  912. ptm->tm_year = st.wYear - 1900;
  913. ptm->tm_mon = st.wMonth - 1;
  914. ptm->tm_wday = st.wDayOfWeek;
  915. ptm->tm_mday = st.wDay;
  916. ptm->tm_hour = st.wHour;
  917. ptm->tm_min = st.wMinute;
  918. ptm->tm_sec = st.wSecond;
  919. ptm->tm_yday = 0; /* hope nobody uses this */
  920. ptm->tm_isdst =
  921. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  922. return ptm;
  923. }
  924. FUNCTION_MAY_BE_UNUSED
  925. static struct tm *
  926. gmtime_s(const time_t *ptime, struct tm *ptm)
  927. {
  928. /* FIXME(lsm): fix this. */
  929. return localtime_s(ptime, ptm);
  930. }
  931. static int mg_atomic_inc(volatile int *addr);
  932. static struct tm tm_array[MAX_WORKER_THREADS];
  933. static int tm_index = 0;
  934. FUNCTION_MAY_BE_UNUSED
  935. static struct tm *
  936. localtime(const time_t *ptime)
  937. {
  938. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  939. return localtime_s(ptime, tm_array + i);
  940. }
  941. FUNCTION_MAY_BE_UNUSED
  942. static struct tm *
  943. gmtime(const time_t *ptime)
  944. {
  945. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  946. return gmtime_s(ptime, tm_array + i);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static size_t
  950. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  951. {
  952. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  953. * for WinCE"); */
  954. return 0;
  955. }
  956. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  957. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  958. #define remove(f) mg_remove(NULL, f)
  959. FUNCTION_MAY_BE_UNUSED
  960. static int
  961. rename(const char *a, const char *b)
  962. {
  963. wchar_t wa[W_PATH_MAX];
  964. wchar_t wb[W_PATH_MAX];
  965. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  966. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  967. return MoveFileW(wa, wb) ? 0 : -1;
  968. }
  969. struct stat {
  970. int64_t st_size;
  971. time_t st_mtime;
  972. };
  973. FUNCTION_MAY_BE_UNUSED
  974. static int
  975. stat(const char *name, struct stat *st)
  976. {
  977. wchar_t wbuf[W_PATH_MAX];
  978. WIN32_FILE_ATTRIBUTE_DATA attr;
  979. time_t creation_time, write_time;
  980. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  981. memset(&attr, 0, sizeof(attr));
  982. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  983. st->st_size =
  984. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  985. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  986. attr.ftLastWriteTime.dwHighDateTime);
  987. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  988. attr.ftCreationTime.dwHighDateTime);
  989. if (creation_time > write_time) {
  990. st->st_mtime = creation_time;
  991. } else {
  992. st->st_mtime = write_time;
  993. }
  994. return 0;
  995. }
  996. #define access(x, a) 1 /* not required anyway */
  997. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  998. /* Values from errno.h in Windows SDK (Visual Studio). */
  999. #define EEXIST 17
  1000. #define EACCES 13
  1001. #define ENOENT 2
  1002. #if defined(GCC_DIAGNOSTIC)
  1003. /* Enable unused function warning again */
  1004. #pragma GCC diagnostic pop
  1005. #endif
  1006. #endif /* defined(_WIN32_WCE) */
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Show no warning in case system functions are not used. */
  1009. #pragma GCC diagnostic push
  1010. #pragma GCC diagnostic ignored "-Wunused-function"
  1011. #endif /* defined(GCC_DIAGNOSTIC) */
  1012. #if defined(__clang__)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma clang diagnostic push
  1015. #pragma clang diagnostic ignored "-Wunused-function"
  1016. #endif
  1017. static pthread_mutex_t global_lock_mutex;
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static void
  1020. mg_global_lock(void)
  1021. {
  1022. (void)pthread_mutex_lock(&global_lock_mutex);
  1023. }
  1024. FUNCTION_MAY_BE_UNUSED
  1025. static void
  1026. mg_global_unlock(void)
  1027. {
  1028. (void)pthread_mutex_unlock(&global_lock_mutex);
  1029. }
  1030. FUNCTION_MAY_BE_UNUSED
  1031. static int
  1032. mg_atomic_inc(volatile int *addr)
  1033. {
  1034. int ret;
  1035. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1036. /* Depending on the SDK, this function uses either
  1037. * (volatile unsigned int *) or (volatile LONG *),
  1038. * so whatever you use, the other SDK is likely to raise a warning. */
  1039. ret = InterlockedIncrement((volatile long *)addr);
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. ret = __sync_add_and_fetch(addr, 1);
  1044. #else
  1045. mg_global_lock();
  1046. ret = (++(*addr));
  1047. mg_global_unlock();
  1048. #endif
  1049. return ret;
  1050. }
  1051. FUNCTION_MAY_BE_UNUSED
  1052. static int
  1053. mg_atomic_dec(volatile int *addr)
  1054. {
  1055. int ret;
  1056. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1057. /* Depending on the SDK, this function uses either
  1058. * (volatile unsigned int *) or (volatile LONG *),
  1059. * so whatever you use, the other SDK is likely to raise a warning. */
  1060. ret = InterlockedDecrement((volatile long *)addr);
  1061. #elif defined(__GNUC__) \
  1062. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1063. && !defined(NO_ATOMICS)
  1064. ret = __sync_sub_and_fetch(addr, 1);
  1065. #else
  1066. mg_global_lock();
  1067. ret = (--(*addr));
  1068. mg_global_unlock();
  1069. #endif
  1070. return ret;
  1071. }
  1072. #if defined(USE_SERVER_STATS)
  1073. static int64_t
  1074. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1075. {
  1076. int64_t ret;
  1077. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1078. ret = InterlockedAdd64(addr, value);
  1079. #elif defined(__GNUC__) \
  1080. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1081. && !defined(NO_ATOMICS)
  1082. ret = __sync_add_and_fetch(addr, value);
  1083. #else
  1084. mg_global_lock();
  1085. *addr += value;
  1086. ret = (*addr);
  1087. mg_global_unlock();
  1088. #endif
  1089. return ret;
  1090. }
  1091. #endif
  1092. #if defined(GCC_DIAGNOSTIC)
  1093. /* Show no warning in case system functions are not used. */
  1094. #pragma GCC diagnostic pop
  1095. #endif /* defined(GCC_DIAGNOSTIC) */
  1096. #if defined(__clang__)
  1097. /* Show no warning in case system functions are not used. */
  1098. #pragma clang diagnostic pop
  1099. #endif
  1100. #if defined(USE_SERVER_STATS)
  1101. struct mg_memory_stat {
  1102. volatile int64_t totalMemUsed;
  1103. volatile int64_t maxMemUsed;
  1104. volatile int blockCount;
  1105. };
  1106. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1107. static void *
  1108. mg_malloc_ex(size_t size,
  1109. struct mg_context *ctx,
  1110. const char *file,
  1111. unsigned line)
  1112. {
  1113. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1114. void *memory = 0;
  1115. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1116. #if defined(MEMORY_DEBUGGING)
  1117. char mallocStr[256];
  1118. #else
  1119. (void)file;
  1120. (void)line;
  1121. #endif
  1122. if (data) {
  1123. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1124. if (mmem > mstat->maxMemUsed) {
  1125. /* could use atomic compare exchange, but this
  1126. * seems overkill for statistics data */
  1127. mstat->maxMemUsed = mmem;
  1128. }
  1129. mg_atomic_inc(&mstat->blockCount);
  1130. ((uintptr_t *)data)[0] = size;
  1131. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1132. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1133. }
  1134. #if defined(MEMORY_DEBUGGING)
  1135. sprintf(mallocStr,
  1136. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1137. memory,
  1138. (unsigned long)size,
  1139. (unsigned long)mstat->totalMemUsed,
  1140. (unsigned long)mstat->blockCount,
  1141. file,
  1142. line);
  1143. #if defined(_WIN32)
  1144. OutputDebugStringA(mallocStr);
  1145. #else
  1146. DEBUG_TRACE("%s", mallocStr);
  1147. #endif
  1148. #endif
  1149. return memory;
  1150. }
  1151. static void *
  1152. mg_calloc_ex(size_t count,
  1153. size_t size,
  1154. struct mg_context *ctx,
  1155. const char *file,
  1156. unsigned line)
  1157. {
  1158. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1159. if (data) {
  1160. memset(data, 0, size * count);
  1161. }
  1162. return data;
  1163. }
  1164. static void
  1165. mg_free_ex(void *memory, const char *file, unsigned line)
  1166. {
  1167. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1168. #if defined(MEMORY_DEBUGGING)
  1169. char mallocStr[256];
  1170. #else
  1171. (void)file;
  1172. (void)line;
  1173. #endif
  1174. if (memory) {
  1175. uintptr_t size = ((uintptr_t *)data)[0];
  1176. struct mg_memory_stat *mstat =
  1177. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1178. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1179. mg_atomic_dec(&mstat->blockCount);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)size,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. #if defined(_WIN32)
  1190. OutputDebugStringA(mallocStr);
  1191. #else
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. #endif
  1195. free(data);
  1196. }
  1197. }
  1198. static void *
  1199. mg_realloc_ex(void *memory,
  1200. size_t newsize,
  1201. struct mg_context *ctx,
  1202. const char *file,
  1203. unsigned line)
  1204. {
  1205. void *data;
  1206. void *_realloc;
  1207. uintptr_t oldsize;
  1208. #if defined(MEMORY_DEBUGGING)
  1209. char mallocStr[256];
  1210. #else
  1211. (void)file;
  1212. (void)line;
  1213. #endif
  1214. if (newsize) {
  1215. if (memory) {
  1216. /* Reallocate existing block */
  1217. struct mg_memory_stat *mstat;
  1218. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1219. oldsize = ((uintptr_t *)data)[0];
  1220. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1221. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1222. if (_realloc) {
  1223. data = _realloc;
  1224. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1225. #if defined(MEMORY_DEBUGGING)
  1226. sprintf(mallocStr,
  1227. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1228. memory,
  1229. (unsigned long)oldsize,
  1230. (unsigned long)mstat->totalMemUsed,
  1231. (unsigned long)mstat->blockCount,
  1232. file,
  1233. line);
  1234. #if defined(_WIN32)
  1235. OutputDebugStringA(mallocStr);
  1236. #else
  1237. DEBUG_TRACE("%s", mallocStr);
  1238. #endif
  1239. #endif
  1240. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1241. #if defined(MEMORY_DEBUGGING)
  1242. sprintf(mallocStr,
  1243. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1244. memory,
  1245. (unsigned long)newsize,
  1246. (unsigned long)mstat->totalMemUsed,
  1247. (unsigned long)mstat->blockCount,
  1248. file,
  1249. line);
  1250. #if defined(_WIN32)
  1251. OutputDebugStringA(mallocStr);
  1252. #else
  1253. DEBUG_TRACE("%s", mallocStr);
  1254. #endif
  1255. #endif
  1256. *(uintptr_t *)data = newsize;
  1257. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1258. } else {
  1259. #if defined(MEMORY_DEBUGGING)
  1260. #if defined(_WIN32)
  1261. OutputDebugStringA("MEM: realloc failed\n");
  1262. #else
  1263. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1264. #endif
  1265. #endif
  1266. return _realloc;
  1267. }
  1268. } else {
  1269. /* Allocate new block */
  1270. data = mg_malloc_ex(newsize, ctx, file, line);
  1271. }
  1272. } else {
  1273. /* Free existing block */
  1274. data = 0;
  1275. mg_free_ex(memory, file, line);
  1276. }
  1277. return data;
  1278. }
  1279. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1280. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1281. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1282. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1283. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1284. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1285. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1286. #else /* USE_SERVER_STATS */
  1287. static __inline void *
  1288. mg_malloc(size_t a)
  1289. {
  1290. return malloc(a);
  1291. }
  1292. static __inline void *
  1293. mg_calloc(size_t a, size_t b)
  1294. {
  1295. return calloc(a, b);
  1296. }
  1297. static __inline void *
  1298. mg_realloc(void *a, size_t b)
  1299. {
  1300. return realloc(a, b);
  1301. }
  1302. static __inline void
  1303. mg_free(void *a)
  1304. {
  1305. free(a);
  1306. }
  1307. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1308. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1309. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1310. #define mg_free_ctx(a, c) mg_free(a)
  1311. #endif /* USE_SERVER_STATS */
  1312. static void mg_vsnprintf(const struct mg_connection *conn,
  1313. int *truncated,
  1314. char *buf,
  1315. size_t buflen,
  1316. const char *fmt,
  1317. va_list ap);
  1318. static void mg_snprintf(const struct mg_connection *conn,
  1319. int *truncated,
  1320. char *buf,
  1321. size_t buflen,
  1322. PRINTF_FORMAT_STRING(const char *fmt),
  1323. ...) PRINTF_ARGS(5, 6);
  1324. /* This following lines are just meant as a reminder to use the mg-functions
  1325. * for memory management */
  1326. #if defined(malloc)
  1327. #undef malloc
  1328. #endif
  1329. #if defined(calloc)
  1330. #undef calloc
  1331. #endif
  1332. #if defined(realloc)
  1333. #undef realloc
  1334. #endif
  1335. #if defined(free)
  1336. #undef free
  1337. #endif
  1338. #if defined(snprintf)
  1339. #undef snprintf
  1340. #endif
  1341. #if defined(vsnprintf)
  1342. #undef vsnprintf
  1343. #endif
  1344. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1345. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1346. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1347. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1348. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1349. #if defined(_WIN32)
  1350. /* vsnprintf must not be used in any system,
  1351. * but this define only works well for Windows. */
  1352. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1353. #endif
  1354. /* mg_init_library counter */
  1355. static int mg_init_library_called = 0;
  1356. #if !defined(NO_SSL)
  1357. static int mg_ssl_initialized = 0;
  1358. #endif
  1359. static pthread_key_t sTlsKey; /* Thread local storage index */
  1360. static int thread_idx_max = 0;
  1361. #if defined(MG_LEGACY_INTERFACE)
  1362. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1363. #endif
  1364. struct mg_workerTLS {
  1365. int is_master;
  1366. unsigned long thread_idx;
  1367. void *user_ptr;
  1368. #if defined(_WIN32)
  1369. HANDLE pthread_cond_helper_mutex;
  1370. struct mg_workerTLS *next_waiting_thread;
  1371. #endif
  1372. const char *alpn_proto;
  1373. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1374. char txtbuf[4];
  1375. #endif
  1376. };
  1377. #if defined(GCC_DIAGNOSTIC)
  1378. /* Show no warning in case system functions are not used. */
  1379. #pragma GCC diagnostic push
  1380. #pragma GCC diagnostic ignored "-Wunused-function"
  1381. #endif /* defined(GCC_DIAGNOSTIC) */
  1382. #if defined(__clang__)
  1383. /* Show no warning in case system functions are not used. */
  1384. #pragma clang diagnostic push
  1385. #pragma clang diagnostic ignored "-Wunused-function"
  1386. #endif
  1387. /* Get a unique thread ID as unsigned long, independent from the data type
  1388. * of thread IDs defined by the operating system API.
  1389. * If two calls to mg_current_thread_id return the same value, they calls
  1390. * are done from the same thread. If they return different values, they are
  1391. * done from different threads. (Provided this function is used in the same
  1392. * process context and threads are not repeatedly created and deleted, but
  1393. * CivetWeb does not do that).
  1394. * This function must match the signature required for SSL id callbacks:
  1395. * CRYPTO_set_id_callback
  1396. */
  1397. FUNCTION_MAY_BE_UNUSED
  1398. static unsigned long
  1399. mg_current_thread_id(void)
  1400. {
  1401. #if defined(_WIN32)
  1402. return GetCurrentThreadId();
  1403. #else
  1404. #if defined(__clang__)
  1405. #pragma clang diagnostic push
  1406. #pragma clang diagnostic ignored "-Wunreachable-code"
  1407. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1408. * or not, so one of the two conditions will be unreachable by construction.
  1409. * Unfortunately the C standard does not define a way to check this at
  1410. * compile time, since the #if preprocessor conditions can not use the sizeof
  1411. * operator as an argument. */
  1412. #endif
  1413. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1414. /* This is the problematic case for CRYPTO_set_id_callback:
  1415. * The OS pthread_t can not be cast to unsigned long. */
  1416. struct mg_workerTLS *tls =
  1417. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1418. if (tls == NULL) {
  1419. /* SSL called from an unknown thread: Create some thread index.
  1420. */
  1421. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1422. tls->is_master = -2; /* -2 means "3rd party thread" */
  1423. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1424. pthread_setspecific(sTlsKey, tls);
  1425. }
  1426. return tls->thread_idx;
  1427. } else {
  1428. /* pthread_t may be any data type, so a simple cast to unsigned long
  1429. * can rise a warning/error, depending on the platform.
  1430. * Here memcpy is used as an anything-to-anything cast. */
  1431. unsigned long ret = 0;
  1432. pthread_t t = pthread_self();
  1433. memcpy(&ret, &t, sizeof(pthread_t));
  1434. return ret;
  1435. }
  1436. #if defined(__clang__)
  1437. #pragma clang diagnostic pop
  1438. #endif
  1439. #endif
  1440. }
  1441. FUNCTION_MAY_BE_UNUSED
  1442. static uint64_t
  1443. mg_get_current_time_ns(void)
  1444. {
  1445. struct timespec tsnow;
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1448. }
  1449. #if defined(GCC_DIAGNOSTIC)
  1450. /* Show no warning in case system functions are not used. */
  1451. #pragma GCC diagnostic pop
  1452. #endif /* defined(GCC_DIAGNOSTIC) */
  1453. #if defined(__clang__)
  1454. /* Show no warning in case system functions are not used. */
  1455. #pragma clang diagnostic pop
  1456. #endif
  1457. #if defined(NEED_DEBUG_TRACE_FUNC)
  1458. static void
  1459. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1460. {
  1461. va_list args;
  1462. struct timespec tsnow;
  1463. /* Get some operating system independent thread id */
  1464. unsigned long thread_id = mg_current_thread_id();
  1465. clock_gettime(CLOCK_REALTIME, &tsnow);
  1466. flockfile(DEBUG_TRACE_STREAM);
  1467. fprintf(DEBUG_TRACE_STREAM,
  1468. "*** %lu.%09lu %lu %s:%u: ",
  1469. (unsigned long)tsnow.tv_sec,
  1470. (unsigned long)tsnow.tv_nsec,
  1471. thread_id,
  1472. func,
  1473. line);
  1474. va_start(args, fmt);
  1475. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1476. va_end(args);
  1477. putc('\n', DEBUG_TRACE_STREAM);
  1478. fflush(DEBUG_TRACE_STREAM);
  1479. funlockfile(DEBUG_TRACE_STREAM);
  1480. }
  1481. #endif /* NEED_DEBUG_TRACE_FUNC */
  1482. #define MD5_STATIC static
  1483. #include "md5.inl"
  1484. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1485. #if defined(NO_SOCKLEN_T)
  1486. typedef int socklen_t;
  1487. #endif /* NO_SOCKLEN_T */
  1488. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1489. #if !defined(MSG_NOSIGNAL)
  1490. #define MSG_NOSIGNAL (0)
  1491. #endif
  1492. #if defined(NO_SSL)
  1493. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1494. typedef struct SSL_CTX SSL_CTX;
  1495. #else
  1496. #if defined(NO_SSL_DL)
  1497. #include <openssl/bn.h>
  1498. #include <openssl/conf.h>
  1499. #include <openssl/crypto.h>
  1500. #include <openssl/dh.h>
  1501. #include <openssl/engine.h>
  1502. #include <openssl/err.h>
  1503. #include <openssl/opensslv.h>
  1504. #include <openssl/pem.h>
  1505. #include <openssl/ssl.h>
  1506. #include <openssl/tls1.h>
  1507. #include <openssl/x509.h>
  1508. #if defined(WOLFSSL_VERSION)
  1509. /* Additional defines for WolfSSL, see
  1510. * https://github.com/civetweb/civetweb/issues/583 */
  1511. #include "wolfssl_extras.inl"
  1512. #endif
  1513. #if defined(OPENSSL_IS_BORINGSSL)
  1514. /* From boringssl/src/include/openssl/mem.h:
  1515. *
  1516. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1517. * However, that was written in a time before Valgrind and ASAN. Since we now
  1518. * have those tools, the OpenSSL allocation functions are simply macros around
  1519. * the standard memory functions.
  1520. *
  1521. * #define OPENSSL_free free */
  1522. #define free free
  1523. // disable for boringssl
  1524. #define CONF_modules_unload(a) ((void)0)
  1525. #define ENGINE_cleanup() ((void)0)
  1526. #endif
  1527. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1528. /* If OpenSSL headers are included, automatically select the API version */
  1529. #if !defined(OPENSSL_API_1_1)
  1530. #define OPENSSL_API_1_1
  1531. #endif
  1532. #define OPENSSL_REMOVE_THREAD_STATE()
  1533. #else
  1534. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1535. #endif
  1536. #else
  1537. /* SSL loaded dynamically from DLL.
  1538. * I put the prototypes here to be independent from OpenSSL source
  1539. * installation. */
  1540. typedef struct ssl_st SSL;
  1541. typedef struct ssl_method_st SSL_METHOD;
  1542. typedef struct ssl_ctx_st SSL_CTX;
  1543. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1544. typedef struct x509_name X509_NAME;
  1545. typedef struct asn1_integer ASN1_INTEGER;
  1546. typedef struct bignum BIGNUM;
  1547. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1548. typedef struct evp_md EVP_MD;
  1549. typedef struct x509 X509;
  1550. #define SSL_CTRL_OPTIONS (32)
  1551. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1552. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1553. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1554. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1555. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1556. #define SSL_VERIFY_NONE (0)
  1557. #define SSL_VERIFY_PEER (1)
  1558. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1559. #define SSL_VERIFY_CLIENT_ONCE (4)
  1560. #define SSL_OP_ALL (0x80000BFFul)
  1561. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1562. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1563. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1564. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1565. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1566. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1567. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1568. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1569. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1570. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1571. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1572. #define SSL_CB_HANDSHAKE_START (0x10)
  1573. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1574. #define SSL_ERROR_NONE (0)
  1575. #define SSL_ERROR_SSL (1)
  1576. #define SSL_ERROR_WANT_READ (2)
  1577. #define SSL_ERROR_WANT_WRITE (3)
  1578. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1579. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1580. #define SSL_ERROR_ZERO_RETURN (6)
  1581. #define SSL_ERROR_WANT_CONNECT (7)
  1582. #define SSL_ERROR_WANT_ACCEPT (8)
  1583. #define TLSEXT_TYPE_server_name (0)
  1584. #define TLSEXT_NAMETYPE_host_name (0)
  1585. #define SSL_TLSEXT_ERR_OK (0)
  1586. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1587. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1588. #define SSL_TLSEXT_ERR_NOACK (3)
  1589. enum ssl_func_category {
  1590. TLS_Mandatory, /* required for HTTPS */
  1591. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1592. TLS_END_OF_LIST
  1593. };
  1594. /* Check if all TLS functions/features are available */
  1595. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1596. struct ssl_func {
  1597. const char *name; /* SSL function name */
  1598. union {
  1599. enum ssl_func_category required; /* Mandatory or optional */
  1600. void (*ptr)(void); /* Function pointer */
  1601. };
  1602. };
  1603. #if defined(OPENSSL_API_1_1)
  1604. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1605. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1606. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1607. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1608. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1609. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1610. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1611. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1612. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1613. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1614. #define OPENSSL_init_ssl \
  1615. (*(int (*)(uint64_t opts, \
  1616. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1617. .ptr)
  1618. #define SSL_CTX_use_PrivateKey_file \
  1619. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1620. #define SSL_CTX_use_certificate_file \
  1621. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1622. #define SSL_CTX_set_default_passwd_cb \
  1623. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1624. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1625. #define SSL_CTX_use_certificate_chain_file \
  1626. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1627. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1628. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1629. #define SSL_CTX_set_verify \
  1630. (*(void (*)(SSL_CTX *, \
  1631. int, \
  1632. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1633. .ptr)
  1634. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1635. #define SSL_CTX_load_verify_locations \
  1636. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1637. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1638. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1639. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1640. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1641. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1642. #define SSL_CIPHER_get_name \
  1643. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1644. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1645. #define SSL_CTX_set_session_id_context \
  1646. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1647. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1648. #define SSL_CTX_set_cipher_list \
  1649. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1650. #define SSL_CTX_set_options \
  1651. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1652. #define SSL_CTX_set_info_callback \
  1653. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1654. ssl_sw[32] \
  1655. .ptr)
  1656. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1657. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1658. #define SSL_CTX_callback_ctrl \
  1659. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1660. #define SSL_get_servername \
  1661. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1662. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1663. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1664. #define SSL_CTX_set_alpn_protos \
  1665. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1666. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1667. const unsigned char **out,
  1668. unsigned char *outlen,
  1669. const unsigned char *in,
  1670. unsigned int inlen,
  1671. void *arg);
  1672. #define SSL_CTX_set_alpn_select_cb \
  1673. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1674. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1675. const unsigned char **out,
  1676. unsigned int *outlen,
  1677. void *arg);
  1678. #define SSL_CTX_set_next_protos_advertised_cb \
  1679. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1680. .ptr)
  1681. #define SSL_CTX_clear_options(ctx, op) \
  1682. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1683. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1684. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1685. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1686. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1687. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1688. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1689. SSL_CTX_callback_ctrl(ctx, \
  1690. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1691. (void (*)(void))cb)
  1692. #define SSL_set_tlsext_host_name(ctx, arg) \
  1693. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1694. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1695. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1696. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1697. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1698. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1699. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1700. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1701. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1702. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1703. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1704. #define X509_NAME_oneline \
  1705. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1706. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1707. #define EVP_get_digestbyname \
  1708. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1709. #define EVP_Digest \
  1710. (*(int (*)( \
  1711. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1712. crypto_sw[9] \
  1713. .ptr)
  1714. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1715. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1716. #define ASN1_INTEGER_to_BN \
  1717. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1718. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1719. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1720. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1721. #define OPENSSL_free(a) CRYPTO_free(a)
  1722. #define OPENSSL_REMOVE_THREAD_STATE()
  1723. /* init_ssl_ctx() function updates this array.
  1724. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1725. * of respective functions. The macros above (like SSL_connect()) are really
  1726. * just calling these functions indirectly via the pointer. */
  1727. static struct ssl_func ssl_sw[] = {
  1728. {"SSL_free", {TLS_Mandatory}},
  1729. {"SSL_accept", {TLS_Mandatory}},
  1730. {"SSL_connect", {TLS_Mandatory}},
  1731. {"SSL_read", {TLS_Mandatory}},
  1732. {"SSL_write", {TLS_Mandatory}},
  1733. {"SSL_get_error", {TLS_Mandatory}},
  1734. {"SSL_set_fd", {TLS_Mandatory}},
  1735. {"SSL_new", {TLS_Mandatory}},
  1736. {"SSL_CTX_new", {TLS_Mandatory}},
  1737. {"TLS_server_method", {TLS_Mandatory}},
  1738. {"OPENSSL_init_ssl", {TLS_Mandatory}},
  1739. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1740. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1741. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1742. {"SSL_CTX_free", {TLS_Mandatory}},
  1743. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1744. {"TLS_client_method", {TLS_Mandatory}},
  1745. {"SSL_pending", {TLS_Mandatory}},
  1746. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1747. {"SSL_shutdown", {TLS_Mandatory}},
  1748. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1749. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1750. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1751. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1752. {"SSL_get_version", {TLS_Mandatory}},
  1753. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1754. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1755. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1756. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1757. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1758. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1759. {"SSL_CTX_set_options", {TLS_Mandatory}},
  1760. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1761. {"SSL_get_ex_data", {TLS_Mandatory}},
  1762. {"SSL_set_ex_data", {TLS_Mandatory}},
  1763. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1764. {"SSL_get_servername", {TLS_Mandatory}},
  1765. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1766. {"SSL_ctrl", {TLS_Mandatory}},
  1767. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1768. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1769. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1770. {NULL, {TLS_END_OF_LIST}}};
  1771. /* Similar array as ssl_sw. These functions could be located in different
  1772. * lib. */
  1773. static struct ssl_func crypto_sw[] = {{"ERR_get_error", {TLS_Mandatory}},
  1774. {"ERR_error_string", {TLS_Mandatory}},
  1775. {"CONF_modules_unload", {TLS_Mandatory}},
  1776. {"X509_free", {TLS_Mandatory}},
  1777. {"X509_get_subject_name",
  1778. {TLS_Mandatory}},
  1779. {"X509_get_issuer_name", {TLS_Mandatory}},
  1780. {"X509_NAME_oneline", {TLS_Mandatory}},
  1781. {"X509_get_serialNumber",
  1782. {TLS_Mandatory}},
  1783. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1784. {"EVP_Digest", {TLS_Mandatory}},
  1785. {"i2d_X509", {TLS_Mandatory}},
  1786. {"BN_bn2hex", {TLS_Mandatory}},
  1787. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1788. {"BN_free", {TLS_Mandatory}},
  1789. {"CRYPTO_free", {TLS_Mandatory}},
  1790. {"ERR_clear_error", {TLS_Mandatory}},
  1791. {NULL, {TLS_END_OF_LIST}}};
  1792. #else
  1793. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1794. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1795. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1796. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1797. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1798. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1799. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1800. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1801. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1802. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1803. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1804. #define SSL_CTX_use_PrivateKey_file \
  1805. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1806. #define SSL_CTX_use_certificate_file \
  1807. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1808. #define SSL_CTX_set_default_passwd_cb \
  1809. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1810. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1811. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1812. #define SSL_CTX_use_certificate_chain_file \
  1813. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1814. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1815. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1816. #define SSL_CTX_set_verify \
  1817. (*(void (*)(SSL_CTX *, \
  1818. int, \
  1819. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1820. .ptr)
  1821. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1822. #define SSL_CTX_load_verify_locations \
  1823. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1824. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1825. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1826. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1827. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1828. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1829. #define SSL_CIPHER_get_name \
  1830. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1831. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1832. #define SSL_CTX_set_session_id_context \
  1833. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1834. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1835. #define SSL_CTX_set_cipher_list \
  1836. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1837. #define SSL_CTX_set_info_callback \
  1838. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1839. .ptr)
  1840. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1841. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1842. #define SSL_CTX_callback_ctrl \
  1843. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1844. #define SSL_get_servername \
  1845. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1846. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1847. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1848. #define SSL_CTX_set_alpn_protos \
  1849. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1850. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1851. const unsigned char **out,
  1852. unsigned char *outlen,
  1853. const unsigned char *in,
  1854. unsigned int inlen,
  1855. void *arg);
  1856. #define SSL_CTX_set_alpn_select_cb \
  1857. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1858. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1859. const unsigned char **out,
  1860. unsigned int *outlen,
  1861. void *arg);
  1862. #define SSL_CTX_set_next_protos_advertised_cb \
  1863. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1864. .ptr)
  1865. #define SSL_CTX_set_options(ctx, op) \
  1866. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1867. #define SSL_CTX_clear_options(ctx, op) \
  1868. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1869. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1870. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1871. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1872. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1873. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1874. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1875. SSL_CTX_callback_ctrl(ctx, \
  1876. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1877. (void (*)(void))cb)
  1878. #define SSL_set_tlsext_host_name(ctx, arg) \
  1879. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1880. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1881. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1882. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1883. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1884. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1885. #define CRYPTO_set_locking_callback \
  1886. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1887. #define CRYPTO_set_id_callback \
  1888. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1889. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1890. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1891. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1892. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1893. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1894. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1895. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1896. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1897. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1898. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1899. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1900. #define X509_NAME_oneline \
  1901. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1902. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1903. #define i2c_ASN1_INTEGER \
  1904. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1905. #define EVP_get_digestbyname \
  1906. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1907. #define EVP_Digest \
  1908. (*(int (*)( \
  1909. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1910. crypto_sw[18] \
  1911. .ptr)
  1912. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1913. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1914. #define ASN1_INTEGER_to_BN \
  1915. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1916. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1917. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1918. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1919. #define OPENSSL_free(a) CRYPTO_free(a)
  1920. /* use here ERR_remove_state,
  1921. * while on some platforms function is not included into library due to
  1922. * deprication */
  1923. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1924. /* init_ssl_ctx() function updates this array.
  1925. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1926. * of respective functions. The macros above (like SSL_connect()) are really
  1927. * just calling these functions indirectly via the pointer. */
  1928. static struct ssl_func ssl_sw[] = {
  1929. {"SSL_free", {TLS_Mandatory}},
  1930. {"SSL_accept", {TLS_Mandatory}},
  1931. {"SSL_connect", {TLS_Mandatory}},
  1932. {"SSL_read", {TLS_Mandatory}},
  1933. {"SSL_write", {TLS_Mandatory}},
  1934. {"SSL_get_error", {TLS_Mandatory}},
  1935. {"SSL_set_fd", {TLS_Mandatory}},
  1936. {"SSL_new", {TLS_Mandatory}},
  1937. {"SSL_CTX_new", {TLS_Mandatory}},
  1938. {"SSLv23_server_method", {TLS_Mandatory}},
  1939. {"SSL_library_init", {TLS_Mandatory}},
  1940. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1941. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1942. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1943. {"SSL_CTX_free", {TLS_Mandatory}},
  1944. {"SSL_load_error_strings", {TLS_Mandatory}},
  1945. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1946. {"SSLv23_client_method", {TLS_Mandatory}},
  1947. {"SSL_pending", {TLS_Mandatory}},
  1948. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1949. {"SSL_shutdown", {TLS_Mandatory}},
  1950. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1951. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1952. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1953. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1954. {"SSL_get_version", {TLS_Mandatory}},
  1955. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1956. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1957. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1958. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1959. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1960. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1961. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1962. {"SSL_get_ex_data", {TLS_Mandatory}},
  1963. {"SSL_set_ex_data", {TLS_Mandatory}},
  1964. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1965. {"SSL_get_servername", {TLS_Mandatory}},
  1966. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1967. {"SSL_ctrl", {TLS_Mandatory}},
  1968. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1969. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1970. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1971. {NULL, {TLS_END_OF_LIST}}};
  1972. /* Similar array as ssl_sw. These functions could be located in different
  1973. * lib. */
  1974. static struct ssl_func crypto_sw[] = {
  1975. {"CRYPTO_num_locks", {TLS_Mandatory}},
  1976. {"CRYPTO_set_locking_callback", {TLS_Mandatory}},
  1977. {"CRYPTO_set_id_callback", {TLS_Mandatory}},
  1978. {"ERR_get_error", {TLS_Mandatory}},
  1979. {"ERR_error_string", {TLS_Mandatory}},
  1980. {"ERR_remove_state", {TLS_Mandatory}},
  1981. {"ERR_free_strings", {TLS_Mandatory}},
  1982. {"ENGINE_cleanup", {TLS_Mandatory}},
  1983. {"CONF_modules_unload", {TLS_Mandatory}},
  1984. {"CRYPTO_cleanup_all_ex_data", {TLS_Mandatory}},
  1985. {"EVP_cleanup", {TLS_Mandatory}},
  1986. {"X509_free", {TLS_Mandatory}},
  1987. {"X509_get_subject_name", {TLS_Mandatory}},
  1988. {"X509_get_issuer_name", {TLS_Mandatory}},
  1989. {"X509_NAME_oneline", {TLS_Mandatory}},
  1990. {"X509_get_serialNumber", {TLS_Mandatory}},
  1991. {"i2c_ASN1_INTEGER", {TLS_Mandatory}},
  1992. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1993. {"EVP_Digest", {TLS_Mandatory}},
  1994. {"i2d_X509", {TLS_Mandatory}},
  1995. {"BN_bn2hex", {TLS_Mandatory}},
  1996. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1997. {"BN_free", {TLS_Mandatory}},
  1998. {"CRYPTO_free", {TLS_Mandatory}},
  1999. {"ERR_clear_error", {TLS_Mandatory}},
  2000. {NULL, {TLS_END_OF_LIST}}};
  2001. #endif /* OPENSSL_API_1_1 */
  2002. #endif /* NO_SSL_DL */
  2003. #endif /* NO_SSL */
  2004. #if !defined(NO_CACHING)
  2005. static const char month_names[][4] = {"Jan",
  2006. "Feb",
  2007. "Mar",
  2008. "Apr",
  2009. "May",
  2010. "Jun",
  2011. "Jul",
  2012. "Aug",
  2013. "Sep",
  2014. "Oct",
  2015. "Nov",
  2016. "Dec"};
  2017. #endif /* !NO_CACHING */
  2018. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2019. * the union u. */
  2020. union usa {
  2021. struct sockaddr sa;
  2022. struct sockaddr_in sin;
  2023. #if defined(USE_IPV6)
  2024. struct sockaddr_in6 sin6;
  2025. #endif
  2026. };
  2027. /* Describes a string (chunk of memory). */
  2028. struct vec {
  2029. const char *ptr;
  2030. size_t len;
  2031. };
  2032. struct mg_file_stat {
  2033. /* File properties filled by mg_stat: */
  2034. uint64_t size;
  2035. time_t last_modified;
  2036. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2037. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2038. * case we need a "Content-Eencoding: gzip" header */
  2039. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2040. };
  2041. struct mg_file_in_memory {
  2042. char *p;
  2043. uint32_t pos;
  2044. char mode;
  2045. };
  2046. struct mg_file_access {
  2047. /* File properties filled by mg_fopen: */
  2048. FILE *fp;
  2049. #if defined(MG_USE_OPEN_FILE)
  2050. /* TODO (low): Remove obsolete "file in memory" implementation.
  2051. * In an "early 2017" discussion at Google groups
  2052. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2053. * we decided to get rid of this feature (after some fade-out
  2054. * phase). */
  2055. const char *membuf;
  2056. #endif
  2057. };
  2058. struct mg_file {
  2059. struct mg_file_stat stat;
  2060. struct mg_file_access access;
  2061. };
  2062. #if defined(MG_USE_OPEN_FILE)
  2063. #define STRUCT_FILE_INITIALIZER \
  2064. { \
  2065. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2066. { \
  2067. (FILE *)NULL, (const char *)NULL \
  2068. } \
  2069. }
  2070. #else
  2071. #define STRUCT_FILE_INITIALIZER \
  2072. { \
  2073. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2074. { \
  2075. (FILE *)NULL \
  2076. } \
  2077. }
  2078. #endif
  2079. /* Describes listening socket, or socket which was accept()-ed by the master
  2080. * thread and queued for future handling by the worker thread. */
  2081. struct socket {
  2082. SOCKET sock; /* Listening socket */
  2083. union usa lsa; /* Local socket address */
  2084. union usa rsa; /* Remote socket address */
  2085. unsigned char is_ssl; /* Is port SSL-ed */
  2086. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2087. * port */
  2088. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2089. };
  2090. /* Enum const for all options must be in sync with
  2091. * static struct mg_option config_options[]
  2092. * This is tested in the unit test (test/private.c)
  2093. * "Private Config Options"
  2094. */
  2095. enum {
  2096. /* Once for each server */
  2097. LISTENING_PORTS,
  2098. NUM_THREADS,
  2099. RUN_AS_USER,
  2100. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2101. * socket option typedef TCP_NODELAY. */
  2102. MAX_REQUEST_SIZE,
  2103. LINGER_TIMEOUT,
  2104. CONNECTION_QUEUE_SIZE,
  2105. LISTEN_BACKLOG_SIZE,
  2106. #if defined(__linux__)
  2107. ALLOW_SENDFILE_CALL,
  2108. #endif
  2109. #if defined(_WIN32)
  2110. CASE_SENSITIVE_FILES,
  2111. #endif
  2112. THROTTLE,
  2113. ACCESS_LOG_FILE,
  2114. ERROR_LOG_FILE,
  2115. ENABLE_KEEP_ALIVE,
  2116. REQUEST_TIMEOUT,
  2117. KEEP_ALIVE_TIMEOUT,
  2118. #if defined(USE_WEBSOCKET)
  2119. WEBSOCKET_TIMEOUT,
  2120. ENABLE_WEBSOCKET_PING_PONG,
  2121. #endif
  2122. DECODE_URL,
  2123. #if defined(USE_LUA)
  2124. LUA_BACKGROUND_SCRIPT,
  2125. LUA_BACKGROUND_SCRIPT_PARAMS,
  2126. #endif
  2127. #if defined(USE_TIMERS)
  2128. CGI_TIMEOUT,
  2129. #endif
  2130. /* Once for each domain */
  2131. DOCUMENT_ROOT,
  2132. CGI_EXTENSIONS,
  2133. CGI_ENVIRONMENT,
  2134. PUT_DELETE_PASSWORDS_FILE,
  2135. CGI_INTERPRETER,
  2136. CGI_INTERPRETER_ARGS,
  2137. PROTECT_URI,
  2138. AUTHENTICATION_DOMAIN,
  2139. ENABLE_AUTH_DOMAIN_CHECK,
  2140. SSI_EXTENSIONS,
  2141. ENABLE_DIRECTORY_LISTING,
  2142. GLOBAL_PASSWORDS_FILE,
  2143. INDEX_FILES,
  2144. ACCESS_CONTROL_LIST,
  2145. EXTRA_MIME_TYPES,
  2146. SSL_CERTIFICATE,
  2147. SSL_CERTIFICATE_CHAIN,
  2148. URL_REWRITE_PATTERN,
  2149. HIDE_FILES,
  2150. SSL_DO_VERIFY_PEER,
  2151. SSL_CA_PATH,
  2152. SSL_CA_FILE,
  2153. SSL_VERIFY_DEPTH,
  2154. SSL_DEFAULT_VERIFY_PATHS,
  2155. SSL_CIPHER_LIST,
  2156. SSL_PROTOCOL_VERSION,
  2157. SSL_SHORT_TRUST,
  2158. #if defined(USE_LUA)
  2159. LUA_PRELOAD_FILE,
  2160. LUA_SCRIPT_EXTENSIONS,
  2161. LUA_SERVER_PAGE_EXTENSIONS,
  2162. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2163. LUA_DEBUG_PARAMS,
  2164. #endif
  2165. #endif
  2166. #if defined(USE_DUKTAPE)
  2167. DUKTAPE_SCRIPT_EXTENSIONS,
  2168. #endif
  2169. #if defined(USE_WEBSOCKET)
  2170. WEBSOCKET_ROOT,
  2171. #endif
  2172. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2173. LUA_WEBSOCKET_EXTENSIONS,
  2174. #endif
  2175. ACCESS_CONTROL_ALLOW_ORIGIN,
  2176. ACCESS_CONTROL_ALLOW_METHODS,
  2177. ACCESS_CONTROL_ALLOW_HEADERS,
  2178. ERROR_PAGES,
  2179. #if !defined(NO_CACHING)
  2180. STATIC_FILE_MAX_AGE,
  2181. STATIC_FILE_CACHE_CONTROL,
  2182. #endif
  2183. #if !defined(NO_SSL)
  2184. STRICT_HTTPS_MAX_AGE,
  2185. #endif
  2186. ADDITIONAL_HEADER,
  2187. ALLOW_INDEX_SCRIPT_SUB_RES,
  2188. #if defined(DAEMONIZE)
  2189. ENABLE_DAEMONIZE,
  2190. #endif
  2191. NUM_OPTIONS
  2192. };
  2193. /* Config option name, config types, default value.
  2194. * Must be in the same order as the enum const above.
  2195. */
  2196. static const struct mg_option config_options[] = {
  2197. /* Once for each server */
  2198. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2199. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2200. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2201. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2202. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2203. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2204. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2205. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2206. #if defined(__linux__)
  2207. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2208. #endif
  2209. #if defined(_WIN32)
  2210. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2211. #endif
  2212. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2213. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2214. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2215. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2216. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2217. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2218. #if defined(USE_WEBSOCKET)
  2219. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2220. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2221. #endif
  2222. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2223. #if defined(USE_LUA)
  2224. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2225. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2226. #endif
  2227. #if defined(USE_TIMERS)
  2228. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2229. #endif
  2230. /* Once for each domain */
  2231. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2232. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2233. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2234. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2235. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2236. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2237. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2238. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2239. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2240. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2241. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2242. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2243. {"index_files",
  2244. MG_CONFIG_TYPE_STRING_LIST,
  2245. #if defined(USE_LUA)
  2246. "index.xhtml,index.html,index.htm,"
  2247. "index.lp,index.lsp,index.lua,index.cgi,"
  2248. "index.shtml,index.php"},
  2249. #else
  2250. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2251. #endif
  2252. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2253. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2254. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2255. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2256. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2257. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2258. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2259. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2260. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2261. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2262. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2263. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2264. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2265. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2266. #if defined(USE_LUA)
  2267. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2268. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2269. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2270. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2271. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2272. #endif
  2273. #endif
  2274. #if defined(USE_DUKTAPE)
  2275. /* The support for duktape is still in alpha version state.
  2276. * The name of this config option might change. */
  2277. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2278. #endif
  2279. #if defined(USE_WEBSOCKET)
  2280. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2281. #endif
  2282. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2283. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2284. #endif
  2285. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2286. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2287. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2288. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2289. #if !defined(NO_CACHING)
  2290. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2291. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2292. #endif
  2293. #if !defined(NO_SSL)
  2294. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2295. #endif
  2296. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2297. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2298. #if defined(DAEMONIZE)
  2299. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2300. #endif
  2301. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2302. /* Check if the config_options and the corresponding enum have compatible
  2303. * sizes. */
  2304. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2305. == (NUM_OPTIONS + 1),
  2306. "config_options and enum not sync");
  2307. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2308. struct mg_handler_info {
  2309. /* Name/Pattern of the URI. */
  2310. char *uri;
  2311. size_t uri_len;
  2312. /* handler type */
  2313. int handler_type;
  2314. /* Handler for http/https or authorization requests. */
  2315. mg_request_handler handler;
  2316. unsigned int refcount;
  2317. int removing;
  2318. /* Handler for ws/wss (websocket) requests. */
  2319. mg_websocket_connect_handler connect_handler;
  2320. mg_websocket_ready_handler ready_handler;
  2321. mg_websocket_data_handler data_handler;
  2322. mg_websocket_close_handler close_handler;
  2323. /* accepted subprotocols for ws/wss requests. */
  2324. struct mg_websocket_subprotocols *subprotocols;
  2325. /* Handler for authorization requests */
  2326. mg_authorization_handler auth_handler;
  2327. /* User supplied argument for the handler function. */
  2328. void *cbdata;
  2329. /* next handler in a linked list */
  2330. struct mg_handler_info *next;
  2331. };
  2332. enum {
  2333. CONTEXT_INVALID,
  2334. CONTEXT_SERVER,
  2335. CONTEXT_HTTP_CLIENT,
  2336. CONTEXT_WS_CLIENT
  2337. };
  2338. struct mg_domain_context {
  2339. SSL_CTX *ssl_ctx; /* SSL context */
  2340. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2341. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2342. int64_t ssl_cert_last_mtime;
  2343. /* Server nonce */
  2344. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2345. unsigned long nonce_count; /* Used nonces, used for authentication */
  2346. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2347. /* linked list of shared lua websockets */
  2348. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2349. #endif
  2350. /* Linked list of domains */
  2351. struct mg_domain_context *next;
  2352. };
  2353. /* Stop flag can be "volatile" or require a lock */
  2354. typedef int volatile stop_flag_t;
  2355. #ifdef STOP_FLAG_NEEDS_LOCK
  2356. static int
  2357. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2358. {
  2359. int r;
  2360. mg_global_lock();
  2361. r = ((*f) == 0);
  2362. mg_global_unlock();
  2363. return r;
  2364. }
  2365. static int
  2366. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2367. {
  2368. int r;
  2369. mg_global_lock();
  2370. r = ((*f) == 2);
  2371. mg_global_unlock();
  2372. return r;
  2373. }
  2374. static void
  2375. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2376. {
  2377. mg_global_lock();
  2378. (*f) = v;
  2379. mg_global_unlock();
  2380. }
  2381. #else /* STOP_FLAG_NEEDS_LOCK */
  2382. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2383. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2384. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2385. #endif /* STOP_FLAG_NEEDS_LOCK */
  2386. struct mg_context {
  2387. /* Part 1 - Physical context:
  2388. * This holds threads, ports, timeouts, ...
  2389. * set for the entire server, independent from the
  2390. * addressed hostname.
  2391. */
  2392. /* Connection related */
  2393. int context_type; /* See CONTEXT_* above */
  2394. struct socket *listening_sockets;
  2395. struct mg_pollfd *listening_socket_fds;
  2396. unsigned int num_listening_sockets;
  2397. struct mg_connection *worker_connections; /* The connection struct, pre-
  2398. * allocated for each worker */
  2399. #if defined(USE_SERVER_STATS)
  2400. int active_connections;
  2401. int max_active_connections;
  2402. int64_t total_connections;
  2403. int64_t total_requests;
  2404. int64_t total_data_read;
  2405. int64_t total_data_written;
  2406. #endif
  2407. /* Thread related */
  2408. stop_flag_t stop_flag; /* Should we stop event loop */
  2409. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2410. pthread_t masterthreadid; /* The master thread ID */
  2411. unsigned int
  2412. cfg_worker_threads; /* The number of configured worker threads. */
  2413. pthread_t *worker_threadids; /* The worker thread IDs */
  2414. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2415. /* Connection to thread dispatching */
  2416. #if defined(ALTERNATIVE_QUEUE)
  2417. struct socket *client_socks;
  2418. void **client_wait_events;
  2419. #else
  2420. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2421. worker thread */
  2422. volatile int sq_head; /* Head of the socket queue */
  2423. volatile int sq_tail; /* Tail of the socket queue */
  2424. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2425. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2426. volatile int sq_blocked; /* Status information: sq is full */
  2427. int sq_size; /* No of elements in socket queue */
  2428. #if defined(USE_SERVER_STATS)
  2429. int sq_max_fill;
  2430. #endif /* USE_SERVER_STATS */
  2431. #endif /* ALTERNATIVE_QUEUE */
  2432. /* Memory related */
  2433. unsigned int max_request_size; /* The max request size */
  2434. #if defined(USE_SERVER_STATS)
  2435. struct mg_memory_stat ctx_memory;
  2436. #endif
  2437. /* Operating system related */
  2438. char *systemName; /* What operating system is running */
  2439. time_t start_time; /* Server start time, used for authentication
  2440. * and for diagnstics. */
  2441. #if defined(USE_TIMERS)
  2442. struct ttimers *timers;
  2443. #endif
  2444. /* Lua specific: Background operations and shared websockets */
  2445. #if defined(USE_LUA)
  2446. void *lua_background_state;
  2447. #endif
  2448. /* Server nonce */
  2449. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2450. * ssl_cert_last_mtime, nonce_count, and
  2451. * next (linked list) */
  2452. /* Server callbacks */
  2453. struct mg_callbacks callbacks; /* User-defined callback function */
  2454. void *user_data; /* User-defined data */
  2455. /* Part 2 - Logical domain:
  2456. * This holds hostname, TLS certificate, document root, ...
  2457. * set for a domain hosted at the server.
  2458. * There may be multiple domains hosted at one physical server.
  2459. * The default domain "dd" is the first element of a list of
  2460. * domains.
  2461. */
  2462. struct mg_domain_context dd; /* default domain */
  2463. };
  2464. #if defined(USE_SERVER_STATS)
  2465. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2466. static struct mg_memory_stat *
  2467. get_memory_stat(struct mg_context *ctx)
  2468. {
  2469. if (ctx) {
  2470. return &(ctx->ctx_memory);
  2471. }
  2472. return &mg_common_memory;
  2473. }
  2474. #endif
  2475. enum {
  2476. CONNECTION_TYPE_INVALID,
  2477. CONNECTION_TYPE_REQUEST,
  2478. CONNECTION_TYPE_RESPONSE
  2479. };
  2480. enum {
  2481. PROTOCOL_TYPE_HTTP1 = 0,
  2482. PROTOCOL_TYPE_WEBSOCKET = 1,
  2483. PROTOCOL_TYPE_HTTP2 = 2
  2484. };
  2485. struct mg_connection {
  2486. int connection_type; /* see CONNECTION_TYPE_* above */
  2487. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2488. struct mg_request_info request_info;
  2489. struct mg_response_info response_info;
  2490. struct mg_context *phys_ctx;
  2491. struct mg_domain_context *dom_ctx;
  2492. #if defined(USE_SERVER_STATS)
  2493. int conn_state; /* 0 = undef, numerical value may change in different
  2494. * versions. For the current definition, see
  2495. * mg_get_connection_info_impl */
  2496. #endif
  2497. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2498. SSL *ssl; /* SSL descriptor */
  2499. struct socket client; /* Connected client */
  2500. time_t conn_birth_time; /* Time (wall clock) when connection was
  2501. * established */
  2502. #if defined(USE_SERVER_STATS)
  2503. time_t conn_close_time; /* Time (wall clock) when connection was
  2504. * closed (or 0 if still open) */
  2505. #endif
  2506. struct timespec req_time; /* Time (since system start) when the request
  2507. * was received */
  2508. int64_t num_bytes_sent; /* Total bytes sent to client */
  2509. int64_t content_len; /* How many bytes of content can be read
  2510. * !is_chunked: Content-Length header value
  2511. * or -1 (until connection closed,
  2512. * not allowed for a request)
  2513. * is_chunked: >= 0, appended gradually
  2514. */
  2515. int64_t consumed_content; /* How many bytes of content have been read */
  2516. int is_chunked; /* Transfer-Encoding is chunked:
  2517. * 0 = not chunked,
  2518. * 1 = chunked, not yet, or some data read,
  2519. * 2 = chunked, has error,
  2520. * 3 = chunked, all data read except trailer,
  2521. * 4 = chunked, all data read
  2522. */
  2523. char *buf; /* Buffer for received data */
  2524. char *path_info; /* PATH_INFO part of the URL */
  2525. int must_close; /* 1 if connection must be closed */
  2526. int accept_gzip; /* 1 if gzip encoding is accepted */
  2527. int in_error_handler; /* 1 if in handler for user defined error
  2528. * pages */
  2529. #if defined(USE_WEBSOCKET)
  2530. int in_websocket_handling; /* 1 if in read_websocket */
  2531. #endif
  2532. int handled_requests; /* Number of requests handled by this connection
  2533. */
  2534. int buf_size; /* Buffer size */
  2535. int request_len; /* Size of the request + headers in a buffer */
  2536. int data_len; /* Total size of data in a buffer */
  2537. int status_code; /* HTTP reply status code, e.g. 200 */
  2538. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2539. * throttle */
  2540. time_t last_throttle_time; /* Last time throttled data was sent */
  2541. int last_throttle_bytes; /* Bytes sent this second */
  2542. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2543. * atomic transmissions for websockets */
  2544. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2545. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2546. #endif
  2547. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2548. * for quick access */
  2549. };
  2550. /* Directory entry */
  2551. struct de {
  2552. struct mg_connection *conn;
  2553. char *file_name;
  2554. struct mg_file_stat file;
  2555. };
  2556. #define mg_cry_internal(conn, fmt, ...) \
  2557. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2558. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2559. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2560. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2561. struct mg_context *ctx,
  2562. const char *func,
  2563. unsigned line,
  2564. const char *fmt,
  2565. ...) PRINTF_ARGS(5, 6);
  2566. #if !defined(NO_THREAD_NAME)
  2567. #if defined(_WIN32) && defined(_MSC_VER)
  2568. /* Set the thread name for debugging purposes in Visual Studio
  2569. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2570. */
  2571. #pragma pack(push, 8)
  2572. typedef struct tagTHREADNAME_INFO {
  2573. DWORD dwType; /* Must be 0x1000. */
  2574. LPCSTR szName; /* Pointer to name (in user addr space). */
  2575. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2576. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2577. } THREADNAME_INFO;
  2578. #pragma pack(pop)
  2579. #elif defined(__linux__)
  2580. #include <sys/prctl.h>
  2581. #include <sys/sendfile.h>
  2582. #if defined(ALTERNATIVE_QUEUE)
  2583. #include <sys/eventfd.h>
  2584. #endif /* ALTERNATIVE_QUEUE */
  2585. #if defined(ALTERNATIVE_QUEUE)
  2586. static void *
  2587. event_create(void)
  2588. {
  2589. int evhdl = eventfd(0, EFD_CLOEXEC);
  2590. int *ret;
  2591. if (evhdl == -1) {
  2592. /* Linux uses -1 on error, Windows NULL. */
  2593. /* However, Linux does not return 0 on success either. */
  2594. return 0;
  2595. }
  2596. ret = (int *)mg_malloc(sizeof(int));
  2597. if (ret) {
  2598. *ret = evhdl;
  2599. } else {
  2600. (void)close(evhdl);
  2601. }
  2602. return (void *)ret;
  2603. }
  2604. static int
  2605. event_wait(void *eventhdl)
  2606. {
  2607. uint64_t u;
  2608. int evhdl, s;
  2609. if (!eventhdl) {
  2610. /* error */
  2611. return 0;
  2612. }
  2613. evhdl = *(int *)eventhdl;
  2614. s = (int)read(evhdl, &u, sizeof(u));
  2615. if (s != sizeof(u)) {
  2616. /* error */
  2617. return 0;
  2618. }
  2619. (void)u; /* the value is not required */
  2620. return 1;
  2621. }
  2622. static int
  2623. event_signal(void *eventhdl)
  2624. {
  2625. uint64_t u = 1;
  2626. int evhdl, s;
  2627. if (!eventhdl) {
  2628. /* error */
  2629. return 0;
  2630. }
  2631. evhdl = *(int *)eventhdl;
  2632. s = (int)write(evhdl, &u, sizeof(u));
  2633. if (s != sizeof(u)) {
  2634. /* error */
  2635. return 0;
  2636. }
  2637. return 1;
  2638. }
  2639. static void
  2640. event_destroy(void *eventhdl)
  2641. {
  2642. int evhdl;
  2643. if (!eventhdl) {
  2644. /* error */
  2645. return;
  2646. }
  2647. evhdl = *(int *)eventhdl;
  2648. close(evhdl);
  2649. mg_free(eventhdl);
  2650. }
  2651. #endif
  2652. #endif
  2653. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2654. struct posix_event {
  2655. pthread_mutex_t mutex;
  2656. pthread_cond_t cond;
  2657. int signaled;
  2658. };
  2659. static void *
  2660. event_create(void)
  2661. {
  2662. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2663. if (ret == 0) {
  2664. /* out of memory */
  2665. return 0;
  2666. }
  2667. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2668. /* pthread mutex not available */
  2669. mg_free(ret);
  2670. return 0;
  2671. }
  2672. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2673. /* pthread cond not available */
  2674. pthread_mutex_destroy(&(ret->mutex));
  2675. mg_free(ret);
  2676. return 0;
  2677. }
  2678. ret->signaled = 0;
  2679. return (void *)ret;
  2680. }
  2681. static int
  2682. event_wait(void *eventhdl)
  2683. {
  2684. struct posix_event *ev = (struct posix_event *)eventhdl;
  2685. pthread_mutex_lock(&(ev->mutex));
  2686. while (!ev->signaled) {
  2687. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2688. }
  2689. ev->signaled = 0;
  2690. pthread_mutex_unlock(&(ev->mutex));
  2691. return 1;
  2692. }
  2693. static int
  2694. event_signal(void *eventhdl)
  2695. {
  2696. struct posix_event *ev = (struct posix_event *)eventhdl;
  2697. pthread_mutex_lock(&(ev->mutex));
  2698. pthread_cond_signal(&(ev->cond));
  2699. ev->signaled = 1;
  2700. pthread_mutex_unlock(&(ev->mutex));
  2701. return 1;
  2702. }
  2703. static void
  2704. event_destroy(void *eventhdl)
  2705. {
  2706. struct posix_event *ev = (struct posix_event *)eventhdl;
  2707. pthread_cond_destroy(&(ev->cond));
  2708. pthread_mutex_destroy(&(ev->mutex));
  2709. mg_free(ev);
  2710. }
  2711. #endif
  2712. static void
  2713. mg_set_thread_name(const char *name)
  2714. {
  2715. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2716. mg_snprintf(
  2717. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2718. #if defined(_WIN32)
  2719. #if defined(_MSC_VER)
  2720. /* Windows and Visual Studio Compiler */
  2721. __try {
  2722. THREADNAME_INFO info;
  2723. info.dwType = 0x1000;
  2724. info.szName = threadName;
  2725. info.dwThreadID = ~0U;
  2726. info.dwFlags = 0;
  2727. RaiseException(0x406D1388,
  2728. 0,
  2729. sizeof(info) / sizeof(ULONG_PTR),
  2730. (ULONG_PTR *)&info);
  2731. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2732. }
  2733. #elif defined(__MINGW32__)
  2734. /* No option known to set thread name for MinGW known */
  2735. #endif
  2736. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2737. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2738. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2739. #if defined(__MACH__)
  2740. /* OS X only current thread name can be changed */
  2741. (void)pthread_setname_np(threadName);
  2742. #else
  2743. (void)pthread_setname_np(pthread_self(), threadName);
  2744. #endif
  2745. #elif defined(__linux__)
  2746. /* On Linux we can use the prctl function.
  2747. * When building for Linux Standard Base (LSB) use
  2748. * NO_THREAD_NAME. However, thread names are a big
  2749. * help for debugging, so the stadard is to set them.
  2750. */
  2751. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2752. #endif
  2753. }
  2754. #else /* !defined(NO_THREAD_NAME) */
  2755. void
  2756. mg_set_thread_name(const char *threadName)
  2757. {
  2758. }
  2759. #endif
  2760. #if defined(MG_LEGACY_INTERFACE)
  2761. const char **
  2762. mg_get_valid_option_names(void)
  2763. {
  2764. /* This function is deprecated. Use mg_get_valid_options instead. */
  2765. static const char
  2766. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2767. int i;
  2768. for (i = 0; config_options[i].name != NULL; i++) {
  2769. data[i * 2] = config_options[i].name;
  2770. data[i * 2 + 1] = config_options[i].default_value;
  2771. }
  2772. return data;
  2773. }
  2774. #endif
  2775. const struct mg_option *
  2776. mg_get_valid_options(void)
  2777. {
  2778. return config_options;
  2779. }
  2780. /* Do not open file (used in is_file_in_memory) */
  2781. #define MG_FOPEN_MODE_NONE (0)
  2782. /* Open file for read only access */
  2783. #define MG_FOPEN_MODE_READ (1)
  2784. /* Open file for writing, create and overwrite */
  2785. #define MG_FOPEN_MODE_WRITE (2)
  2786. /* Open file for writing, create and append */
  2787. #define MG_FOPEN_MODE_APPEND (4)
  2788. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2789. * output filep and return 1, otherwise return 0 and don't modify anything.
  2790. */
  2791. static int
  2792. open_file_in_memory(const struct mg_connection *conn,
  2793. const char *path,
  2794. struct mg_file *filep,
  2795. int mode)
  2796. {
  2797. #if defined(MG_USE_OPEN_FILE)
  2798. size_t size = 0;
  2799. const char *buf = NULL;
  2800. if (!conn) {
  2801. return 0;
  2802. }
  2803. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2804. return 0;
  2805. }
  2806. if (conn->phys_ctx->callbacks.open_file) {
  2807. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2808. if (buf != NULL) {
  2809. if (filep == NULL) {
  2810. /* This is a file in memory, but we cannot store the
  2811. * properties
  2812. * now.
  2813. * Called from "is_file_in_memory" function. */
  2814. return 1;
  2815. }
  2816. /* NOTE: override filep->size only on success. Otherwise, it
  2817. * might
  2818. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2819. filep->access.membuf = buf;
  2820. filep->access.fp = NULL;
  2821. /* Size was set by the callback */
  2822. filep->stat.size = size;
  2823. /* Assume the data may change during runtime by setting
  2824. * last_modified = now */
  2825. filep->stat.last_modified = time(NULL);
  2826. filep->stat.is_directory = 0;
  2827. filep->stat.is_gzipped = 0;
  2828. }
  2829. }
  2830. return (buf != NULL);
  2831. #else
  2832. (void)conn;
  2833. (void)path;
  2834. (void)filep;
  2835. (void)mode;
  2836. return 0;
  2837. #endif
  2838. }
  2839. static int
  2840. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2841. {
  2842. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2843. }
  2844. static int
  2845. is_file_opened(const struct mg_file_access *fileacc)
  2846. {
  2847. if (!fileacc) {
  2848. return 0;
  2849. }
  2850. #if defined(MG_USE_OPEN_FILE)
  2851. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2852. #else
  2853. return (fileacc->fp != NULL);
  2854. #endif
  2855. }
  2856. #if !defined(NO_FILESYSTEMS)
  2857. static int mg_stat(const struct mg_connection *conn,
  2858. const char *path,
  2859. struct mg_file_stat *filep);
  2860. /* mg_fopen will open a file either in memory or on the disk.
  2861. * The input parameter path is a string in UTF-8 encoding.
  2862. * The input parameter mode is MG_FOPEN_MODE_*
  2863. * On success, either fp or membuf will be set in the output
  2864. * struct file. All status members will also be set.
  2865. * The function returns 1 on success, 0 on error. */
  2866. static int
  2867. mg_fopen(const struct mg_connection *conn,
  2868. const char *path,
  2869. int mode,
  2870. struct mg_file *filep)
  2871. {
  2872. int found;
  2873. if (!filep) {
  2874. return 0;
  2875. }
  2876. filep->access.fp = NULL;
  2877. #if defined(MG_USE_OPEN_FILE)
  2878. filep->access.membuf = NULL;
  2879. #endif
  2880. if (!is_file_in_memory(conn, path)) {
  2881. /* filep is initialized in mg_stat: all fields with memset to,
  2882. * some fields like size and modification date with values */
  2883. found = mg_stat(conn, path, &(filep->stat));
  2884. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2885. /* file does not exist and will not be created */
  2886. return 0;
  2887. }
  2888. #if defined(_WIN32)
  2889. {
  2890. wchar_t wbuf[W_PATH_MAX];
  2891. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2892. switch (mode) {
  2893. case MG_FOPEN_MODE_READ:
  2894. filep->access.fp = _wfopen(wbuf, L"rb");
  2895. break;
  2896. case MG_FOPEN_MODE_WRITE:
  2897. filep->access.fp = _wfopen(wbuf, L"wb");
  2898. break;
  2899. case MG_FOPEN_MODE_APPEND:
  2900. filep->access.fp = _wfopen(wbuf, L"ab");
  2901. break;
  2902. }
  2903. }
  2904. #else
  2905. /* Linux et al already use unicode. No need to convert. */
  2906. switch (mode) {
  2907. case MG_FOPEN_MODE_READ:
  2908. filep->access.fp = fopen(path, "r");
  2909. break;
  2910. case MG_FOPEN_MODE_WRITE:
  2911. filep->access.fp = fopen(path, "w");
  2912. break;
  2913. case MG_FOPEN_MODE_APPEND:
  2914. filep->access.fp = fopen(path, "a");
  2915. break;
  2916. }
  2917. #endif
  2918. if (!found) {
  2919. /* File did not exist before fopen was called.
  2920. * Maybe it has been created now. Get stat info
  2921. * like creation time now. */
  2922. found = mg_stat(conn, path, &(filep->stat));
  2923. (void)found;
  2924. }
  2925. /* file is on disk */
  2926. return (filep->access.fp != NULL);
  2927. } else {
  2928. #if defined(MG_USE_OPEN_FILE)
  2929. /* is_file_in_memory returned true */
  2930. if (open_file_in_memory(conn, path, filep, mode)) {
  2931. /* file is in memory */
  2932. return (filep->access.membuf != NULL);
  2933. }
  2934. #endif
  2935. }
  2936. /* Open failed */
  2937. return 0;
  2938. }
  2939. /* return 0 on success, just like fclose */
  2940. static int
  2941. mg_fclose(struct mg_file_access *fileacc)
  2942. {
  2943. int ret = -1;
  2944. if (fileacc != NULL) {
  2945. if (fileacc->fp != NULL) {
  2946. ret = fclose(fileacc->fp);
  2947. #if defined(MG_USE_OPEN_FILE)
  2948. } else if (fileacc->membuf != NULL) {
  2949. ret = 0;
  2950. #endif
  2951. }
  2952. /* reset all members of fileacc */
  2953. memset(fileacc, 0, sizeof(*fileacc));
  2954. }
  2955. return ret;
  2956. }
  2957. #endif /* NO_FILESYSTEMS */
  2958. static void
  2959. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2960. {
  2961. for (; *src != '\0' && n > 1; n--) {
  2962. *dst++ = *src++;
  2963. }
  2964. *dst = '\0';
  2965. }
  2966. static int
  2967. lowercase(const char *s)
  2968. {
  2969. return tolower((unsigned char)*s);
  2970. }
  2971. int
  2972. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2973. {
  2974. int diff = 0;
  2975. if (len > 0) {
  2976. do {
  2977. diff = lowercase(s1++) - lowercase(s2++);
  2978. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2979. }
  2980. return diff;
  2981. }
  2982. int
  2983. mg_strcasecmp(const char *s1, const char *s2)
  2984. {
  2985. int diff;
  2986. do {
  2987. diff = lowercase(s1++) - lowercase(s2++);
  2988. } while (diff == 0 && s1[-1] != '\0');
  2989. return diff;
  2990. }
  2991. static char *
  2992. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2993. {
  2994. char *p;
  2995. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2996. * defined */
  2997. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2998. mg_strlcpy(p, ptr, len + 1);
  2999. }
  3000. return p;
  3001. }
  3002. static char *
  3003. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3004. {
  3005. return mg_strndup_ctx(str, strlen(str), ctx);
  3006. }
  3007. static char *
  3008. mg_strdup(const char *str)
  3009. {
  3010. return mg_strndup_ctx(str, strlen(str), NULL);
  3011. }
  3012. static const char *
  3013. mg_strcasestr(const char *big_str, const char *small_str)
  3014. {
  3015. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3016. if (big_len >= small_len) {
  3017. for (i = 0; i <= (big_len - small_len); i++) {
  3018. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3019. return big_str + i;
  3020. }
  3021. }
  3022. }
  3023. return NULL;
  3024. }
  3025. /* Return null terminated string of given maximum length.
  3026. * Report errors if length is exceeded. */
  3027. static void
  3028. mg_vsnprintf(const struct mg_connection *conn,
  3029. int *truncated,
  3030. char *buf,
  3031. size_t buflen,
  3032. const char *fmt,
  3033. va_list ap)
  3034. {
  3035. int n, ok;
  3036. if (buflen == 0) {
  3037. if (truncated) {
  3038. *truncated = 1;
  3039. }
  3040. return;
  3041. }
  3042. #if defined(__clang__)
  3043. #pragma clang diagnostic push
  3044. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3045. /* Using fmt as a non-literal is intended here, since it is mostly called
  3046. * indirectly by mg_snprintf */
  3047. #endif
  3048. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3049. ok = (n >= 0) && ((size_t)n < buflen);
  3050. #if defined(__clang__)
  3051. #pragma clang diagnostic pop
  3052. #endif
  3053. if (ok) {
  3054. if (truncated) {
  3055. *truncated = 0;
  3056. }
  3057. } else {
  3058. if (truncated) {
  3059. *truncated = 1;
  3060. }
  3061. mg_cry_internal(conn,
  3062. "truncating vsnprintf buffer: [%.*s]",
  3063. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3064. buf);
  3065. n = (int)buflen - 1;
  3066. }
  3067. buf[n] = '\0';
  3068. }
  3069. static void
  3070. mg_snprintf(const struct mg_connection *conn,
  3071. int *truncated,
  3072. char *buf,
  3073. size_t buflen,
  3074. const char *fmt,
  3075. ...)
  3076. {
  3077. va_list ap;
  3078. va_start(ap, fmt);
  3079. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3080. va_end(ap);
  3081. }
  3082. static int
  3083. get_option_index(const char *name)
  3084. {
  3085. int i;
  3086. for (i = 0; config_options[i].name != NULL; i++) {
  3087. if (strcmp(config_options[i].name, name) == 0) {
  3088. return i;
  3089. }
  3090. }
  3091. return -1;
  3092. }
  3093. const char *
  3094. mg_get_option(const struct mg_context *ctx, const char *name)
  3095. {
  3096. int i;
  3097. if ((i = get_option_index(name)) == -1) {
  3098. return NULL;
  3099. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3100. return "";
  3101. } else {
  3102. return ctx->dd.config[i];
  3103. }
  3104. }
  3105. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3106. struct mg_context *
  3107. mg_get_context(const struct mg_connection *conn)
  3108. {
  3109. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3110. }
  3111. void *
  3112. mg_get_user_data(const struct mg_context *ctx)
  3113. {
  3114. return (ctx == NULL) ? NULL : ctx->user_data;
  3115. }
  3116. void *
  3117. mg_get_user_context_data(const struct mg_connection *conn)
  3118. {
  3119. return mg_get_user_data(mg_get_context(conn));
  3120. }
  3121. void *
  3122. mg_get_thread_pointer(const struct mg_connection *conn)
  3123. {
  3124. /* both methods should return the same pointer */
  3125. if (conn) {
  3126. /* quick access, in case conn is known */
  3127. return conn->tls_user_ptr;
  3128. } else {
  3129. /* otherwise get pointer from thread local storage (TLS) */
  3130. struct mg_workerTLS *tls =
  3131. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3132. return tls->user_ptr;
  3133. }
  3134. }
  3135. void
  3136. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3137. {
  3138. if (conn != NULL) {
  3139. conn->request_info.conn_data = data;
  3140. }
  3141. }
  3142. void *
  3143. mg_get_user_connection_data(const struct mg_connection *conn)
  3144. {
  3145. if (conn != NULL) {
  3146. return conn->request_info.conn_data;
  3147. }
  3148. return NULL;
  3149. }
  3150. #if defined(MG_LEGACY_INTERFACE)
  3151. /* Deprecated: Use mg_get_server_ports instead. */
  3152. size_t
  3153. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3154. {
  3155. size_t i;
  3156. if (!ctx) {
  3157. return 0;
  3158. }
  3159. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3160. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3161. ports[i] =
  3162. #if defined(USE_IPV6)
  3163. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3164. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3165. :
  3166. #endif
  3167. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3168. }
  3169. return i;
  3170. }
  3171. #endif
  3172. int
  3173. mg_get_server_ports(const struct mg_context *ctx,
  3174. int size,
  3175. struct mg_server_port *ports)
  3176. {
  3177. int i, cnt = 0;
  3178. if (size <= 0) {
  3179. return -1;
  3180. }
  3181. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3182. if (!ctx) {
  3183. return -1;
  3184. }
  3185. if (!ctx->listening_sockets) {
  3186. return -1;
  3187. }
  3188. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3189. ports[cnt].port =
  3190. #if defined(USE_IPV6)
  3191. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3192. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3193. :
  3194. #endif
  3195. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3196. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3197. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3198. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3199. /* IPv4 */
  3200. ports[cnt].protocol = 1;
  3201. cnt++;
  3202. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3203. /* IPv6 */
  3204. ports[cnt].protocol = 3;
  3205. cnt++;
  3206. }
  3207. }
  3208. return cnt;
  3209. }
  3210. static void
  3211. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3212. {
  3213. buf[0] = '\0';
  3214. if (!usa) {
  3215. return;
  3216. }
  3217. if (usa->sa.sa_family == AF_INET) {
  3218. getnameinfo(&usa->sa,
  3219. sizeof(usa->sin),
  3220. buf,
  3221. (unsigned)len,
  3222. NULL,
  3223. 0,
  3224. NI_NUMERICHOST);
  3225. }
  3226. #if defined(USE_IPV6)
  3227. else if (usa->sa.sa_family == AF_INET6) {
  3228. getnameinfo(&usa->sa,
  3229. sizeof(usa->sin6),
  3230. buf,
  3231. (unsigned)len,
  3232. NULL,
  3233. 0,
  3234. NI_NUMERICHOST);
  3235. }
  3236. #endif
  3237. }
  3238. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3239. * included in all responses other than 100, 101, 5xx. */
  3240. static void
  3241. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3242. {
  3243. #if !defined(REENTRANT_TIME)
  3244. struct tm *tm;
  3245. tm = ((t != NULL) ? gmtime(t) : NULL);
  3246. if (tm != NULL) {
  3247. #else
  3248. struct tm _tm;
  3249. struct tm *tm = &_tm;
  3250. if (t != NULL) {
  3251. gmtime_r(t, tm);
  3252. #endif
  3253. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3254. } else {
  3255. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3256. buf[buf_len - 1] = '\0';
  3257. }
  3258. }
  3259. /* difftime for struct timespec. Return value is in seconds. */
  3260. static double
  3261. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3262. {
  3263. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3264. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3265. }
  3266. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3267. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3268. const char *func,
  3269. unsigned line,
  3270. const char *fmt,
  3271. va_list ap);
  3272. #include "external_mg_cry_internal_impl.inl"
  3273. #elif !defined(NO_FILESYSTEMS)
  3274. /* Print error message to the opened error log stream. */
  3275. static void
  3276. mg_cry_internal_impl(const struct mg_connection *conn,
  3277. const char *func,
  3278. unsigned line,
  3279. const char *fmt,
  3280. va_list ap)
  3281. {
  3282. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3283. struct mg_file fi;
  3284. time_t timestamp;
  3285. /* Unused, in the RELEASE build */
  3286. (void)func;
  3287. (void)line;
  3288. #if defined(GCC_DIAGNOSTIC)
  3289. #pragma GCC diagnostic push
  3290. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3291. #endif
  3292. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3293. #if defined(GCC_DIAGNOSTIC)
  3294. #pragma GCC diagnostic pop
  3295. #endif
  3296. buf[sizeof(buf) - 1] = 0;
  3297. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3298. if (!conn) {
  3299. puts(buf);
  3300. return;
  3301. }
  3302. /* Do not lock when getting the callback value, here and below.
  3303. * I suppose this is fine, since function cannot disappear in the
  3304. * same way string option can. */
  3305. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3306. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3307. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3308. if (mg_fopen(conn,
  3309. conn->dom_ctx->config[ERROR_LOG_FILE],
  3310. MG_FOPEN_MODE_APPEND,
  3311. &fi)
  3312. == 0) {
  3313. fi.access.fp = NULL;
  3314. }
  3315. } else {
  3316. fi.access.fp = NULL;
  3317. }
  3318. if (fi.access.fp != NULL) {
  3319. flockfile(fi.access.fp);
  3320. timestamp = time(NULL);
  3321. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3322. fprintf(fi.access.fp,
  3323. "[%010lu] [error] [client %s] ",
  3324. (unsigned long)timestamp,
  3325. src_addr);
  3326. if (conn->request_info.request_method != NULL) {
  3327. fprintf(fi.access.fp,
  3328. "%s %s: ",
  3329. conn->request_info.request_method,
  3330. conn->request_info.request_uri
  3331. ? conn->request_info.request_uri
  3332. : "");
  3333. }
  3334. fprintf(fi.access.fp, "%s", buf);
  3335. fputc('\n', fi.access.fp);
  3336. fflush(fi.access.fp);
  3337. funlockfile(fi.access.fp);
  3338. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3339. * mg_cry here anyway ;-) */
  3340. }
  3341. }
  3342. }
  3343. #else
  3344. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3345. #endif /* Externally provided function */
  3346. /* Construct fake connection structure. Used for logging, if connection
  3347. * is not applicable at the moment of logging. */
  3348. static struct mg_connection *
  3349. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3350. {
  3351. static const struct mg_connection conn_zero = {0};
  3352. *fc = conn_zero;
  3353. fc->phys_ctx = ctx;
  3354. fc->dom_ctx = &(ctx->dd);
  3355. return fc;
  3356. }
  3357. static void
  3358. mg_cry_internal_wrap(const struct mg_connection *conn,
  3359. struct mg_context *ctx,
  3360. const char *func,
  3361. unsigned line,
  3362. const char *fmt,
  3363. ...)
  3364. {
  3365. va_list ap;
  3366. va_start(ap, fmt);
  3367. if (!conn && ctx) {
  3368. struct mg_connection fc;
  3369. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3370. } else {
  3371. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3372. }
  3373. va_end(ap);
  3374. }
  3375. void
  3376. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3377. {
  3378. va_list ap;
  3379. va_start(ap, fmt);
  3380. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3381. va_end(ap);
  3382. }
  3383. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3384. const char *
  3385. mg_version(void)
  3386. {
  3387. return CIVETWEB_VERSION;
  3388. }
  3389. const struct mg_request_info *
  3390. mg_get_request_info(const struct mg_connection *conn)
  3391. {
  3392. if (!conn) {
  3393. return NULL;
  3394. }
  3395. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3396. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3397. char txt[16];
  3398. struct mg_workerTLS *tls =
  3399. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3400. sprintf(txt, "%03i", conn->response_info.status_code);
  3401. if (strlen(txt) == 3) {
  3402. memcpy(tls->txtbuf, txt, 4);
  3403. } else {
  3404. strcpy(tls->txtbuf, "ERR");
  3405. }
  3406. ((struct mg_connection *)conn)->request_info.local_uri =
  3407. ((struct mg_connection *)conn)->request_info.request_uri =
  3408. tls->txtbuf; /* use thread safe buffer */
  3409. ((struct mg_connection *)conn)->request_info.num_headers =
  3410. conn->response_info.num_headers;
  3411. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3412. conn->response_info.http_headers,
  3413. sizeof(conn->response_info.http_headers));
  3414. } else
  3415. #endif
  3416. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3417. return NULL;
  3418. }
  3419. return &conn->request_info;
  3420. }
  3421. const struct mg_response_info *
  3422. mg_get_response_info(const struct mg_connection *conn)
  3423. {
  3424. if (!conn) {
  3425. return NULL;
  3426. }
  3427. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3428. return NULL;
  3429. }
  3430. return &conn->response_info;
  3431. }
  3432. static const char *
  3433. get_proto_name(const struct mg_connection *conn)
  3434. {
  3435. #if defined(__clang__)
  3436. #pragma clang diagnostic push
  3437. #pragma clang diagnostic ignored "-Wunreachable-code"
  3438. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3439. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3440. * unreachable, but splitting into four different #ifdef clauses here is more
  3441. * complicated.
  3442. */
  3443. #endif
  3444. const struct mg_request_info *ri = &conn->request_info;
  3445. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3446. ? (ri->is_ssl ? "wss" : "ws")
  3447. : (ri->is_ssl ? "https" : "http"));
  3448. return proto;
  3449. #if defined(__clang__)
  3450. #pragma clang diagnostic pop
  3451. #endif
  3452. }
  3453. int
  3454. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3455. {
  3456. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3457. return -1;
  3458. } else {
  3459. int truncated = 0;
  3460. const struct mg_request_info *ri = &conn->request_info;
  3461. const char *proto = get_proto_name(conn);
  3462. if (ri->local_uri == NULL) {
  3463. return -1;
  3464. }
  3465. if ((ri->request_uri != NULL)
  3466. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3467. /* The request uri is different from the local uri.
  3468. * This is usually if an absolute URI, including server
  3469. * name has been provided. */
  3470. mg_snprintf(conn,
  3471. &truncated,
  3472. buf,
  3473. buflen,
  3474. "%s://%s",
  3475. proto,
  3476. ri->request_uri);
  3477. if (truncated) {
  3478. return -1;
  3479. }
  3480. return 0;
  3481. } else {
  3482. /* The common case is a relative URI, so we have to
  3483. * construct an absolute URI from server name and port */
  3484. #if defined(USE_IPV6)
  3485. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3486. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3487. : htons(conn->client.lsa.sin.sin_port);
  3488. #else
  3489. int port = htons(conn->client.lsa.sin.sin_port);
  3490. #endif
  3491. int def_port = ri->is_ssl ? 443 : 80;
  3492. int auth_domain_check_enabled =
  3493. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3494. && (!mg_strcasecmp(
  3495. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3496. const char *server_domain =
  3497. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3498. char portstr[16];
  3499. char server_ip[48];
  3500. if (port != def_port) {
  3501. sprintf(portstr, ":%u", (unsigned)port);
  3502. } else {
  3503. portstr[0] = 0;
  3504. }
  3505. if (!auth_domain_check_enabled || !server_domain) {
  3506. sockaddr_to_string(server_ip,
  3507. sizeof(server_ip),
  3508. &conn->client.lsa);
  3509. server_domain = server_ip;
  3510. }
  3511. mg_snprintf(conn,
  3512. &truncated,
  3513. buf,
  3514. buflen,
  3515. "%s://%s%s%s",
  3516. proto,
  3517. server_domain,
  3518. portstr,
  3519. ri->local_uri);
  3520. if (truncated) {
  3521. return -1;
  3522. }
  3523. return 0;
  3524. }
  3525. }
  3526. }
  3527. /* Skip the characters until one of the delimiters characters found.
  3528. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3529. * Advance pointer to buffer to the next word. Return found 0-terminated
  3530. * word.
  3531. * Delimiters can be quoted with quotechar. */
  3532. static char *
  3533. skip_quoted(char **buf,
  3534. const char *delimiters,
  3535. const char *whitespace,
  3536. char quotechar)
  3537. {
  3538. char *p, *begin_word, *end_word, *end_whitespace;
  3539. begin_word = *buf;
  3540. end_word = begin_word + strcspn(begin_word, delimiters);
  3541. /* Check for quotechar */
  3542. if (end_word > begin_word) {
  3543. p = end_word - 1;
  3544. while (*p == quotechar) {
  3545. /* While the delimiter is quoted, look for the next delimiter.
  3546. */
  3547. /* This happens, e.g., in calls from parse_auth_header,
  3548. * if the user name contains a " character. */
  3549. /* If there is anything beyond end_word, copy it. */
  3550. if (*end_word != '\0') {
  3551. size_t end_off = strcspn(end_word + 1, delimiters);
  3552. memmove(p, end_word, end_off + 1);
  3553. p += end_off; /* p must correspond to end_word - 1 */
  3554. end_word += end_off + 1;
  3555. } else {
  3556. *p = '\0';
  3557. break;
  3558. }
  3559. }
  3560. for (p++; p < end_word; p++) {
  3561. *p = '\0';
  3562. }
  3563. }
  3564. if (*end_word == '\0') {
  3565. *buf = end_word;
  3566. } else {
  3567. #if defined(GCC_DIAGNOSTIC)
  3568. /* Disable spurious conversion warning for GCC */
  3569. #pragma GCC diagnostic push
  3570. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3571. #endif /* defined(GCC_DIAGNOSTIC) */
  3572. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3573. #if defined(GCC_DIAGNOSTIC)
  3574. #pragma GCC diagnostic pop
  3575. #endif /* defined(GCC_DIAGNOSTIC) */
  3576. for (p = end_word; p < end_whitespace; p++) {
  3577. *p = '\0';
  3578. }
  3579. *buf = end_whitespace;
  3580. }
  3581. return begin_word;
  3582. }
  3583. /* Return HTTP header value, or NULL if not found. */
  3584. static const char *
  3585. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3586. {
  3587. int i;
  3588. for (i = 0; i < num_hdr; i++) {
  3589. if (!mg_strcasecmp(name, hdr[i].name)) {
  3590. return hdr[i].value;
  3591. }
  3592. }
  3593. return NULL;
  3594. }
  3595. #if defined(USE_WEBSOCKET)
  3596. /* Retrieve requested HTTP header multiple values, and return the number of
  3597. * found occurrences */
  3598. static int
  3599. get_req_headers(const struct mg_request_info *ri,
  3600. const char *name,
  3601. const char **output,
  3602. int output_max_size)
  3603. {
  3604. int i;
  3605. int cnt = 0;
  3606. if (ri) {
  3607. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3608. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3609. output[cnt++] = ri->http_headers[i].value;
  3610. }
  3611. }
  3612. }
  3613. return cnt;
  3614. }
  3615. #endif
  3616. const char *
  3617. mg_get_header(const struct mg_connection *conn, const char *name)
  3618. {
  3619. if (!conn) {
  3620. return NULL;
  3621. }
  3622. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3623. return get_header(conn->request_info.http_headers,
  3624. conn->request_info.num_headers,
  3625. name);
  3626. }
  3627. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3628. return get_header(conn->response_info.http_headers,
  3629. conn->response_info.num_headers,
  3630. name);
  3631. }
  3632. return NULL;
  3633. }
  3634. static const char *
  3635. get_http_version(const struct mg_connection *conn)
  3636. {
  3637. if (!conn) {
  3638. return NULL;
  3639. }
  3640. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3641. return conn->request_info.http_version;
  3642. }
  3643. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3644. return conn->response_info.http_version;
  3645. }
  3646. return NULL;
  3647. }
  3648. /* A helper function for traversing a comma separated list of values.
  3649. * It returns a list pointer shifted to the next value, or NULL if the end
  3650. * of the list found.
  3651. * Value is stored in val vector. If value has form "x=y", then eq_val
  3652. * vector is initialized to point to the "y" part, and val vector length
  3653. * is adjusted to point only to "x". */
  3654. static const char *
  3655. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3656. {
  3657. int end;
  3658. reparse:
  3659. if (val == NULL || list == NULL || *list == '\0') {
  3660. /* End of the list */
  3661. return NULL;
  3662. }
  3663. /* Skip over leading LWS */
  3664. while (*list == ' ' || *list == '\t')
  3665. list++;
  3666. val->ptr = list;
  3667. if ((list = strchr(val->ptr, ',')) != NULL) {
  3668. /* Comma found. Store length and shift the list ptr */
  3669. val->len = ((size_t)(list - val->ptr));
  3670. list++;
  3671. } else {
  3672. /* This value is the last one */
  3673. list = val->ptr + strlen(val->ptr);
  3674. val->len = ((size_t)(list - val->ptr));
  3675. }
  3676. /* Adjust length for trailing LWS */
  3677. end = (int)val->len - 1;
  3678. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3679. end--;
  3680. val->len = (size_t)(end) + (size_t)(1);
  3681. if (val->len == 0) {
  3682. /* Ignore any empty entries. */
  3683. goto reparse;
  3684. }
  3685. if (eq_val != NULL) {
  3686. /* Value has form "x=y", adjust pointers and lengths
  3687. * so that val points to "x", and eq_val points to "y". */
  3688. eq_val->len = 0;
  3689. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3690. if (eq_val->ptr != NULL) {
  3691. eq_val->ptr++; /* Skip over '=' character */
  3692. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3693. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3694. }
  3695. }
  3696. return list;
  3697. }
  3698. /* A helper function for checking if a comma separated list of values
  3699. * contains
  3700. * the given option (case insensitvely).
  3701. * 'header' can be NULL, in which case false is returned. */
  3702. static int
  3703. header_has_option(const char *header, const char *option)
  3704. {
  3705. struct vec opt_vec;
  3706. struct vec eq_vec;
  3707. DEBUG_ASSERT(option != NULL);
  3708. DEBUG_ASSERT(option[0] != '\0');
  3709. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3710. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3711. return 1;
  3712. }
  3713. return 0;
  3714. }
  3715. /* Perform case-insensitive match of string against pattern */
  3716. static ptrdiff_t
  3717. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3718. {
  3719. const char *or_str;
  3720. ptrdiff_t i, j, len, res;
  3721. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3722. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3723. return (res > 0) ? res
  3724. : match_prefix(or_str + 1,
  3725. (size_t)((pattern + pattern_len)
  3726. - (or_str + 1)),
  3727. str);
  3728. }
  3729. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3730. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3731. continue;
  3732. } else if (pattern[i] == '$') {
  3733. return (str[j] == '\0') ? j : -1;
  3734. } else if (pattern[i] == '*') {
  3735. i++;
  3736. if (pattern[i] == '*') {
  3737. i++;
  3738. len = (ptrdiff_t)strlen(str + j);
  3739. } else {
  3740. len = (ptrdiff_t)strcspn(str + j, "/");
  3741. }
  3742. if (i == (ptrdiff_t)pattern_len) {
  3743. return j + len;
  3744. }
  3745. do {
  3746. res = match_prefix(pattern + i,
  3747. (pattern_len - (size_t)i),
  3748. str + j + len);
  3749. } while (res == -1 && len-- > 0);
  3750. return (res == -1) ? -1 : j + res + len;
  3751. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3752. return -1;
  3753. }
  3754. }
  3755. return (ptrdiff_t)j;
  3756. }
  3757. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3758. * This function must tolerate situations when connection info is not
  3759. * set up, for example if request parsing failed. */
  3760. static int
  3761. should_keep_alive(const struct mg_connection *conn)
  3762. {
  3763. const char *http_version;
  3764. const char *header;
  3765. /* First satisfy needs of the server */
  3766. if ((conn == NULL) || conn->must_close) {
  3767. /* Close, if civetweb framework needs to close */
  3768. return 0;
  3769. }
  3770. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3771. /* Close, if keep alive is not enabled */
  3772. return 0;
  3773. }
  3774. /* Check explicit wish of the client */
  3775. header = mg_get_header(conn, "Connection");
  3776. if (header) {
  3777. /* If there is a connection header from the client, obey */
  3778. if (header_has_option(header, "keep-alive")) {
  3779. return 1;
  3780. }
  3781. return 0;
  3782. }
  3783. /* Use default of the standard */
  3784. http_version = get_http_version(conn);
  3785. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3786. /* HTTP 1.1 default is keep alive */
  3787. return 1;
  3788. }
  3789. /* HTTP 1.0 (and earlier) default is to close the connection */
  3790. return 0;
  3791. }
  3792. static int
  3793. should_decode_url(const struct mg_connection *conn)
  3794. {
  3795. if (!conn || !conn->dom_ctx) {
  3796. return 0;
  3797. }
  3798. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3799. }
  3800. static const char *
  3801. suggest_connection_header(const struct mg_connection *conn)
  3802. {
  3803. return should_keep_alive(conn) ? "keep-alive" : "close";
  3804. }
  3805. static int
  3806. send_no_cache_header(struct mg_connection *conn)
  3807. {
  3808. /* Send all current and obsolete cache opt-out directives. */
  3809. return mg_printf(conn,
  3810. "Cache-Control: no-cache, no-store, "
  3811. "must-revalidate, private, max-age=0\r\n"
  3812. "Pragma: no-cache\r\n"
  3813. "Expires: 0\r\n");
  3814. }
  3815. static int
  3816. send_static_cache_header(struct mg_connection *conn)
  3817. {
  3818. #if !defined(NO_CACHING)
  3819. int max_age;
  3820. const char *cache_control =
  3821. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3822. if (cache_control != NULL) {
  3823. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3824. }
  3825. /* Read the server config to check how long a file may be cached.
  3826. * The configuration is in seconds. */
  3827. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3828. if (max_age <= 0) {
  3829. /* 0 means "do not cache". All values <0 are reserved
  3830. * and may be used differently in the future. */
  3831. /* If a file should not be cached, do not only send
  3832. * max-age=0, but also pragmas and Expires headers. */
  3833. return send_no_cache_header(conn);
  3834. }
  3835. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3836. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3837. /* See also https://www.mnot.net/cache_docs/ */
  3838. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3839. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3840. * leap
  3841. * year to 31622400 seconds. For the moment, we just send whatever has
  3842. * been configured, still the behavior for >1 year should be considered
  3843. * as undefined. */
  3844. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3845. #else /* NO_CACHING */
  3846. return send_no_cache_header(conn);
  3847. #endif /* !NO_CACHING */
  3848. }
  3849. static int
  3850. send_additional_header(struct mg_connection *conn)
  3851. {
  3852. int i = 0;
  3853. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3854. #if !defined(NO_SSL)
  3855. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3856. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3857. if (max_age >= 0) {
  3858. i += mg_printf(conn,
  3859. "Strict-Transport-Security: max-age=%u\r\n",
  3860. (unsigned)max_age);
  3861. }
  3862. }
  3863. #endif
  3864. if (header && header[0]) {
  3865. i += mg_printf(conn, "%s\r\n", header);
  3866. }
  3867. return i;
  3868. }
  3869. #if !defined(NO_FILESYSTEMS)
  3870. static void handle_file_based_request(struct mg_connection *conn,
  3871. const char *path,
  3872. struct mg_file *filep);
  3873. #endif /* NO_FILESYSTEMS */
  3874. const char *
  3875. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3876. {
  3877. /* See IANA HTTP status code assignment:
  3878. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3879. */
  3880. switch (response_code) {
  3881. /* RFC2616 Section 10.1 - Informational 1xx */
  3882. case 100:
  3883. return "Continue"; /* RFC2616 Section 10.1.1 */
  3884. case 101:
  3885. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3886. case 102:
  3887. return "Processing"; /* RFC2518 Section 10.1 */
  3888. /* RFC2616 Section 10.2 - Successful 2xx */
  3889. case 200:
  3890. return "OK"; /* RFC2616 Section 10.2.1 */
  3891. case 201:
  3892. return "Created"; /* RFC2616 Section 10.2.2 */
  3893. case 202:
  3894. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3895. case 203:
  3896. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3897. case 204:
  3898. return "No Content"; /* RFC2616 Section 10.2.5 */
  3899. case 205:
  3900. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3901. case 206:
  3902. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3903. case 207:
  3904. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3905. */
  3906. case 208:
  3907. return "Already Reported"; /* RFC5842 Section 7.1 */
  3908. case 226:
  3909. return "IM used"; /* RFC3229 Section 10.4.1 */
  3910. /* RFC2616 Section 10.3 - Redirection 3xx */
  3911. case 300:
  3912. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3913. case 301:
  3914. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3915. case 302:
  3916. return "Found"; /* RFC2616 Section 10.3.3 */
  3917. case 303:
  3918. return "See Other"; /* RFC2616 Section 10.3.4 */
  3919. case 304:
  3920. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3921. case 305:
  3922. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3923. case 307:
  3924. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3925. case 308:
  3926. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3927. /* RFC2616 Section 10.4 - Client Error 4xx */
  3928. case 400:
  3929. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3930. case 401:
  3931. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3932. case 402:
  3933. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3934. case 403:
  3935. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3936. case 404:
  3937. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3938. case 405:
  3939. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3940. case 406:
  3941. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3942. case 407:
  3943. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3944. case 408:
  3945. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3946. case 409:
  3947. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3948. case 410:
  3949. return "Gone"; /* RFC2616 Section 10.4.11 */
  3950. case 411:
  3951. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3952. case 412:
  3953. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3954. case 413:
  3955. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3956. case 414:
  3957. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3958. case 415:
  3959. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3960. case 416:
  3961. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3962. */
  3963. case 417:
  3964. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3965. case 421:
  3966. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3967. case 422:
  3968. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3969. * Section 11.2 */
  3970. case 423:
  3971. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3972. case 424:
  3973. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3974. * Section 11.4 */
  3975. case 426:
  3976. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3977. case 428:
  3978. return "Precondition Required"; /* RFC 6585, Section 3 */
  3979. case 429:
  3980. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3981. case 431:
  3982. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3983. case 451:
  3984. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3985. * Section 3 */
  3986. /* RFC2616 Section 10.5 - Server Error 5xx */
  3987. case 500:
  3988. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3989. case 501:
  3990. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3991. case 502:
  3992. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3993. case 503:
  3994. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3995. case 504:
  3996. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3997. case 505:
  3998. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3999. case 506:
  4000. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4001. case 507:
  4002. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4003. * Section 11.5 */
  4004. case 508:
  4005. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4006. case 510:
  4007. return "Not Extended"; /* RFC 2774, Section 7 */
  4008. case 511:
  4009. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4010. /* Other status codes, not shown in the IANA HTTP status code
  4011. * assignment.
  4012. * E.g., "de facto" standards due to common use, ... */
  4013. case 418:
  4014. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4015. case 419:
  4016. return "Authentication Timeout"; /* common use */
  4017. case 420:
  4018. return "Enhance Your Calm"; /* common use */
  4019. case 440:
  4020. return "Login Timeout"; /* common use */
  4021. case 509:
  4022. return "Bandwidth Limit Exceeded"; /* common use */
  4023. default:
  4024. /* This error code is unknown. This should not happen. */
  4025. if (conn) {
  4026. mg_cry_internal(conn,
  4027. "Unknown HTTP response code: %u",
  4028. response_code);
  4029. }
  4030. /* Return at least a category according to RFC 2616 Section 10. */
  4031. if (response_code >= 100 && response_code < 200) {
  4032. /* Unknown informational status code */
  4033. return "Information";
  4034. }
  4035. if (response_code >= 200 && response_code < 300) {
  4036. /* Unknown success code */
  4037. return "Success";
  4038. }
  4039. if (response_code >= 300 && response_code < 400) {
  4040. /* Unknown redirection code */
  4041. return "Redirection";
  4042. }
  4043. if (response_code >= 400 && response_code < 500) {
  4044. /* Unknown request error code */
  4045. return "Client Error";
  4046. }
  4047. if (response_code >= 500 && response_code < 600) {
  4048. /* Unknown server error code */
  4049. return "Server Error";
  4050. }
  4051. /* Response code not even within reasonable range */
  4052. return "";
  4053. }
  4054. }
  4055. static int
  4056. mg_send_http_error_impl(struct mg_connection *conn,
  4057. int status,
  4058. const char *fmt,
  4059. va_list args)
  4060. {
  4061. char errmsg_buf[MG_BUF_LEN];
  4062. va_list ap;
  4063. int has_body;
  4064. char date[64];
  4065. time_t curtime = time(NULL);
  4066. #if !defined(NO_FILESYSTEMS)
  4067. char path_buf[PATH_MAX];
  4068. int len, i, page_handler_found, scope, truncated;
  4069. const char *error_handler = NULL;
  4070. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4071. const char *error_page_file_ext, *tstr;
  4072. #endif /* NO_FILESYSTEMS */
  4073. int handled_by_callback = 0;
  4074. const char *status_text = mg_get_response_code_text(conn, status);
  4075. if ((conn == NULL) || (fmt == NULL)) {
  4076. return -2;
  4077. }
  4078. /* Set status (for log) */
  4079. conn->status_code = status;
  4080. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4081. has_body = ((status > 199) && (status != 204) && (status != 304));
  4082. /* Prepare message in buf, if required */
  4083. if (has_body
  4084. || (!conn->in_error_handler
  4085. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4086. /* Store error message in errmsg_buf */
  4087. va_copy(ap, args);
  4088. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4089. va_end(ap);
  4090. /* In a debug build, print all html errors */
  4091. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4092. }
  4093. /* If there is a http_error callback, call it.
  4094. * But don't do it recursively, if callback calls mg_send_http_error again.
  4095. */
  4096. if (!conn->in_error_handler
  4097. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4098. /* Mark in_error_handler to avoid recursion and call user callback. */
  4099. conn->in_error_handler = 1;
  4100. handled_by_callback =
  4101. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4102. == 0);
  4103. conn->in_error_handler = 0;
  4104. }
  4105. if (!handled_by_callback) {
  4106. /* Check for recursion */
  4107. if (conn->in_error_handler) {
  4108. DEBUG_TRACE(
  4109. "Recursion when handling error %u - fall back to default",
  4110. status);
  4111. #if !defined(NO_FILESYSTEMS)
  4112. } else {
  4113. /* Send user defined error pages, if defined */
  4114. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4115. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4116. page_handler_found = 0;
  4117. if (error_handler != NULL) {
  4118. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4119. switch (scope) {
  4120. case 1: /* Handler for specific error, e.g. 404 error */
  4121. mg_snprintf(conn,
  4122. &truncated,
  4123. path_buf,
  4124. sizeof(path_buf) - 32,
  4125. "%serror%03u.",
  4126. error_handler,
  4127. status);
  4128. break;
  4129. case 2: /* Handler for error group, e.g., 5xx error
  4130. * handler
  4131. * for all server errors (500-599) */
  4132. mg_snprintf(conn,
  4133. &truncated,
  4134. path_buf,
  4135. sizeof(path_buf) - 32,
  4136. "%serror%01uxx.",
  4137. error_handler,
  4138. status / 100);
  4139. break;
  4140. default: /* Handler for all errors */
  4141. mg_snprintf(conn,
  4142. &truncated,
  4143. path_buf,
  4144. sizeof(path_buf) - 32,
  4145. "%serror.",
  4146. error_handler);
  4147. break;
  4148. }
  4149. /* String truncation in buf may only occur if
  4150. * error_handler is too long. This string is
  4151. * from the config, not from a client. */
  4152. (void)truncated;
  4153. /* The following code is redundant, but it should avoid
  4154. * false positives in static source code analyzers and
  4155. * vulnerability scanners.
  4156. */
  4157. path_buf[sizeof(path_buf) - 32] = 0;
  4158. len = (int)strlen(path_buf);
  4159. if (len > (int)sizeof(path_buf) - 32) {
  4160. len = (int)sizeof(path_buf) - 32;
  4161. }
  4162. /* Start with the file extenstion from the configuration. */
  4163. tstr = strchr(error_page_file_ext, '.');
  4164. while (tstr) {
  4165. for (i = 1;
  4166. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4167. i++) {
  4168. /* buffer overrun is not possible here, since
  4169. * (i < 32) && (len < sizeof(path_buf) - 32)
  4170. * ==> (i + len) < sizeof(path_buf) */
  4171. path_buf[len + i - 1] = tstr[i];
  4172. }
  4173. /* buffer overrun is not possible here, since
  4174. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4175. * ==> (i + len) <= sizeof(path_buf) */
  4176. path_buf[len + i - 1] = 0;
  4177. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4178. DEBUG_TRACE("Check error page %s - found",
  4179. path_buf);
  4180. page_handler_found = 1;
  4181. break;
  4182. }
  4183. DEBUG_TRACE("Check error page %s - not found",
  4184. path_buf);
  4185. /* Continue with the next file extenstion from the
  4186. * configuration (if there is a next one). */
  4187. tstr = strchr(tstr + i, '.');
  4188. }
  4189. }
  4190. }
  4191. if (page_handler_found) {
  4192. conn->in_error_handler = 1;
  4193. handle_file_based_request(conn, path_buf, &error_page_file);
  4194. conn->in_error_handler = 0;
  4195. return 0;
  4196. }
  4197. #endif /* NO_FILESYSTEMS */
  4198. }
  4199. /* No custom error page. Send default error page. */
  4200. gmt_time_string(date, sizeof(date), &curtime);
  4201. conn->must_close = 1;
  4202. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4203. send_no_cache_header(conn);
  4204. send_additional_header(conn);
  4205. if (has_body) {
  4206. mg_printf(conn,
  4207. "%s",
  4208. "Content-Type: text/plain; charset=utf-8\r\n");
  4209. }
  4210. mg_printf(conn,
  4211. "Date: %s\r\n"
  4212. "Connection: close\r\n\r\n",
  4213. date);
  4214. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4215. if (has_body) {
  4216. /* For other errors, send a generic error message. */
  4217. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4218. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4219. } else {
  4220. /* No body allowed. Close the connection. */
  4221. DEBUG_TRACE("Error %i", status);
  4222. }
  4223. }
  4224. return 0;
  4225. }
  4226. int
  4227. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4228. {
  4229. va_list ap;
  4230. int ret;
  4231. va_start(ap, fmt);
  4232. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4233. va_end(ap);
  4234. return ret;
  4235. }
  4236. int
  4237. mg_send_http_ok(struct mg_connection *conn,
  4238. const char *mime_type,
  4239. long long content_length)
  4240. {
  4241. char date[64];
  4242. time_t curtime = time(NULL);
  4243. if ((mime_type == NULL) || (*mime_type == 0)) {
  4244. /* No content type defined: default to text/html */
  4245. mime_type = "text/html";
  4246. }
  4247. gmt_time_string(date, sizeof(date), &curtime);
  4248. mg_printf(conn,
  4249. "HTTP/1.1 200 OK\r\n"
  4250. "Content-Type: %s\r\n"
  4251. "Date: %s\r\n"
  4252. "Connection: %s\r\n",
  4253. mime_type,
  4254. date,
  4255. suggest_connection_header(conn));
  4256. send_no_cache_header(conn);
  4257. send_additional_header(conn);
  4258. if (content_length < 0) {
  4259. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4260. } else {
  4261. mg_printf(conn,
  4262. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4263. (uint64_t)content_length);
  4264. }
  4265. return 0;
  4266. }
  4267. int
  4268. mg_send_http_redirect(struct mg_connection *conn,
  4269. const char *target_url,
  4270. int redirect_code)
  4271. {
  4272. /* Send a 30x redirect response.
  4273. *
  4274. * Redirect types (status codes):
  4275. *
  4276. * Status | Perm/Temp | Method | Version
  4277. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4278. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4279. * 303 | temporary | always use GET | HTTP/1.1
  4280. * 307 | temporary | always keep method | HTTP/1.1
  4281. * 308 | permanent | always keep method | HTTP/1.1
  4282. */
  4283. const char *redirect_text;
  4284. int ret;
  4285. size_t content_len = 0;
  4286. char reply[MG_BUF_LEN];
  4287. /* In case redirect_code=0, use 307. */
  4288. if (redirect_code == 0) {
  4289. redirect_code = 307;
  4290. }
  4291. /* In case redirect_code is none of the above, return error. */
  4292. if ((redirect_code != 301) && (redirect_code != 302)
  4293. && (redirect_code != 303) && (redirect_code != 307)
  4294. && (redirect_code != 308)) {
  4295. /* Parameter error */
  4296. return -2;
  4297. }
  4298. /* Get proper text for response code */
  4299. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4300. /* If target_url is not defined, redirect to "/". */
  4301. if ((target_url == NULL) || (*target_url == 0)) {
  4302. target_url = "/";
  4303. }
  4304. #if defined(MG_SEND_REDIRECT_BODY)
  4305. /* TODO: condition name? */
  4306. /* Prepare a response body with a hyperlink.
  4307. *
  4308. * According to RFC2616 (and RFC1945 before):
  4309. * Unless the request method was HEAD, the entity of the
  4310. * response SHOULD contain a short hypertext note with a hyperlink to
  4311. * the new URI(s).
  4312. *
  4313. * However, this response body is not useful in M2M communication.
  4314. * Probably the original reason in the RFC was, clients not supporting
  4315. * a 30x HTTP redirect could still show the HTML page and let the user
  4316. * press the link. Since current browsers support 30x HTTP, the additional
  4317. * HTML body does not seem to make sense anymore.
  4318. *
  4319. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4320. * but it only notes:
  4321. * The server's response payload usually contains a short
  4322. * hypertext note with a hyperlink to the new URI(s).
  4323. *
  4324. * Deactivated by default. If you need the 30x body, set the define.
  4325. */
  4326. mg_snprintf(
  4327. conn,
  4328. NULL /* ignore truncation */,
  4329. reply,
  4330. sizeof(reply),
  4331. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4332. redirect_text,
  4333. target_url,
  4334. target_url);
  4335. content_len = strlen(reply);
  4336. #else
  4337. reply[0] = 0;
  4338. #endif
  4339. /* Do not send any additional header. For all other options,
  4340. * including caching, there are suitable defaults. */
  4341. ret = mg_printf(conn,
  4342. "HTTP/1.1 %i %s\r\n"
  4343. "Location: %s\r\n"
  4344. "Content-Length: %u\r\n"
  4345. "Connection: %s\r\n\r\n",
  4346. redirect_code,
  4347. redirect_text,
  4348. target_url,
  4349. (unsigned int)content_len,
  4350. suggest_connection_header(conn));
  4351. /* Send response body */
  4352. if (ret > 0) {
  4353. /* ... unless it is a HEAD request */
  4354. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4355. ret = mg_write(conn, reply, content_len);
  4356. }
  4357. }
  4358. return (ret > 0) ? ret : -1;
  4359. }
  4360. #if defined(_WIN32)
  4361. /* Create substitutes for POSIX functions in Win32. */
  4362. #if defined(GCC_DIAGNOSTIC)
  4363. /* Show no warning in case system functions are not used. */
  4364. #pragma GCC diagnostic push
  4365. #pragma GCC diagnostic ignored "-Wunused-function"
  4366. #endif
  4367. static int
  4368. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4369. {
  4370. (void)unused;
  4371. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4372. InitializeCriticalSection(&mutex->sec);
  4373. return 0;
  4374. }
  4375. static int
  4376. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4377. {
  4378. DeleteCriticalSection(&mutex->sec);
  4379. return 0;
  4380. }
  4381. static int
  4382. pthread_mutex_lock(pthread_mutex_t *mutex)
  4383. {
  4384. EnterCriticalSection(&mutex->sec);
  4385. return 0;
  4386. }
  4387. static int
  4388. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4389. {
  4390. LeaveCriticalSection(&mutex->sec);
  4391. return 0;
  4392. }
  4393. FUNCTION_MAY_BE_UNUSED
  4394. static int
  4395. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4396. {
  4397. (void)unused;
  4398. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4399. cv->waiting_thread = NULL;
  4400. return 0;
  4401. }
  4402. FUNCTION_MAY_BE_UNUSED
  4403. static int
  4404. pthread_cond_timedwait(pthread_cond_t *cv,
  4405. pthread_mutex_t *mutex,
  4406. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4407. {
  4408. struct mg_workerTLS **ptls,
  4409. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4410. int ok;
  4411. int64_t nsnow, nswaitabs, nswaitrel;
  4412. DWORD mswaitrel;
  4413. pthread_mutex_lock(&cv->threadIdSec);
  4414. /* Add this thread to cv's waiting list */
  4415. ptls = &cv->waiting_thread;
  4416. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4417. ;
  4418. tls->next_waiting_thread = NULL;
  4419. *ptls = tls;
  4420. pthread_mutex_unlock(&cv->threadIdSec);
  4421. if (abstime) {
  4422. nsnow = mg_get_current_time_ns();
  4423. nswaitabs =
  4424. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4425. nswaitrel = nswaitabs - nsnow;
  4426. if (nswaitrel < 0) {
  4427. nswaitrel = 0;
  4428. }
  4429. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4430. } else {
  4431. mswaitrel = (DWORD)INFINITE;
  4432. }
  4433. pthread_mutex_unlock(mutex);
  4434. ok = (WAIT_OBJECT_0
  4435. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4436. if (!ok) {
  4437. ok = 1;
  4438. pthread_mutex_lock(&cv->threadIdSec);
  4439. ptls = &cv->waiting_thread;
  4440. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4441. if (*ptls == tls) {
  4442. *ptls = tls->next_waiting_thread;
  4443. ok = 0;
  4444. break;
  4445. }
  4446. }
  4447. pthread_mutex_unlock(&cv->threadIdSec);
  4448. if (ok) {
  4449. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4450. (DWORD)INFINITE);
  4451. }
  4452. }
  4453. /* This thread has been removed from cv's waiting list */
  4454. pthread_mutex_lock(mutex);
  4455. return ok ? 0 : -1;
  4456. }
  4457. FUNCTION_MAY_BE_UNUSED
  4458. static int
  4459. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4460. {
  4461. return pthread_cond_timedwait(cv, mutex, NULL);
  4462. }
  4463. FUNCTION_MAY_BE_UNUSED
  4464. static int
  4465. pthread_cond_signal(pthread_cond_t *cv)
  4466. {
  4467. HANDLE wkup = NULL;
  4468. BOOL ok = FALSE;
  4469. pthread_mutex_lock(&cv->threadIdSec);
  4470. if (cv->waiting_thread) {
  4471. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4472. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4473. ok = SetEvent(wkup);
  4474. DEBUG_ASSERT(ok);
  4475. }
  4476. pthread_mutex_unlock(&cv->threadIdSec);
  4477. return ok ? 0 : 1;
  4478. }
  4479. FUNCTION_MAY_BE_UNUSED
  4480. static int
  4481. pthread_cond_broadcast(pthread_cond_t *cv)
  4482. {
  4483. pthread_mutex_lock(&cv->threadIdSec);
  4484. while (cv->waiting_thread) {
  4485. pthread_cond_signal(cv);
  4486. }
  4487. pthread_mutex_unlock(&cv->threadIdSec);
  4488. return 0;
  4489. }
  4490. FUNCTION_MAY_BE_UNUSED
  4491. static int
  4492. pthread_cond_destroy(pthread_cond_t *cv)
  4493. {
  4494. pthread_mutex_lock(&cv->threadIdSec);
  4495. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4496. pthread_mutex_unlock(&cv->threadIdSec);
  4497. pthread_mutex_destroy(&cv->threadIdSec);
  4498. return 0;
  4499. }
  4500. #if defined(ALTERNATIVE_QUEUE)
  4501. FUNCTION_MAY_BE_UNUSED
  4502. static void *
  4503. event_create(void)
  4504. {
  4505. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4506. }
  4507. FUNCTION_MAY_BE_UNUSED
  4508. static int
  4509. event_wait(void *eventhdl)
  4510. {
  4511. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4512. return (res == WAIT_OBJECT_0);
  4513. }
  4514. FUNCTION_MAY_BE_UNUSED
  4515. static int
  4516. event_signal(void *eventhdl)
  4517. {
  4518. return (int)SetEvent((HANDLE)eventhdl);
  4519. }
  4520. FUNCTION_MAY_BE_UNUSED
  4521. static void
  4522. event_destroy(void *eventhdl)
  4523. {
  4524. CloseHandle((HANDLE)eventhdl);
  4525. }
  4526. #endif
  4527. #if defined(GCC_DIAGNOSTIC)
  4528. /* Enable unused function warning again */
  4529. #pragma GCC diagnostic pop
  4530. #endif
  4531. /* For Windows, change all slashes to backslashes in path names. */
  4532. static void
  4533. change_slashes_to_backslashes(char *path)
  4534. {
  4535. int i;
  4536. for (i = 0; path[i] != '\0'; i++) {
  4537. if (path[i] == '/') {
  4538. path[i] = '\\';
  4539. }
  4540. /* remove double backslash (check i > 0 to preserve UNC paths,
  4541. * like \\server\file.txt) */
  4542. if ((i > 0) && (path[i] == '\\')) {
  4543. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4544. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4545. }
  4546. }
  4547. }
  4548. }
  4549. static int
  4550. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4551. {
  4552. int diff;
  4553. do {
  4554. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4555. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4556. s1++;
  4557. s2++;
  4558. } while ((diff == 0) && (s1[-1] != L'\0'));
  4559. return diff;
  4560. }
  4561. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4562. * wbuf and wbuf_len is a target buffer and its length. */
  4563. static void
  4564. path_to_unicode(const struct mg_connection *conn,
  4565. const char *path,
  4566. wchar_t *wbuf,
  4567. size_t wbuf_len)
  4568. {
  4569. char buf[PATH_MAX], buf2[PATH_MAX];
  4570. wchar_t wbuf2[W_PATH_MAX + 1];
  4571. DWORD long_len, err;
  4572. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4573. mg_strlcpy(buf, path, sizeof(buf));
  4574. change_slashes_to_backslashes(buf);
  4575. /* Convert to Unicode and back. If doubly-converted string does not
  4576. * match the original, something is fishy, reject. */
  4577. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4578. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4579. WideCharToMultiByte(
  4580. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4581. if (strcmp(buf, buf2) != 0) {
  4582. wbuf[0] = L'\0';
  4583. }
  4584. /* Windows file systems are not case sensitive, but you can still use
  4585. * uppercase and lowercase letters (on all modern file systems).
  4586. * The server can check if the URI uses the same upper/lowercase
  4587. * letters an the file system, effectively making Windows servers
  4588. * case sensitive (like Linux servers are). It is still not possible
  4589. * to use two files with the same name in different cases on Windows
  4590. * (like /a and /A) - this would be possible in Linux.
  4591. * As a default, Windows is not case sensitive, but the case sensitive
  4592. * file name check can be activated by an additional configuration. */
  4593. if (conn) {
  4594. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4595. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4596. "yes")) {
  4597. /* Use case sensitive compare function */
  4598. fcompare = wcscmp;
  4599. }
  4600. }
  4601. (void)conn; /* conn is currently unused */
  4602. #if !defined(_WIN32_WCE)
  4603. /* Only accept a full file path, not a Windows short (8.3) path. */
  4604. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4605. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4606. if (long_len == 0) {
  4607. err = GetLastError();
  4608. if (err == ERROR_FILE_NOT_FOUND) {
  4609. /* File does not exist. This is not always a problem here. */
  4610. return;
  4611. }
  4612. }
  4613. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4614. /* Short name is used. */
  4615. wbuf[0] = L'\0';
  4616. }
  4617. #else
  4618. (void)long_len;
  4619. (void)wbuf2;
  4620. (void)err;
  4621. if (strchr(path, '~')) {
  4622. wbuf[0] = L'\0';
  4623. }
  4624. #endif
  4625. }
  4626. #if !defined(NO_FILESYSTEMS)
  4627. static int
  4628. mg_stat(const struct mg_connection *conn,
  4629. const char *path,
  4630. struct mg_file_stat *filep)
  4631. {
  4632. wchar_t wbuf[W_PATH_MAX];
  4633. WIN32_FILE_ATTRIBUTE_DATA info;
  4634. time_t creation_time;
  4635. size_t len;
  4636. if (!filep) {
  4637. return 0;
  4638. }
  4639. memset(filep, 0, sizeof(*filep));
  4640. if (conn && is_file_in_memory(conn, path)) {
  4641. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4642. * memset */
  4643. /* Quick fix (for 1.9.x): */
  4644. /* mg_stat must fill all fields, also for files in memory */
  4645. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4646. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4647. filep->size = tmp_file.stat.size;
  4648. filep->location = 2;
  4649. /* TODO: for 1.10: restructure how files in memory are handled */
  4650. /* The "file in memory" feature is a candidate for deletion.
  4651. * Please join the discussion at
  4652. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4653. */
  4654. filep->last_modified = time(NULL); /* TODO */
  4655. /* last_modified = now ... assumes the file may change during
  4656. * runtime,
  4657. * so every mg_fopen call may return different data */
  4658. /* last_modified = conn->phys_ctx.start_time;
  4659. * May be used it the data does not change during runtime. This
  4660. * allows
  4661. * browser caching. Since we do not know, we have to assume the file
  4662. * in memory may change. */
  4663. return 1;
  4664. }
  4665. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4666. /* Windows happily opens files with some garbage at the end of file name.
  4667. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4668. * "a.cgi", despite one would expect an error back. */
  4669. len = strlen(path);
  4670. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4671. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4672. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4673. filep->last_modified =
  4674. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4675. info.ftLastWriteTime.dwHighDateTime);
  4676. /* On Windows, the file creation time can be higher than the
  4677. * modification time, e.g. when a file is copied.
  4678. * Since the Last-Modified timestamp is used for caching
  4679. * it should be based on the most recent timestamp. */
  4680. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4681. info.ftCreationTime.dwHighDateTime);
  4682. if (creation_time > filep->last_modified) {
  4683. filep->last_modified = creation_time;
  4684. }
  4685. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4686. return 1;
  4687. }
  4688. return 0;
  4689. }
  4690. #endif
  4691. static int
  4692. mg_remove(const struct mg_connection *conn, const char *path)
  4693. {
  4694. wchar_t wbuf[W_PATH_MAX];
  4695. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4696. return DeleteFileW(wbuf) ? 0 : -1;
  4697. }
  4698. static int
  4699. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4700. {
  4701. wchar_t wbuf[W_PATH_MAX];
  4702. (void)mode;
  4703. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4704. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4705. }
  4706. /* Create substitutes for POSIX functions in Win32. */
  4707. #if defined(GCC_DIAGNOSTIC)
  4708. /* Show no warning in case system functions are not used. */
  4709. #pragma GCC diagnostic push
  4710. #pragma GCC diagnostic ignored "-Wunused-function"
  4711. #endif
  4712. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4713. FUNCTION_MAY_BE_UNUSED
  4714. static DIR *
  4715. mg_opendir(const struct mg_connection *conn, const char *name)
  4716. {
  4717. DIR *dir = NULL;
  4718. wchar_t wpath[W_PATH_MAX];
  4719. DWORD attrs;
  4720. if (name == NULL) {
  4721. SetLastError(ERROR_BAD_ARGUMENTS);
  4722. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4723. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4724. } else {
  4725. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4726. attrs = GetFileAttributesW(wpath);
  4727. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4728. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4729. (void)wcscat(wpath, L"\\*");
  4730. dir->handle = FindFirstFileW(wpath, &dir->info);
  4731. dir->result.d_name[0] = '\0';
  4732. } else {
  4733. mg_free(dir);
  4734. dir = NULL;
  4735. }
  4736. }
  4737. return dir;
  4738. }
  4739. FUNCTION_MAY_BE_UNUSED
  4740. static int
  4741. mg_closedir(DIR *dir)
  4742. {
  4743. int result = 0;
  4744. if (dir != NULL) {
  4745. if (dir->handle != INVALID_HANDLE_VALUE)
  4746. result = FindClose(dir->handle) ? 0 : -1;
  4747. mg_free(dir);
  4748. } else {
  4749. result = -1;
  4750. SetLastError(ERROR_BAD_ARGUMENTS);
  4751. }
  4752. return result;
  4753. }
  4754. FUNCTION_MAY_BE_UNUSED
  4755. static struct dirent *
  4756. mg_readdir(DIR *dir)
  4757. {
  4758. struct dirent *result = 0;
  4759. if (dir) {
  4760. if (dir->handle != INVALID_HANDLE_VALUE) {
  4761. result = &dir->result;
  4762. (void)WideCharToMultiByte(CP_UTF8,
  4763. 0,
  4764. dir->info.cFileName,
  4765. -1,
  4766. result->d_name,
  4767. sizeof(result->d_name),
  4768. NULL,
  4769. NULL);
  4770. if (!FindNextFileW(dir->handle, &dir->info)) {
  4771. (void)FindClose(dir->handle);
  4772. dir->handle = INVALID_HANDLE_VALUE;
  4773. }
  4774. } else {
  4775. SetLastError(ERROR_FILE_NOT_FOUND);
  4776. }
  4777. } else {
  4778. SetLastError(ERROR_BAD_ARGUMENTS);
  4779. }
  4780. return result;
  4781. }
  4782. #if !defined(HAVE_POLL)
  4783. #undef POLLIN
  4784. #undef POLLPRI
  4785. #undef POLLOUT
  4786. #define POLLIN (1) /* Data ready - read will not block. */
  4787. #define POLLPRI (2) /* Priority data ready. */
  4788. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4789. FUNCTION_MAY_BE_UNUSED
  4790. static int
  4791. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4792. {
  4793. struct timeval tv;
  4794. fd_set rset;
  4795. fd_set wset;
  4796. unsigned int i;
  4797. int result;
  4798. SOCKET maxfd = 0;
  4799. memset(&tv, 0, sizeof(tv));
  4800. tv.tv_sec = milliseconds / 1000;
  4801. tv.tv_usec = (milliseconds % 1000) * 1000;
  4802. FD_ZERO(&rset);
  4803. FD_ZERO(&wset);
  4804. for (i = 0; i < n; i++) {
  4805. if (pfd[i].events & POLLIN) {
  4806. FD_SET(pfd[i].fd, &rset);
  4807. }
  4808. if (pfd[i].events & POLLOUT) {
  4809. FD_SET(pfd[i].fd, &wset);
  4810. }
  4811. pfd[i].revents = 0;
  4812. if (pfd[i].fd > maxfd) {
  4813. maxfd = pfd[i].fd;
  4814. }
  4815. }
  4816. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4817. for (i = 0; i < n; i++) {
  4818. if (FD_ISSET(pfd[i].fd, &rset)) {
  4819. pfd[i].revents |= POLLIN;
  4820. }
  4821. if (FD_ISSET(pfd[i].fd, &wset)) {
  4822. pfd[i].revents |= POLLOUT;
  4823. }
  4824. }
  4825. }
  4826. /* We should subtract the time used in select from remaining
  4827. * "milliseconds", in particular if called from mg_poll with a
  4828. * timeout quantum.
  4829. * Unfortunately, the remaining time is not stored in "tv" in all
  4830. * implementations, so the result in "tv" must be considered undefined.
  4831. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4832. return result;
  4833. }
  4834. #endif /* HAVE_POLL */
  4835. #if defined(GCC_DIAGNOSTIC)
  4836. /* Enable unused function warning again */
  4837. #pragma GCC diagnostic pop
  4838. #endif
  4839. static void
  4840. set_close_on_exec(SOCKET sock,
  4841. const struct mg_connection *conn /* may be null */,
  4842. struct mg_context *ctx /* may be null */)
  4843. {
  4844. (void)conn; /* Unused. */
  4845. (void)ctx;
  4846. #if defined(_WIN32_WCE)
  4847. (void)sock;
  4848. #else
  4849. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4850. #endif
  4851. }
  4852. int
  4853. mg_start_thread(mg_thread_func_t f, void *p)
  4854. {
  4855. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4856. /* Compile-time option to control stack size, e.g.
  4857. * -DUSE_STACK_SIZE=16384
  4858. */
  4859. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4860. == ((uintptr_t)(-1L)))
  4861. ? -1
  4862. : 0);
  4863. #else
  4864. return (
  4865. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4866. ? -1
  4867. : 0);
  4868. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4869. }
  4870. /* Start a thread storing the thread context. */
  4871. static int
  4872. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4873. void *p,
  4874. pthread_t *threadidptr)
  4875. {
  4876. uintptr_t uip;
  4877. HANDLE threadhandle;
  4878. int result = -1;
  4879. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4880. threadhandle = (HANDLE)uip;
  4881. if ((uip != 0) && (threadidptr != NULL)) {
  4882. *threadidptr = threadhandle;
  4883. result = 0;
  4884. }
  4885. return result;
  4886. }
  4887. /* Wait for a thread to finish. */
  4888. static int
  4889. mg_join_thread(pthread_t threadid)
  4890. {
  4891. int result;
  4892. DWORD dwevent;
  4893. result = -1;
  4894. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4895. if (dwevent == WAIT_FAILED) {
  4896. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4897. } else {
  4898. if (dwevent == WAIT_OBJECT_0) {
  4899. CloseHandle(threadid);
  4900. result = 0;
  4901. }
  4902. }
  4903. return result;
  4904. }
  4905. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4906. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4907. /* Create substitutes for POSIX functions in Win32. */
  4908. #if defined(GCC_DIAGNOSTIC)
  4909. /* Show no warning in case system functions are not used. */
  4910. #pragma GCC diagnostic push
  4911. #pragma GCC diagnostic ignored "-Wunused-function"
  4912. #endif
  4913. FUNCTION_MAY_BE_UNUSED
  4914. static HANDLE
  4915. dlopen(const char *dll_name, int flags)
  4916. {
  4917. wchar_t wbuf[W_PATH_MAX];
  4918. (void)flags;
  4919. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4920. return LoadLibraryW(wbuf);
  4921. }
  4922. FUNCTION_MAY_BE_UNUSED
  4923. static int
  4924. dlclose(void *handle)
  4925. {
  4926. int result;
  4927. if (FreeLibrary((HMODULE)handle) != 0) {
  4928. result = 0;
  4929. } else {
  4930. result = -1;
  4931. }
  4932. return result;
  4933. }
  4934. #if defined(GCC_DIAGNOSTIC)
  4935. /* Enable unused function warning again */
  4936. #pragma GCC diagnostic pop
  4937. #endif
  4938. #endif
  4939. #if !defined(NO_CGI)
  4940. #define SIGKILL (0)
  4941. static int
  4942. kill(pid_t pid, int sig_num)
  4943. {
  4944. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4945. (void)CloseHandle((HANDLE)pid);
  4946. return 0;
  4947. }
  4948. #if !defined(WNOHANG)
  4949. #define WNOHANG (1)
  4950. #endif
  4951. static pid_t
  4952. waitpid(pid_t pid, int *status, int flags)
  4953. {
  4954. DWORD timeout = INFINITE;
  4955. DWORD waitres;
  4956. (void)status; /* Currently not used by any client here */
  4957. if ((flags | WNOHANG) == WNOHANG) {
  4958. timeout = 0;
  4959. }
  4960. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4961. if (waitres == WAIT_OBJECT_0) {
  4962. return pid;
  4963. }
  4964. if (waitres == WAIT_TIMEOUT) {
  4965. return 0;
  4966. }
  4967. return (pid_t)-1;
  4968. }
  4969. static void
  4970. trim_trailing_whitespaces(char *s)
  4971. {
  4972. char *e = s + strlen(s);
  4973. while ((e > s) && isspace((unsigned char)e[-1])) {
  4974. *(--e) = '\0';
  4975. }
  4976. }
  4977. static pid_t
  4978. spawn_process(struct mg_connection *conn,
  4979. const char *prog,
  4980. char *envblk,
  4981. char *envp[],
  4982. int fdin[2],
  4983. int fdout[2],
  4984. int fderr[2],
  4985. const char *dir)
  4986. {
  4987. HANDLE me;
  4988. char *p, *interp;
  4989. char *interp_arg = 0;
  4990. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4991. buf[PATH_MAX];
  4992. int truncated;
  4993. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4994. STARTUPINFOA si;
  4995. PROCESS_INFORMATION pi = {0};
  4996. (void)envp;
  4997. memset(&si, 0, sizeof(si));
  4998. si.cb = sizeof(si);
  4999. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5000. si.wShowWindow = SW_HIDE;
  5001. me = GetCurrentProcess();
  5002. DuplicateHandle(me,
  5003. (HANDLE)_get_osfhandle(fdin[0]),
  5004. me,
  5005. &si.hStdInput,
  5006. 0,
  5007. TRUE,
  5008. DUPLICATE_SAME_ACCESS);
  5009. DuplicateHandle(me,
  5010. (HANDLE)_get_osfhandle(fdout[1]),
  5011. me,
  5012. &si.hStdOutput,
  5013. 0,
  5014. TRUE,
  5015. DUPLICATE_SAME_ACCESS);
  5016. DuplicateHandle(me,
  5017. (HANDLE)_get_osfhandle(fderr[1]),
  5018. me,
  5019. &si.hStdError,
  5020. 0,
  5021. TRUE,
  5022. DUPLICATE_SAME_ACCESS);
  5023. /* Mark handles that should not be inherited. See
  5024. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5025. */
  5026. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5027. HANDLE_FLAG_INHERIT,
  5028. 0);
  5029. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5030. HANDLE_FLAG_INHERIT,
  5031. 0);
  5032. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5033. HANDLE_FLAG_INHERIT,
  5034. 0);
  5035. /* First check, if there is a CGI interpreter configured for all CGI
  5036. * scripts. */
  5037. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5038. if (interp != NULL) {
  5039. /* If there is a configured interpreter, check for additional arguments
  5040. */
  5041. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5042. } else {
  5043. /* Otherwise, the interpreter must be stated in the first line of the
  5044. * CGI script file, after a #! (shebang) mark. */
  5045. buf[0] = buf[1] = '\0';
  5046. /* Get the full script path */
  5047. mg_snprintf(
  5048. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5049. if (truncated) {
  5050. pi.hProcess = (pid_t)-1;
  5051. goto spawn_cleanup;
  5052. }
  5053. /* Open the script file, to read the first line */
  5054. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5055. #if defined(MG_USE_OPEN_FILE)
  5056. p = (char *)file.access.membuf;
  5057. #else
  5058. p = (char *)NULL;
  5059. #endif
  5060. /* Read the first line of the script into the buffer */
  5061. mg_fgets(buf, sizeof(buf), &file, &p);
  5062. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5063. buf[sizeof(buf) - 1] = '\0';
  5064. }
  5065. if ((buf[0] == '#') && (buf[1] == '!')) {
  5066. trim_trailing_whitespaces(buf + 2);
  5067. } else {
  5068. buf[2] = '\0';
  5069. }
  5070. interp = buf + 2;
  5071. }
  5072. if (interp[0] != '\0') {
  5073. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5074. interp = full_interp;
  5075. }
  5076. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5077. if (interp[0] != '\0') {
  5078. /* This is an interpreted script file. We must call the interpreter. */
  5079. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5080. mg_snprintf(conn,
  5081. &truncated,
  5082. cmdline,
  5083. sizeof(cmdline),
  5084. "\"%s\" %s \"%s\\%s\"",
  5085. interp,
  5086. interp_arg,
  5087. full_dir,
  5088. prog);
  5089. } else {
  5090. mg_snprintf(conn,
  5091. &truncated,
  5092. cmdline,
  5093. sizeof(cmdline),
  5094. "\"%s\" \"%s\\%s\"",
  5095. interp,
  5096. full_dir,
  5097. prog);
  5098. }
  5099. } else {
  5100. /* This is (probably) a compiled program. We call it directly. */
  5101. mg_snprintf(conn,
  5102. &truncated,
  5103. cmdline,
  5104. sizeof(cmdline),
  5105. "\"%s\\%s\"",
  5106. full_dir,
  5107. prog);
  5108. }
  5109. if (truncated) {
  5110. pi.hProcess = (pid_t)-1;
  5111. goto spawn_cleanup;
  5112. }
  5113. DEBUG_TRACE("Running [%s]", cmdline);
  5114. if (CreateProcessA(NULL,
  5115. cmdline,
  5116. NULL,
  5117. NULL,
  5118. TRUE,
  5119. CREATE_NEW_PROCESS_GROUP,
  5120. envblk,
  5121. NULL,
  5122. &si,
  5123. &pi)
  5124. == 0) {
  5125. mg_cry_internal(
  5126. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5127. pi.hProcess = (pid_t)-1;
  5128. /* goto spawn_cleanup; */
  5129. }
  5130. spawn_cleanup:
  5131. (void)CloseHandle(si.hStdOutput);
  5132. (void)CloseHandle(si.hStdError);
  5133. (void)CloseHandle(si.hStdInput);
  5134. if (pi.hThread != NULL) {
  5135. (void)CloseHandle(pi.hThread);
  5136. }
  5137. return (pid_t)pi.hProcess;
  5138. }
  5139. #endif /* !NO_CGI */
  5140. static int
  5141. set_blocking_mode(SOCKET sock)
  5142. {
  5143. unsigned long non_blocking = 0;
  5144. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5145. }
  5146. static int
  5147. set_non_blocking_mode(SOCKET sock)
  5148. {
  5149. unsigned long non_blocking = 1;
  5150. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5151. }
  5152. #else
  5153. #if !defined(NO_FILESYSTEMS)
  5154. static int
  5155. mg_stat(const struct mg_connection *conn,
  5156. const char *path,
  5157. struct mg_file_stat *filep)
  5158. {
  5159. struct stat st;
  5160. if (!filep) {
  5161. return 0;
  5162. }
  5163. memset(filep, 0, sizeof(*filep));
  5164. if (conn && is_file_in_memory(conn, path)) {
  5165. /* Quick fix (for 1.9.x): */
  5166. /* mg_stat must fill all fields, also for files in memory */
  5167. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5168. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5169. filep->size = tmp_file.stat.size;
  5170. filep->last_modified = time(NULL);
  5171. filep->location = 2;
  5172. /* TODO: remove legacy "files in memory" feature */
  5173. return 1;
  5174. }
  5175. if (0 == stat(path, &st)) {
  5176. filep->size = (uint64_t)(st.st_size);
  5177. filep->last_modified = st.st_mtime;
  5178. filep->is_directory = S_ISDIR(st.st_mode);
  5179. return 1;
  5180. }
  5181. return 0;
  5182. }
  5183. #endif /* NO_FILESYSTEMS */
  5184. static void
  5185. set_close_on_exec(int fd,
  5186. const struct mg_connection *conn /* may be null */,
  5187. struct mg_context *ctx /* may be null */)
  5188. {
  5189. #if defined(__ZEPHYR__)
  5190. (void)fd;
  5191. (void)conn;
  5192. (void)ctx;
  5193. #else
  5194. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5195. if (conn || ctx) {
  5196. struct mg_connection fc;
  5197. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5198. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5199. __func__,
  5200. strerror(ERRNO));
  5201. }
  5202. }
  5203. #endif
  5204. }
  5205. int
  5206. mg_start_thread(mg_thread_func_t func, void *param)
  5207. {
  5208. pthread_t thread_id;
  5209. pthread_attr_t attr;
  5210. int result;
  5211. (void)pthread_attr_init(&attr);
  5212. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5213. #if defined(__ZEPHYR__)
  5214. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5215. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5216. /* Compile-time option to control stack size,
  5217. * e.g. -DUSE_STACK_SIZE=16384 */
  5218. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5219. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5220. result = pthread_create(&thread_id, &attr, func, param);
  5221. pthread_attr_destroy(&attr);
  5222. return result;
  5223. }
  5224. /* Start a thread storing the thread context. */
  5225. static int
  5226. mg_start_thread_with_id(mg_thread_func_t func,
  5227. void *param,
  5228. pthread_t *threadidptr)
  5229. {
  5230. pthread_t thread_id;
  5231. pthread_attr_t attr;
  5232. int result;
  5233. (void)pthread_attr_init(&attr);
  5234. #if defined(__ZEPHYR__)
  5235. pthread_attr_setstack(&attr,
  5236. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5237. ZEPHYR_STACK_SIZE);
  5238. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5239. /* Compile-time option to control stack size,
  5240. * e.g. -DUSE_STACK_SIZE=16384 */
  5241. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5242. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5243. result = pthread_create(&thread_id, &attr, func, param);
  5244. pthread_attr_destroy(&attr);
  5245. if ((result == 0) && (threadidptr != NULL)) {
  5246. *threadidptr = thread_id;
  5247. }
  5248. return result;
  5249. }
  5250. /* Wait for a thread to finish. */
  5251. static int
  5252. mg_join_thread(pthread_t threadid)
  5253. {
  5254. int result;
  5255. result = pthread_join(threadid, NULL);
  5256. return result;
  5257. }
  5258. #if !defined(NO_CGI)
  5259. static pid_t
  5260. spawn_process(struct mg_connection *conn,
  5261. const char *prog,
  5262. char *envblk,
  5263. char *envp[],
  5264. int fdin[2],
  5265. int fdout[2],
  5266. int fderr[2],
  5267. const char *dir)
  5268. {
  5269. pid_t pid;
  5270. const char *interp;
  5271. (void)envblk;
  5272. if ((pid = fork()) == -1) {
  5273. /* Parent */
  5274. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5275. } else if (pid != 0) {
  5276. /* Make sure children close parent-side descriptors.
  5277. * The caller will close the child-side immediately. */
  5278. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5279. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5280. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5281. } else {
  5282. /* Child */
  5283. if (chdir(dir) != 0) {
  5284. mg_cry_internal(
  5285. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5286. } else if (dup2(fdin[0], 0) == -1) {
  5287. mg_cry_internal(conn,
  5288. "%s: dup2(%d, 0): %s",
  5289. __func__,
  5290. fdin[0],
  5291. strerror(ERRNO));
  5292. } else if (dup2(fdout[1], 1) == -1) {
  5293. mg_cry_internal(conn,
  5294. "%s: dup2(%d, 1): %s",
  5295. __func__,
  5296. fdout[1],
  5297. strerror(ERRNO));
  5298. } else if (dup2(fderr[1], 2) == -1) {
  5299. mg_cry_internal(conn,
  5300. "%s: dup2(%d, 2): %s",
  5301. __func__,
  5302. fderr[1],
  5303. strerror(ERRNO));
  5304. } else {
  5305. struct sigaction sa;
  5306. /* Keep stderr and stdout in two different pipes.
  5307. * Stdout will be sent back to the client,
  5308. * stderr should go into a server error log. */
  5309. (void)close(fdin[0]);
  5310. (void)close(fdout[1]);
  5311. (void)close(fderr[1]);
  5312. /* Close write end fdin and read end fdout and fderr */
  5313. (void)close(fdin[1]);
  5314. (void)close(fdout[0]);
  5315. (void)close(fderr[0]);
  5316. /* After exec, all signal handlers are restored to their default
  5317. * values, with one exception of SIGCHLD. According to
  5318. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5319. * will leave unchanged after exec if it was set to be ignored.
  5320. * Restore it to default action. */
  5321. memset(&sa, 0, sizeof(sa));
  5322. sa.sa_handler = SIG_DFL;
  5323. sigaction(SIGCHLD, &sa, NULL);
  5324. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5325. if (interp == NULL) {
  5326. /* no interpreter configured, call the programm directly */
  5327. (void)execle(prog, prog, NULL, envp);
  5328. mg_cry_internal(conn,
  5329. "%s: execle(%s): %s",
  5330. __func__,
  5331. prog,
  5332. strerror(ERRNO));
  5333. } else {
  5334. /* call the configured interpreter */
  5335. const char *interp_args =
  5336. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5337. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5338. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5339. } else {
  5340. (void)execle(interp, interp, prog, NULL, envp);
  5341. }
  5342. mg_cry_internal(conn,
  5343. "%s: execle(%s %s): %s",
  5344. __func__,
  5345. interp,
  5346. prog,
  5347. strerror(ERRNO));
  5348. }
  5349. }
  5350. exit(EXIT_FAILURE);
  5351. }
  5352. return pid;
  5353. }
  5354. #endif /* !NO_CGI */
  5355. static int
  5356. set_non_blocking_mode(SOCKET sock)
  5357. {
  5358. int flags = fcntl(sock, F_GETFL, 0);
  5359. if (flags < 0) {
  5360. return -1;
  5361. }
  5362. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5363. return -1;
  5364. }
  5365. return 0;
  5366. }
  5367. static int
  5368. set_blocking_mode(SOCKET sock)
  5369. {
  5370. int flags = fcntl(sock, F_GETFL, 0);
  5371. if (flags < 0) {
  5372. return -1;
  5373. }
  5374. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5375. return -1;
  5376. }
  5377. return 0;
  5378. }
  5379. #endif /* _WIN32 / else */
  5380. /* End of initial operating system specific define block. */
  5381. /* Get a random number (independent of C rand function) */
  5382. static uint64_t
  5383. get_random(void)
  5384. {
  5385. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5386. static uint64_t lcg = 0; /* Linear congruential generator */
  5387. uint64_t now = mg_get_current_time_ns();
  5388. if (lfsr == 0) {
  5389. /* lfsr will be only 0 if has not been initialized,
  5390. * so this code is called only once. */
  5391. lfsr = mg_get_current_time_ns();
  5392. lcg = mg_get_current_time_ns();
  5393. } else {
  5394. /* Get the next step of both random number generators. */
  5395. lfsr = (lfsr >> 1)
  5396. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5397. << 63);
  5398. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5399. }
  5400. /* Combining two pseudo-random number generators and a high resolution
  5401. * part
  5402. * of the current server time will make it hard (impossible?) to guess
  5403. * the
  5404. * next number. */
  5405. return (lfsr ^ lcg ^ now);
  5406. }
  5407. static int
  5408. mg_poll(struct mg_pollfd *pfd,
  5409. unsigned int n,
  5410. int milliseconds,
  5411. stop_flag_t *stop_flag)
  5412. {
  5413. /* Call poll, but only for a maximum time of a few seconds.
  5414. * This will allow to stop the server after some seconds, instead
  5415. * of having to wait for a long socket timeout. */
  5416. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5417. do {
  5418. int result;
  5419. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5420. /* Shut down signal */
  5421. return -2;
  5422. }
  5423. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5424. ms_now = milliseconds;
  5425. }
  5426. result = poll(pfd, n, ms_now);
  5427. if (result != 0) {
  5428. /* Poll returned either success (1) or error (-1).
  5429. * Forward both to the caller. */
  5430. return result;
  5431. }
  5432. /* Poll returned timeout (0). */
  5433. if (milliseconds > 0) {
  5434. milliseconds -= ms_now;
  5435. }
  5436. } while (milliseconds != 0);
  5437. /* timeout: return 0 */
  5438. return 0;
  5439. }
  5440. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5441. * descriptor.
  5442. * Return value:
  5443. * >=0 .. number of bytes successfully written
  5444. * -1 .. timeout
  5445. * -2 .. error
  5446. */
  5447. static int
  5448. push_inner(struct mg_context *ctx,
  5449. FILE *fp,
  5450. SOCKET sock,
  5451. SSL *ssl,
  5452. const char *buf,
  5453. int len,
  5454. double timeout)
  5455. {
  5456. uint64_t start = 0, now = 0, timeout_ns = 0;
  5457. int n, err;
  5458. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5459. #if defined(_WIN32)
  5460. typedef int len_t;
  5461. #else
  5462. typedef size_t len_t;
  5463. #endif
  5464. if (timeout > 0) {
  5465. now = mg_get_current_time_ns();
  5466. start = now;
  5467. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5468. }
  5469. if (ctx == NULL) {
  5470. return -2;
  5471. }
  5472. #if defined(NO_SSL)
  5473. if (ssl) {
  5474. return -2;
  5475. }
  5476. #endif
  5477. /* Try to read until it succeeds, fails, times out, or the server
  5478. * shuts down. */
  5479. for (;;) {
  5480. #if !defined(NO_SSL)
  5481. if (ssl != NULL) {
  5482. ERR_clear_error();
  5483. n = SSL_write(ssl, buf, len);
  5484. if (n <= 0) {
  5485. err = SSL_get_error(ssl, n);
  5486. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5487. err = ERRNO;
  5488. } else if ((err == SSL_ERROR_WANT_READ)
  5489. || (err == SSL_ERROR_WANT_WRITE)) {
  5490. n = 0;
  5491. } else {
  5492. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5493. ERR_clear_error();
  5494. return -2;
  5495. }
  5496. ERR_clear_error();
  5497. } else {
  5498. err = 0;
  5499. }
  5500. } else
  5501. #endif
  5502. if (fp != NULL) {
  5503. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5504. if (ferror(fp)) {
  5505. n = -1;
  5506. err = ERRNO;
  5507. } else {
  5508. err = 0;
  5509. }
  5510. } else {
  5511. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5512. err = (n < 0) ? ERRNO : 0;
  5513. #if defined(_WIN32)
  5514. if (err == WSAEWOULDBLOCK) {
  5515. err = 0;
  5516. n = 0;
  5517. }
  5518. #else
  5519. if (err == EWOULDBLOCK) {
  5520. err = 0;
  5521. n = 0;
  5522. }
  5523. #endif
  5524. if (n < 0) {
  5525. /* shutdown of the socket at client side */
  5526. return -2;
  5527. }
  5528. }
  5529. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5530. return -2;
  5531. }
  5532. if ((n > 0) || ((n == 0) && (len == 0))) {
  5533. /* some data has been read, or no data was requested */
  5534. return n;
  5535. }
  5536. if (n < 0) {
  5537. /* socket error - check errno */
  5538. DEBUG_TRACE("send() failed, error %d", err);
  5539. /* TODO (mid): error handling depending on the error code.
  5540. * These codes are different between Windows and Linux.
  5541. * Currently there is no problem with failing send calls,
  5542. * if there is a reproducible situation, it should be
  5543. * investigated in detail.
  5544. */
  5545. return -2;
  5546. }
  5547. /* Only in case n=0 (timeout), repeat calling the write function */
  5548. /* If send failed, wait before retry */
  5549. if (fp != NULL) {
  5550. /* For files, just wait a fixed time.
  5551. * Maybe it helps, maybe not. */
  5552. mg_sleep(5);
  5553. } else {
  5554. /* For sockets, wait for the socket using poll */
  5555. struct mg_pollfd pfd[1];
  5556. int pollres;
  5557. pfd[0].fd = sock;
  5558. pfd[0].events = POLLOUT;
  5559. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5560. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5561. return -2;
  5562. }
  5563. if (pollres > 0) {
  5564. continue;
  5565. }
  5566. }
  5567. if (timeout > 0) {
  5568. now = mg_get_current_time_ns();
  5569. if ((now - start) > timeout_ns) {
  5570. /* Timeout */
  5571. break;
  5572. }
  5573. }
  5574. }
  5575. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5576. used */
  5577. return -1;
  5578. }
  5579. static int
  5580. push_all(struct mg_context *ctx,
  5581. FILE *fp,
  5582. SOCKET sock,
  5583. SSL *ssl,
  5584. const char *buf,
  5585. int len)
  5586. {
  5587. double timeout = -1.0;
  5588. int n, nwritten = 0;
  5589. if (ctx == NULL) {
  5590. return -1;
  5591. }
  5592. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5593. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5594. }
  5595. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5596. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5597. if (n < 0) {
  5598. if (nwritten == 0) {
  5599. nwritten = -1; /* Propagate the error */
  5600. }
  5601. break;
  5602. } else if (n == 0) {
  5603. break; /* No more data to write */
  5604. } else {
  5605. nwritten += n;
  5606. len -= n;
  5607. }
  5608. }
  5609. return nwritten;
  5610. }
  5611. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5612. * Return value:
  5613. * >=0 .. number of bytes successfully read
  5614. * -1 .. timeout
  5615. * -2 .. error
  5616. */
  5617. static int
  5618. pull_inner(FILE *fp,
  5619. struct mg_connection *conn,
  5620. char *buf,
  5621. int len,
  5622. double timeout)
  5623. {
  5624. int nread, err = 0;
  5625. #if defined(_WIN32)
  5626. typedef int len_t;
  5627. #else
  5628. typedef size_t len_t;
  5629. #endif
  5630. /* We need an additional wait loop around this, because in some cases
  5631. * with TLSwe may get data from the socket but not from SSL_read.
  5632. * In this case we need to repeat at least once.
  5633. */
  5634. if (fp != NULL) {
  5635. #if !defined(_WIN32_WCE)
  5636. /* Use read() instead of fread(), because if we're reading from the
  5637. * CGI pipe, fread() may block until IO buffer is filled up. We
  5638. * cannot afford to block and must pass all read bytes immediately
  5639. * to the client. */
  5640. nread = (int)read(fileno(fp), buf, (size_t)len);
  5641. #else
  5642. /* WinCE does not support CGI pipes */
  5643. nread = (int)fread(buf, 1, (size_t)len, fp);
  5644. #endif
  5645. err = (nread < 0) ? ERRNO : 0;
  5646. if ((nread == 0) && (len > 0)) {
  5647. /* Should get data, but got EOL */
  5648. return -2;
  5649. }
  5650. #if !defined(NO_SSL)
  5651. } else if (conn->ssl != NULL) {
  5652. int ssl_pending;
  5653. struct mg_pollfd pfd[1];
  5654. int pollres;
  5655. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5656. /* We already know there is no more data buffered in conn->buf
  5657. * but there is more available in the SSL layer. So don't poll
  5658. * conn->client.sock yet. */
  5659. if (ssl_pending > len) {
  5660. ssl_pending = len;
  5661. }
  5662. pollres = 1;
  5663. } else {
  5664. pfd[0].fd = conn->client.sock;
  5665. pfd[0].events = POLLIN;
  5666. pollres = mg_poll(pfd,
  5667. 1,
  5668. (int)(timeout * 1000.0),
  5669. &(conn->phys_ctx->stop_flag));
  5670. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5671. return -2;
  5672. }
  5673. }
  5674. if (pollres > 0) {
  5675. ERR_clear_error();
  5676. nread = SSL_read(conn->ssl, buf,
  5677. (ssl_pending > 0) ? ssl_pending : len);
  5678. if (nread <= 0) {
  5679. err = SSL_get_error(conn->ssl, nread);
  5680. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5681. err = ERRNO;
  5682. } else if ((err == SSL_ERROR_WANT_READ)
  5683. || (err == SSL_ERROR_WANT_WRITE)) {
  5684. nread = 0;
  5685. } else {
  5686. /* All errors should return -2 */
  5687. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5688. ERR_clear_error();
  5689. return -2;
  5690. }
  5691. ERR_clear_error();
  5692. } else {
  5693. err = 0;
  5694. }
  5695. } else if (pollres < 0) {
  5696. /* Error */
  5697. return -2;
  5698. } else {
  5699. /* pollres = 0 means timeout */
  5700. nread = 0;
  5701. }
  5702. #endif
  5703. } else {
  5704. struct mg_pollfd pfd[1];
  5705. int pollres;
  5706. pfd[0].fd = conn->client.sock;
  5707. pfd[0].events = POLLIN;
  5708. pollres = mg_poll(pfd,
  5709. 1,
  5710. (int)(timeout * 1000.0),
  5711. &(conn->phys_ctx->stop_flag));
  5712. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5713. return -2;
  5714. }
  5715. if (pollres > 0) {
  5716. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5717. err = (nread < 0) ? ERRNO : 0;
  5718. if (nread <= 0) {
  5719. /* shutdown of the socket at client side */
  5720. return -2;
  5721. }
  5722. } else if (pollres < 0) {
  5723. /* error callint poll */
  5724. return -2;
  5725. } else {
  5726. /* pollres = 0 means timeout */
  5727. nread = 0;
  5728. }
  5729. }
  5730. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5731. return -2;
  5732. }
  5733. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5734. /* some data has been read, or no data was requested */
  5735. return nread;
  5736. }
  5737. if (nread < 0) {
  5738. /* socket error - check errno */
  5739. #if defined(_WIN32)
  5740. if (err == WSAEWOULDBLOCK) {
  5741. /* TODO (low): check if this is still required */
  5742. /* standard case if called from close_socket_gracefully */
  5743. return -2;
  5744. } else if (err == WSAETIMEDOUT) {
  5745. /* TODO (low): check if this is still required */
  5746. /* timeout is handled by the while loop */
  5747. return 0;
  5748. } else if (err == WSAECONNABORTED) {
  5749. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5750. return -2;
  5751. } else {
  5752. DEBUG_TRACE("recv() failed, error %d", err);
  5753. return -2;
  5754. }
  5755. #else
  5756. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5757. * if the timeout is reached and if the socket was set to non-
  5758. * blocking in close_socket_gracefully, so we can not distinguish
  5759. * here. We have to wait for the timeout in both cases for now.
  5760. */
  5761. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5762. /* TODO (low): check if this is still required */
  5763. /* EAGAIN/EWOULDBLOCK:
  5764. * standard case if called from close_socket_gracefully
  5765. * => should return -1 */
  5766. /* or timeout occurred
  5767. * => the code must stay in the while loop */
  5768. /* EINTR can be generated on a socket with a timeout set even
  5769. * when SA_RESTART is effective for all relevant signals
  5770. * (see signal(7)).
  5771. * => stay in the while loop */
  5772. } else {
  5773. DEBUG_TRACE("recv() failed, error %d", err);
  5774. return -2;
  5775. }
  5776. #endif
  5777. }
  5778. /* Timeout occurred, but no data available. */
  5779. return -1;
  5780. }
  5781. static int
  5782. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5783. {
  5784. int n, nread = 0;
  5785. double timeout = -1.0;
  5786. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5787. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5788. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5789. }
  5790. if (timeout >= 0.0) {
  5791. start_time = mg_get_current_time_ns();
  5792. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5793. }
  5794. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5795. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5796. if (n == -2) {
  5797. if (nread == 0) {
  5798. nread = -1; /* Propagate the error */
  5799. }
  5800. break;
  5801. } else if (n == -1) {
  5802. /* timeout */
  5803. if (timeout >= 0.0) {
  5804. now = mg_get_current_time_ns();
  5805. if ((now - start_time) <= timeout_ns) {
  5806. continue;
  5807. }
  5808. }
  5809. break;
  5810. } else if (n == 0) {
  5811. break; /* No more data to read */
  5812. } else {
  5813. nread += n;
  5814. len -= n;
  5815. }
  5816. }
  5817. return nread;
  5818. }
  5819. static void
  5820. discard_unread_request_data(struct mg_connection *conn)
  5821. {
  5822. char buf[MG_BUF_LEN];
  5823. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5824. ;
  5825. }
  5826. static int
  5827. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5828. {
  5829. int64_t content_len, n, buffered_len, nread;
  5830. int64_t len64 =
  5831. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5832. * int, we may not read more
  5833. * bytes */
  5834. const char *body;
  5835. if (conn == NULL) {
  5836. return 0;
  5837. }
  5838. /* If Content-Length is not set for a response with body data,
  5839. * we do not know in advance how much data should be read. */
  5840. content_len = conn->content_len;
  5841. if (content_len < 0) {
  5842. /* The body data is completed when the connection is closed. */
  5843. content_len = INT64_MAX;
  5844. }
  5845. nread = 0;
  5846. if (conn->consumed_content < content_len) {
  5847. /* Adjust number of bytes to read. */
  5848. int64_t left_to_read = content_len - conn->consumed_content;
  5849. if (left_to_read < len64) {
  5850. /* Do not read more than the total content length of the
  5851. * request.
  5852. */
  5853. len64 = left_to_read;
  5854. }
  5855. /* Return buffered data */
  5856. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5857. - conn->consumed_content;
  5858. if (buffered_len > 0) {
  5859. if (len64 < buffered_len) {
  5860. buffered_len = len64;
  5861. }
  5862. body = conn->buf + conn->request_len + conn->consumed_content;
  5863. memcpy(buf, body, (size_t)buffered_len);
  5864. len64 -= buffered_len;
  5865. conn->consumed_content += buffered_len;
  5866. nread += buffered_len;
  5867. buf = (char *)buf + buffered_len;
  5868. }
  5869. /* We have returned all buffered data. Read new data from the remote
  5870. * socket.
  5871. */
  5872. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5873. conn->consumed_content += n;
  5874. nread += n;
  5875. } else {
  5876. nread = ((nread > 0) ? nread : n);
  5877. }
  5878. }
  5879. return (int)nread;
  5880. }
  5881. int
  5882. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5883. {
  5884. if (len > INT_MAX) {
  5885. len = INT_MAX;
  5886. }
  5887. if (conn == NULL) {
  5888. return 0;
  5889. }
  5890. if (conn->is_chunked) {
  5891. size_t all_read = 0;
  5892. while (len > 0) {
  5893. if (conn->is_chunked >= 3) {
  5894. /* No more data left to read */
  5895. return 0;
  5896. }
  5897. if (conn->is_chunked != 1) {
  5898. /* Has error */
  5899. return -1;
  5900. }
  5901. if (conn->consumed_content != conn->content_len) {
  5902. /* copy from the current chunk */
  5903. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5904. if (read_ret < 1) {
  5905. /* read error */
  5906. conn->is_chunked = 2;
  5907. return -1;
  5908. }
  5909. all_read += (size_t)read_ret;
  5910. len -= (size_t)read_ret;
  5911. if (conn->consumed_content == conn->content_len) {
  5912. /* Add data bytes in the current chunk have been read,
  5913. * so we are expecting \r\n now. */
  5914. char x[2];
  5915. conn->content_len += 2;
  5916. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5917. || (x[1] != '\n')) {
  5918. /* Protocol violation */
  5919. conn->is_chunked = 2;
  5920. return -1;
  5921. }
  5922. }
  5923. } else {
  5924. /* fetch a new chunk */
  5925. size_t i;
  5926. char lenbuf[64];
  5927. char *end = NULL;
  5928. unsigned long chunkSize = 0;
  5929. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5930. conn->content_len++;
  5931. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5932. lenbuf[i] = 0;
  5933. }
  5934. if ((i > 0) && (lenbuf[i] == '\r')
  5935. && (lenbuf[i - 1] != '\r')) {
  5936. continue;
  5937. }
  5938. if ((i > 1) && (lenbuf[i] == '\n')
  5939. && (lenbuf[i - 1] == '\r')) {
  5940. lenbuf[i + 1] = 0;
  5941. chunkSize = strtoul(lenbuf, &end, 16);
  5942. if (chunkSize == 0) {
  5943. /* regular end of content */
  5944. conn->is_chunked = 3;
  5945. }
  5946. break;
  5947. }
  5948. if (!isxdigit((unsigned char)lenbuf[i])) {
  5949. /* illegal character for chunk length */
  5950. conn->is_chunked = 2;
  5951. return -1;
  5952. }
  5953. }
  5954. if ((end == NULL) || (*end != '\r')) {
  5955. /* chunksize not set correctly */
  5956. conn->is_chunked = 2;
  5957. return -1;
  5958. }
  5959. if (chunkSize == 0) {
  5960. /* try discarding trailer for keep-alive */
  5961. conn->content_len += 2;
  5962. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5963. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5964. conn->is_chunked = 4;
  5965. }
  5966. break;
  5967. }
  5968. /* append a new chunk */
  5969. conn->content_len += (int64_t)chunkSize;
  5970. }
  5971. }
  5972. return (int)all_read;
  5973. }
  5974. return mg_read_inner(conn, buf, len);
  5975. }
  5976. int
  5977. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5978. {
  5979. time_t now;
  5980. int n, total, allowed;
  5981. if (conn == NULL) {
  5982. return 0;
  5983. }
  5984. if (len > INT_MAX) {
  5985. return -1;
  5986. }
  5987. if (conn->throttle > 0) {
  5988. if ((now = time(NULL)) != conn->last_throttle_time) {
  5989. conn->last_throttle_time = now;
  5990. conn->last_throttle_bytes = 0;
  5991. }
  5992. allowed = conn->throttle - conn->last_throttle_bytes;
  5993. if (allowed > (int)len) {
  5994. allowed = (int)len;
  5995. }
  5996. if ((total = push_all(conn->phys_ctx,
  5997. NULL,
  5998. conn->client.sock,
  5999. conn->ssl,
  6000. (const char *)buf,
  6001. allowed))
  6002. == allowed) {
  6003. buf = (const char *)buf + total;
  6004. conn->last_throttle_bytes += total;
  6005. while ((total < (int)len)
  6006. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6007. allowed = (conn->throttle > ((int)len - total))
  6008. ? (int)len - total
  6009. : conn->throttle;
  6010. if ((n = push_all(conn->phys_ctx,
  6011. NULL,
  6012. conn->client.sock,
  6013. conn->ssl,
  6014. (const char *)buf,
  6015. allowed))
  6016. != allowed) {
  6017. break;
  6018. }
  6019. sleep(1);
  6020. conn->last_throttle_bytes = allowed;
  6021. conn->last_throttle_time = time(NULL);
  6022. buf = (const char *)buf + n;
  6023. total += n;
  6024. }
  6025. }
  6026. } else {
  6027. total = push_all(conn->phys_ctx,
  6028. NULL,
  6029. conn->client.sock,
  6030. conn->ssl,
  6031. (const char *)buf,
  6032. (int)len);
  6033. }
  6034. if (total > 0) {
  6035. conn->num_bytes_sent += total;
  6036. }
  6037. return total;
  6038. }
  6039. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6040. int
  6041. mg_send_chunk(struct mg_connection *conn,
  6042. const char *chunk,
  6043. unsigned int chunk_len)
  6044. {
  6045. char lenbuf[16];
  6046. size_t lenbuf_len;
  6047. int ret;
  6048. int t;
  6049. /* First store the length information in a text buffer. */
  6050. sprintf(lenbuf, "%x\r\n", chunk_len);
  6051. lenbuf_len = strlen(lenbuf);
  6052. /* Then send length information, chunk and terminating \r\n. */
  6053. ret = mg_write(conn, lenbuf, lenbuf_len);
  6054. if (ret != (int)lenbuf_len) {
  6055. return -1;
  6056. }
  6057. t = ret;
  6058. ret = mg_write(conn, chunk, chunk_len);
  6059. if (ret != (int)chunk_len) {
  6060. return -1;
  6061. }
  6062. t += ret;
  6063. ret = mg_write(conn, "\r\n", 2);
  6064. if (ret != 2) {
  6065. return -1;
  6066. }
  6067. t += ret;
  6068. return t;
  6069. }
  6070. #if defined(GCC_DIAGNOSTIC)
  6071. /* This block forwards format strings to printf implementations,
  6072. * so we need to disable the format-nonliteral warning. */
  6073. #pragma GCC diagnostic push
  6074. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6075. #endif
  6076. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6077. static int
  6078. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6079. {
  6080. va_list ap_copy;
  6081. size_t size = MG_BUF_LEN / 4;
  6082. int len = -1;
  6083. *buf = NULL;
  6084. while (len < 0) {
  6085. if (*buf) {
  6086. mg_free(*buf);
  6087. }
  6088. size *= 4;
  6089. *buf = (char *)mg_malloc(size);
  6090. if (!*buf) {
  6091. break;
  6092. }
  6093. va_copy(ap_copy, ap);
  6094. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6095. va_end(ap_copy);
  6096. (*buf)[size - 1] = 0;
  6097. }
  6098. return len;
  6099. }
  6100. /* Print message to buffer. If buffer is large enough to hold the message,
  6101. * return buffer. If buffer is to small, allocate large enough buffer on
  6102. * heap,
  6103. * and return allocated buffer. */
  6104. static int
  6105. alloc_vprintf(char **out_buf,
  6106. char *prealloc_buf,
  6107. size_t prealloc_size,
  6108. const char *fmt,
  6109. va_list ap)
  6110. {
  6111. va_list ap_copy;
  6112. int len;
  6113. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6114. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6115. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6116. * Therefore, we make two passes: on first pass, get required message
  6117. * length.
  6118. * On second pass, actually print the message. */
  6119. va_copy(ap_copy, ap);
  6120. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6121. va_end(ap_copy);
  6122. if (len < 0) {
  6123. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6124. * Switch to alternative code path that uses incremental
  6125. * allocations.
  6126. */
  6127. va_copy(ap_copy, ap);
  6128. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6129. va_end(ap_copy);
  6130. } else if ((size_t)(len) >= prealloc_size) {
  6131. /* The pre-allocated buffer not large enough. */
  6132. /* Allocate a new buffer. */
  6133. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6134. if (!*out_buf) {
  6135. /* Allocation failed. Return -1 as "out of memory" error. */
  6136. return -1;
  6137. }
  6138. /* Buffer allocation successful. Store the string there. */
  6139. va_copy(ap_copy, ap);
  6140. IGNORE_UNUSED_RESULT(
  6141. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6142. va_end(ap_copy);
  6143. } else {
  6144. /* The pre-allocated buffer is large enough.
  6145. * Use it to store the string and return the address. */
  6146. va_copy(ap_copy, ap);
  6147. IGNORE_UNUSED_RESULT(
  6148. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6149. va_end(ap_copy);
  6150. *out_buf = prealloc_buf;
  6151. }
  6152. return len;
  6153. }
  6154. #if defined(GCC_DIAGNOSTIC)
  6155. /* Enable format-nonliteral warning again. */
  6156. #pragma GCC diagnostic pop
  6157. #endif
  6158. static int
  6159. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6160. {
  6161. char mem[MG_BUF_LEN];
  6162. char *buf = NULL;
  6163. int len;
  6164. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6165. len = mg_write(conn, buf, (size_t)len);
  6166. }
  6167. if (buf != mem) {
  6168. mg_free(buf);
  6169. }
  6170. return len;
  6171. }
  6172. int
  6173. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6174. {
  6175. va_list ap;
  6176. int result;
  6177. va_start(ap, fmt);
  6178. result = mg_vprintf(conn, fmt, ap);
  6179. va_end(ap);
  6180. return result;
  6181. }
  6182. int
  6183. mg_url_decode(const char *src,
  6184. int src_len,
  6185. char *dst,
  6186. int dst_len,
  6187. int is_form_url_encoded)
  6188. {
  6189. int i, j, a, b;
  6190. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6191. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6192. if ((i < src_len - 2) && (src[i] == '%')
  6193. && isxdigit((unsigned char)src[i + 1])
  6194. && isxdigit((unsigned char)src[i + 2])) {
  6195. a = tolower((unsigned char)src[i + 1]);
  6196. b = tolower((unsigned char)src[i + 2]);
  6197. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6198. i += 2;
  6199. } else if (is_form_url_encoded && (src[i] == '+')) {
  6200. dst[j] = ' ';
  6201. } else {
  6202. dst[j] = src[i];
  6203. }
  6204. }
  6205. dst[j] = '\0'; /* Null-terminate the destination */
  6206. return (i >= src_len) ? j : -1;
  6207. }
  6208. /* form url decoding of an entire string */
  6209. static void
  6210. url_decode_in_place(char *buf)
  6211. {
  6212. int len = (int)strlen(buf);
  6213. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6214. }
  6215. int
  6216. mg_get_var(const char *data,
  6217. size_t data_len,
  6218. const char *name,
  6219. char *dst,
  6220. size_t dst_len)
  6221. {
  6222. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6223. }
  6224. int
  6225. mg_get_var2(const char *data,
  6226. size_t data_len,
  6227. const char *name,
  6228. char *dst,
  6229. size_t dst_len,
  6230. size_t occurrence)
  6231. {
  6232. const char *p, *e, *s;
  6233. size_t name_len;
  6234. int len;
  6235. if ((dst == NULL) || (dst_len == 0)) {
  6236. len = -2;
  6237. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6238. len = -1;
  6239. dst[0] = '\0';
  6240. } else {
  6241. name_len = strlen(name);
  6242. e = data + data_len;
  6243. len = -1;
  6244. dst[0] = '\0';
  6245. /* data is "var1=val1&var2=val2...". Find variable first */
  6246. for (p = data; p + name_len < e; p++) {
  6247. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6248. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6249. /* Point p to variable value */
  6250. p += name_len + 1;
  6251. /* Point s to the end of the value */
  6252. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6253. if (s == NULL) {
  6254. s = e;
  6255. }
  6256. DEBUG_ASSERT(s >= p);
  6257. if (s < p) {
  6258. return -3;
  6259. }
  6260. /* Decode variable into destination buffer */
  6261. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6262. /* Redirect error code from -1 to -2 (destination buffer too
  6263. * small). */
  6264. if (len == -1) {
  6265. len = -2;
  6266. }
  6267. break;
  6268. }
  6269. }
  6270. }
  6271. return len;
  6272. }
  6273. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6274. int
  6275. mg_split_form_urlencoded(char *data,
  6276. struct mg_header *form_fields,
  6277. unsigned num_form_fields)
  6278. {
  6279. char *b;
  6280. int i;
  6281. int num = 0;
  6282. if (data == NULL) {
  6283. /* parameter error */
  6284. return -1;
  6285. }
  6286. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6287. /* determine the number of expected fields */
  6288. if (data[0] == 0) {
  6289. return 0;
  6290. }
  6291. /* count number of & to return the number of key-value-pairs */
  6292. num = 1;
  6293. while (*data) {
  6294. if (*data == '&') {
  6295. num++;
  6296. }
  6297. data++;
  6298. }
  6299. return num;
  6300. }
  6301. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6302. /* parameter error */
  6303. return -1;
  6304. }
  6305. for (i = 0; i < (int)num_form_fields; i++) {
  6306. /* extract key-value pairs from input data */
  6307. while ((*data == ' ') || (*data == '\t')) {
  6308. /* skip initial spaces */
  6309. data++;
  6310. }
  6311. if (*data == 0) {
  6312. /* end of string reached */
  6313. break;
  6314. }
  6315. form_fields[num].name = data;
  6316. /* find & or = */
  6317. b = data;
  6318. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6319. b++;
  6320. }
  6321. if (*b == 0) {
  6322. /* last key without value */
  6323. form_fields[num].value = NULL;
  6324. } else if (*b == '&') {
  6325. /* mid key without value */
  6326. form_fields[num].value = NULL;
  6327. } else {
  6328. /* terminate string */
  6329. *b = 0;
  6330. /* value starts after '=' */
  6331. data = b + 1;
  6332. form_fields[num].value = data;
  6333. }
  6334. /* new field is stored */
  6335. num++;
  6336. /* find a next key */
  6337. b = strchr(data, '&');
  6338. if (b == 0) {
  6339. /* no more data */
  6340. break;
  6341. } else {
  6342. /* terminate value of last field at '&' */
  6343. *b = 0;
  6344. /* next key-value-pairs starts after '&' */
  6345. data = b + 1;
  6346. }
  6347. }
  6348. /* Decode all values */
  6349. for (i = 0; i < num; i++) {
  6350. if (form_fields[i].name) {
  6351. url_decode_in_place((char *)form_fields[i].name);
  6352. }
  6353. if (form_fields[i].value) {
  6354. url_decode_in_place((char *)form_fields[i].value);
  6355. }
  6356. }
  6357. /* return number of fields found */
  6358. return num;
  6359. }
  6360. /* HCP24: some changes to compare hole var_name */
  6361. int
  6362. mg_get_cookie(const char *cookie_header,
  6363. const char *var_name,
  6364. char *dst,
  6365. size_t dst_size)
  6366. {
  6367. const char *s, *p, *end;
  6368. int name_len, len = -1;
  6369. if ((dst == NULL) || (dst_size == 0)) {
  6370. return -2;
  6371. }
  6372. dst[0] = '\0';
  6373. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6374. return -1;
  6375. }
  6376. name_len = (int)strlen(var_name);
  6377. end = s + strlen(s);
  6378. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6379. if (s[name_len] == '=') {
  6380. /* HCP24: now check is it a substring or a full cookie name */
  6381. if ((s == cookie_header) || (s[-1] == ' ')) {
  6382. s += name_len + 1;
  6383. if ((p = strchr(s, ' ')) == NULL) {
  6384. p = end;
  6385. }
  6386. if (p[-1] == ';') {
  6387. p--;
  6388. }
  6389. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6390. s++;
  6391. p--;
  6392. }
  6393. if ((size_t)(p - s) < dst_size) {
  6394. len = (int)(p - s);
  6395. mg_strlcpy(dst, s, (size_t)len + 1);
  6396. } else {
  6397. len = -3;
  6398. }
  6399. break;
  6400. }
  6401. }
  6402. }
  6403. return len;
  6404. }
  6405. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6406. static void
  6407. base64_encode(const unsigned char *src, int src_len, char *dst)
  6408. {
  6409. static const char *b64 =
  6410. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6411. int i, j, a, b, c;
  6412. for (i = j = 0; i < src_len; i += 3) {
  6413. a = src[i];
  6414. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6415. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6416. dst[j++] = b64[a >> 2];
  6417. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6418. if (i + 1 < src_len) {
  6419. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6420. }
  6421. if (i + 2 < src_len) {
  6422. dst[j++] = b64[c & 63];
  6423. }
  6424. }
  6425. while (j % 4 != 0) {
  6426. dst[j++] = '=';
  6427. }
  6428. dst[j++] = '\0';
  6429. }
  6430. #endif
  6431. #if defined(USE_LUA)
  6432. static unsigned char
  6433. b64reverse(char letter)
  6434. {
  6435. if ((letter >= 'A') && (letter <= 'Z')) {
  6436. return letter - 'A';
  6437. }
  6438. if ((letter >= 'a') && (letter <= 'z')) {
  6439. return letter - 'a' + 26;
  6440. }
  6441. if ((letter >= '0') && (letter <= '9')) {
  6442. return letter - '0' + 52;
  6443. }
  6444. if (letter == '+') {
  6445. return 62;
  6446. }
  6447. if (letter == '/') {
  6448. return 63;
  6449. }
  6450. if (letter == '=') {
  6451. return 255; /* normal end */
  6452. }
  6453. return 254; /* error */
  6454. }
  6455. static int
  6456. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6457. {
  6458. int i;
  6459. unsigned char a, b, c, d;
  6460. *dst_len = 0;
  6461. for (i = 0; i < src_len; i += 4) {
  6462. a = b64reverse(src[i]);
  6463. if (a >= 254) {
  6464. return i;
  6465. }
  6466. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6467. if (b >= 254) {
  6468. return i + 1;
  6469. }
  6470. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6471. if (c == 254) {
  6472. return i + 2;
  6473. }
  6474. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6475. if (d == 254) {
  6476. return i + 3;
  6477. }
  6478. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6479. if (c != 255) {
  6480. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6481. if (d != 255) {
  6482. dst[(*dst_len)++] = (c << 6) + d;
  6483. }
  6484. }
  6485. }
  6486. return -1;
  6487. }
  6488. #endif
  6489. static int
  6490. is_put_or_delete_method(const struct mg_connection *conn)
  6491. {
  6492. if (conn) {
  6493. const char *s = conn->request_info.request_method;
  6494. return (s != NULL)
  6495. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6496. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6497. }
  6498. return 0;
  6499. }
  6500. #if !defined(NO_FILES)
  6501. static int
  6502. extention_matches_script(
  6503. struct mg_connection *conn, /* in: request (must be valid) */
  6504. const char *filename /* in: filename (must be valid) */
  6505. )
  6506. {
  6507. #if !defined(NO_CGI)
  6508. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6509. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6510. filename)
  6511. > 0) {
  6512. return 1;
  6513. }
  6514. #endif
  6515. #if defined(USE_LUA)
  6516. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6517. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6518. filename)
  6519. > 0) {
  6520. return 1;
  6521. }
  6522. #endif
  6523. #if defined(USE_DUKTAPE)
  6524. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6525. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6526. filename)
  6527. > 0) {
  6528. return 1;
  6529. }
  6530. #endif
  6531. /* filename and conn could be unused, if all preocessor conditions
  6532. * are false (no script language supported). */
  6533. (void)filename;
  6534. (void)conn;
  6535. return 0;
  6536. }
  6537. /* For given directory path, substitute it to valid index file.
  6538. * Return 1 if index file has been found, 0 if not found.
  6539. * If the file is found, it's stats is returned in stp. */
  6540. static int
  6541. substitute_index_file(struct mg_connection *conn,
  6542. char *path,
  6543. size_t path_len,
  6544. struct mg_file_stat *filestat)
  6545. {
  6546. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6547. struct vec filename_vec;
  6548. size_t n = strlen(path);
  6549. int found = 0;
  6550. /* The 'path' given to us points to the directory. Remove all trailing
  6551. * directory separator characters from the end of the path, and
  6552. * then append single directory separator character. */
  6553. while ((n > 0) && (path[n - 1] == '/')) {
  6554. n--;
  6555. }
  6556. path[n] = '/';
  6557. /* Traverse index files list. For each entry, append it to the given
  6558. * path and see if the file exists. If it exists, break the loop */
  6559. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6560. /* Ignore too long entries that may overflow path buffer */
  6561. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6562. continue;
  6563. }
  6564. /* Prepare full path to the index file */
  6565. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6566. /* Does it exist? */
  6567. if (mg_stat(conn, path, filestat)) {
  6568. /* Yes it does, break the loop */
  6569. found = 1;
  6570. break;
  6571. }
  6572. }
  6573. /* If no index file exists, restore directory path */
  6574. if (!found) {
  6575. path[n] = '\0';
  6576. }
  6577. return found;
  6578. }
  6579. #endif
  6580. static void
  6581. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6582. char *filename, /* out: filename */
  6583. size_t filename_buf_len, /* in: size of filename buffer */
  6584. struct mg_file_stat *filestat, /* out: file status structure */
  6585. int *is_found, /* out: file found (directly) */
  6586. int *is_script_resource, /* out: handled by a script? */
  6587. int *is_websocket_request, /* out: websocket connetion? */
  6588. int *is_put_or_delete_request /* out: put/delete a file? */
  6589. )
  6590. {
  6591. char const *accept_encoding;
  6592. #if !defined(NO_FILES)
  6593. const char *uri = conn->request_info.local_uri;
  6594. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6595. const char *rewrite;
  6596. struct vec a, b;
  6597. ptrdiff_t match_len;
  6598. char gz_path[PATH_MAX];
  6599. int truncated;
  6600. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6601. char *tmp_str;
  6602. size_t tmp_str_len, sep_pos;
  6603. int allow_substitute_script_subresources;
  6604. #endif
  6605. #else
  6606. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6607. #endif
  6608. /* Step 1: Set all initially unknown outputs to zero */
  6609. memset(filestat, 0, sizeof(*filestat));
  6610. *filename = 0;
  6611. *is_found = 0;
  6612. *is_script_resource = 0;
  6613. /* Step 2: Check if the request attempts to modify the file system */
  6614. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6615. /* Step 3: Check if it is a websocket request, and modify the document
  6616. * root if required */
  6617. #if defined(USE_WEBSOCKET)
  6618. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6619. #if !defined(NO_FILES)
  6620. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6621. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6622. }
  6623. #endif /* !NO_FILES */
  6624. #else /* USE_WEBSOCKET */
  6625. *is_websocket_request = 0;
  6626. #endif /* USE_WEBSOCKET */
  6627. /* Step 4: Check if gzip encoded response is allowed */
  6628. conn->accept_gzip = 0;
  6629. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6630. if (strstr(accept_encoding, "gzip") != NULL) {
  6631. conn->accept_gzip = 1;
  6632. }
  6633. }
  6634. #if !defined(NO_FILES)
  6635. /* Step 5: If there is no root directory, don't look for files. */
  6636. /* Note that root == NULL is a regular use case here. This occurs,
  6637. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6638. * config is not required. */
  6639. if (root == NULL) {
  6640. /* all file related outputs have already been set to 0, just return
  6641. */
  6642. return;
  6643. }
  6644. /* Step 6: Determine the local file path from the root path and the
  6645. * request uri. */
  6646. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6647. * part of the path one byte on the right. */
  6648. mg_snprintf(
  6649. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6650. if (truncated) {
  6651. goto interpret_cleanup;
  6652. }
  6653. /* Step 7: URI rewriting */
  6654. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6655. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6656. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6657. mg_snprintf(conn,
  6658. &truncated,
  6659. filename,
  6660. filename_buf_len - 1,
  6661. "%.*s%s",
  6662. (int)b.len,
  6663. b.ptr,
  6664. uri + match_len);
  6665. break;
  6666. }
  6667. }
  6668. if (truncated) {
  6669. goto interpret_cleanup;
  6670. }
  6671. /* Step 8: Check if the file exists at the server */
  6672. /* Local file path and name, corresponding to requested URI
  6673. * is now stored in "filename" variable. */
  6674. if (mg_stat(conn, filename, filestat)) {
  6675. int uri_len = (int)strlen(uri);
  6676. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6677. /* 8.1: File exists. */
  6678. *is_found = 1;
  6679. /* 8.2: Check if it is a script type. */
  6680. if (extention_matches_script(conn, filename)) {
  6681. /* The request addresses a CGI resource, Lua script or
  6682. * server-side javascript.
  6683. * The URI corresponds to the script itself (like
  6684. * /path/script.cgi), and there is no additional resource
  6685. * path (like /path/script.cgi/something).
  6686. * Requests that modify (replace or delete) a resource, like
  6687. * PUT and DELETE requests, should replace/delete the script
  6688. * file.
  6689. * Requests that read or write from/to a resource, like GET and
  6690. * POST requests, should call the script and return the
  6691. * generated response. */
  6692. *is_script_resource = (!*is_put_or_delete_request);
  6693. }
  6694. /* 8.3: If the request target is a directory, there could be
  6695. * a substitute file (index.html, index.cgi, ...). */
  6696. if (filestat->is_directory && is_uri_end_slash) {
  6697. /* Use a local copy here, since substitute_index_file will
  6698. * change the content of the file status */
  6699. struct mg_file_stat tmp_filestat;
  6700. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6701. if (substitute_index_file(
  6702. conn, filename, filename_buf_len, &tmp_filestat)) {
  6703. /* Substitute file found. Copy stat to the output, then
  6704. * check if the file is a script file */
  6705. *filestat = tmp_filestat;
  6706. if (extention_matches_script(conn, filename)) {
  6707. /* Substitute file is a script file */
  6708. *is_script_resource = 1;
  6709. } else {
  6710. /* Substitute file is a regular file */
  6711. *is_script_resource = 0;
  6712. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6713. }
  6714. }
  6715. /* If there is no substitute file, the server could return
  6716. * a directory listing in a later step */
  6717. }
  6718. return;
  6719. }
  6720. /* Step 9: Check for zipped files: */
  6721. /* If we can't find the actual file, look for the file
  6722. * with the same name but a .gz extension. If we find it,
  6723. * use that and set the gzipped flag in the file struct
  6724. * to indicate that the response need to have the content-
  6725. * encoding: gzip header.
  6726. * We can only do this if the browser declares support. */
  6727. if (conn->accept_gzip) {
  6728. mg_snprintf(
  6729. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6730. if (truncated) {
  6731. goto interpret_cleanup;
  6732. }
  6733. if (mg_stat(conn, gz_path, filestat)) {
  6734. if (filestat) {
  6735. filestat->is_gzipped = 1;
  6736. *is_found = 1;
  6737. }
  6738. /* Currently gz files can not be scripts. */
  6739. return;
  6740. }
  6741. }
  6742. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6743. /* Step 10: Script resources may handle sub-resources */
  6744. /* Support PATH_INFO for CGI scripts. */
  6745. tmp_str_len = strlen(filename);
  6746. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6747. if (!tmp_str) {
  6748. /* Out of memory */
  6749. goto interpret_cleanup;
  6750. }
  6751. memcpy(tmp_str, filename, tmp_str_len + 1);
  6752. /* Check config, if index scripts may have sub-resources */
  6753. allow_substitute_script_subresources =
  6754. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6755. "yes");
  6756. sep_pos = tmp_str_len;
  6757. while (sep_pos > 0) {
  6758. sep_pos--;
  6759. if (tmp_str[sep_pos] == '/') {
  6760. int is_script = 0, does_exist = 0;
  6761. tmp_str[sep_pos] = 0;
  6762. if (tmp_str[0]) {
  6763. is_script = extention_matches_script(conn, tmp_str);
  6764. does_exist = mg_stat(conn, tmp_str, filestat);
  6765. }
  6766. if (does_exist && is_script) {
  6767. filename[sep_pos] = 0;
  6768. memmove(filename + sep_pos + 2,
  6769. filename + sep_pos + 1,
  6770. strlen(filename + sep_pos + 1) + 1);
  6771. conn->path_info = filename + sep_pos + 1;
  6772. filename[sep_pos + 1] = '/';
  6773. *is_script_resource = 1;
  6774. *is_found = 1;
  6775. break;
  6776. }
  6777. if (allow_substitute_script_subresources) {
  6778. if (substitute_index_file(
  6779. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6780. /* some intermediate directory has an index file */
  6781. if (extention_matches_script(conn, tmp_str)) {
  6782. DEBUG_TRACE("Substitute script %s serving path %s",
  6783. tmp_str,
  6784. filename);
  6785. /* this index file is a script */
  6786. mg_snprintf(conn,
  6787. &truncated,
  6788. filename,
  6789. filename_buf_len,
  6790. "%s//%s",
  6791. tmp_str,
  6792. filename + sep_pos + 1);
  6793. if (truncated) {
  6794. mg_free(tmp_str);
  6795. goto interpret_cleanup;
  6796. }
  6797. sep_pos = strlen(tmp_str);
  6798. filename[sep_pos] = 0;
  6799. conn->path_info = filename + sep_pos + 1;
  6800. *is_script_resource = 1;
  6801. *is_found = 1;
  6802. break;
  6803. } else {
  6804. DEBUG_TRACE("Substitute file %s serving path %s",
  6805. tmp_str,
  6806. filename);
  6807. /* non-script files will not have sub-resources */
  6808. filename[sep_pos] = 0;
  6809. conn->path_info = 0;
  6810. *is_script_resource = 0;
  6811. *is_found = 0;
  6812. break;
  6813. }
  6814. }
  6815. }
  6816. tmp_str[sep_pos] = '/';
  6817. }
  6818. }
  6819. mg_free(tmp_str);
  6820. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6821. #endif /* !defined(NO_FILES) */
  6822. return;
  6823. #if !defined(NO_FILES)
  6824. /* Reset all outputs */
  6825. interpret_cleanup:
  6826. memset(filestat, 0, sizeof(*filestat));
  6827. *filename = 0;
  6828. *is_found = 0;
  6829. *is_script_resource = 0;
  6830. *is_websocket_request = 0;
  6831. *is_put_or_delete_request = 0;
  6832. #endif /* !defined(NO_FILES) */
  6833. }
  6834. /* Check whether full request is buffered. Return:
  6835. * -1 if request or response is malformed
  6836. * 0 if request or response is not yet fully buffered
  6837. * >0 actual request length, including last \r\n\r\n */
  6838. static int
  6839. get_http_header_len(const char *buf, int buflen)
  6840. {
  6841. int i;
  6842. for (i = 0; i < buflen; i++) {
  6843. /* Do an unsigned comparison in some conditions below */
  6844. const unsigned char c = (unsigned char)buf[i];
  6845. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6846. && !isprint(c)) {
  6847. /* abort scan as soon as one malformed character is found */
  6848. return -1;
  6849. }
  6850. if (i < buflen - 1) {
  6851. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6852. /* Two newline, no carriage return - not standard compliant,
  6853. * but it should be accepted */
  6854. return i + 2;
  6855. }
  6856. }
  6857. if (i < buflen - 3) {
  6858. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6859. && (buf[i + 3] == '\n')) {
  6860. /* Two \r\n - standard compliant */
  6861. return i + 4;
  6862. }
  6863. }
  6864. }
  6865. return 0;
  6866. }
  6867. #if !defined(NO_CACHING)
  6868. /* Convert month to the month number. Return -1 on error, or month number */
  6869. static int
  6870. get_month_index(const char *s)
  6871. {
  6872. size_t i;
  6873. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6874. if (!strcmp(s, month_names[i])) {
  6875. return (int)i;
  6876. }
  6877. }
  6878. return -1;
  6879. }
  6880. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6881. static time_t
  6882. parse_date_string(const char *datetime)
  6883. {
  6884. char month_str[32] = {0};
  6885. int second, minute, hour, day, month, year;
  6886. time_t result = (time_t)0;
  6887. struct tm tm;
  6888. if ((sscanf(datetime,
  6889. "%d/%3s/%d %d:%d:%d",
  6890. &day,
  6891. month_str,
  6892. &year,
  6893. &hour,
  6894. &minute,
  6895. &second)
  6896. == 6)
  6897. || (sscanf(datetime,
  6898. "%d %3s %d %d:%d:%d",
  6899. &day,
  6900. month_str,
  6901. &year,
  6902. &hour,
  6903. &minute,
  6904. &second)
  6905. == 6)
  6906. || (sscanf(datetime,
  6907. "%*3s, %d %3s %d %d:%d:%d",
  6908. &day,
  6909. month_str,
  6910. &year,
  6911. &hour,
  6912. &minute,
  6913. &second)
  6914. == 6)
  6915. || (sscanf(datetime,
  6916. "%d-%3s-%d %d:%d:%d",
  6917. &day,
  6918. month_str,
  6919. &year,
  6920. &hour,
  6921. &minute,
  6922. &second)
  6923. == 6)) {
  6924. month = get_month_index(month_str);
  6925. if ((month >= 0) && (year >= 1970)) {
  6926. memset(&tm, 0, sizeof(tm));
  6927. tm.tm_year = year - 1900;
  6928. tm.tm_mon = month;
  6929. tm.tm_mday = day;
  6930. tm.tm_hour = hour;
  6931. tm.tm_min = minute;
  6932. tm.tm_sec = second;
  6933. result = timegm(&tm);
  6934. }
  6935. }
  6936. return result;
  6937. }
  6938. #endif /* !NO_CACHING */
  6939. /* Pre-process URIs according to RFC + protect against directory disclosure
  6940. * attacks by removing '..', excessive '/' and '\' characters */
  6941. static void
  6942. remove_dot_segments(char *inout)
  6943. {
  6944. /* Windows backend protection
  6945. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6946. * in URI by slash */
  6947. char *out_end = inout;
  6948. char *in = inout;
  6949. if (!in) {
  6950. /* Param error. */
  6951. return;
  6952. }
  6953. while (*in) {
  6954. if (*in == '\\') {
  6955. *in = '/';
  6956. }
  6957. in++;
  6958. }
  6959. /* Algorithm "remove_dot_segments" from
  6960. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6961. /* Step 1:
  6962. * The input buffer is initialized.
  6963. * The output buffer is initialized to the empty string.
  6964. */
  6965. in = inout;
  6966. /* Step 2:
  6967. * While the input buffer is not empty, loop as follows:
  6968. */
  6969. /* Less than out_end of the inout buffer is used as output, so keep
  6970. * condition: out_end <= in */
  6971. while (*in) {
  6972. /* Step 2a:
  6973. * If the input buffer begins with a prefix of "../" or "./",
  6974. * then remove that prefix from the input buffer;
  6975. */
  6976. if (!strncmp(in, "../", 3)) {
  6977. in += 3;
  6978. } else if (!strncmp(in, "./", 2)) {
  6979. in += 2;
  6980. }
  6981. /* otherwise */
  6982. /* Step 2b:
  6983. * if the input buffer begins with a prefix of "/./" or "/.",
  6984. * where "." is a complete path segment, then replace that
  6985. * prefix with "/" in the input buffer;
  6986. */
  6987. else if (!strncmp(in, "/./", 3)) {
  6988. in += 2;
  6989. } else if (!strcmp(in, "/.")) {
  6990. in[1] = 0;
  6991. }
  6992. /* otherwise */
  6993. /* Step 2c:
  6994. * if the input buffer begins with a prefix of "/../" or "/..",
  6995. * where ".." is a complete path segment, then replace that
  6996. * prefix with "/" in the input buffer and remove the last
  6997. * segment and its preceding "/" (if any) from the output
  6998. * buffer;
  6999. */
  7000. else if (!strncmp(in, "/../", 4)) {
  7001. in += 3;
  7002. if (inout != out_end) {
  7003. /* remove last segment */
  7004. do {
  7005. out_end--;
  7006. } while ((inout != out_end) && (*out_end != '/'));
  7007. }
  7008. } else if (!strcmp(in, "/..")) {
  7009. in[1] = 0;
  7010. if (inout != out_end) {
  7011. /* remove last segment */
  7012. do {
  7013. out_end--;
  7014. } while ((inout != out_end) && (*out_end != '/'));
  7015. }
  7016. }
  7017. /* otherwise */
  7018. /* Step 2d:
  7019. * if the input buffer consists only of "." or "..", then remove
  7020. * that from the input buffer;
  7021. */
  7022. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7023. *in = 0;
  7024. }
  7025. /* otherwise */
  7026. /* Step 2e:
  7027. * move the first path segment in the input buffer to the end of
  7028. * the output buffer, including the initial "/" character (if
  7029. * any) and any subsequent characters up to, but not including,
  7030. * the next "/" character or the end of the input buffer.
  7031. */
  7032. else {
  7033. do {
  7034. *out_end = *in;
  7035. out_end++;
  7036. in++;
  7037. } while ((*in != 0) && (*in != '/'));
  7038. }
  7039. }
  7040. /* Step 3:
  7041. * Finally, the output buffer is returned as the result of
  7042. * remove_dot_segments.
  7043. */
  7044. /* Terminate output */
  7045. *out_end = 0;
  7046. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7047. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7048. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7049. * or "//" anymore.
  7050. */
  7051. out_end = in = inout;
  7052. while (*in) {
  7053. if (*in == '.') {
  7054. /* remove . at the end or preceding of / */
  7055. char *in_ahead = in;
  7056. do {
  7057. in_ahead++;
  7058. } while (*in_ahead == '.');
  7059. if (*in_ahead == '/') {
  7060. in = in_ahead;
  7061. if ((out_end != inout) && (out_end[-1] == '/')) {
  7062. /* remove generated // */
  7063. out_end--;
  7064. }
  7065. } else if (*in_ahead == 0) {
  7066. in = in_ahead;
  7067. } else {
  7068. do {
  7069. *out_end++ = '.';
  7070. in++;
  7071. } while (in != in_ahead);
  7072. }
  7073. } else if (*in == '/') {
  7074. /* replace // by / */
  7075. *out_end++ = '/';
  7076. do {
  7077. in++;
  7078. } while (*in == '/');
  7079. } else {
  7080. *out_end++ = *in;
  7081. in++;
  7082. }
  7083. }
  7084. *out_end = 0;
  7085. }
  7086. static const struct {
  7087. const char *extension;
  7088. size_t ext_len;
  7089. const char *mime_type;
  7090. } builtin_mime_types[] = {
  7091. /* IANA registered MIME types
  7092. * (http://www.iana.org/assignments/media-types)
  7093. * application types */
  7094. {".doc", 4, "application/msword"},
  7095. {".eps", 4, "application/postscript"},
  7096. {".exe", 4, "application/octet-stream"},
  7097. {".js", 3, "application/javascript"},
  7098. {".json", 5, "application/json"},
  7099. {".pdf", 4, "application/pdf"},
  7100. {".ps", 3, "application/postscript"},
  7101. {".rtf", 4, "application/rtf"},
  7102. {".xhtml", 6, "application/xhtml+xml"},
  7103. {".xsl", 4, "application/xml"},
  7104. {".xslt", 5, "application/xml"},
  7105. /* fonts */
  7106. {".ttf", 4, "application/font-sfnt"},
  7107. {".cff", 4, "application/font-sfnt"},
  7108. {".otf", 4, "application/font-sfnt"},
  7109. {".aat", 4, "application/font-sfnt"},
  7110. {".sil", 4, "application/font-sfnt"},
  7111. {".pfr", 4, "application/font-tdpfr"},
  7112. {".woff", 5, "application/font-woff"},
  7113. /* audio */
  7114. {".mp3", 4, "audio/mpeg"},
  7115. {".oga", 4, "audio/ogg"},
  7116. {".ogg", 4, "audio/ogg"},
  7117. /* image */
  7118. {".gif", 4, "image/gif"},
  7119. {".ief", 4, "image/ief"},
  7120. {".jpeg", 5, "image/jpeg"},
  7121. {".jpg", 4, "image/jpeg"},
  7122. {".jpm", 4, "image/jpm"},
  7123. {".jpx", 4, "image/jpx"},
  7124. {".png", 4, "image/png"},
  7125. {".svg", 4, "image/svg+xml"},
  7126. {".tif", 4, "image/tiff"},
  7127. {".tiff", 5, "image/tiff"},
  7128. /* model */
  7129. {".wrl", 4, "model/vrml"},
  7130. /* text */
  7131. {".css", 4, "text/css"},
  7132. {".csv", 4, "text/csv"},
  7133. {".htm", 4, "text/html"},
  7134. {".html", 5, "text/html"},
  7135. {".sgm", 4, "text/sgml"},
  7136. {".shtm", 5, "text/html"},
  7137. {".shtml", 6, "text/html"},
  7138. {".txt", 4, "text/plain"},
  7139. {".xml", 4, "text/xml"},
  7140. /* video */
  7141. {".mov", 4, "video/quicktime"},
  7142. {".mp4", 4, "video/mp4"},
  7143. {".mpeg", 5, "video/mpeg"},
  7144. {".mpg", 4, "video/mpeg"},
  7145. {".ogv", 4, "video/ogg"},
  7146. {".qt", 3, "video/quicktime"},
  7147. /* not registered types
  7148. * (http://reference.sitepoint.com/html/mime-types-full,
  7149. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7150. {".arj", 4, "application/x-arj-compressed"},
  7151. {".gz", 3, "application/x-gunzip"},
  7152. {".rar", 4, "application/x-arj-compressed"},
  7153. {".swf", 4, "application/x-shockwave-flash"},
  7154. {".tar", 4, "application/x-tar"},
  7155. {".tgz", 4, "application/x-tar-gz"},
  7156. {".torrent", 8, "application/x-bittorrent"},
  7157. {".ppt", 4, "application/x-mspowerpoint"},
  7158. {".xls", 4, "application/x-msexcel"},
  7159. {".zip", 4, "application/x-zip-compressed"},
  7160. {".aac",
  7161. 4,
  7162. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7163. {".aif", 4, "audio/x-aif"},
  7164. {".m3u", 4, "audio/x-mpegurl"},
  7165. {".mid", 4, "audio/x-midi"},
  7166. {".ra", 3, "audio/x-pn-realaudio"},
  7167. {".ram", 4, "audio/x-pn-realaudio"},
  7168. {".wav", 4, "audio/x-wav"},
  7169. {".bmp", 4, "image/bmp"},
  7170. {".ico", 4, "image/x-icon"},
  7171. {".pct", 4, "image/x-pct"},
  7172. {".pict", 5, "image/pict"},
  7173. {".rgb", 4, "image/x-rgb"},
  7174. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7175. {".asf", 4, "video/x-ms-asf"},
  7176. {".avi", 4, "video/x-msvideo"},
  7177. {".m4v", 4, "video/x-m4v"},
  7178. {NULL, 0, NULL}};
  7179. const char *
  7180. mg_get_builtin_mime_type(const char *path)
  7181. {
  7182. const char *ext;
  7183. size_t i, path_len;
  7184. path_len = strlen(path);
  7185. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7186. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7187. if ((path_len > builtin_mime_types[i].ext_len)
  7188. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7189. return builtin_mime_types[i].mime_type;
  7190. }
  7191. }
  7192. return "text/plain";
  7193. }
  7194. /* Look at the "path" extension and figure what mime type it has.
  7195. * Store mime type in the vector. */
  7196. static void
  7197. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7198. {
  7199. struct vec ext_vec, mime_vec;
  7200. const char *list, *ext;
  7201. size_t path_len;
  7202. path_len = strlen(path);
  7203. if ((conn == NULL) || (vec == NULL)) {
  7204. if (vec != NULL) {
  7205. memset(vec, '\0', sizeof(struct vec));
  7206. }
  7207. return;
  7208. }
  7209. /* Scan user-defined mime types first, in case user wants to
  7210. * override default mime types. */
  7211. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7212. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7213. /* ext now points to the path suffix */
  7214. ext = path + path_len - ext_vec.len;
  7215. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7216. *vec = mime_vec;
  7217. return;
  7218. }
  7219. }
  7220. vec->ptr = mg_get_builtin_mime_type(path);
  7221. vec->len = strlen(vec->ptr);
  7222. }
  7223. /* Stringify binary data. Output buffer must be twice as big as input,
  7224. * because each byte takes 2 bytes in string representation */
  7225. static void
  7226. bin2str(char *to, const unsigned char *p, size_t len)
  7227. {
  7228. static const char *hex = "0123456789abcdef";
  7229. for (; len--; p++) {
  7230. *to++ = hex[p[0] >> 4];
  7231. *to++ = hex[p[0] & 0x0f];
  7232. }
  7233. *to = '\0';
  7234. }
  7235. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7236. */
  7237. char *
  7238. mg_md5(char buf[33], ...)
  7239. {
  7240. md5_byte_t hash[16];
  7241. const char *p;
  7242. va_list ap;
  7243. md5_state_t ctx;
  7244. md5_init(&ctx);
  7245. va_start(ap, buf);
  7246. while ((p = va_arg(ap, const char *)) != NULL) {
  7247. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7248. }
  7249. va_end(ap);
  7250. md5_finish(&ctx, hash);
  7251. bin2str(buf, hash, sizeof(hash));
  7252. return buf;
  7253. }
  7254. /* Check the user's password, return 1 if OK */
  7255. static int
  7256. check_password(const char *method,
  7257. const char *ha1,
  7258. const char *uri,
  7259. const char *nonce,
  7260. const char *nc,
  7261. const char *cnonce,
  7262. const char *qop,
  7263. const char *response)
  7264. {
  7265. char ha2[32 + 1], expected_response[32 + 1];
  7266. /* Some of the parameters may be NULL */
  7267. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7268. || (qop == NULL) || (response == NULL)) {
  7269. return 0;
  7270. }
  7271. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7272. if (strlen(response) != 32) {
  7273. return 0;
  7274. }
  7275. mg_md5(ha2, method, ":", uri, NULL);
  7276. mg_md5(expected_response,
  7277. ha1,
  7278. ":",
  7279. nonce,
  7280. ":",
  7281. nc,
  7282. ":",
  7283. cnonce,
  7284. ":",
  7285. qop,
  7286. ":",
  7287. ha2,
  7288. NULL);
  7289. return mg_strcasecmp(response, expected_response) == 0;
  7290. }
  7291. #if !defined(NO_FILESYSTEMS)
  7292. /* Use the global passwords file, if specified by auth_gpass option,
  7293. * or search for .htpasswd in the requested directory. */
  7294. static void
  7295. open_auth_file(struct mg_connection *conn,
  7296. const char *path,
  7297. struct mg_file *filep)
  7298. {
  7299. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7300. char name[PATH_MAX];
  7301. const char *p, *e,
  7302. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7303. int truncated;
  7304. if (gpass != NULL) {
  7305. /* Use global passwords file */
  7306. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7307. #if defined(DEBUG)
  7308. /* Use mg_cry_internal here, since gpass has been
  7309. * configured. */
  7310. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7311. #endif
  7312. }
  7313. /* Important: using local struct mg_file to test path for
  7314. * is_directory flag. If filep is used, mg_stat() makes it
  7315. * appear as if auth file was opened.
  7316. * TODO(mid): Check if this is still required after rewriting
  7317. * mg_stat */
  7318. } else if (mg_stat(conn, path, &filep->stat)
  7319. && filep->stat.is_directory) {
  7320. mg_snprintf(conn,
  7321. &truncated,
  7322. name,
  7323. sizeof(name),
  7324. "%s/%s",
  7325. path,
  7326. PASSWORDS_FILE_NAME);
  7327. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7328. #if defined(DEBUG)
  7329. /* Don't use mg_cry_internal here, but only a trace, since
  7330. * this is a typical case. It will occur for every directory
  7331. * without a password file. */
  7332. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7333. #endif
  7334. }
  7335. } else {
  7336. /* Try to find .htpasswd in requested directory. */
  7337. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7338. if (e[0] == '/') {
  7339. break;
  7340. }
  7341. }
  7342. mg_snprintf(conn,
  7343. &truncated,
  7344. name,
  7345. sizeof(name),
  7346. "%.*s/%s",
  7347. (int)(e - p),
  7348. p,
  7349. PASSWORDS_FILE_NAME);
  7350. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7351. #if defined(DEBUG)
  7352. /* Don't use mg_cry_internal here, but only a trace, since
  7353. * this is a typical case. It will occur for every directory
  7354. * without a password file. */
  7355. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7356. #endif
  7357. }
  7358. }
  7359. }
  7360. }
  7361. #endif /* NO_FILESYSTEMS */
  7362. /* Parsed Authorization header */
  7363. struct ah {
  7364. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7365. };
  7366. /* Return 1 on success. Always initializes the ah structure. */
  7367. static int
  7368. parse_auth_header(struct mg_connection *conn,
  7369. char *buf,
  7370. size_t buf_size,
  7371. struct ah *ah)
  7372. {
  7373. char *name, *value, *s;
  7374. const char *auth_header;
  7375. uint64_t nonce;
  7376. if (!ah || !conn) {
  7377. return 0;
  7378. }
  7379. (void)memset(ah, 0, sizeof(*ah));
  7380. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7381. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7382. return 0;
  7383. }
  7384. /* Make modifiable copy of the auth header */
  7385. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7386. s = buf;
  7387. /* Parse authorization header */
  7388. for (;;) {
  7389. /* Gobble initial spaces */
  7390. while (isspace((unsigned char)*s)) {
  7391. s++;
  7392. }
  7393. name = skip_quoted(&s, "=", " ", 0);
  7394. /* Value is either quote-delimited, or ends at first comma or space.
  7395. */
  7396. if (s[0] == '\"') {
  7397. s++;
  7398. value = skip_quoted(&s, "\"", " ", '\\');
  7399. if (s[0] == ',') {
  7400. s++;
  7401. }
  7402. } else {
  7403. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7404. * uses spaces */
  7405. }
  7406. if (*name == '\0') {
  7407. break;
  7408. }
  7409. if (!strcmp(name, "username")) {
  7410. ah->user = value;
  7411. } else if (!strcmp(name, "cnonce")) {
  7412. ah->cnonce = value;
  7413. } else if (!strcmp(name, "response")) {
  7414. ah->response = value;
  7415. } else if (!strcmp(name, "uri")) {
  7416. ah->uri = value;
  7417. } else if (!strcmp(name, "qop")) {
  7418. ah->qop = value;
  7419. } else if (!strcmp(name, "nc")) {
  7420. ah->nc = value;
  7421. } else if (!strcmp(name, "nonce")) {
  7422. ah->nonce = value;
  7423. }
  7424. }
  7425. #if !defined(NO_NONCE_CHECK)
  7426. /* Read the nonce from the response. */
  7427. if (ah->nonce == NULL) {
  7428. return 0;
  7429. }
  7430. s = NULL;
  7431. nonce = strtoull(ah->nonce, &s, 10);
  7432. if ((s == NULL) || (*s != 0)) {
  7433. return 0;
  7434. }
  7435. /* Convert the nonce from the client to a number. */
  7436. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7437. /* The converted number corresponds to the time the nounce has been
  7438. * created. This should not be earlier than the server start. */
  7439. /* Server side nonce check is valuable in all situations but one:
  7440. * if the server restarts frequently, but the client should not see
  7441. * that, so the server should accept nonces from previous starts. */
  7442. /* However, the reasonable default is to not accept a nonce from a
  7443. * previous start, so if anyone changed the access rights between
  7444. * two restarts, a new login is required. */
  7445. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7446. /* nonce is from a previous start of the server and no longer valid
  7447. * (replay attack?) */
  7448. return 0;
  7449. }
  7450. /* Check if the nonce is too high, so it has not (yet) been used by the
  7451. * server. */
  7452. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7453. + conn->dom_ctx->nonce_count)) {
  7454. return 0;
  7455. }
  7456. #else
  7457. (void)nonce;
  7458. #endif
  7459. /* CGI needs it as REMOTE_USER */
  7460. if (ah->user != NULL) {
  7461. conn->request_info.remote_user =
  7462. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7463. } else {
  7464. return 0;
  7465. }
  7466. return 1;
  7467. }
  7468. static const char *
  7469. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7470. {
  7471. #if defined(MG_USE_OPEN_FILE)
  7472. const char *eof;
  7473. size_t len;
  7474. const char *memend;
  7475. #else
  7476. (void)p; /* parameter is unused */
  7477. #endif
  7478. if (!filep) {
  7479. return NULL;
  7480. }
  7481. #if defined(MG_USE_OPEN_FILE)
  7482. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7483. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7484. /* Search for \n from p till the end of stream */
  7485. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7486. if (eof != NULL) {
  7487. eof += 1; /* Include \n */
  7488. } else {
  7489. eof = memend; /* Copy remaining data */
  7490. }
  7491. len =
  7492. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7493. memcpy(buf, *p, len);
  7494. buf[len] = '\0';
  7495. *p += len;
  7496. return len ? eof : NULL;
  7497. } else /* filep->access.fp block below */
  7498. #endif
  7499. if (filep->access.fp != NULL) {
  7500. return fgets(buf, (int)size, filep->access.fp);
  7501. } else {
  7502. return NULL;
  7503. }
  7504. }
  7505. /* Define the initial recursion depth for procesesing htpasswd files that
  7506. * include other htpasswd
  7507. * (or even the same) files. It is not difficult to provide a file or files
  7508. * s.t. they force civetweb
  7509. * to infinitely recurse and then crash.
  7510. */
  7511. #define INITIAL_DEPTH 9
  7512. #if INITIAL_DEPTH <= 0
  7513. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7514. #endif
  7515. #if !defined(NO_FILESYSTEMS)
  7516. struct read_auth_file_struct {
  7517. struct mg_connection *conn;
  7518. struct ah ah;
  7519. const char *domain;
  7520. char buf[256 + 256 + 40];
  7521. const char *f_user;
  7522. const char *f_domain;
  7523. const char *f_ha1;
  7524. };
  7525. static int
  7526. read_auth_file(struct mg_file *filep,
  7527. struct read_auth_file_struct *workdata,
  7528. int depth)
  7529. {
  7530. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7531. int is_authorized = 0;
  7532. struct mg_file fp;
  7533. size_t l;
  7534. if (!filep || !workdata || (0 == depth)) {
  7535. return 0;
  7536. }
  7537. /* Loop over passwords file */
  7538. #if defined(MG_USE_OPEN_FILE)
  7539. p = (char *)filep->access.membuf;
  7540. #endif
  7541. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7542. l = strlen(workdata->buf);
  7543. while (l > 0) {
  7544. if (isspace((unsigned char)workdata->buf[l - 1])
  7545. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7546. l--;
  7547. workdata->buf[l] = 0;
  7548. } else
  7549. break;
  7550. }
  7551. if (l < 1) {
  7552. continue;
  7553. }
  7554. workdata->f_user = workdata->buf;
  7555. if (workdata->f_user[0] == ':') {
  7556. /* user names may not contain a ':' and may not be empty,
  7557. * so lines starting with ':' may be used for a special purpose
  7558. */
  7559. if (workdata->f_user[1] == '#') {
  7560. /* :# is a comment */
  7561. continue;
  7562. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7563. if (mg_fopen(workdata->conn,
  7564. workdata->f_user + 9,
  7565. MG_FOPEN_MODE_READ,
  7566. &fp)) {
  7567. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7568. (void)mg_fclose(
  7569. &fp.access); /* ignore error on read only file */
  7570. /* No need to continue processing files once we have a
  7571. * match, since nothing will reset it back
  7572. * to 0.
  7573. */
  7574. if (is_authorized) {
  7575. return is_authorized;
  7576. }
  7577. } else {
  7578. mg_cry_internal(workdata->conn,
  7579. "%s: cannot open authorization file: %s",
  7580. __func__,
  7581. workdata->buf);
  7582. }
  7583. continue;
  7584. }
  7585. /* everything is invalid for the moment (might change in the
  7586. * future) */
  7587. mg_cry_internal(workdata->conn,
  7588. "%s: syntax error in authorization file: %s",
  7589. __func__,
  7590. workdata->buf);
  7591. continue;
  7592. }
  7593. workdata->f_domain = strchr(workdata->f_user, ':');
  7594. if (workdata->f_domain == NULL) {
  7595. mg_cry_internal(workdata->conn,
  7596. "%s: syntax error in authorization file: %s",
  7597. __func__,
  7598. workdata->buf);
  7599. continue;
  7600. }
  7601. *(char *)(workdata->f_domain) = 0;
  7602. (workdata->f_domain)++;
  7603. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7604. if (workdata->f_ha1 == NULL) {
  7605. mg_cry_internal(workdata->conn,
  7606. "%s: syntax error in authorization file: %s",
  7607. __func__,
  7608. workdata->buf);
  7609. continue;
  7610. }
  7611. *(char *)(workdata->f_ha1) = 0;
  7612. (workdata->f_ha1)++;
  7613. if (!strcmp(workdata->ah.user, workdata->f_user)
  7614. && !strcmp(workdata->domain, workdata->f_domain)) {
  7615. return check_password(workdata->conn->request_info.request_method,
  7616. workdata->f_ha1,
  7617. workdata->ah.uri,
  7618. workdata->ah.nonce,
  7619. workdata->ah.nc,
  7620. workdata->ah.cnonce,
  7621. workdata->ah.qop,
  7622. workdata->ah.response);
  7623. }
  7624. }
  7625. return is_authorized;
  7626. }
  7627. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7628. static int
  7629. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7630. {
  7631. struct read_auth_file_struct workdata;
  7632. char buf[MG_BUF_LEN];
  7633. if (!conn || !conn->dom_ctx) {
  7634. return 0;
  7635. }
  7636. memset(&workdata, 0, sizeof(workdata));
  7637. workdata.conn = conn;
  7638. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7639. return 0;
  7640. }
  7641. if (realm) {
  7642. workdata.domain = realm;
  7643. } else {
  7644. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7645. }
  7646. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7647. }
  7648. /* Public function to check http digest authentication header */
  7649. int
  7650. mg_check_digest_access_authentication(struct mg_connection *conn,
  7651. const char *realm,
  7652. const char *filename)
  7653. {
  7654. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7655. int auth;
  7656. if (!conn || !filename) {
  7657. return -1;
  7658. }
  7659. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7660. return -2;
  7661. }
  7662. auth = authorize(conn, &file, realm);
  7663. mg_fclose(&file.access);
  7664. return auth;
  7665. }
  7666. #endif /* NO_FILESYSTEMS */
  7667. /* Return 1 if request is authorised, 0 otherwise. */
  7668. static int
  7669. check_authorization(struct mg_connection *conn, const char *path)
  7670. {
  7671. #if !defined(NO_FILESYSTEMS)
  7672. char fname[PATH_MAX];
  7673. struct vec uri_vec, filename_vec;
  7674. const char *list;
  7675. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7676. int authorized = 1, truncated;
  7677. if (!conn || !conn->dom_ctx) {
  7678. return 0;
  7679. }
  7680. list = conn->dom_ctx->config[PROTECT_URI];
  7681. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7682. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7683. mg_snprintf(conn,
  7684. &truncated,
  7685. fname,
  7686. sizeof(fname),
  7687. "%.*s",
  7688. (int)filename_vec.len,
  7689. filename_vec.ptr);
  7690. if (truncated
  7691. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7692. mg_cry_internal(conn,
  7693. "%s: cannot open %s: %s",
  7694. __func__,
  7695. fname,
  7696. strerror(errno));
  7697. }
  7698. break;
  7699. }
  7700. }
  7701. if (!is_file_opened(&file.access)) {
  7702. open_auth_file(conn, path, &file);
  7703. }
  7704. if (is_file_opened(&file.access)) {
  7705. authorized = authorize(conn, &file, NULL);
  7706. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7707. }
  7708. return authorized;
  7709. #else
  7710. (void)conn;
  7711. (void)path;
  7712. return 1;
  7713. #endif /* NO_FILESYSTEMS */
  7714. }
  7715. /* Internal function. Assumes conn is valid */
  7716. static void
  7717. send_authorization_request(struct mg_connection *conn, const char *realm)
  7718. {
  7719. char date[64];
  7720. time_t curtime = time(NULL);
  7721. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7722. if (!realm) {
  7723. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7724. }
  7725. mg_lock_context(conn->phys_ctx);
  7726. nonce += conn->dom_ctx->nonce_count;
  7727. ++conn->dom_ctx->nonce_count;
  7728. mg_unlock_context(conn->phys_ctx);
  7729. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7730. conn->status_code = 401;
  7731. conn->must_close = 1;
  7732. gmt_time_string(date, sizeof(date), &curtime);
  7733. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7734. send_no_cache_header(conn);
  7735. send_additional_header(conn);
  7736. mg_printf(conn,
  7737. "Date: %s\r\n"
  7738. "Connection: %s\r\n"
  7739. "Content-Length: 0\r\n"
  7740. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7741. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7742. date,
  7743. suggest_connection_header(conn),
  7744. realm,
  7745. nonce);
  7746. }
  7747. /* Interface function. Parameters are provided by the user, so do
  7748. * at least some basic checks.
  7749. */
  7750. int
  7751. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7752. const char *realm)
  7753. {
  7754. if (conn && conn->dom_ctx) {
  7755. send_authorization_request(conn, realm);
  7756. return 0;
  7757. }
  7758. return -1;
  7759. }
  7760. #if !defined(NO_FILES)
  7761. static int
  7762. is_authorized_for_put(struct mg_connection *conn)
  7763. {
  7764. if (conn) {
  7765. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7766. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7767. int ret = 0;
  7768. if (passfile != NULL
  7769. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7770. ret = authorize(conn, &file, NULL);
  7771. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7772. }
  7773. return ret;
  7774. }
  7775. return 0;
  7776. }
  7777. #endif
  7778. int
  7779. mg_modify_passwords_file(const char *fname,
  7780. const char *domain,
  7781. const char *user,
  7782. const char *pass)
  7783. {
  7784. int found, i;
  7785. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7786. FILE *fp, *fp2;
  7787. found = 0;
  7788. fp = fp2 = NULL;
  7789. /* Regard empty password as no password - remove user record. */
  7790. if ((pass != NULL) && (pass[0] == '\0')) {
  7791. pass = NULL;
  7792. }
  7793. /* Other arguments must not be empty */
  7794. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7795. return 0;
  7796. }
  7797. /* Using the given file format, user name and domain must not contain
  7798. * ':'
  7799. */
  7800. if (strchr(user, ':') != NULL) {
  7801. return 0;
  7802. }
  7803. if (strchr(domain, ':') != NULL) {
  7804. return 0;
  7805. }
  7806. /* Do not allow control characters like newline in user name and domain.
  7807. * Do not allow excessively long names either. */
  7808. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7809. if (iscntrl((unsigned char)user[i])) {
  7810. return 0;
  7811. }
  7812. }
  7813. if (user[i]) {
  7814. return 0;
  7815. }
  7816. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7817. if (iscntrl((unsigned char)domain[i])) {
  7818. return 0;
  7819. }
  7820. }
  7821. if (domain[i]) {
  7822. return 0;
  7823. }
  7824. /* The maximum length of the path to the password file is limited */
  7825. if ((strlen(fname) + 4) >= PATH_MAX) {
  7826. return 0;
  7827. }
  7828. /* Create a temporary file name. Length has been checked before. */
  7829. strcpy(tmp, fname);
  7830. strcat(tmp, ".tmp");
  7831. /* Create the file if does not exist */
  7832. /* Use of fopen here is OK, since fname is only ASCII */
  7833. if ((fp = fopen(fname, "a+")) != NULL) {
  7834. (void)fclose(fp);
  7835. }
  7836. /* Open the given file and temporary file */
  7837. if ((fp = fopen(fname, "r")) == NULL) {
  7838. return 0;
  7839. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7840. fclose(fp);
  7841. return 0;
  7842. }
  7843. /* Copy the stuff to temporary file */
  7844. while (fgets(line, sizeof(line), fp) != NULL) {
  7845. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7846. continue;
  7847. }
  7848. u[255] = 0;
  7849. d[255] = 0;
  7850. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7851. found++;
  7852. if (pass != NULL) {
  7853. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7854. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7855. }
  7856. } else {
  7857. fprintf(fp2, "%s", line);
  7858. }
  7859. }
  7860. /* If new user, just add it */
  7861. if (!found && (pass != NULL)) {
  7862. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7863. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7864. }
  7865. /* Close files */
  7866. fclose(fp);
  7867. fclose(fp2);
  7868. /* Put the temp file in place of real file */
  7869. IGNORE_UNUSED_RESULT(remove(fname));
  7870. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7871. return 1;
  7872. }
  7873. static int
  7874. is_valid_port(unsigned long port)
  7875. {
  7876. return (port <= 0xffff);
  7877. }
  7878. static int
  7879. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7880. {
  7881. struct addrinfo hints, *res, *ressave;
  7882. int func_ret = 0;
  7883. int gai_ret;
  7884. memset(&hints, 0, sizeof(struct addrinfo));
  7885. hints.ai_family = af;
  7886. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7887. if (gai_ret != 0) {
  7888. /* gai_strerror could be used to convert gai_ret to a string */
  7889. /* POSIX return values: see
  7890. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7891. */
  7892. /* Windows return values: see
  7893. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7894. */
  7895. return 0;
  7896. }
  7897. ressave = res;
  7898. while (res) {
  7899. if (dstlen >= (size_t)res->ai_addrlen) {
  7900. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7901. func_ret = 1;
  7902. }
  7903. res = res->ai_next;
  7904. }
  7905. freeaddrinfo(ressave);
  7906. return func_ret;
  7907. }
  7908. static int
  7909. connect_socket(struct mg_context *ctx /* may be NULL */,
  7910. const char *host,
  7911. int port,
  7912. int use_ssl,
  7913. char *ebuf,
  7914. size_t ebuf_len,
  7915. SOCKET *sock /* output: socket, must not be NULL */,
  7916. union usa *sa /* output: socket address, must not be NULL */
  7917. )
  7918. {
  7919. int ip_ver = 0;
  7920. int conn_ret = -1;
  7921. int sockerr = 0;
  7922. *sock = INVALID_SOCKET;
  7923. memset(sa, 0, sizeof(*sa));
  7924. if (ebuf_len > 0) {
  7925. *ebuf = 0;
  7926. }
  7927. if (host == NULL) {
  7928. mg_snprintf(NULL,
  7929. NULL, /* No truncation check for ebuf */
  7930. ebuf,
  7931. ebuf_len,
  7932. "%s",
  7933. "NULL host");
  7934. return 0;
  7935. }
  7936. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7937. mg_snprintf(NULL,
  7938. NULL, /* No truncation check for ebuf */
  7939. ebuf,
  7940. ebuf_len,
  7941. "%s",
  7942. "invalid port");
  7943. return 0;
  7944. }
  7945. #if !defined(NO_SSL)
  7946. #if !defined(NO_SSL_DL)
  7947. #if defined(OPENSSL_API_1_1)
  7948. if (use_ssl && (TLS_client_method == NULL)) {
  7949. mg_snprintf(NULL,
  7950. NULL, /* No truncation check for ebuf */
  7951. ebuf,
  7952. ebuf_len,
  7953. "%s",
  7954. "SSL is not initialized");
  7955. return 0;
  7956. }
  7957. #else
  7958. if (use_ssl && (SSLv23_client_method == NULL)) {
  7959. mg_snprintf(NULL,
  7960. NULL, /* No truncation check for ebuf */
  7961. ebuf,
  7962. ebuf_len,
  7963. "%s",
  7964. "SSL is not initialized");
  7965. return 0;
  7966. }
  7967. #endif /* OPENSSL_API_1_1 */
  7968. #else
  7969. (void)use_ssl;
  7970. #endif /* NO_SSL_DL */
  7971. #else
  7972. (void)use_ssl;
  7973. #endif /* !defined(NO_SSL) */
  7974. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7975. sa->sin.sin_family = AF_INET;
  7976. sa->sin.sin_port = htons((uint16_t)port);
  7977. ip_ver = 4;
  7978. #if defined(USE_IPV6)
  7979. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7980. sa->sin6.sin6_family = AF_INET6;
  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))) {
  7991. sa->sin6.sin6_family = AF_INET6;
  7992. sa->sin6.sin6_port = htons((uint16_t)port);
  7993. ip_ver = 6;
  7994. }
  7995. mg_free(h);
  7996. }
  7997. #endif
  7998. }
  7999. if (ip_ver == 0) {
  8000. mg_snprintf(NULL,
  8001. NULL, /* No truncation check for ebuf */
  8002. ebuf,
  8003. ebuf_len,
  8004. "%s",
  8005. "host not found");
  8006. return 0;
  8007. }
  8008. if (ip_ver == 4) {
  8009. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8010. }
  8011. #if defined(USE_IPV6)
  8012. else if (ip_ver == 6) {
  8013. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8014. }
  8015. #endif
  8016. if (*sock == INVALID_SOCKET) {
  8017. mg_snprintf(NULL,
  8018. NULL, /* No truncation check for ebuf */
  8019. ebuf,
  8020. ebuf_len,
  8021. "socket(): %s",
  8022. strerror(ERRNO));
  8023. return 0;
  8024. }
  8025. if (0 != set_non_blocking_mode(*sock)) {
  8026. mg_snprintf(NULL,
  8027. NULL, /* No truncation check for ebuf */
  8028. ebuf,
  8029. ebuf_len,
  8030. "Cannot set socket to non-blocking: %s",
  8031. strerror(ERRNO));
  8032. closesocket(*sock);
  8033. *sock = INVALID_SOCKET;
  8034. return 0;
  8035. }
  8036. set_close_on_exec(*sock, NULL, ctx);
  8037. if (ip_ver == 4) {
  8038. /* connected with IPv4 */
  8039. conn_ret = connect(*sock,
  8040. (struct sockaddr *)((void *)&sa->sin),
  8041. sizeof(sa->sin));
  8042. }
  8043. #if defined(USE_IPV6)
  8044. else if (ip_ver == 6) {
  8045. /* connected with IPv6 */
  8046. conn_ret = connect(*sock,
  8047. (struct sockaddr *)((void *)&sa->sin6),
  8048. sizeof(sa->sin6));
  8049. }
  8050. #endif
  8051. if (conn_ret != 0) {
  8052. sockerr = ERRNO;
  8053. }
  8054. #if defined(_WIN32)
  8055. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8056. #else
  8057. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8058. #endif
  8059. /* Data for getsockopt */
  8060. void *psockerr = &sockerr;
  8061. int ret;
  8062. #if defined(_WIN32)
  8063. int len = (int)sizeof(sockerr);
  8064. #else
  8065. socklen_t len = (socklen_t)sizeof(sockerr);
  8066. #endif
  8067. /* Data for poll */
  8068. struct mg_pollfd pfd[1];
  8069. int pollres;
  8070. int ms_wait = 10000; /* 10 second timeout */
  8071. stop_flag_t nonstop;
  8072. STOP_FLAG_ASSIGN(&nonstop, 0);
  8073. /* For a non-blocking socket, the connect sequence is:
  8074. * 1) call connect (will not block)
  8075. * 2) wait until the socket is ready for writing (select or poll)
  8076. * 3) check connection state with getsockopt
  8077. */
  8078. pfd[0].fd = *sock;
  8079. pfd[0].events = POLLOUT;
  8080. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8081. if (pollres != 1) {
  8082. /* Not connected */
  8083. mg_snprintf(NULL,
  8084. NULL, /* No truncation check for ebuf */
  8085. ebuf,
  8086. ebuf_len,
  8087. "connect(%s:%d): timeout",
  8088. host,
  8089. port);
  8090. closesocket(*sock);
  8091. *sock = INVALID_SOCKET;
  8092. return 0;
  8093. }
  8094. #if defined(_WIN32)
  8095. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8096. #else
  8097. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8098. #endif
  8099. if ((ret == 0) && (sockerr == 0)) {
  8100. conn_ret = 0;
  8101. }
  8102. }
  8103. if (conn_ret != 0) {
  8104. /* Not connected */
  8105. mg_snprintf(NULL,
  8106. NULL, /* No truncation check for ebuf */
  8107. ebuf,
  8108. ebuf_len,
  8109. "connect(%s:%d): error %s",
  8110. host,
  8111. port,
  8112. strerror(sockerr));
  8113. closesocket(*sock);
  8114. *sock = INVALID_SOCKET;
  8115. return 0;
  8116. }
  8117. return 1;
  8118. }
  8119. int
  8120. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8121. {
  8122. static const char *dont_escape = "._-$,;~()";
  8123. static const char *hex = "0123456789abcdef";
  8124. char *pos = dst;
  8125. const char *end = dst + dst_len - 1;
  8126. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8127. if (isalnum((unsigned char)*src)
  8128. || (strchr(dont_escape, *src) != NULL)) {
  8129. *pos = *src;
  8130. } else if (pos + 2 < end) {
  8131. pos[0] = '%';
  8132. pos[1] = hex[(unsigned char)*src >> 4];
  8133. pos[2] = hex[(unsigned char)*src & 0xf];
  8134. pos += 2;
  8135. } else {
  8136. break;
  8137. }
  8138. }
  8139. *pos = '\0';
  8140. return (*src == '\0') ? (int)(pos - dst) : -1;
  8141. }
  8142. /* Return 0 on success, non-zero if an error occurs. */
  8143. static int
  8144. print_dir_entry(struct de *de)
  8145. {
  8146. size_t namesize, escsize, i;
  8147. char *href, *esc, *p;
  8148. char size[64], mod[64];
  8149. #if defined(REENTRANT_TIME)
  8150. struct tm _tm;
  8151. struct tm *tm = &_tm;
  8152. #else
  8153. struct tm *tm;
  8154. #endif
  8155. /* Estimate worst case size for encoding and escaping */
  8156. namesize = strlen(de->file_name) + 1;
  8157. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8158. href = (char *)mg_malloc(namesize * 3 + escsize);
  8159. if (href == NULL) {
  8160. return -1;
  8161. }
  8162. mg_url_encode(de->file_name, href, namesize * 3);
  8163. esc = NULL;
  8164. if (escsize > 0) {
  8165. /* HTML escaping needed */
  8166. esc = href + namesize * 3;
  8167. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8168. mg_strlcpy(p, de->file_name + i, 2);
  8169. if (*p == '&') {
  8170. strcpy(p, "&amp;");
  8171. } else if (*p == '<') {
  8172. strcpy(p, "&lt;");
  8173. } else if (*p == '>') {
  8174. strcpy(p, "&gt;");
  8175. }
  8176. }
  8177. }
  8178. if (de->file.is_directory) {
  8179. mg_snprintf(de->conn,
  8180. NULL, /* Buffer is big enough */
  8181. size,
  8182. sizeof(size),
  8183. "%s",
  8184. "[DIRECTORY]");
  8185. } else {
  8186. /* We use (signed) cast below because MSVC 6 compiler cannot
  8187. * convert unsigned __int64 to double. Sigh. */
  8188. if (de->file.size < 1024) {
  8189. mg_snprintf(de->conn,
  8190. NULL, /* Buffer is big enough */
  8191. size,
  8192. sizeof(size),
  8193. "%d",
  8194. (int)de->file.size);
  8195. } else if (de->file.size < 0x100000) {
  8196. mg_snprintf(de->conn,
  8197. NULL, /* Buffer is big enough */
  8198. size,
  8199. sizeof(size),
  8200. "%.1fk",
  8201. (double)de->file.size / 1024.0);
  8202. } else if (de->file.size < 0x40000000) {
  8203. mg_snprintf(de->conn,
  8204. NULL, /* Buffer is big enough */
  8205. size,
  8206. sizeof(size),
  8207. "%.1fM",
  8208. (double)de->file.size / 1048576);
  8209. } else {
  8210. mg_snprintf(de->conn,
  8211. NULL, /* Buffer is big enough */
  8212. size,
  8213. sizeof(size),
  8214. "%.1fG",
  8215. (double)de->file.size / 1073741824);
  8216. }
  8217. }
  8218. /* Note: mg_snprintf will not cause a buffer overflow above.
  8219. * So, string truncation checks are not required here. */
  8220. #if defined(REENTRANT_TIME)
  8221. localtime_r(&de->file.last_modified, tm);
  8222. #else
  8223. tm = localtime(&de->file.last_modified);
  8224. #endif
  8225. if (tm != NULL) {
  8226. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8227. } else {
  8228. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8229. mod[sizeof(mod) - 1] = '\0';
  8230. }
  8231. mg_printf(de->conn,
  8232. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8233. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8234. href,
  8235. de->file.is_directory ? "/" : "",
  8236. esc ? esc : de->file_name,
  8237. de->file.is_directory ? "/" : "",
  8238. mod,
  8239. size);
  8240. mg_free(href);
  8241. return 0;
  8242. }
  8243. /* This function is called from send_directory() and used for
  8244. * sorting directory entries by size, or name, or modification time.
  8245. * On windows, __cdecl specification is needed in case if project is built
  8246. * with __stdcall convention. qsort always requires __cdels callback. */
  8247. static int WINCDECL
  8248. compare_dir_entries(const void *p1, const void *p2)
  8249. {
  8250. if (p1 && p2) {
  8251. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8252. const char *query_string = a->conn->request_info.query_string;
  8253. int cmp_result = 0;
  8254. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8255. query_string = "n";
  8256. }
  8257. if (a->file.is_directory && !b->file.is_directory) {
  8258. return -1; /* Always put directories on top */
  8259. } else if (!a->file.is_directory && b->file.is_directory) {
  8260. return 1; /* Always put directories on top */
  8261. } else if (*query_string == 'n') {
  8262. cmp_result = strcmp(a->file_name, b->file_name);
  8263. } else if (*query_string == 's') {
  8264. cmp_result = (a->file.size == b->file.size)
  8265. ? 0
  8266. : ((a->file.size > b->file.size) ? 1 : -1);
  8267. } else if (*query_string == 'd') {
  8268. cmp_result =
  8269. (a->file.last_modified == b->file.last_modified)
  8270. ? 0
  8271. : ((a->file.last_modified > b->file.last_modified) ? 1
  8272. : -1);
  8273. }
  8274. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8275. }
  8276. return 0;
  8277. }
  8278. static int
  8279. must_hide_file(struct mg_connection *conn, const char *path)
  8280. {
  8281. if (conn && conn->dom_ctx) {
  8282. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8283. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8284. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8285. || ((pattern != NULL)
  8286. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8287. }
  8288. return 0;
  8289. }
  8290. #if !defined(NO_FILESYSTEMS)
  8291. static int
  8292. scan_directory(struct mg_connection *conn,
  8293. const char *dir,
  8294. void *data,
  8295. int (*cb)(struct de *, void *))
  8296. {
  8297. char path[PATH_MAX];
  8298. struct dirent *dp;
  8299. DIR *dirp;
  8300. struct de de;
  8301. int truncated;
  8302. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8303. return 0;
  8304. } else {
  8305. de.conn = conn;
  8306. while ((dp = mg_readdir(dirp)) != NULL) {
  8307. /* Do not show current dir and hidden files */
  8308. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8309. || must_hide_file(conn, dp->d_name)) {
  8310. continue;
  8311. }
  8312. mg_snprintf(
  8313. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8314. /* If we don't memset stat structure to zero, mtime will have
  8315. * garbage and strftime() will segfault later on in
  8316. * print_dir_entry(). memset is required only if mg_stat()
  8317. * fails. For more details, see
  8318. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8319. memset(&de.file, 0, sizeof(de.file));
  8320. if (truncated) {
  8321. /* If the path is not complete, skip processing. */
  8322. continue;
  8323. }
  8324. if (!mg_stat(conn, path, &de.file)) {
  8325. mg_cry_internal(conn,
  8326. "%s: mg_stat(%s) failed: %s",
  8327. __func__,
  8328. path,
  8329. strerror(ERRNO));
  8330. }
  8331. de.file_name = dp->d_name;
  8332. cb(&de, data);
  8333. }
  8334. (void)mg_closedir(dirp);
  8335. }
  8336. return 1;
  8337. }
  8338. #endif /* NO_FILESYSTEMS */
  8339. #if !defined(NO_FILES)
  8340. static int
  8341. remove_directory(struct mg_connection *conn, const char *dir)
  8342. {
  8343. char path[PATH_MAX];
  8344. struct dirent *dp;
  8345. DIR *dirp;
  8346. struct de de;
  8347. int truncated;
  8348. int ok = 1;
  8349. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8350. return 0;
  8351. } else {
  8352. de.conn = conn;
  8353. while ((dp = mg_readdir(dirp)) != NULL) {
  8354. /* Do not show current dir (but show hidden files as they will
  8355. * also be removed) */
  8356. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8357. continue;
  8358. }
  8359. mg_snprintf(
  8360. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8361. /* If we don't memset stat structure to zero, mtime will have
  8362. * garbage and strftime() will segfault later on in
  8363. * print_dir_entry(). memset is required only if mg_stat()
  8364. * fails. For more details, see
  8365. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8366. memset(&de.file, 0, sizeof(de.file));
  8367. if (truncated) {
  8368. /* Do not delete anything shorter */
  8369. ok = 0;
  8370. continue;
  8371. }
  8372. if (!mg_stat(conn, path, &de.file)) {
  8373. mg_cry_internal(conn,
  8374. "%s: mg_stat(%s) failed: %s",
  8375. __func__,
  8376. path,
  8377. strerror(ERRNO));
  8378. ok = 0;
  8379. }
  8380. if (de.file.is_directory) {
  8381. if (remove_directory(conn, path) == 0) {
  8382. ok = 0;
  8383. }
  8384. } else {
  8385. /* This will fail file is the file is in memory */
  8386. if (mg_remove(conn, path) == 0) {
  8387. ok = 0;
  8388. }
  8389. }
  8390. }
  8391. (void)mg_closedir(dirp);
  8392. IGNORE_UNUSED_RESULT(rmdir(dir));
  8393. }
  8394. return ok;
  8395. }
  8396. #endif
  8397. struct dir_scan_data {
  8398. struct de *entries;
  8399. unsigned int num_entries;
  8400. unsigned int arr_size;
  8401. };
  8402. /* Behaves like realloc(), but frees original pointer on failure */
  8403. static void *
  8404. realloc2(void *ptr, size_t size)
  8405. {
  8406. void *new_ptr = mg_realloc(ptr, size);
  8407. if ((new_ptr == NULL) && (size > 0)) {
  8408. mg_free(ptr);
  8409. }
  8410. return new_ptr;
  8411. }
  8412. #if !defined(NO_FILESYSTEMS)
  8413. static int
  8414. dir_scan_callback(struct de *de, void *data)
  8415. {
  8416. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8417. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8418. dsd->arr_size *= 2;
  8419. dsd->entries =
  8420. (struct de *)realloc2(dsd->entries,
  8421. dsd->arr_size * sizeof(dsd->entries[0]));
  8422. }
  8423. if (dsd->entries == NULL) {
  8424. /* TODO(lsm, low): propagate an error to the caller */
  8425. dsd->num_entries = 0;
  8426. } else {
  8427. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8428. dsd->entries[dsd->num_entries].file = de->file;
  8429. dsd->entries[dsd->num_entries].conn = de->conn;
  8430. dsd->num_entries++;
  8431. }
  8432. return 0;
  8433. }
  8434. static void
  8435. handle_directory_request(struct mg_connection *conn, const char *dir)
  8436. {
  8437. unsigned int i;
  8438. int sort_direction;
  8439. struct dir_scan_data data = {NULL, 0, 128};
  8440. char date[64], *esc, *p;
  8441. const char *title;
  8442. time_t curtime = time(NULL);
  8443. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8444. mg_send_http_error(conn,
  8445. 500,
  8446. "Error: Cannot open directory\nopendir(%s): %s",
  8447. dir,
  8448. strerror(ERRNO));
  8449. return;
  8450. }
  8451. gmt_time_string(date, sizeof(date), &curtime);
  8452. if (!conn) {
  8453. return;
  8454. }
  8455. esc = NULL;
  8456. title = conn->request_info.local_uri;
  8457. if (title[strcspn(title, "&<>")]) {
  8458. /* HTML escaping needed */
  8459. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8460. if (esc) {
  8461. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8462. mg_strlcpy(p, title + i, 2);
  8463. if (*p == '&') {
  8464. strcpy(p, "&amp;");
  8465. } else if (*p == '<') {
  8466. strcpy(p, "&lt;");
  8467. } else if (*p == '>') {
  8468. strcpy(p, "&gt;");
  8469. }
  8470. }
  8471. } else {
  8472. title = "";
  8473. }
  8474. }
  8475. sort_direction = ((conn->request_info.query_string != NULL)
  8476. && (conn->request_info.query_string[0] != '\0')
  8477. && (conn->request_info.query_string[1] == 'd'))
  8478. ? 'a'
  8479. : 'd';
  8480. conn->must_close = 1;
  8481. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8482. send_static_cache_header(conn);
  8483. send_additional_header(conn);
  8484. mg_printf(conn,
  8485. "Date: %s\r\n"
  8486. "Connection: close\r\n"
  8487. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8488. date);
  8489. mg_printf(conn,
  8490. "<html><head><title>Index of %s</title>"
  8491. "<style>th {text-align: left;}</style></head>"
  8492. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8493. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8494. "<th><a href=\"?d%c\">Modified</a></th>"
  8495. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8496. "<tr><td colspan=\"3\"><hr></td></tr>",
  8497. esc ? esc : title,
  8498. esc ? esc : title,
  8499. sort_direction,
  8500. sort_direction,
  8501. sort_direction);
  8502. mg_free(esc);
  8503. /* Print first entry - link to a parent directory */
  8504. mg_printf(conn,
  8505. "<tr><td><a href=\"%s\">%s</a></td>"
  8506. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8507. "..",
  8508. "Parent directory",
  8509. "-",
  8510. "-");
  8511. /* Sort and print directory entries */
  8512. if (data.entries != NULL) {
  8513. qsort(data.entries,
  8514. (size_t)data.num_entries,
  8515. sizeof(data.entries[0]),
  8516. compare_dir_entries);
  8517. for (i = 0; i < data.num_entries; i++) {
  8518. print_dir_entry(&data.entries[i]);
  8519. mg_free(data.entries[i].file_name);
  8520. }
  8521. mg_free(data.entries);
  8522. }
  8523. mg_printf(conn, "%s", "</table></pre></body></html>");
  8524. conn->status_code = 200;
  8525. }
  8526. #endif /* NO_FILESYSTEMS */
  8527. /* Send len bytes from the opened file to the client. */
  8528. static void
  8529. send_file_data(struct mg_connection *conn,
  8530. struct mg_file *filep,
  8531. int64_t offset,
  8532. int64_t len)
  8533. {
  8534. char buf[MG_BUF_LEN];
  8535. int to_read, num_read, num_written;
  8536. int64_t size;
  8537. if (!filep || !conn) {
  8538. return;
  8539. }
  8540. /* Sanity check the offset */
  8541. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8542. : (int64_t)(filep->stat.size);
  8543. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8544. #if defined(MG_USE_OPEN_FILE)
  8545. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8546. /* file stored in memory */
  8547. if (len > size - offset) {
  8548. len = size - offset;
  8549. }
  8550. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8551. } else /* else block below */
  8552. #endif
  8553. if (len > 0 && filep->access.fp != NULL) {
  8554. /* file stored on disk */
  8555. #if defined(__linux__)
  8556. /* sendfile is only available for Linux */
  8557. if ((conn->ssl == 0) && (conn->throttle == 0)
  8558. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8559. "yes"))) {
  8560. off_t sf_offs = (off_t)offset;
  8561. ssize_t sf_sent;
  8562. int sf_file = fileno(filep->access.fp);
  8563. int loop_cnt = 0;
  8564. do {
  8565. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8566. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8567. size_t sf_tosend =
  8568. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8569. sf_sent =
  8570. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8571. if (sf_sent > 0) {
  8572. len -= sf_sent;
  8573. offset += sf_sent;
  8574. } else if (loop_cnt == 0) {
  8575. /* This file can not be sent using sendfile.
  8576. * This might be the case for pseudo-files in the
  8577. * /sys/ and /proc/ file system.
  8578. * Use the regular user mode copy code instead. */
  8579. break;
  8580. } else if (sf_sent == 0) {
  8581. /* No error, but 0 bytes sent. May be EOF? */
  8582. return;
  8583. }
  8584. loop_cnt++;
  8585. } while ((len > 0) && (sf_sent >= 0));
  8586. if (sf_sent > 0) {
  8587. return; /* OK */
  8588. }
  8589. /* sf_sent<0 means error, thus fall back to the classic way */
  8590. /* This is always the case, if sf_file is not a "normal" file,
  8591. * e.g., for sending data from the output of a CGI process. */
  8592. offset = (int64_t)sf_offs;
  8593. }
  8594. #endif
  8595. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8596. mg_cry_internal(conn,
  8597. "%s: fseeko() failed: %s",
  8598. __func__,
  8599. strerror(ERRNO));
  8600. mg_send_http_error(
  8601. conn,
  8602. 500,
  8603. "%s",
  8604. "Error: Unable to access file at requested position.");
  8605. } else {
  8606. while (len > 0) {
  8607. /* Calculate how much to read from the file in the buffer */
  8608. to_read = sizeof(buf);
  8609. if ((int64_t)to_read > len) {
  8610. to_read = (int)len;
  8611. }
  8612. /* Read from file, exit the loop on error */
  8613. if ((num_read =
  8614. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8615. <= 0) {
  8616. break;
  8617. }
  8618. /* Send read bytes to the client, exit the loop on error */
  8619. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8620. != num_read) {
  8621. break;
  8622. }
  8623. /* Both read and were successful, adjust counters */
  8624. len -= num_written;
  8625. }
  8626. }
  8627. }
  8628. }
  8629. static int
  8630. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8631. {
  8632. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8633. }
  8634. static void
  8635. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8636. {
  8637. if ((filestat != NULL) && (buf != NULL)) {
  8638. mg_snprintf(NULL,
  8639. NULL, /* All calls to construct_etag use 64 byte buffer */
  8640. buf,
  8641. buf_len,
  8642. "\"%lx.%" INT64_FMT "\"",
  8643. (unsigned long)filestat->last_modified,
  8644. filestat->size);
  8645. }
  8646. }
  8647. static void
  8648. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8649. {
  8650. if (filep != NULL && filep->fp != NULL) {
  8651. #if defined(_WIN32)
  8652. (void)conn; /* Unused. */
  8653. #else
  8654. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8655. mg_cry_internal(conn,
  8656. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8657. __func__,
  8658. strerror(ERRNO));
  8659. }
  8660. #endif
  8661. }
  8662. }
  8663. #if defined(USE_ZLIB)
  8664. #include "mod_zlib.inl"
  8665. #endif
  8666. #if !defined(NO_FILESYSTEMS)
  8667. static void
  8668. handle_static_file_request(struct mg_connection *conn,
  8669. const char *path,
  8670. struct mg_file *filep,
  8671. const char *mime_type,
  8672. const char *additional_headers)
  8673. {
  8674. char date[64], lm[64], etag[64];
  8675. char range[128]; /* large enough, so there will be no overflow */
  8676. const char *msg = "OK";
  8677. const char *range_hdr;
  8678. time_t curtime = time(NULL);
  8679. int64_t cl, r1, r2;
  8680. struct vec mime_vec;
  8681. int n, truncated;
  8682. char gz_path[PATH_MAX];
  8683. const char *encoding = "";
  8684. const char *origin_hdr;
  8685. const char *cors_orig_cfg;
  8686. const char *cors1, *cors2, *cors3;
  8687. int is_head_request;
  8688. #if defined(USE_ZLIB)
  8689. /* Compression is allowed, unless there is a reason not to use
  8690. * compression. If the file is already compressed, too small or a
  8691. * "range" request was made, on the fly compression is not possible. */
  8692. int allow_on_the_fly_compression = 1;
  8693. #endif
  8694. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8695. return;
  8696. }
  8697. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8698. if (mime_type == NULL) {
  8699. get_mime_type(conn, path, &mime_vec);
  8700. } else {
  8701. mime_vec.ptr = mime_type;
  8702. mime_vec.len = strlen(mime_type);
  8703. }
  8704. if (filep->stat.size > INT64_MAX) {
  8705. mg_send_http_error(conn,
  8706. 500,
  8707. "Error: File size is too large to send\n%" INT64_FMT,
  8708. filep->stat.size);
  8709. return;
  8710. }
  8711. cl = (int64_t)filep->stat.size;
  8712. conn->status_code = 200;
  8713. range[0] = '\0';
  8714. #if defined(USE_ZLIB)
  8715. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8716. * it's important to rewrite the filename after resolving
  8717. * the mime type from it, to preserve the actual file's type */
  8718. if (!conn->accept_gzip) {
  8719. allow_on_the_fly_compression = 0;
  8720. }
  8721. #endif
  8722. /* Check if there is a range header */
  8723. range_hdr = mg_get_header(conn, "Range");
  8724. /* For gzipped files, add *.gz */
  8725. if (filep->stat.is_gzipped) {
  8726. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8727. if (truncated) {
  8728. mg_send_http_error(conn,
  8729. 500,
  8730. "Error: Path of zipped file too long (%s)",
  8731. path);
  8732. return;
  8733. }
  8734. path = gz_path;
  8735. encoding = "Content-Encoding: gzip\r\n";
  8736. #if defined(USE_ZLIB)
  8737. /* File is already compressed. No "on the fly" compression. */
  8738. allow_on_the_fly_compression = 0;
  8739. #endif
  8740. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8741. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8742. struct mg_file_stat file_stat;
  8743. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8744. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8745. && !file_stat.is_directory) {
  8746. file_stat.is_gzipped = 1;
  8747. filep->stat = file_stat;
  8748. cl = (int64_t)filep->stat.size;
  8749. path = gz_path;
  8750. encoding = "Content-Encoding: gzip\r\n";
  8751. #if defined(USE_ZLIB)
  8752. /* File is already compressed. No "on the fly" compression. */
  8753. allow_on_the_fly_compression = 0;
  8754. #endif
  8755. }
  8756. }
  8757. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8758. mg_send_http_error(conn,
  8759. 500,
  8760. "Error: Cannot open file\nfopen(%s): %s",
  8761. path,
  8762. strerror(ERRNO));
  8763. return;
  8764. }
  8765. fclose_on_exec(&filep->access, conn);
  8766. /* If "Range" request was made: parse header, send only selected part
  8767. * of the file. */
  8768. r1 = r2 = 0;
  8769. if ((range_hdr != NULL)
  8770. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8771. && (r2 >= 0)) {
  8772. /* actually, range requests don't play well with a pre-gzipped
  8773. * file (since the range is specified in the uncompressed space) */
  8774. if (filep->stat.is_gzipped) {
  8775. mg_send_http_error(
  8776. conn,
  8777. 416, /* 416 = Range Not Satisfiable */
  8778. "%s",
  8779. "Error: Range requests in gzipped files are not supported");
  8780. (void)mg_fclose(
  8781. &filep->access); /* ignore error on read only file */
  8782. return;
  8783. }
  8784. conn->status_code = 206;
  8785. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8786. mg_snprintf(conn,
  8787. NULL, /* range buffer is big enough */
  8788. range,
  8789. sizeof(range),
  8790. "Content-Range: bytes "
  8791. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8792. r1,
  8793. r1 + cl - 1,
  8794. filep->stat.size);
  8795. msg = "Partial Content";
  8796. #if defined(USE_ZLIB)
  8797. /* Do not compress ranges. */
  8798. allow_on_the_fly_compression = 0;
  8799. #endif
  8800. }
  8801. /* Do not compress small files. Small files do not benefit from file
  8802. * compression, but there is still some overhead. */
  8803. #if defined(USE_ZLIB)
  8804. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8805. /* File is below the size limit. */
  8806. allow_on_the_fly_compression = 0;
  8807. }
  8808. #endif
  8809. /* Standard CORS header */
  8810. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8811. origin_hdr = mg_get_header(conn, "Origin");
  8812. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8813. /* Cross-origin resource sharing (CORS), see
  8814. * http://www.html5rocks.com/en/tutorials/cors/,
  8815. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8816. * -
  8817. * preflight is not supported for files. */
  8818. cors1 = "Access-Control-Allow-Origin: ";
  8819. cors2 = cors_orig_cfg;
  8820. cors3 = "\r\n";
  8821. } else {
  8822. cors1 = cors2 = cors3 = "";
  8823. }
  8824. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8825. * according to
  8826. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8827. gmt_time_string(date, sizeof(date), &curtime);
  8828. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8829. construct_etag(etag, sizeof(etag), &filep->stat);
  8830. /* Send header */
  8831. (void)mg_printf(conn,
  8832. "HTTP/1.1 %d %s\r\n"
  8833. "%s%s%s" /* CORS */
  8834. "Date: %s\r\n"
  8835. "Last-Modified: %s\r\n"
  8836. "Etag: %s\r\n"
  8837. "Content-Type: %.*s\r\n"
  8838. "Connection: %s\r\n",
  8839. conn->status_code,
  8840. msg,
  8841. cors1,
  8842. cors2,
  8843. cors3,
  8844. date,
  8845. lm,
  8846. etag,
  8847. (int)mime_vec.len,
  8848. mime_vec.ptr,
  8849. suggest_connection_header(conn));
  8850. send_static_cache_header(conn);
  8851. send_additional_header(conn);
  8852. #if defined(USE_ZLIB)
  8853. /* On the fly compression allowed */
  8854. if (allow_on_the_fly_compression) {
  8855. /* For on the fly compression, we don't know the content size in
  8856. * advance, so we have to use chunked encoding */
  8857. (void)mg_printf(conn,
  8858. "Content-Encoding: gzip\r\n"
  8859. "Transfer-Encoding: chunked\r\n");
  8860. } else
  8861. #endif
  8862. {
  8863. /* Without on-the-fly compression, we know the content-length
  8864. * and we can use ranges (with on-the-fly compression we cannot).
  8865. * So we send these response headers only in this case. */
  8866. (void)mg_printf(conn,
  8867. "Content-Length: %" INT64_FMT "\r\n"
  8868. "Accept-Ranges: bytes\r\n"
  8869. "%s" /* range */
  8870. "%s" /* encoding */,
  8871. cl,
  8872. range,
  8873. encoding);
  8874. }
  8875. /* The previous code must not add any header starting with X- to make
  8876. * sure no one of the additional_headers is included twice */
  8877. if (additional_headers != NULL) {
  8878. (void)mg_printf(conn,
  8879. "%.*s\r\n\r\n",
  8880. (int)strlen(additional_headers),
  8881. additional_headers);
  8882. } else {
  8883. (void)mg_printf(conn, "\r\n");
  8884. }
  8885. if (!is_head_request) {
  8886. #if defined(USE_ZLIB)
  8887. if (allow_on_the_fly_compression) {
  8888. /* Compress and send */
  8889. send_compressed_data(conn, filep);
  8890. } else
  8891. #endif
  8892. {
  8893. /* Send file directly */
  8894. send_file_data(conn, filep, r1, cl);
  8895. }
  8896. }
  8897. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8898. }
  8899. int
  8900. mg_send_file_body(struct mg_connection *conn, const char *path)
  8901. {
  8902. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8903. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8904. return -1;
  8905. }
  8906. fclose_on_exec(&file.access, conn);
  8907. send_file_data(conn, &file, 0, INT64_MAX);
  8908. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8909. return 0; /* >= 0 for OK */
  8910. }
  8911. #endif /* NO_FILESYSTEMS */
  8912. #if !defined(NO_CACHING)
  8913. /* Return True if we should reply 304 Not Modified. */
  8914. static int
  8915. is_not_modified(const struct mg_connection *conn,
  8916. const struct mg_file_stat *filestat)
  8917. {
  8918. char etag[64];
  8919. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8920. const char *inm = mg_get_header(conn, "If-None-Match");
  8921. construct_etag(etag, sizeof(etag), filestat);
  8922. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8923. || ((ims != NULL)
  8924. && (filestat->last_modified <= parse_date_string(ims)));
  8925. }
  8926. static void
  8927. handle_not_modified_static_file_request(struct mg_connection *conn,
  8928. struct mg_file *filep)
  8929. {
  8930. char date[64], lm[64], etag[64];
  8931. time_t curtime = time(NULL);
  8932. if ((conn == NULL) || (filep == NULL)) {
  8933. return;
  8934. }
  8935. conn->status_code = 304;
  8936. gmt_time_string(date, sizeof(date), &curtime);
  8937. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8938. construct_etag(etag, sizeof(etag), &filep->stat);
  8939. (void)mg_printf(conn,
  8940. "HTTP/1.1 %d %s\r\n"
  8941. "Date: %s\r\n",
  8942. conn->status_code,
  8943. mg_get_response_code_text(conn, conn->status_code),
  8944. date);
  8945. send_static_cache_header(conn);
  8946. send_additional_header(conn);
  8947. (void)mg_printf(conn,
  8948. "Last-Modified: %s\r\n"
  8949. "Etag: %s\r\n"
  8950. "Connection: %s\r\n"
  8951. "\r\n",
  8952. lm,
  8953. etag,
  8954. suggest_connection_header(conn));
  8955. }
  8956. #endif
  8957. #if !defined(NO_FILESYSTEMS)
  8958. void
  8959. mg_send_file(struct mg_connection *conn, const char *path)
  8960. {
  8961. mg_send_mime_file2(conn, path, NULL, NULL);
  8962. }
  8963. void
  8964. mg_send_mime_file(struct mg_connection *conn,
  8965. const char *path,
  8966. const char *mime_type)
  8967. {
  8968. mg_send_mime_file2(conn, path, mime_type, NULL);
  8969. }
  8970. void
  8971. mg_send_mime_file2(struct mg_connection *conn,
  8972. const char *path,
  8973. const char *mime_type,
  8974. const char *additional_headers)
  8975. {
  8976. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8977. if (!conn) {
  8978. /* No conn */
  8979. return;
  8980. }
  8981. if (mg_stat(conn, path, &file.stat)) {
  8982. #if !defined(NO_CACHING)
  8983. if (is_not_modified(conn, &file.stat)) {
  8984. /* Send 304 "Not Modified" - this must not send any body data */
  8985. handle_not_modified_static_file_request(conn, &file);
  8986. } else
  8987. #endif /* NO_CACHING */
  8988. if (file.stat.is_directory) {
  8989. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8990. "yes")) {
  8991. handle_directory_request(conn, path);
  8992. } else {
  8993. mg_send_http_error(conn,
  8994. 403,
  8995. "%s",
  8996. "Error: Directory listing denied");
  8997. }
  8998. } else {
  8999. handle_static_file_request(
  9000. conn, path, &file, mime_type, additional_headers);
  9001. }
  9002. } else {
  9003. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9004. }
  9005. }
  9006. /* For a given PUT path, create all intermediate subdirectories.
  9007. * Return 0 if the path itself is a directory.
  9008. * Return 1 if the path leads to a file.
  9009. * Return -1 for if the path is too long.
  9010. * Return -2 if path can not be created.
  9011. */
  9012. static int
  9013. put_dir(struct mg_connection *conn, const char *path)
  9014. {
  9015. char buf[PATH_MAX];
  9016. const char *s, *p;
  9017. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9018. size_t len;
  9019. int res = 1;
  9020. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9021. len = (size_t)(p - path);
  9022. if (len >= sizeof(buf)) {
  9023. /* path too long */
  9024. res = -1;
  9025. break;
  9026. }
  9027. memcpy(buf, path, len);
  9028. buf[len] = '\0';
  9029. /* Try to create intermediate directory */
  9030. DEBUG_TRACE("mkdir(%s)", buf);
  9031. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9032. /* path does not exixt and can not be created */
  9033. res = -2;
  9034. break;
  9035. }
  9036. /* Is path itself a directory? */
  9037. if (p[1] == '\0') {
  9038. res = 0;
  9039. }
  9040. }
  9041. return res;
  9042. }
  9043. static void
  9044. remove_bad_file(const struct mg_connection *conn, const char *path)
  9045. {
  9046. int r = mg_remove(conn, path);
  9047. if (r != 0) {
  9048. mg_cry_internal(conn,
  9049. "%s: Cannot remove invalid file %s",
  9050. __func__,
  9051. path);
  9052. }
  9053. }
  9054. long long
  9055. mg_store_body(struct mg_connection *conn, const char *path)
  9056. {
  9057. char buf[MG_BUF_LEN];
  9058. long long len = 0;
  9059. int ret, n;
  9060. struct mg_file fi;
  9061. if (conn->consumed_content != 0) {
  9062. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9063. return -11;
  9064. }
  9065. ret = put_dir(conn, path);
  9066. if (ret < 0) {
  9067. /* -1 for path too long,
  9068. * -2 for path can not be created. */
  9069. return ret;
  9070. }
  9071. if (ret != 1) {
  9072. /* Return 0 means, path itself is a directory. */
  9073. return 0;
  9074. }
  9075. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9076. return -12;
  9077. }
  9078. ret = mg_read(conn, buf, sizeof(buf));
  9079. while (ret > 0) {
  9080. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9081. if (n != ret) {
  9082. (void)mg_fclose(
  9083. &fi.access); /* File is bad and will be removed anyway. */
  9084. remove_bad_file(conn, path);
  9085. return -13;
  9086. }
  9087. len += ret;
  9088. ret = mg_read(conn, buf, sizeof(buf));
  9089. }
  9090. /* File is open for writing. If fclose fails, there was probably an
  9091. * error flushing the buffer to disk, so the file on disk might be
  9092. * broken. Delete it and return an error to the caller. */
  9093. if (mg_fclose(&fi.access) != 0) {
  9094. remove_bad_file(conn, path);
  9095. return -14;
  9096. }
  9097. return len;
  9098. }
  9099. #endif /* NO_FILESYSTEMS */
  9100. /* Parse a buffer:
  9101. * Forward the string pointer till the end of a word, then
  9102. * terminate it and forward till the begin of the next word.
  9103. */
  9104. static int
  9105. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9106. {
  9107. /* Forward until a space is found - use isgraph here */
  9108. /* See http://www.cplusplus.com/reference/cctype/ */
  9109. while (isgraph((unsigned char)**ppw)) {
  9110. (*ppw)++;
  9111. }
  9112. /* Check end of word */
  9113. if (eol) {
  9114. /* must be a end of line */
  9115. if ((**ppw != '\r') && (**ppw != '\n')) {
  9116. return -1;
  9117. }
  9118. } else {
  9119. /* must be a end of a word, but not a line */
  9120. if (**ppw != ' ') {
  9121. return -1;
  9122. }
  9123. }
  9124. /* Terminate and forward to the next word */
  9125. do {
  9126. **ppw = 0;
  9127. (*ppw)++;
  9128. } while (isspace((unsigned char)**ppw));
  9129. /* Check after term */
  9130. if (!eol) {
  9131. /* if it's not the end of line, there must be a next word */
  9132. if (!isgraph((unsigned char)**ppw)) {
  9133. return -1;
  9134. }
  9135. }
  9136. /* ok */
  9137. return 1;
  9138. }
  9139. /* Parse HTTP headers from the given buffer, advance buf pointer
  9140. * to the point where parsing stopped.
  9141. * All parameters must be valid pointers (not NULL).
  9142. * Return <0 on error. */
  9143. static int
  9144. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9145. {
  9146. int i;
  9147. int num_headers = 0;
  9148. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9149. char *dp = *buf;
  9150. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9151. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9152. dp++;
  9153. }
  9154. if (dp == *buf) {
  9155. /* End of headers reached. */
  9156. break;
  9157. }
  9158. if (*dp != ':') {
  9159. /* This is not a valid field. */
  9160. return -1;
  9161. }
  9162. /* End of header key (*dp == ':') */
  9163. /* Truncate here and set the key name */
  9164. *dp = 0;
  9165. hdr[i].name = *buf;
  9166. /* Skip all spaces */
  9167. do {
  9168. dp++;
  9169. } while ((*dp == ' ') || (*dp == '\t'));
  9170. /* The rest of the line is the value */
  9171. hdr[i].value = dp;
  9172. /* Find end of line */
  9173. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9174. dp++;
  9175. };
  9176. /* eliminate \r */
  9177. if (*dp == '\r') {
  9178. *dp = 0;
  9179. dp++;
  9180. if (*dp != '\n') {
  9181. /* This is not a valid line. */
  9182. return -1;
  9183. }
  9184. }
  9185. /* here *dp is either 0 or '\n' */
  9186. /* in any case, we have a new header */
  9187. num_headers = i + 1;
  9188. if (*dp) {
  9189. *dp = 0;
  9190. dp++;
  9191. *buf = dp;
  9192. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9193. /* This is the end of the header */
  9194. break;
  9195. }
  9196. } else {
  9197. *buf = dp;
  9198. break;
  9199. }
  9200. }
  9201. return num_headers;
  9202. }
  9203. struct mg_http_method_info {
  9204. const char *name;
  9205. int request_has_body;
  9206. int response_has_body;
  9207. int is_safe;
  9208. int is_idempotent;
  9209. int is_cacheable;
  9210. };
  9211. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9212. static const struct mg_http_method_info http_methods[] = {
  9213. /* HTTP (RFC 2616) */
  9214. {"GET", 0, 1, 1, 1, 1},
  9215. {"POST", 1, 1, 0, 0, 0},
  9216. {"PUT", 1, 0, 0, 1, 0},
  9217. {"DELETE", 0, 0, 0, 1, 0},
  9218. {"HEAD", 0, 0, 1, 1, 1},
  9219. {"OPTIONS", 0, 0, 1, 1, 0},
  9220. {"CONNECT", 1, 1, 0, 0, 0},
  9221. /* TRACE method (RFC 2616) is not supported for security reasons */
  9222. /* PATCH method (RFC 5789) */
  9223. {"PATCH", 1, 0, 0, 0, 0},
  9224. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9225. /* WEBDAV (RFC 2518) */
  9226. {"PROPFIND", 0, 1, 1, 1, 0},
  9227. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9228. * Some PROPFIND results MAY be cached, with care,
  9229. * as there is no cache validation mechanism for
  9230. * most properties. This method is both safe and
  9231. * idempotent (see Section 9.1 of [RFC2616]). */
  9232. {"MKCOL", 0, 0, 0, 1, 0},
  9233. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9234. * When MKCOL is invoked without a request body,
  9235. * the newly created collection SHOULD have no
  9236. * members. A MKCOL request message may contain
  9237. * a message body. The precise behavior of a MKCOL
  9238. * request when the body is present is undefined,
  9239. * ... ==> We do not support MKCOL with body data.
  9240. * This method is idempotent, but not safe (see
  9241. * Section 9.1 of [RFC2616]). Responses to this
  9242. * method MUST NOT be cached. */
  9243. /* Unsupported WEBDAV Methods: */
  9244. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9245. /* + 11 methods from RFC 3253 */
  9246. /* ORDERPATCH (RFC 3648) */
  9247. /* ACL (RFC 3744) */
  9248. /* SEARCH (RFC 5323) */
  9249. /* + MicroSoft extensions
  9250. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9251. /* REPORT method (RFC 3253) */
  9252. {"REPORT", 1, 1, 1, 1, 1},
  9253. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9254. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9255. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9256. * to be useful for REST in case a "GET request with body" is
  9257. * required. */
  9258. {NULL, 0, 0, 0, 0, 0}
  9259. /* end of list */
  9260. };
  9261. static const struct mg_http_method_info *
  9262. get_http_method_info(const char *method)
  9263. {
  9264. /* Check if the method is known to the server. The list of all known
  9265. * HTTP methods can be found here at
  9266. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9267. */
  9268. const struct mg_http_method_info *m = http_methods;
  9269. while (m->name) {
  9270. if (!strcmp(m->name, method)) {
  9271. return m;
  9272. }
  9273. m++;
  9274. }
  9275. return NULL;
  9276. }
  9277. static int
  9278. is_valid_http_method(const char *method)
  9279. {
  9280. return (get_http_method_info(method) != NULL);
  9281. }
  9282. /* Parse HTTP request, fill in mg_request_info structure.
  9283. * This function modifies the buffer by NUL-terminating
  9284. * HTTP request components, header names and header values.
  9285. * Parameters:
  9286. * buf (in/out): pointer to the HTTP header to parse and split
  9287. * len (in): length of HTTP header buffer
  9288. * re (out): parsed header as mg_request_info
  9289. * buf and ri must be valid pointers (not NULL), len>0.
  9290. * Returns <0 on error. */
  9291. static int
  9292. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9293. {
  9294. int request_length;
  9295. int init_skip = 0;
  9296. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9297. * remote_port */
  9298. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9299. NULL;
  9300. ri->num_headers = 0;
  9301. /* RFC says that all initial whitespaces should be ingored */
  9302. /* This included all leading \r and \n (isspace) */
  9303. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9304. while ((len > 0) && isspace((unsigned char)*buf)) {
  9305. buf++;
  9306. len--;
  9307. init_skip++;
  9308. }
  9309. if (len == 0) {
  9310. /* Incomplete request */
  9311. return 0;
  9312. }
  9313. /* Control characters are not allowed, including zero */
  9314. if (iscntrl((unsigned char)*buf)) {
  9315. return -1;
  9316. }
  9317. /* Find end of HTTP header */
  9318. request_length = get_http_header_len(buf, len);
  9319. if (request_length <= 0) {
  9320. return request_length;
  9321. }
  9322. buf[request_length - 1] = '\0';
  9323. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9324. return -1;
  9325. }
  9326. /* The first word has to be the HTTP method */
  9327. ri->request_method = buf;
  9328. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9329. return -1;
  9330. }
  9331. /* Check for a valid http method */
  9332. if (!is_valid_http_method(ri->request_method)) {
  9333. return -1;
  9334. }
  9335. /* The second word is the URI */
  9336. ri->request_uri = buf;
  9337. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9338. return -1;
  9339. }
  9340. /* Next would be the HTTP version */
  9341. ri->http_version = buf;
  9342. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9343. return -1;
  9344. }
  9345. /* Check for a valid HTTP version key */
  9346. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9347. /* Invalid request */
  9348. return -1;
  9349. }
  9350. ri->http_version += 5;
  9351. /* Parse all HTTP headers */
  9352. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9353. if (ri->num_headers < 0) {
  9354. /* Error while parsing headers */
  9355. return -1;
  9356. }
  9357. return request_length + init_skip;
  9358. }
  9359. static int
  9360. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9361. {
  9362. int response_length;
  9363. int init_skip = 0;
  9364. char *tmp, *tmp2;
  9365. long l;
  9366. /* Initialize elements. */
  9367. ri->http_version = ri->status_text = NULL;
  9368. ri->num_headers = ri->status_code = 0;
  9369. /* RFC says that all initial whitespaces should be ingored */
  9370. /* This included all leading \r and \n (isspace) */
  9371. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9372. while ((len > 0) && isspace((unsigned char)*buf)) {
  9373. buf++;
  9374. len--;
  9375. init_skip++;
  9376. }
  9377. if (len == 0) {
  9378. /* Incomplete request */
  9379. return 0;
  9380. }
  9381. /* Control characters are not allowed, including zero */
  9382. if (iscntrl((unsigned char)*buf)) {
  9383. return -1;
  9384. }
  9385. /* Find end of HTTP header */
  9386. response_length = get_http_header_len(buf, len);
  9387. if (response_length <= 0) {
  9388. return response_length;
  9389. }
  9390. buf[response_length - 1] = '\0';
  9391. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9392. return -1;
  9393. }
  9394. /* The first word is the HTTP version */
  9395. /* Check for a valid HTTP version key */
  9396. if (strncmp(buf, "HTTP/", 5) != 0) {
  9397. /* Invalid request */
  9398. return -1;
  9399. }
  9400. buf += 5;
  9401. if (!isgraph((unsigned char)buf[0])) {
  9402. /* Invalid request */
  9403. return -1;
  9404. }
  9405. ri->http_version = buf;
  9406. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9407. return -1;
  9408. }
  9409. /* The second word is the status as a number */
  9410. tmp = buf;
  9411. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9412. return -1;
  9413. }
  9414. l = strtol(tmp, &tmp2, 10);
  9415. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9416. /* Everything else but a 3 digit code is invalid */
  9417. return -1;
  9418. }
  9419. ri->status_code = (int)l;
  9420. /* The rest of the line is the status text */
  9421. ri->status_text = buf;
  9422. /* Find end of status text */
  9423. /* isgraph or isspace = isprint */
  9424. while (isprint((unsigned char)*buf)) {
  9425. buf++;
  9426. }
  9427. if ((*buf != '\r') && (*buf != '\n')) {
  9428. return -1;
  9429. }
  9430. /* Terminate string and forward buf to next line */
  9431. do {
  9432. *buf = 0;
  9433. buf++;
  9434. } while (isspace((unsigned char)*buf));
  9435. /* Parse all HTTP headers */
  9436. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9437. if (ri->num_headers < 0) {
  9438. /* Error while parsing headers */
  9439. return -1;
  9440. }
  9441. return response_length + init_skip;
  9442. }
  9443. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9444. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9445. * buffer (which marks the end of HTTP request). Buffer buf may already
  9446. * have some data. The length of the data is stored in nread.
  9447. * Upon every read operation, increase nread by the number of bytes read. */
  9448. static int
  9449. read_message(FILE *fp,
  9450. struct mg_connection *conn,
  9451. char *buf,
  9452. int bufsiz,
  9453. int *nread)
  9454. {
  9455. int request_len, n = 0;
  9456. struct timespec last_action_time;
  9457. double request_timeout;
  9458. if (!conn) {
  9459. return 0;
  9460. }
  9461. memset(&last_action_time, 0, sizeof(last_action_time));
  9462. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9463. /* value of request_timeout is in seconds, config in milliseconds */
  9464. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9465. } else {
  9466. request_timeout = -1.0;
  9467. }
  9468. if (conn->handled_requests > 0) {
  9469. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9470. request_timeout =
  9471. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9472. }
  9473. }
  9474. request_len = get_http_header_len(buf, *nread);
  9475. while (request_len == 0) {
  9476. /* Full request not yet received */
  9477. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9478. /* Server is to be stopped. */
  9479. return -1;
  9480. }
  9481. if (*nread >= bufsiz) {
  9482. /* Request too long */
  9483. return -2;
  9484. }
  9485. n = pull_inner(
  9486. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9487. if (n == -2) {
  9488. /* Receive error */
  9489. return -1;
  9490. }
  9491. /* update clock after every read request */
  9492. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9493. if (n > 0) {
  9494. *nread += n;
  9495. request_len = get_http_header_len(buf, *nread);
  9496. }
  9497. if ((request_len == 0) && (request_timeout >= 0)) {
  9498. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9499. > request_timeout) {
  9500. /* Timeout */
  9501. return -1;
  9502. }
  9503. }
  9504. }
  9505. return request_len;
  9506. }
  9507. #if !defined(NO_CGI) || !defined(NO_FILES)
  9508. static int
  9509. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9510. {
  9511. const char *expect;
  9512. char buf[MG_BUF_LEN];
  9513. int success = 0;
  9514. if (!conn) {
  9515. return 0;
  9516. }
  9517. expect = mg_get_header(conn, "Expect");
  9518. DEBUG_ASSERT(fp != NULL);
  9519. if (!fp) {
  9520. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9521. return 0;
  9522. }
  9523. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9524. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9525. */
  9526. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9527. } else {
  9528. if (expect != NULL) {
  9529. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9530. conn->status_code = 100;
  9531. } else {
  9532. conn->status_code = 200;
  9533. }
  9534. DEBUG_ASSERT(conn->consumed_content == 0);
  9535. if (conn->consumed_content != 0) {
  9536. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9537. return 0;
  9538. }
  9539. for (;;) {
  9540. int nread = mg_read(conn, buf, sizeof(buf));
  9541. if (nread <= 0) {
  9542. success = (nread == 0);
  9543. break;
  9544. }
  9545. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9546. break;
  9547. }
  9548. }
  9549. /* Each error code path in this function must send an error */
  9550. if (!success) {
  9551. /* NOTE: Maybe some data has already been sent. */
  9552. /* TODO (low): If some data has been sent, a correct error
  9553. * reply can no longer be sent, so just close the connection */
  9554. mg_send_http_error(conn, 500, "%s", "");
  9555. }
  9556. }
  9557. return success;
  9558. }
  9559. #endif
  9560. #if defined(USE_TIMERS)
  9561. #define TIMER_API static
  9562. #include "timer.inl"
  9563. #endif /* USE_TIMERS */
  9564. #if !defined(NO_CGI)
  9565. /* This structure helps to create an environment for the spawned CGI
  9566. * program.
  9567. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9568. * last element must be NULL.
  9569. * However, on Windows there is a requirement that all these
  9570. * VARIABLE=VALUE\0
  9571. * strings must reside in a contiguous buffer. The end of the buffer is
  9572. * marked by two '\0' characters.
  9573. * We satisfy both worlds: we create an envp array (which is vars), all
  9574. * entries are actually pointers inside buf. */
  9575. struct cgi_environment {
  9576. struct mg_connection *conn;
  9577. /* Data block */
  9578. char *buf; /* Environment buffer */
  9579. size_t buflen; /* Space available in buf */
  9580. size_t bufused; /* Space taken in buf */
  9581. /* Index block */
  9582. char **var; /* char **envp */
  9583. size_t varlen; /* Number of variables available in var */
  9584. size_t varused; /* Number of variables stored in var */
  9585. };
  9586. static void addenv(struct cgi_environment *env,
  9587. PRINTF_FORMAT_STRING(const char *fmt),
  9588. ...) PRINTF_ARGS(2, 3);
  9589. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9590. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9591. static void
  9592. addenv(struct cgi_environment *env, const char *fmt, ...)
  9593. {
  9594. size_t i, n, space;
  9595. int truncated = 0;
  9596. char *added;
  9597. va_list ap;
  9598. if ((env->varlen - env->varused) < 2) {
  9599. mg_cry_internal(env->conn,
  9600. "%s: Cannot register CGI variable [%s]",
  9601. __func__,
  9602. fmt);
  9603. return;
  9604. }
  9605. /* Calculate how much space is left in the buffer */
  9606. space = (env->buflen - env->bufused);
  9607. do {
  9608. /* Space for "\0\0" is always needed. */
  9609. if (space <= 2) {
  9610. /* Allocate new buffer */
  9611. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9612. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9613. if (!added) {
  9614. /* Out of memory */
  9615. mg_cry_internal(
  9616. env->conn,
  9617. "%s: Cannot allocate memory for CGI variable [%s]",
  9618. __func__,
  9619. fmt);
  9620. return;
  9621. }
  9622. /* Retarget pointers */
  9623. env->buf = added;
  9624. env->buflen = n;
  9625. for (i = 0, n = 0; i < env->varused; i++) {
  9626. env->var[i] = added + n;
  9627. n += strlen(added + n) + 1;
  9628. }
  9629. space = (env->buflen - env->bufused);
  9630. }
  9631. /* Make a pointer to the free space int the buffer */
  9632. added = env->buf + env->bufused;
  9633. /* Copy VARIABLE=VALUE\0 string into the free space */
  9634. va_start(ap, fmt);
  9635. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9636. va_end(ap);
  9637. /* Do not add truncated strings to the environment */
  9638. if (truncated) {
  9639. /* Reallocate the buffer */
  9640. space = 0;
  9641. }
  9642. } while (truncated);
  9643. /* Calculate number of bytes added to the environment */
  9644. n = strlen(added) + 1;
  9645. env->bufused += n;
  9646. /* Append a pointer to the added string into the envp array */
  9647. env->var[env->varused] = added;
  9648. env->varused++;
  9649. }
  9650. /* Return 0 on success, non-zero if an error occurs. */
  9651. static int
  9652. prepare_cgi_environment(struct mg_connection *conn,
  9653. const char *prog,
  9654. struct cgi_environment *env)
  9655. {
  9656. const char *s;
  9657. struct vec var_vec;
  9658. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9659. int i, truncated, uri_len;
  9660. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9661. return -1;
  9662. }
  9663. env->conn = conn;
  9664. env->buflen = CGI_ENVIRONMENT_SIZE;
  9665. env->bufused = 0;
  9666. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9667. if (env->buf == NULL) {
  9668. mg_cry_internal(conn,
  9669. "%s: Not enough memory for environmental buffer",
  9670. __func__);
  9671. return -1;
  9672. }
  9673. env->varlen = MAX_CGI_ENVIR_VARS;
  9674. env->varused = 0;
  9675. env->var =
  9676. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9677. if (env->var == NULL) {
  9678. mg_cry_internal(conn,
  9679. "%s: Not enough memory for environmental variables",
  9680. __func__);
  9681. mg_free(env->buf);
  9682. return -1;
  9683. }
  9684. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9685. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9686. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9687. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9688. /* Prepare the environment block */
  9689. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9690. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9691. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9692. #if defined(USE_IPV6)
  9693. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9694. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9695. } else
  9696. #endif
  9697. {
  9698. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9699. }
  9700. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9701. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9702. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9703. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9704. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9705. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9706. /* SCRIPT_NAME */
  9707. uri_len = (int)strlen(conn->request_info.local_uri);
  9708. if (conn->path_info == NULL) {
  9709. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9710. /* URI: /path_to_script/script.cgi */
  9711. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9712. } else {
  9713. /* URI: /path_to_script/ ... using index.cgi */
  9714. const char *index_file = strrchr(prog, '/');
  9715. if (index_file) {
  9716. addenv(env,
  9717. "SCRIPT_NAME=%s%s",
  9718. conn->request_info.local_uri,
  9719. index_file + 1);
  9720. }
  9721. }
  9722. } else {
  9723. /* URI: /path_to_script/script.cgi/path_info */
  9724. addenv(env,
  9725. "SCRIPT_NAME=%.*s",
  9726. uri_len - (int)strlen(conn->path_info),
  9727. conn->request_info.local_uri);
  9728. }
  9729. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9730. if (conn->path_info == NULL) {
  9731. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9732. } else {
  9733. addenv(env,
  9734. "PATH_TRANSLATED=%s%s",
  9735. conn->dom_ctx->config[DOCUMENT_ROOT],
  9736. conn->path_info);
  9737. }
  9738. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9739. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9740. addenv(env, "CONTENT_TYPE=%s", s);
  9741. }
  9742. if (conn->request_info.query_string != NULL) {
  9743. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9744. }
  9745. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9746. addenv(env, "CONTENT_LENGTH=%s", s);
  9747. }
  9748. if ((s = getenv("PATH")) != NULL) {
  9749. addenv(env, "PATH=%s", s);
  9750. }
  9751. if (conn->path_info != NULL) {
  9752. addenv(env, "PATH_INFO=%s", conn->path_info);
  9753. }
  9754. if (conn->status_code > 0) {
  9755. /* CGI error handler should show the status code */
  9756. addenv(env, "STATUS=%d", conn->status_code);
  9757. }
  9758. #if defined(_WIN32)
  9759. if ((s = getenv("COMSPEC")) != NULL) {
  9760. addenv(env, "COMSPEC=%s", s);
  9761. }
  9762. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9763. addenv(env, "SYSTEMROOT=%s", s);
  9764. }
  9765. if ((s = getenv("SystemDrive")) != NULL) {
  9766. addenv(env, "SystemDrive=%s", s);
  9767. }
  9768. if ((s = getenv("ProgramFiles")) != NULL) {
  9769. addenv(env, "ProgramFiles=%s", s);
  9770. }
  9771. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9772. addenv(env, "ProgramFiles(x86)=%s", s);
  9773. }
  9774. #else
  9775. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9776. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9777. }
  9778. #endif /* _WIN32 */
  9779. if ((s = getenv("PERLLIB")) != NULL) {
  9780. addenv(env, "PERLLIB=%s", s);
  9781. }
  9782. if (conn->request_info.remote_user != NULL) {
  9783. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9784. addenv(env, "%s", "AUTH_TYPE=Digest");
  9785. }
  9786. /* Add all headers as HTTP_* variables */
  9787. for (i = 0; i < conn->request_info.num_headers; i++) {
  9788. (void)mg_snprintf(conn,
  9789. &truncated,
  9790. http_var_name,
  9791. sizeof(http_var_name),
  9792. "HTTP_%s",
  9793. conn->request_info.http_headers[i].name);
  9794. if (truncated) {
  9795. mg_cry_internal(conn,
  9796. "%s: HTTP header variable too long [%s]",
  9797. __func__,
  9798. conn->request_info.http_headers[i].name);
  9799. continue;
  9800. }
  9801. /* Convert variable name into uppercase, and change - to _ */
  9802. for (p = http_var_name; *p != '\0'; p++) {
  9803. if (*p == '-') {
  9804. *p = '_';
  9805. }
  9806. *p = (char)toupper((unsigned char)*p);
  9807. }
  9808. addenv(env,
  9809. "%s=%s",
  9810. http_var_name,
  9811. conn->request_info.http_headers[i].value);
  9812. }
  9813. /* Add user-specified variables */
  9814. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9815. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9816. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9817. }
  9818. env->var[env->varused] = NULL;
  9819. env->buf[env->bufused] = '\0';
  9820. return 0;
  9821. }
  9822. /* Data for CGI process control: PID and number of references */
  9823. struct process_control_data {
  9824. pid_t pid;
  9825. int references;
  9826. };
  9827. static int
  9828. abort_process(void *data)
  9829. {
  9830. /* Waitpid checks for child status and won't work for a pid that does
  9831. * not identify a child of the current process. Thus, if the pid is
  9832. * reused, we will not affect a different process. */
  9833. struct process_control_data *proc = (struct process_control_data *)data;
  9834. int status = 0;
  9835. int refs;
  9836. pid_t ret_pid;
  9837. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9838. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9839. /* Stop child process */
  9840. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9841. kill(proc->pid, SIGABRT);
  9842. /* Wait until process is terminated (don't leave zombies) */
  9843. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9844. ;
  9845. } else {
  9846. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9847. }
  9848. /* Dec reference counter */
  9849. refs = mg_atomic_dec(&proc->references);
  9850. if (refs == 0) {
  9851. /* no more references - free data */
  9852. mg_free(data);
  9853. }
  9854. return 0;
  9855. }
  9856. /* Local (static) function assumes all arguments are valid. */
  9857. static void
  9858. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9859. {
  9860. char *buf;
  9861. size_t buflen;
  9862. int headers_len, data_len, i, truncated;
  9863. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9864. const char *status, *status_text, *connection_state;
  9865. char *pbuf, dir[PATH_MAX], *p;
  9866. struct mg_request_info ri;
  9867. struct cgi_environment blk;
  9868. FILE *in = NULL, *out = NULL, *err = NULL;
  9869. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9870. pid_t pid = (pid_t)-1;
  9871. struct process_control_data *proc = NULL;
  9872. #if defined(USE_TIMERS)
  9873. double cgi_timeout = -1.0;
  9874. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9875. /* Get timeout in seconds */
  9876. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9877. }
  9878. #endif
  9879. buf = NULL;
  9880. buflen = conn->phys_ctx->max_request_size;
  9881. i = prepare_cgi_environment(conn, prog, &blk);
  9882. if (i != 0) {
  9883. blk.buf = NULL;
  9884. blk.var = NULL;
  9885. goto done;
  9886. }
  9887. /* CGI must be executed in its own directory. 'dir' must point to the
  9888. * directory containing executable program, 'p' must point to the
  9889. * executable program name relative to 'dir'. */
  9890. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9891. if (truncated) {
  9892. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9893. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9894. goto done;
  9895. }
  9896. if ((p = strrchr(dir, '/')) != NULL) {
  9897. *p++ = '\0';
  9898. } else {
  9899. dir[0] = '.';
  9900. dir[1] = '\0';
  9901. p = (char *)prog;
  9902. }
  9903. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9904. status = strerror(ERRNO);
  9905. mg_cry_internal(
  9906. conn,
  9907. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9908. prog,
  9909. status);
  9910. mg_send_http_error(conn,
  9911. 500,
  9912. "Error: Cannot create CGI pipe: %s",
  9913. status);
  9914. goto done;
  9915. }
  9916. proc = (struct process_control_data *)
  9917. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9918. if (proc == NULL) {
  9919. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9920. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9921. goto done;
  9922. }
  9923. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9924. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9925. if (pid == (pid_t)-1) {
  9926. status = strerror(ERRNO);
  9927. mg_cry_internal(
  9928. conn,
  9929. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9930. prog,
  9931. status);
  9932. mg_send_http_error(conn,
  9933. 500,
  9934. "Error: Cannot spawn CGI process [%s]: %s",
  9935. prog,
  9936. status);
  9937. mg_free(proc);
  9938. proc = NULL;
  9939. goto done;
  9940. }
  9941. /* Store data in shared process_control_data */
  9942. proc->pid = pid;
  9943. proc->references = 1;
  9944. #if defined(USE_TIMERS)
  9945. if (cgi_timeout > 0.0) {
  9946. proc->references = 2;
  9947. // Start a timer for CGI
  9948. timer_add(conn->phys_ctx,
  9949. cgi_timeout /* in seconds */,
  9950. 0.0,
  9951. 1,
  9952. abort_process,
  9953. (void *)proc);
  9954. }
  9955. #endif
  9956. /* Parent closes only one side of the pipes.
  9957. * If we don't mark them as closed, close() attempt before
  9958. * return from this function throws an exception on Windows.
  9959. * Windows does not like when closed descriptor is closed again. */
  9960. (void)close(fdin[0]);
  9961. (void)close(fdout[1]);
  9962. (void)close(fderr[1]);
  9963. fdin[0] = fdout[1] = fderr[1] = -1;
  9964. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9965. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9966. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9967. status = strerror(ERRNO);
  9968. mg_cry_internal(conn,
  9969. "Error: CGI program \"%s\": Can not open fd: %s",
  9970. prog,
  9971. status);
  9972. mg_send_http_error(conn,
  9973. 500,
  9974. "Error: CGI can not open fd\nfdopen: %s",
  9975. status);
  9976. goto done;
  9977. }
  9978. setbuf(in, NULL);
  9979. setbuf(out, NULL);
  9980. setbuf(err, NULL);
  9981. fout.access.fp = out;
  9982. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9983. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9984. conn->content_len);
  9985. /* This is a POST/PUT request, or another request with body data. */
  9986. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9987. /* Error sending the body data */
  9988. mg_cry_internal(
  9989. conn,
  9990. "Error: CGI program \"%s\": Forward body data failed",
  9991. prog);
  9992. goto done;
  9993. }
  9994. }
  9995. /* Close so child gets an EOF. */
  9996. fclose(in);
  9997. in = NULL;
  9998. fdin[1] = -1;
  9999. /* Now read CGI reply into a buffer. We need to set correct
  10000. * status code, thus we need to see all HTTP headers first.
  10001. * Do not send anything back to client, until we buffer in all
  10002. * HTTP headers. */
  10003. data_len = 0;
  10004. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10005. if (buf == NULL) {
  10006. mg_send_http_error(conn,
  10007. 500,
  10008. "Error: Not enough memory for CGI buffer (%u bytes)",
  10009. (unsigned int)buflen);
  10010. mg_cry_internal(
  10011. conn,
  10012. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10013. "bytes)",
  10014. prog,
  10015. (unsigned int)buflen);
  10016. goto done;
  10017. }
  10018. DEBUG_TRACE("CGI: %s", "wait for response");
  10019. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10020. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10021. if (headers_len <= 0) {
  10022. /* Could not parse the CGI response. Check if some error message on
  10023. * stderr. */
  10024. i = pull_all(err, conn, buf, (int)buflen);
  10025. if (i > 0) {
  10026. /* CGI program explicitly sent an error */
  10027. /* Write the error message to the internal log */
  10028. mg_cry_internal(conn,
  10029. "Error: CGI program \"%s\" sent error "
  10030. "message: [%.*s]",
  10031. prog,
  10032. i,
  10033. buf);
  10034. /* Don't send the error message back to the client */
  10035. mg_send_http_error(conn,
  10036. 500,
  10037. "Error: CGI program \"%s\" failed.",
  10038. prog);
  10039. } else {
  10040. /* CGI program did not explicitly send an error, but a broken
  10041. * respon header */
  10042. mg_cry_internal(conn,
  10043. "Error: CGI program sent malformed or too big "
  10044. "(>%u bytes) HTTP headers: [%.*s]",
  10045. (unsigned)buflen,
  10046. data_len,
  10047. buf);
  10048. mg_send_http_error(conn,
  10049. 500,
  10050. "Error: CGI program sent malformed or too big "
  10051. "(>%u bytes) HTTP headers: [%.*s]",
  10052. (unsigned)buflen,
  10053. data_len,
  10054. buf);
  10055. }
  10056. /* in both cases, abort processing CGI */
  10057. goto done;
  10058. }
  10059. pbuf = buf;
  10060. buf[headers_len - 1] = '\0';
  10061. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10062. /* Make up and send the status line */
  10063. status_text = "OK";
  10064. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10065. != NULL) {
  10066. conn->status_code = atoi(status);
  10067. status_text = status;
  10068. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10069. status_text++;
  10070. }
  10071. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10072. != NULL) {
  10073. conn->status_code = 307;
  10074. } else {
  10075. conn->status_code = 200;
  10076. }
  10077. connection_state =
  10078. get_header(ri.http_headers, ri.num_headers, "Connection");
  10079. if (!header_has_option(connection_state, "keep-alive")) {
  10080. conn->must_close = 1;
  10081. }
  10082. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10083. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10084. /* Send headers */
  10085. for (i = 0; i < ri.num_headers; i++) {
  10086. DEBUG_TRACE("CGI header: %s: %s",
  10087. ri.http_headers[i].name,
  10088. ri.http_headers[i].value);
  10089. mg_printf(conn,
  10090. "%s: %s\r\n",
  10091. ri.http_headers[i].name,
  10092. ri.http_headers[i].value);
  10093. }
  10094. mg_write(conn, "\r\n", 2);
  10095. /* Send chunk of data that may have been read after the headers */
  10096. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10097. /* Read the rest of CGI output and send to the client */
  10098. DEBUG_TRACE("CGI: %s", "forward all data");
  10099. send_file_data(conn, &fout, 0, INT64_MAX);
  10100. DEBUG_TRACE("CGI: %s", "all data sent");
  10101. done:
  10102. mg_free(blk.var);
  10103. mg_free(blk.buf);
  10104. if (pid != (pid_t)-1) {
  10105. abort_process((void *)proc);
  10106. }
  10107. if (fdin[0] != -1) {
  10108. close(fdin[0]);
  10109. }
  10110. if (fdout[1] != -1) {
  10111. close(fdout[1]);
  10112. }
  10113. if (fderr[1] != -1) {
  10114. close(fderr[1]);
  10115. }
  10116. if (in != NULL) {
  10117. fclose(in);
  10118. } else if (fdin[1] != -1) {
  10119. close(fdin[1]);
  10120. }
  10121. if (out != NULL) {
  10122. fclose(out);
  10123. } else if (fdout[0] != -1) {
  10124. close(fdout[0]);
  10125. }
  10126. if (err != NULL) {
  10127. fclose(err);
  10128. } else if (fderr[0] != -1) {
  10129. close(fderr[0]);
  10130. }
  10131. mg_free(buf);
  10132. }
  10133. #endif /* !NO_CGI */
  10134. #if !defined(NO_FILES)
  10135. static void
  10136. mkcol(struct mg_connection *conn, const char *path)
  10137. {
  10138. int rc, body_len;
  10139. struct de de;
  10140. char date[64];
  10141. time_t curtime = time(NULL);
  10142. if (conn == NULL) {
  10143. return;
  10144. }
  10145. /* TODO (mid): Check the mg_send_http_error situations in this function
  10146. */
  10147. memset(&de.file, 0, sizeof(de.file));
  10148. if (!mg_stat(conn, path, &de.file)) {
  10149. mg_cry_internal(conn,
  10150. "%s: mg_stat(%s) failed: %s",
  10151. __func__,
  10152. path,
  10153. strerror(ERRNO));
  10154. }
  10155. if (de.file.last_modified) {
  10156. /* TODO (mid): This check does not seem to make any sense ! */
  10157. /* TODO (mid): Add a webdav unit test first, before changing
  10158. * anything here. */
  10159. mg_send_http_error(
  10160. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10161. return;
  10162. }
  10163. body_len = conn->data_len - conn->request_len;
  10164. if (body_len > 0) {
  10165. mg_send_http_error(
  10166. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10167. return;
  10168. }
  10169. rc = mg_mkdir(conn, path, 0755);
  10170. if (rc == 0) {
  10171. conn->status_code = 201;
  10172. gmt_time_string(date, sizeof(date), &curtime);
  10173. mg_printf(conn,
  10174. "HTTP/1.1 %d Created\r\n"
  10175. "Date: %s\r\n",
  10176. conn->status_code,
  10177. date);
  10178. send_static_cache_header(conn);
  10179. send_additional_header(conn);
  10180. mg_printf(conn,
  10181. "Content-Length: 0\r\n"
  10182. "Connection: %s\r\n\r\n",
  10183. suggest_connection_header(conn));
  10184. } else {
  10185. if (errno == EEXIST) {
  10186. mg_send_http_error(
  10187. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10188. } else if (errno == EACCES) {
  10189. mg_send_http_error(
  10190. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10191. } else if (errno == ENOENT) {
  10192. mg_send_http_error(
  10193. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10194. } else {
  10195. mg_send_http_error(
  10196. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10197. }
  10198. }
  10199. }
  10200. static void
  10201. put_file(struct mg_connection *conn, const char *path)
  10202. {
  10203. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10204. const char *range;
  10205. int64_t r1, r2;
  10206. int rc;
  10207. char date[64];
  10208. time_t curtime = time(NULL);
  10209. if (conn == NULL) {
  10210. return;
  10211. }
  10212. if (mg_stat(conn, path, &file.stat)) {
  10213. /* File already exists */
  10214. conn->status_code = 200;
  10215. if (file.stat.is_directory) {
  10216. /* This is an already existing directory,
  10217. * so there is nothing to do for the server. */
  10218. rc = 0;
  10219. } else {
  10220. /* File exists and is not a directory. */
  10221. /* Can it be replaced? */
  10222. #if defined(MG_USE_OPEN_FILE)
  10223. if (file.access.membuf != NULL) {
  10224. /* This is an "in-memory" file, that can not be replaced */
  10225. mg_send_http_error(conn,
  10226. 405,
  10227. "Error: Put not possible\nReplacing %s "
  10228. "is not supported",
  10229. path);
  10230. return;
  10231. }
  10232. #endif
  10233. /* Check if the server may write this file */
  10234. if (access(path, W_OK) == 0) {
  10235. /* Access granted */
  10236. rc = 1;
  10237. } else {
  10238. mg_send_http_error(
  10239. conn,
  10240. 403,
  10241. "Error: Put not possible\nReplacing %s is not allowed",
  10242. path);
  10243. return;
  10244. }
  10245. }
  10246. } else {
  10247. /* File should be created */
  10248. conn->status_code = 201;
  10249. rc = put_dir(conn, path);
  10250. }
  10251. if (rc == 0) {
  10252. /* put_dir returns 0 if path is a directory */
  10253. gmt_time_string(date, sizeof(date), &curtime);
  10254. mg_printf(conn,
  10255. "HTTP/1.1 %d %s\r\n",
  10256. conn->status_code,
  10257. mg_get_response_code_text(NULL, conn->status_code));
  10258. send_no_cache_header(conn);
  10259. send_additional_header(conn);
  10260. mg_printf(conn,
  10261. "Date: %s\r\n"
  10262. "Content-Length: 0\r\n"
  10263. "Connection: %s\r\n\r\n",
  10264. date,
  10265. suggest_connection_header(conn));
  10266. /* Request to create a directory has been fulfilled successfully.
  10267. * No need to put a file. */
  10268. return;
  10269. }
  10270. if (rc == -1) {
  10271. /* put_dir returns -1 if the path is too long */
  10272. mg_send_http_error(conn,
  10273. 414,
  10274. "Error: Path too long\nput_dir(%s): %s",
  10275. path,
  10276. strerror(ERRNO));
  10277. return;
  10278. }
  10279. if (rc == -2) {
  10280. /* put_dir returns -2 if the directory can not be created */
  10281. mg_send_http_error(conn,
  10282. 500,
  10283. "Error: Can not create directory\nput_dir(%s): %s",
  10284. path,
  10285. strerror(ERRNO));
  10286. return;
  10287. }
  10288. /* A file should be created or overwritten. */
  10289. /* Currently CivetWeb does not nead read+write access. */
  10290. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10291. || file.access.fp == NULL) {
  10292. (void)mg_fclose(&file.access);
  10293. mg_send_http_error(conn,
  10294. 500,
  10295. "Error: Can not create file\nfopen(%s): %s",
  10296. path,
  10297. strerror(ERRNO));
  10298. return;
  10299. }
  10300. fclose_on_exec(&file.access, conn);
  10301. range = mg_get_header(conn, "Content-Range");
  10302. r1 = r2 = 0;
  10303. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10304. conn->status_code = 206; /* Partial content */
  10305. fseeko(file.access.fp, r1, SEEK_SET);
  10306. }
  10307. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10308. /* forward_body_data failed.
  10309. * The error code has already been sent to the client,
  10310. * and conn->status_code is already set. */
  10311. (void)mg_fclose(&file.access);
  10312. return;
  10313. }
  10314. if (mg_fclose(&file.access) != 0) {
  10315. /* fclose failed. This might have different reasons, but a likely
  10316. * one is "no space on disk", http 507. */
  10317. conn->status_code = 507;
  10318. }
  10319. gmt_time_string(date, sizeof(date), &curtime);
  10320. mg_printf(conn,
  10321. "HTTP/1.1 %d %s\r\n",
  10322. conn->status_code,
  10323. mg_get_response_code_text(NULL, conn->status_code));
  10324. send_no_cache_header(conn);
  10325. send_additional_header(conn);
  10326. mg_printf(conn,
  10327. "Date: %s\r\n"
  10328. "Content-Length: 0\r\n"
  10329. "Connection: %s\r\n\r\n",
  10330. date,
  10331. suggest_connection_header(conn));
  10332. }
  10333. static void
  10334. delete_file(struct mg_connection *conn, const char *path)
  10335. {
  10336. struct de de;
  10337. memset(&de.file, 0, sizeof(de.file));
  10338. if (!mg_stat(conn, path, &de.file)) {
  10339. /* mg_stat returns 0 if the file does not exist */
  10340. mg_send_http_error(conn,
  10341. 404,
  10342. "Error: Cannot delete file\nFile %s not found",
  10343. path);
  10344. return;
  10345. }
  10346. #if 0 /* Ignore if a file in memory is inside a folder */
  10347. if (de.access.membuf != NULL) {
  10348. /* the file is cached in memory */
  10349. mg_send_http_error(
  10350. conn,
  10351. 405,
  10352. "Error: Delete not possible\nDeleting %s is not supported",
  10353. path);
  10354. return;
  10355. }
  10356. #endif
  10357. if (de.file.is_directory) {
  10358. if (remove_directory(conn, path)) {
  10359. /* Delete is successful: Return 204 without content. */
  10360. mg_send_http_error(conn, 204, "%s", "");
  10361. } else {
  10362. /* Delete is not successful: Return 500 (Server error). */
  10363. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10364. }
  10365. return;
  10366. }
  10367. /* This is an existing file (not a directory).
  10368. * Check if write permission is granted. */
  10369. if (access(path, W_OK) != 0) {
  10370. /* File is read only */
  10371. mg_send_http_error(
  10372. conn,
  10373. 403,
  10374. "Error: Delete not possible\nDeleting %s is not allowed",
  10375. path);
  10376. return;
  10377. }
  10378. /* Try to delete it. */
  10379. if (mg_remove(conn, path) == 0) {
  10380. /* Delete was successful: Return 204 without content. */
  10381. mg_send_http_error(conn, 204, "%s", "");
  10382. } else {
  10383. /* Delete not successful (file locked). */
  10384. mg_send_http_error(conn,
  10385. 423,
  10386. "Error: Cannot delete file\nremove(%s): %s",
  10387. path,
  10388. strerror(ERRNO));
  10389. }
  10390. }
  10391. #endif /* !NO_FILES */
  10392. #if !defined(NO_FILESYSTEMS)
  10393. static void
  10394. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10395. static void
  10396. do_ssi_include(struct mg_connection *conn,
  10397. const char *ssi,
  10398. char *tag,
  10399. int include_level)
  10400. {
  10401. char file_name[MG_BUF_LEN], path[512], *p;
  10402. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10403. size_t len;
  10404. int truncated = 0;
  10405. if (conn == NULL) {
  10406. return;
  10407. }
  10408. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10409. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10410. * always < MG_BUF_LEN. */
  10411. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10412. /* File name is relative to the webserver root */
  10413. file_name[511] = 0;
  10414. (void)mg_snprintf(conn,
  10415. &truncated,
  10416. path,
  10417. sizeof(path),
  10418. "%s/%s",
  10419. conn->dom_ctx->config[DOCUMENT_ROOT],
  10420. file_name);
  10421. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10422. /* File name is relative to the webserver working directory
  10423. * or it is absolute system path */
  10424. file_name[511] = 0;
  10425. (void)
  10426. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10427. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10428. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10429. /* File name is relative to the currect document */
  10430. file_name[511] = 0;
  10431. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10432. if (!truncated) {
  10433. if ((p = strrchr(path, '/')) != NULL) {
  10434. p[1] = '\0';
  10435. }
  10436. len = strlen(path);
  10437. (void)mg_snprintf(conn,
  10438. &truncated,
  10439. path + len,
  10440. sizeof(path) - len,
  10441. "%s",
  10442. file_name);
  10443. }
  10444. } else {
  10445. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10446. return;
  10447. }
  10448. if (truncated) {
  10449. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10450. return;
  10451. }
  10452. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10453. mg_cry_internal(conn,
  10454. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10455. tag,
  10456. path,
  10457. strerror(ERRNO));
  10458. } else {
  10459. fclose_on_exec(&file.access, conn);
  10460. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10461. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10462. path)
  10463. > 0) {
  10464. send_ssi_file(conn, path, &file, include_level + 1);
  10465. } else {
  10466. send_file_data(conn, &file, 0, INT64_MAX);
  10467. }
  10468. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10469. }
  10470. }
  10471. #if !defined(NO_POPEN)
  10472. static void
  10473. do_ssi_exec(struct mg_connection *conn, char *tag)
  10474. {
  10475. char cmd[1024] = "";
  10476. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10477. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10478. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10479. } else {
  10480. cmd[1023] = 0;
  10481. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10482. mg_cry_internal(conn,
  10483. "Cannot SSI #exec: [%s]: %s",
  10484. cmd,
  10485. strerror(ERRNO));
  10486. } else {
  10487. send_file_data(conn, &file, 0, INT64_MAX);
  10488. pclose(file.access.fp);
  10489. }
  10490. }
  10491. }
  10492. #endif /* !NO_POPEN */
  10493. static int
  10494. mg_fgetc(struct mg_file *filep, int offset)
  10495. {
  10496. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10497. if (filep == NULL) {
  10498. return EOF;
  10499. }
  10500. #if defined(MG_USE_OPEN_FILE)
  10501. if ((filep->access.membuf != NULL) && (offset >= 0)
  10502. && (((unsigned int)(offset)) < filep->stat.size)) {
  10503. return ((const unsigned char *)filep->access.membuf)[offset];
  10504. } else /* else block below */
  10505. #endif
  10506. if (filep->access.fp != NULL) {
  10507. return fgetc(filep->access.fp);
  10508. } else {
  10509. return EOF;
  10510. }
  10511. }
  10512. static void
  10513. send_ssi_file(struct mg_connection *conn,
  10514. const char *path,
  10515. struct mg_file *filep,
  10516. int include_level)
  10517. {
  10518. char buf[MG_BUF_LEN];
  10519. int ch, offset, len, in_tag, in_ssi_tag;
  10520. if (include_level > 10) {
  10521. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10522. return;
  10523. }
  10524. in_tag = in_ssi_tag = len = offset = 0;
  10525. /* Read file, byte by byte, and look for SSI include tags */
  10526. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10527. if (in_tag) {
  10528. /* We are in a tag, either SSI tag or html tag */
  10529. if (ch == '>') {
  10530. /* Tag is closing */
  10531. buf[len++] = '>';
  10532. if (in_ssi_tag) {
  10533. /* Handle SSI tag */
  10534. buf[len] = 0;
  10535. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10536. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10537. #if !defined(NO_POPEN)
  10538. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10539. do_ssi_exec(conn, buf + 9);
  10540. #endif /* !NO_POPEN */
  10541. } else {
  10542. mg_cry_internal(conn,
  10543. "%s: unknown SSI "
  10544. "command: \"%s\"",
  10545. path,
  10546. buf);
  10547. }
  10548. len = 0;
  10549. in_ssi_tag = in_tag = 0;
  10550. } else {
  10551. /* Not an SSI tag */
  10552. /* Flush buffer */
  10553. (void)mg_write(conn, buf, (size_t)len);
  10554. len = 0;
  10555. in_tag = 0;
  10556. }
  10557. } else {
  10558. /* Tag is still open */
  10559. buf[len++] = (char)(ch & 0xff);
  10560. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10561. /* All SSI tags start with <!--# */
  10562. in_ssi_tag = 1;
  10563. }
  10564. if ((len + 2) > (int)sizeof(buf)) {
  10565. /* Tag to long for buffer */
  10566. mg_cry_internal(conn, "%s: tag is too large", path);
  10567. return;
  10568. }
  10569. }
  10570. } else {
  10571. /* We are not in a tag yet. */
  10572. if (ch == '<') {
  10573. /* Tag is opening */
  10574. in_tag = 1;
  10575. if (len > 0) {
  10576. /* Flush current buffer.
  10577. * Buffer is filled with "len" bytes. */
  10578. (void)mg_write(conn, buf, (size_t)len);
  10579. }
  10580. /* Store the < */
  10581. len = 1;
  10582. buf[0] = '<';
  10583. } else {
  10584. /* No Tag */
  10585. /* Add data to buffer */
  10586. buf[len++] = (char)(ch & 0xff);
  10587. /* Flush if buffer is full */
  10588. if (len == (int)sizeof(buf)) {
  10589. mg_write(conn, buf, (size_t)len);
  10590. len = 0;
  10591. }
  10592. }
  10593. }
  10594. }
  10595. /* Send the rest of buffered data */
  10596. if (len > 0) {
  10597. mg_write(conn, buf, (size_t)len);
  10598. }
  10599. }
  10600. static void
  10601. handle_ssi_file_request(struct mg_connection *conn,
  10602. const char *path,
  10603. struct mg_file *filep)
  10604. {
  10605. char date[64];
  10606. time_t curtime = time(NULL);
  10607. const char *cors_orig_cfg;
  10608. const char *cors1, *cors2, *cors3;
  10609. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10610. return;
  10611. }
  10612. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10613. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10614. /* Cross-origin resource sharing (CORS). */
  10615. cors1 = "Access-Control-Allow-Origin: ";
  10616. cors2 = cors_orig_cfg;
  10617. cors3 = "\r\n";
  10618. } else {
  10619. cors1 = cors2 = cors3 = "";
  10620. }
  10621. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10622. /* File exists (precondition for calling this function),
  10623. * but can not be opened by the server. */
  10624. mg_send_http_error(conn,
  10625. 500,
  10626. "Error: Cannot read file\nfopen(%s): %s",
  10627. path,
  10628. strerror(ERRNO));
  10629. } else {
  10630. conn->must_close = 1;
  10631. gmt_time_string(date, sizeof(date), &curtime);
  10632. fclose_on_exec(&filep->access, conn);
  10633. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10634. send_no_cache_header(conn);
  10635. send_additional_header(conn);
  10636. mg_printf(conn,
  10637. "%s%s%s"
  10638. "Date: %s\r\n"
  10639. "Content-Type: text/html\r\n"
  10640. "Connection: %s\r\n\r\n",
  10641. cors1,
  10642. cors2,
  10643. cors3,
  10644. date,
  10645. suggest_connection_header(conn));
  10646. send_ssi_file(conn, path, filep, 0);
  10647. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10648. }
  10649. }
  10650. #endif /* NO_FILESYSTEMS */
  10651. #if !defined(NO_FILES)
  10652. static void
  10653. send_options(struct mg_connection *conn)
  10654. {
  10655. char date[64];
  10656. time_t curtime = time(NULL);
  10657. if (!conn) {
  10658. return;
  10659. }
  10660. conn->status_code = 200;
  10661. conn->must_close = 1;
  10662. gmt_time_string(date, sizeof(date), &curtime);
  10663. /* We do not set a "Cache-Control" header here, but leave the default.
  10664. * Since browsers do not send an OPTIONS request, we can not test the
  10665. * effect anyway. */
  10666. mg_printf(conn,
  10667. "HTTP/1.1 200 OK\r\n"
  10668. "Date: %s\r\n"
  10669. "Connection: %s\r\n"
  10670. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10671. "PROPFIND, MKCOL\r\n"
  10672. "DAV: 1\r\n",
  10673. date,
  10674. suggest_connection_header(conn));
  10675. send_additional_header(conn);
  10676. mg_printf(conn, "\r\n");
  10677. }
  10678. /* Writes PROPFIND properties for a collection element */
  10679. static int
  10680. print_props(struct mg_connection *conn,
  10681. const char *uri,
  10682. const char *name,
  10683. struct mg_file_stat *filep)
  10684. {
  10685. size_t href_size, i, j;
  10686. int len;
  10687. char *href, mtime[64];
  10688. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10689. return 0;
  10690. }
  10691. /* Estimate worst case size for encoding */
  10692. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10693. href = (char *)mg_malloc(href_size);
  10694. if (href == NULL) {
  10695. return 0;
  10696. }
  10697. len = mg_url_encode(uri, href, href_size);
  10698. if (len >= 0) {
  10699. /* Append an extra string */
  10700. mg_url_encode(name, href + len, href_size - (size_t)len);
  10701. }
  10702. /* Directory separator should be preserved. */
  10703. for (i = j = 0; href[i]; j++) {
  10704. if (!strncmp(href + i, "%2f", 3)) {
  10705. href[j] = '/';
  10706. i += 3;
  10707. } else {
  10708. href[j] = href[i++];
  10709. }
  10710. }
  10711. href[j] = '\0';
  10712. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10713. mg_printf(conn,
  10714. "<d:response>"
  10715. "<d:href>%s</d:href>"
  10716. "<d:propstat>"
  10717. "<d:prop>"
  10718. "<d:resourcetype>%s</d:resourcetype>"
  10719. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10720. "<d:getlastmodified>%s</d:getlastmodified>"
  10721. "</d:prop>"
  10722. "<d:status>HTTP/1.1 200 OK</d:status>"
  10723. "</d:propstat>"
  10724. "</d:response>\n",
  10725. href,
  10726. filep->is_directory ? "<d:collection/>" : "",
  10727. filep->size,
  10728. mtime);
  10729. mg_free(href);
  10730. return 1;
  10731. }
  10732. static int
  10733. print_dav_dir_entry(struct de *de, void *data)
  10734. {
  10735. struct mg_connection *conn = (struct mg_connection *)data;
  10736. if (!de || !conn
  10737. || !print_props(
  10738. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10739. return -1;
  10740. }
  10741. return 0;
  10742. }
  10743. static void
  10744. handle_propfind(struct mg_connection *conn,
  10745. const char *path,
  10746. struct mg_file_stat *filep)
  10747. {
  10748. const char *depth = mg_get_header(conn, "Depth");
  10749. char date[64];
  10750. time_t curtime = time(NULL);
  10751. gmt_time_string(date, sizeof(date), &curtime);
  10752. if (!conn || !path || !filep || !conn->dom_ctx) {
  10753. return;
  10754. }
  10755. conn->must_close = 1;
  10756. conn->status_code = 207;
  10757. mg_printf(conn,
  10758. "HTTP/1.1 207 Multi-Status\r\n"
  10759. "Date: %s\r\n",
  10760. date);
  10761. send_static_cache_header(conn);
  10762. send_additional_header(conn);
  10763. mg_printf(conn,
  10764. "Connection: %s\r\n"
  10765. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10766. suggest_connection_header(conn));
  10767. mg_printf(conn,
  10768. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10769. "<d:multistatus xmlns:d='DAV:'>\n");
  10770. /* Print properties for the requested resource itself */
  10771. print_props(conn, conn->request_info.local_uri, "", filep);
  10772. /* If it is a directory, print directory entries too if Depth is not 0
  10773. */
  10774. if (filep->is_directory
  10775. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10776. "yes")
  10777. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10778. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10779. }
  10780. mg_printf(conn, "%s\n", "</d:multistatus>");
  10781. }
  10782. #endif
  10783. void
  10784. mg_lock_connection(struct mg_connection *conn)
  10785. {
  10786. if (conn) {
  10787. (void)pthread_mutex_lock(&conn->mutex);
  10788. }
  10789. }
  10790. void
  10791. mg_unlock_connection(struct mg_connection *conn)
  10792. {
  10793. if (conn) {
  10794. (void)pthread_mutex_unlock(&conn->mutex);
  10795. }
  10796. }
  10797. void
  10798. mg_lock_context(struct mg_context *ctx)
  10799. {
  10800. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10801. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10802. }
  10803. }
  10804. void
  10805. mg_unlock_context(struct mg_context *ctx)
  10806. {
  10807. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10808. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10809. }
  10810. }
  10811. #if defined(USE_LUA)
  10812. #include "mod_lua.inl"
  10813. #endif /* USE_LUA */
  10814. #if defined(USE_DUKTAPE)
  10815. #include "mod_duktape.inl"
  10816. #endif /* USE_DUKTAPE */
  10817. #if defined(USE_WEBSOCKET)
  10818. #if !defined(NO_SSL_DL)
  10819. #define SHA_API static
  10820. #include "sha1.inl"
  10821. #endif
  10822. static int
  10823. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10824. {
  10825. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10826. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10827. SHA_CTX sha_ctx;
  10828. int truncated;
  10829. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10830. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10831. if (truncated) {
  10832. conn->must_close = 1;
  10833. return 0;
  10834. }
  10835. DEBUG_TRACE("%s", "Send websocket handshake");
  10836. SHA1_Init(&sha_ctx);
  10837. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10838. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10839. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10840. mg_printf(conn,
  10841. "HTTP/1.1 101 Switching Protocols\r\n"
  10842. "Upgrade: websocket\r\n"
  10843. "Connection: Upgrade\r\n"
  10844. "Sec-WebSocket-Accept: %s\r\n",
  10845. b64_sha);
  10846. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10847. mg_printf(conn,
  10848. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10849. conn->request_info.acceptedWebSocketSubprotocol);
  10850. } else {
  10851. mg_printf(conn, "%s", "\r\n");
  10852. }
  10853. return 1;
  10854. }
  10855. #if !defined(MG_MAX_UNANSWERED_PING)
  10856. /* Configuration of the maximum number of websocket PINGs that might
  10857. * stay unanswered before the connection is considered broken.
  10858. * Note: The name of this define may still change (until it is
  10859. * defined as a compile parameter in a documentation).
  10860. */
  10861. #define MG_MAX_UNANSWERED_PING (5)
  10862. #endif
  10863. static void
  10864. read_websocket(struct mg_connection *conn,
  10865. mg_websocket_data_handler ws_data_handler,
  10866. void *callback_data)
  10867. {
  10868. /* Pointer to the beginning of the portion of the incoming websocket
  10869. * message queue.
  10870. * The original websocket upgrade request is never removed, so the queue
  10871. * begins after it. */
  10872. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10873. int n, error, exit_by_callback;
  10874. int ret;
  10875. /* body_len is the length of the entire queue in bytes
  10876. * len is the length of the current message
  10877. * data_len is the length of the current message's data payload
  10878. * header_len is the length of the current message's header */
  10879. size_t i, len, mask_len = 0, header_len, body_len;
  10880. uint64_t data_len = 0;
  10881. /* "The masking key is a 32-bit value chosen at random by the client."
  10882. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10883. */
  10884. unsigned char mask[4];
  10885. /* data points to the place where the message is stored when passed to
  10886. * the websocket_data callback. This is either mem on the stack, or a
  10887. * dynamically allocated buffer if it is too large. */
  10888. unsigned char mem[4096];
  10889. unsigned char mop; /* mask flag and opcode */
  10890. /* Variables used for connection monitoring */
  10891. double timeout = -1.0;
  10892. int enable_ping_pong = 0;
  10893. int ping_count = 0;
  10894. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10895. enable_ping_pong =
  10896. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10897. "yes");
  10898. }
  10899. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10900. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10901. }
  10902. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10903. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10904. }
  10905. /* Enter data processing loop */
  10906. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10907. conn->request_info.remote_addr,
  10908. conn->request_info.remote_port);
  10909. conn->in_websocket_handling = 1;
  10910. mg_set_thread_name("wsock");
  10911. /* Loop continuously, reading messages from the socket, invoking the
  10912. * callback, and waiting repeatedly until an error occurs. */
  10913. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10914. && (!conn->must_close)) {
  10915. header_len = 0;
  10916. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10917. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10918. len = buf[1] & 127;
  10919. mask_len = (buf[1] & 128) ? 4 : 0;
  10920. if ((len < 126) && (body_len >= mask_len)) {
  10921. /* inline 7-bit length field */
  10922. data_len = len;
  10923. header_len = 2 + mask_len;
  10924. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10925. /* 16-bit length field */
  10926. header_len = 4 + mask_len;
  10927. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10928. } else if (body_len >= (10 + mask_len)) {
  10929. /* 64-bit length field */
  10930. uint32_t l1, l2;
  10931. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10932. memcpy(&l2, &buf[6], 4);
  10933. header_len = 10 + mask_len;
  10934. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10935. if (data_len > (uint64_t)0x7FFF0000ul) {
  10936. /* no can do */
  10937. mg_cry_internal(
  10938. conn,
  10939. "%s",
  10940. "websocket out of memory; closing connection");
  10941. break;
  10942. }
  10943. }
  10944. }
  10945. if ((header_len > 0) && (body_len >= header_len)) {
  10946. /* Allocate space to hold websocket payload */
  10947. unsigned char *data = mem;
  10948. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10949. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10950. conn->phys_ctx);
  10951. if (data == NULL) {
  10952. /* Allocation failed, exit the loop and then close the
  10953. * connection */
  10954. mg_cry_internal(
  10955. conn,
  10956. "%s",
  10957. "websocket out of memory; closing connection");
  10958. break;
  10959. }
  10960. }
  10961. /* Copy the mask before we shift the queue and destroy it */
  10962. if (mask_len > 0) {
  10963. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10964. } else {
  10965. memset(mask, 0, sizeof(mask));
  10966. }
  10967. /* Read frame payload from the first message in the queue into
  10968. * data and advance the queue by moving the memory in place. */
  10969. DEBUG_ASSERT(body_len >= header_len);
  10970. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10971. mop = buf[0]; /* current mask and opcode */
  10972. /* Overflow case */
  10973. len = body_len - header_len;
  10974. memcpy(data, buf + header_len, len);
  10975. error = 0;
  10976. while ((uint64_t)len < data_len) {
  10977. n = pull_inner(NULL,
  10978. conn,
  10979. (char *)(data + len),
  10980. (int)(data_len - len),
  10981. timeout);
  10982. if (n <= -2) {
  10983. error = 1;
  10984. break;
  10985. } else if (n > 0) {
  10986. len += (size_t)n;
  10987. } else {
  10988. /* Timeout: should retry */
  10989. /* TODO: retry condition */
  10990. }
  10991. }
  10992. if (error) {
  10993. mg_cry_internal(
  10994. conn,
  10995. "%s",
  10996. "Websocket pull failed; closing connection");
  10997. if (data != mem) {
  10998. mg_free(data);
  10999. }
  11000. break;
  11001. }
  11002. conn->data_len = conn->request_len;
  11003. } else {
  11004. mop = buf[0]; /* current mask and opcode, overwritten by
  11005. * memmove() */
  11006. /* Length of the message being read at the front of the
  11007. * queue. Cast to 31 bit is OK, since we limited
  11008. * data_len before. */
  11009. len = (size_t)data_len + header_len;
  11010. /* Copy the data payload into the data pointer for the
  11011. * callback. Cast to 31 bit is OK, since we
  11012. * limited data_len */
  11013. memcpy(data, buf + header_len, (size_t)data_len);
  11014. /* Move the queue forward len bytes */
  11015. memmove(buf, buf + len, body_len - len);
  11016. /* Mark the queue as advanced */
  11017. conn->data_len -= (int)len;
  11018. }
  11019. /* Apply mask if necessary */
  11020. if (mask_len > 0) {
  11021. for (i = 0; i < (size_t)data_len; i++) {
  11022. data[i] ^= mask[i & 3];
  11023. }
  11024. }
  11025. exit_by_callback = 0;
  11026. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11027. /* filter PONG messages */
  11028. DEBUG_TRACE("PONG from %s:%u",
  11029. conn->request_info.remote_addr,
  11030. conn->request_info.remote_port);
  11031. /* No unanwered PINGs left */
  11032. ping_count = 0;
  11033. } else if (enable_ping_pong
  11034. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11035. /* reply PING messages */
  11036. DEBUG_TRACE("Reply PING from %s:%u",
  11037. conn->request_info.remote_addr,
  11038. conn->request_info.remote_port);
  11039. ret = mg_websocket_write(conn,
  11040. MG_WEBSOCKET_OPCODE_PONG,
  11041. (char *)data,
  11042. (size_t)data_len);
  11043. if (ret <= 0) {
  11044. /* Error: send failed */
  11045. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11046. break;
  11047. }
  11048. } else {
  11049. /* Exit the loop if callback signals to exit (server side),
  11050. * or "connection close" opcode received (client side). */
  11051. if ((ws_data_handler != NULL)
  11052. && !ws_data_handler(conn,
  11053. mop,
  11054. (char *)data,
  11055. (size_t)data_len,
  11056. callback_data)) {
  11057. exit_by_callback = 1;
  11058. }
  11059. }
  11060. /* It a buffer has been allocated, free it again */
  11061. if (data != mem) {
  11062. mg_free(data);
  11063. }
  11064. if (exit_by_callback) {
  11065. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11066. conn->request_info.remote_addr,
  11067. conn->request_info.remote_port);
  11068. break;
  11069. }
  11070. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11071. /* Opcode == 8, connection close */
  11072. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11073. conn->request_info.remote_addr,
  11074. conn->request_info.remote_port);
  11075. break;
  11076. }
  11077. /* Not breaking the loop, process next websocket frame. */
  11078. } else {
  11079. /* Read from the socket into the next available location in the
  11080. * message queue. */
  11081. n = pull_inner(NULL,
  11082. conn,
  11083. conn->buf + conn->data_len,
  11084. conn->buf_size - conn->data_len,
  11085. timeout);
  11086. if (n <= -2) {
  11087. /* Error, no bytes read */
  11088. DEBUG_TRACE("PULL from %s:%u failed",
  11089. conn->request_info.remote_addr,
  11090. conn->request_info.remote_port);
  11091. break;
  11092. }
  11093. if (n > 0) {
  11094. conn->data_len += n;
  11095. /* Reset open PING count */
  11096. ping_count = 0;
  11097. } else {
  11098. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11099. && (!conn->must_close)) {
  11100. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11101. /* Stop sending PING */
  11102. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11103. "- closing connection",
  11104. ping_count,
  11105. conn->request_info.remote_addr,
  11106. conn->request_info.remote_port);
  11107. break;
  11108. }
  11109. if (enable_ping_pong) {
  11110. /* Send Websocket PING message */
  11111. DEBUG_TRACE("PING to %s:%u",
  11112. conn->request_info.remote_addr,
  11113. conn->request_info.remote_port);
  11114. ret = mg_websocket_write(conn,
  11115. MG_WEBSOCKET_OPCODE_PING,
  11116. NULL,
  11117. 0);
  11118. if (ret <= 0) {
  11119. /* Error: send failed */
  11120. DEBUG_TRACE("Send PING failed (%i)", ret);
  11121. break;
  11122. }
  11123. ping_count++;
  11124. }
  11125. }
  11126. /* Timeout: should retry */
  11127. /* TODO: get timeout def */
  11128. }
  11129. }
  11130. }
  11131. /* Leave data processing loop */
  11132. mg_set_thread_name("worker");
  11133. conn->in_websocket_handling = 0;
  11134. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11135. conn->request_info.remote_addr,
  11136. conn->request_info.remote_port);
  11137. }
  11138. static int
  11139. mg_websocket_write_exec(struct mg_connection *conn,
  11140. int opcode,
  11141. const char *data,
  11142. size_t dataLen,
  11143. uint32_t masking_key)
  11144. {
  11145. unsigned char header[14];
  11146. size_t headerLen;
  11147. int retval;
  11148. #if defined(GCC_DIAGNOSTIC)
  11149. /* Disable spurious conversion warning for GCC */
  11150. #pragma GCC diagnostic push
  11151. #pragma GCC diagnostic ignored "-Wconversion"
  11152. #endif
  11153. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11154. #if defined(GCC_DIAGNOSTIC)
  11155. #pragma GCC diagnostic pop
  11156. #endif
  11157. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11158. if (dataLen < 126) {
  11159. /* inline 7-bit length field */
  11160. header[1] = (unsigned char)dataLen;
  11161. headerLen = 2;
  11162. } else if (dataLen <= 0xFFFF) {
  11163. /* 16-bit length field */
  11164. uint16_t len = htons((uint16_t)dataLen);
  11165. header[1] = 126;
  11166. memcpy(header + 2, &len, 2);
  11167. headerLen = 4;
  11168. } else {
  11169. /* 64-bit length field */
  11170. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11171. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11172. header[1] = 127;
  11173. memcpy(header + 2, &len1, 4);
  11174. memcpy(header + 6, &len2, 4);
  11175. headerLen = 10;
  11176. }
  11177. if (masking_key) {
  11178. /* add mask */
  11179. header[1] |= 0x80;
  11180. memcpy(header + headerLen, &masking_key, 4);
  11181. headerLen += 4;
  11182. }
  11183. /* Note that POSIX/Winsock's send() is threadsafe
  11184. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11185. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11186. * push(), although that is only a problem if the packet is large or
  11187. * outgoing buffer is full). */
  11188. /* TODO: Check if this lock should be moved to user land.
  11189. * Currently the server sets this lock for websockets, but
  11190. * not for any other connection. It must be set for every
  11191. * conn read/written by more than one thread, no matter if
  11192. * it is a websocket or regular connection. */
  11193. (void)mg_lock_connection(conn);
  11194. retval = mg_write(conn, header, headerLen);
  11195. if (retval != (int)headerLen) {
  11196. /* Did not send complete header */
  11197. retval = -1;
  11198. } else {
  11199. if (dataLen > 0) {
  11200. retval = mg_write(conn, data, dataLen);
  11201. }
  11202. /* if dataLen == 0, the header length (2) is returned */
  11203. }
  11204. /* TODO: Remove this unlock as well, when lock is removed. */
  11205. mg_unlock_connection(conn);
  11206. return retval;
  11207. }
  11208. int
  11209. mg_websocket_write(struct mg_connection *conn,
  11210. int opcode,
  11211. const char *data,
  11212. size_t dataLen)
  11213. {
  11214. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11215. }
  11216. static void
  11217. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11218. {
  11219. size_t i = 0;
  11220. i = 0;
  11221. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11222. /* Convert in 32 bit words, if data is 4 byte aligned */
  11223. while (i < (in_len - 3)) {
  11224. *(uint32_t *)(void *)(out + i) =
  11225. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11226. i += 4;
  11227. }
  11228. }
  11229. if (i != in_len) {
  11230. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11231. while (i < in_len) {
  11232. *(uint8_t *)(void *)(out + i) =
  11233. *(uint8_t *)(void *)(in + i)
  11234. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11235. i++;
  11236. }
  11237. }
  11238. }
  11239. int
  11240. mg_websocket_client_write(struct mg_connection *conn,
  11241. int opcode,
  11242. const char *data,
  11243. size_t dataLen)
  11244. {
  11245. int retval = -1;
  11246. char *masked_data =
  11247. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11248. uint32_t masking_key = 0;
  11249. if (masked_data == NULL) {
  11250. /* Return -1 in an error case */
  11251. mg_cry_internal(conn,
  11252. "%s",
  11253. "Cannot allocate buffer for masked websocket response: "
  11254. "Out of memory");
  11255. return -1;
  11256. }
  11257. do {
  11258. /* Get a masking key - but not 0 */
  11259. masking_key = (uint32_t)get_random();
  11260. } while (masking_key == 0);
  11261. mask_data(data, dataLen, masking_key, masked_data);
  11262. retval = mg_websocket_write_exec(
  11263. conn, opcode, masked_data, dataLen, masking_key);
  11264. mg_free(masked_data);
  11265. return retval;
  11266. }
  11267. static void
  11268. handle_websocket_request(struct mg_connection *conn,
  11269. const char *path,
  11270. int is_callback_resource,
  11271. struct mg_websocket_subprotocols *subprotocols,
  11272. mg_websocket_connect_handler ws_connect_handler,
  11273. mg_websocket_ready_handler ws_ready_handler,
  11274. mg_websocket_data_handler ws_data_handler,
  11275. mg_websocket_close_handler ws_close_handler,
  11276. void *cbData)
  11277. {
  11278. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11279. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11280. ptrdiff_t lua_websock = 0;
  11281. #if !defined(USE_LUA)
  11282. (void)path;
  11283. #endif
  11284. /* Step 1: Check websocket protocol version. */
  11285. /* Step 1.1: Check Sec-WebSocket-Key. */
  11286. if (!websock_key) {
  11287. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11288. * requires a Sec-WebSocket-Key header.
  11289. */
  11290. /* It could be the hixie draft version
  11291. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11292. */
  11293. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11294. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11295. char key3[8];
  11296. if ((key1 != NULL) && (key2 != NULL)) {
  11297. /* This version uses 8 byte body data in a GET request */
  11298. conn->content_len = 8;
  11299. if (8 == mg_read(conn, key3, 8)) {
  11300. /* This is the hixie version */
  11301. mg_send_http_error(conn,
  11302. 426,
  11303. "%s",
  11304. "Protocol upgrade to RFC 6455 required");
  11305. return;
  11306. }
  11307. }
  11308. /* This is an unknown version */
  11309. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11310. return;
  11311. }
  11312. /* Step 1.2: Check websocket protocol version. */
  11313. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11314. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11315. /* Reject wrong versions */
  11316. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11317. return;
  11318. }
  11319. /* Step 1.3: Could check for "Host", but we do not really nead this
  11320. * value for anything, so just ignore it. */
  11321. /* Step 2: If a callback is responsible, call it. */
  11322. if (is_callback_resource) {
  11323. /* Step 2.1 check and select subprotocol */
  11324. const char *protocols[64]; // max 64 headers
  11325. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11326. "Sec-WebSocket-Protocol",
  11327. protocols,
  11328. 64);
  11329. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11330. int cnt = 0;
  11331. int idx;
  11332. unsigned long len;
  11333. const char *sep, *curSubProtocol,
  11334. *acceptedWebSocketSubprotocol = NULL;
  11335. /* look for matching subprotocol */
  11336. do {
  11337. const char *protocol = protocols[cnt];
  11338. do {
  11339. sep = strchr(protocol, ',');
  11340. curSubProtocol = protocol;
  11341. len = sep ? (unsigned long)(sep - protocol)
  11342. : (unsigned long)strlen(protocol);
  11343. while (sep && isspace((unsigned char)*++sep))
  11344. ; // ignore leading whitespaces
  11345. protocol = sep;
  11346. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11347. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11348. && (strncmp(curSubProtocol,
  11349. subprotocols->subprotocols[idx],
  11350. len)
  11351. == 0)) {
  11352. acceptedWebSocketSubprotocol =
  11353. subprotocols->subprotocols[idx];
  11354. break;
  11355. }
  11356. }
  11357. } while (sep && !acceptedWebSocketSubprotocol);
  11358. } while (++cnt < nbSubprotocolHeader
  11359. && !acceptedWebSocketSubprotocol);
  11360. conn->request_info.acceptedWebSocketSubprotocol =
  11361. acceptedWebSocketSubprotocol;
  11362. } else if (nbSubprotocolHeader > 0) {
  11363. /* keep legacy behavior */
  11364. const char *protocol = protocols[0];
  11365. /* The protocol is a comma separated list of names. */
  11366. /* The server must only return one value from this list. */
  11367. /* First check if it is a list or just a single value. */
  11368. const char *sep = strrchr(protocol, ',');
  11369. if (sep == NULL) {
  11370. /* Just a single protocol -> accept it. */
  11371. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11372. } else {
  11373. /* Multiple protocols -> accept the last one. */
  11374. /* This is just a quick fix if the client offers multiple
  11375. * protocols. The handler should have a list of accepted
  11376. * protocols on his own
  11377. * and use it to select one protocol among those the client
  11378. * has
  11379. * offered.
  11380. */
  11381. while (isspace((unsigned char)*++sep)) {
  11382. ; /* ignore leading whitespaces */
  11383. }
  11384. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11385. }
  11386. }
  11387. if ((ws_connect_handler != NULL)
  11388. && (ws_connect_handler(conn, cbData) != 0)) {
  11389. /* C callback has returned non-zero, do not proceed with
  11390. * handshake.
  11391. */
  11392. /* Note that C callbacks are no longer called when Lua is
  11393. * responsible, so C can no longer filter callbacks for Lua. */
  11394. return;
  11395. }
  11396. }
  11397. #if defined(USE_LUA)
  11398. /* Step 3: No callback. Check if Lua is responsible. */
  11399. else {
  11400. /* Step 3.1: Check if Lua is responsible. */
  11401. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11402. lua_websock = match_prefix(
  11403. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11404. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11405. path);
  11406. }
  11407. if (lua_websock) {
  11408. /* Step 3.2: Lua is responsible: call it. */
  11409. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11410. if (!conn->lua_websocket_state) {
  11411. /* Lua rejected the new client */
  11412. return;
  11413. }
  11414. }
  11415. }
  11416. #endif
  11417. /* Step 4: Check if there is a responsible websocket handler. */
  11418. if (!is_callback_resource && !lua_websock) {
  11419. /* There is no callback, and Lua is not responsible either. */
  11420. /* Reply with a 404 Not Found. We are still at a standard
  11421. * HTTP request here, before the websocket handshake, so
  11422. * we can still send standard HTTP error replies. */
  11423. mg_send_http_error(conn, 404, "%s", "Not found");
  11424. return;
  11425. }
  11426. /* Step 5: The websocket connection has been accepted */
  11427. if (!send_websocket_handshake(conn, websock_key)) {
  11428. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11429. return;
  11430. }
  11431. /* Step 6: Call the ready handler */
  11432. if (is_callback_resource) {
  11433. if (ws_ready_handler != NULL) {
  11434. ws_ready_handler(conn, cbData);
  11435. }
  11436. #if defined(USE_LUA)
  11437. } else if (lua_websock) {
  11438. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11439. /* the ready handler returned false */
  11440. return;
  11441. }
  11442. #endif
  11443. }
  11444. /* Step 7: Enter the read loop */
  11445. if (is_callback_resource) {
  11446. read_websocket(conn, ws_data_handler, cbData);
  11447. #if defined(USE_LUA)
  11448. } else if (lua_websock) {
  11449. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11450. #endif
  11451. }
  11452. /* Step 8: Call the close handler */
  11453. if (ws_close_handler) {
  11454. ws_close_handler(conn, cbData);
  11455. }
  11456. }
  11457. #endif /* !USE_WEBSOCKET */
  11458. /* Is upgrade request:
  11459. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11460. * 1 = upgrade to websocket
  11461. * 2 = upgrade to HTTP/2
  11462. * -1 = upgrade to unknown protocol
  11463. */
  11464. static int
  11465. should_switch_to_protocol(const struct mg_connection *conn)
  11466. {
  11467. const char *upgrade, *connection;
  11468. /* A websocket protocoll has the following HTTP headers:
  11469. *
  11470. * Connection: Upgrade
  11471. * Upgrade: Websocket
  11472. */
  11473. connection = mg_get_header(conn, "Connection");
  11474. if (connection == NULL) {
  11475. return PROTOCOL_TYPE_HTTP1;
  11476. }
  11477. if (!mg_strcasestr(connection, "upgrade")) {
  11478. return PROTOCOL_TYPE_HTTP1;
  11479. }
  11480. upgrade = mg_get_header(conn, "Upgrade");
  11481. if (upgrade == NULL) {
  11482. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11483. return -1;
  11484. }
  11485. /* Upgrade to ... */
  11486. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11487. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11488. * "Sec-WebSocket-Version" are also required.
  11489. * Don't check them here, since even an unsupported websocket protocol
  11490. * request still IS a websocket request (in contrast to a standard HTTP
  11491. * request). It will fail later in handle_websocket_request.
  11492. */
  11493. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11494. }
  11495. if (0 != mg_strcasestr(upgrade, "h2")) {
  11496. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11497. }
  11498. /* Upgrade to another protocol */
  11499. return -1;
  11500. }
  11501. static int
  11502. isbyte(int n)
  11503. {
  11504. return (n >= 0) && (n <= 255);
  11505. }
  11506. static int
  11507. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11508. {
  11509. int n, a, b, c, d, slash = 32, len = 0;
  11510. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11511. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11512. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11513. && (slash < 33)) {
  11514. len = n;
  11515. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11516. | (uint32_t)d;
  11517. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11518. }
  11519. return len;
  11520. }
  11521. static int
  11522. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11523. {
  11524. int throttle = 0;
  11525. struct vec vec, val;
  11526. uint32_t net, mask;
  11527. char mult;
  11528. double v;
  11529. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11530. mult = ',';
  11531. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11532. || (v < 0)
  11533. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11534. && (mult != ','))) {
  11535. continue;
  11536. }
  11537. v *= (lowercase(&mult) == 'k')
  11538. ? 1024
  11539. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11540. if (vec.len == 1 && vec.ptr[0] == '*') {
  11541. throttle = (int)v;
  11542. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11543. if ((remote_ip & mask) == net) {
  11544. throttle = (int)v;
  11545. }
  11546. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11547. throttle = (int)v;
  11548. }
  11549. }
  11550. return throttle;
  11551. }
  11552. static uint32_t
  11553. get_remote_ip(const struct mg_connection *conn)
  11554. {
  11555. if (!conn) {
  11556. return 0;
  11557. }
  11558. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11559. }
  11560. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11561. #include "handle_form.inl"
  11562. #if defined(MG_LEGACY_INTERFACE)
  11563. /* Implement the deprecated mg_upload function by calling the new
  11564. * mg_handle_form_request function. While mg_upload could only handle
  11565. * HTML forms sent as POST request in multipart/form-data format
  11566. * containing only file input elements, mg_handle_form_request can
  11567. * handle all form input elements and all standard request methods. */
  11568. struct mg_upload_user_data {
  11569. struct mg_connection *conn;
  11570. const char *destination_dir;
  11571. int num_uploaded_files;
  11572. };
  11573. /* Helper function for deprecated mg_upload. */
  11574. static int
  11575. mg_upload_field_found(const char *key,
  11576. const char *filename,
  11577. char *path,
  11578. size_t pathlen,
  11579. void *user_data)
  11580. {
  11581. int truncated = 0;
  11582. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11583. (void)key;
  11584. if (!filename) {
  11585. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11586. return FORM_FIELD_STORAGE_ABORT;
  11587. }
  11588. mg_snprintf(fud->conn,
  11589. &truncated,
  11590. path,
  11591. pathlen - 1,
  11592. "%s/%s",
  11593. fud->destination_dir,
  11594. filename);
  11595. if (truncated) {
  11596. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11597. return FORM_FIELD_STORAGE_ABORT;
  11598. }
  11599. return FORM_FIELD_STORAGE_STORE;
  11600. }
  11601. /* Helper function for deprecated mg_upload. */
  11602. static int
  11603. mg_upload_field_get(const char *key,
  11604. const char *value,
  11605. size_t value_size,
  11606. void *user_data)
  11607. {
  11608. /* Function should never be called */
  11609. (void)key;
  11610. (void)value;
  11611. (void)value_size;
  11612. (void)user_data;
  11613. return 0;
  11614. }
  11615. /* Helper function for deprecated mg_upload. */
  11616. static int
  11617. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11618. {
  11619. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11620. (void)file_size;
  11621. fud->num_uploaded_files++;
  11622. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11623. return 0;
  11624. }
  11625. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11626. int
  11627. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11628. {
  11629. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11630. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11631. mg_upload_field_get,
  11632. mg_upload_field_stored,
  11633. 0};
  11634. int ret;
  11635. fdh.user_data = (void *)&fud;
  11636. ret = mg_handle_form_request(conn, &fdh);
  11637. if (ret < 0) {
  11638. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11639. }
  11640. return fud.num_uploaded_files;
  11641. }
  11642. #endif
  11643. static int
  11644. get_first_ssl_listener_index(const struct mg_context *ctx)
  11645. {
  11646. unsigned int i;
  11647. int idx = -1;
  11648. if (ctx) {
  11649. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11650. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11651. }
  11652. }
  11653. return idx;
  11654. }
  11655. /* Return host (without port) */
  11656. /* Use mg_free to free the result */
  11657. static const char *
  11658. alloc_get_host(struct mg_connection *conn)
  11659. {
  11660. char buf[1025];
  11661. size_t buflen = sizeof(buf);
  11662. const char *host_header = get_header(conn->request_info.http_headers,
  11663. conn->request_info.num_headers,
  11664. "Host");
  11665. char *host;
  11666. if (host_header != NULL) {
  11667. char *pos;
  11668. /* Create a local copy of the "Host" header, since it might be
  11669. * modified here. */
  11670. mg_strlcpy(buf, host_header, buflen);
  11671. buf[buflen - 1] = '\0';
  11672. host = buf;
  11673. while (isspace((unsigned char)*host)) {
  11674. host++;
  11675. }
  11676. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11677. * is found. */
  11678. if (*host == '[') {
  11679. pos = strchr(host, ']');
  11680. if (!pos) {
  11681. /* Malformed hostname starts with '[', but no ']' found */
  11682. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11683. return NULL;
  11684. }
  11685. /* terminate after ']' */
  11686. pos[1] = 0;
  11687. } else {
  11688. /* Otherwise, a ':' separates hostname and port number */
  11689. pos = strchr(host, ':');
  11690. if (pos != NULL) {
  11691. *pos = '\0';
  11692. }
  11693. }
  11694. if (conn->ssl) {
  11695. /* This is a HTTPS connection, maybe we have a hostname
  11696. * from SNI (set in ssl_servername_callback). */
  11697. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11698. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11699. /* We are not using the default domain */
  11700. if (mg_strcasecmp(host, sslhost)) {
  11701. /* Mismatch between SNI domain and HTTP domain */
  11702. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11703. sslhost,
  11704. host);
  11705. return NULL;
  11706. }
  11707. }
  11708. DEBUG_TRACE("HTTPS Host: %s", host);
  11709. } else {
  11710. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11711. while (dom) {
  11712. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11713. /* Found matching domain */
  11714. DEBUG_TRACE("HTTP domain %s found",
  11715. dom->config[AUTHENTICATION_DOMAIN]);
  11716. /* TODO: Check if this is a HTTP or HTTPS domain */
  11717. conn->dom_ctx = dom;
  11718. break;
  11719. }
  11720. mg_lock_context(conn->phys_ctx);
  11721. dom = dom->next;
  11722. mg_unlock_context(conn->phys_ctx);
  11723. }
  11724. DEBUG_TRACE("HTTP Host: %s", host);
  11725. }
  11726. } else {
  11727. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11728. host = buf;
  11729. DEBUG_TRACE("IP: %s", host);
  11730. }
  11731. return mg_strdup_ctx(host, conn->phys_ctx);
  11732. }
  11733. static void
  11734. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11735. {
  11736. char target_url[MG_BUF_LEN];
  11737. int truncated = 0;
  11738. conn->must_close = 1;
  11739. /* Send host, port, uri and (if it exists) ?query_string */
  11740. if (conn->host) {
  11741. /* Use "308 Permanent Redirect" */
  11742. int redirect_code = 308;
  11743. /* Create target URL */
  11744. mg_snprintf(
  11745. conn,
  11746. &truncated,
  11747. target_url,
  11748. sizeof(target_url),
  11749. "https://%s:%d%s%s%s",
  11750. conn->host,
  11751. #if defined(USE_IPV6)
  11752. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11753. == AF_INET6)
  11754. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11755. .lsa.sin6.sin6_port)
  11756. :
  11757. #endif
  11758. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11759. .lsa.sin.sin_port),
  11760. conn->request_info.local_uri,
  11761. (conn->request_info.query_string == NULL) ? "" : "?",
  11762. (conn->request_info.query_string == NULL)
  11763. ? ""
  11764. : conn->request_info.query_string);
  11765. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11766. * is used as buffer size) */
  11767. if (truncated) {
  11768. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11769. return;
  11770. }
  11771. /* Use redirect helper function */
  11772. mg_send_http_redirect(conn, target_url, redirect_code);
  11773. }
  11774. }
  11775. static void
  11776. mg_set_handler_type(struct mg_context *phys_ctx,
  11777. struct mg_domain_context *dom_ctx,
  11778. const char *uri,
  11779. int handler_type,
  11780. int is_delete_request,
  11781. mg_request_handler handler,
  11782. struct mg_websocket_subprotocols *subprotocols,
  11783. mg_websocket_connect_handler connect_handler,
  11784. mg_websocket_ready_handler ready_handler,
  11785. mg_websocket_data_handler data_handler,
  11786. mg_websocket_close_handler close_handler,
  11787. mg_authorization_handler auth_handler,
  11788. void *cbdata)
  11789. {
  11790. struct mg_handler_info *tmp_rh, **lastref;
  11791. size_t urilen = strlen(uri);
  11792. if (handler_type == WEBSOCKET_HANDLER) {
  11793. DEBUG_ASSERT(handler == NULL);
  11794. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11795. || ready_handler != NULL || data_handler != NULL
  11796. || close_handler != NULL);
  11797. DEBUG_ASSERT(auth_handler == NULL);
  11798. if (handler != NULL) {
  11799. return;
  11800. }
  11801. if (!is_delete_request && (connect_handler == NULL)
  11802. && (ready_handler == NULL) && (data_handler == NULL)
  11803. && (close_handler == NULL)) {
  11804. return;
  11805. }
  11806. if (auth_handler != NULL) {
  11807. return;
  11808. }
  11809. } else if (handler_type == REQUEST_HANDLER) {
  11810. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11811. && data_handler == NULL && close_handler == NULL);
  11812. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11813. DEBUG_ASSERT(auth_handler == NULL);
  11814. if ((connect_handler != NULL) || (ready_handler != NULL)
  11815. || (data_handler != NULL) || (close_handler != NULL)) {
  11816. return;
  11817. }
  11818. if (!is_delete_request && (handler == NULL)) {
  11819. return;
  11820. }
  11821. if (auth_handler != NULL) {
  11822. return;
  11823. }
  11824. } else { /* AUTH_HANDLER */
  11825. DEBUG_ASSERT(handler == NULL);
  11826. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11827. && data_handler == NULL && close_handler == NULL);
  11828. DEBUG_ASSERT(auth_handler != NULL);
  11829. if (handler != NULL) {
  11830. return;
  11831. }
  11832. if ((connect_handler != NULL) || (ready_handler != NULL)
  11833. || (data_handler != NULL) || (close_handler != NULL)) {
  11834. return;
  11835. }
  11836. if (!is_delete_request && (auth_handler == NULL)) {
  11837. return;
  11838. }
  11839. }
  11840. if (!phys_ctx || !dom_ctx) {
  11841. return;
  11842. }
  11843. mg_lock_context(phys_ctx);
  11844. /* first try to find an existing handler */
  11845. do {
  11846. lastref = &(dom_ctx->handlers);
  11847. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11848. if (tmp_rh->handler_type == handler_type
  11849. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11850. if (!is_delete_request) {
  11851. /* update existing handler */
  11852. if (handler_type == REQUEST_HANDLER) {
  11853. /* Wait for end of use before updating */
  11854. if (tmp_rh->refcount) {
  11855. mg_unlock_context(phys_ctx);
  11856. mg_sleep(1);
  11857. mg_lock_context(phys_ctx);
  11858. /* tmp_rh might have been freed, search again. */
  11859. break;
  11860. }
  11861. /* Ok, the handler is no more use -> Update it */
  11862. tmp_rh->handler = handler;
  11863. } else if (handler_type == WEBSOCKET_HANDLER) {
  11864. tmp_rh->subprotocols = subprotocols;
  11865. tmp_rh->connect_handler = connect_handler;
  11866. tmp_rh->ready_handler = ready_handler;
  11867. tmp_rh->data_handler = data_handler;
  11868. tmp_rh->close_handler = close_handler;
  11869. } else { /* AUTH_HANDLER */
  11870. tmp_rh->auth_handler = auth_handler;
  11871. }
  11872. tmp_rh->cbdata = cbdata;
  11873. } else {
  11874. /* remove existing handler */
  11875. if (handler_type == REQUEST_HANDLER) {
  11876. /* Wait for end of use before removing */
  11877. if (tmp_rh->refcount) {
  11878. tmp_rh->removing = 1;
  11879. mg_unlock_context(phys_ctx);
  11880. mg_sleep(1);
  11881. mg_lock_context(phys_ctx);
  11882. /* tmp_rh might have been freed, search again. */
  11883. break;
  11884. }
  11885. /* Ok, the handler is no more used */
  11886. }
  11887. *lastref = tmp_rh->next;
  11888. mg_free(tmp_rh->uri);
  11889. mg_free(tmp_rh);
  11890. }
  11891. mg_unlock_context(phys_ctx);
  11892. return;
  11893. }
  11894. lastref = &(tmp_rh->next);
  11895. }
  11896. } while (tmp_rh != NULL);
  11897. if (is_delete_request) {
  11898. /* no handler to set, this was a remove request to a non-existing
  11899. * handler */
  11900. mg_unlock_context(phys_ctx);
  11901. return;
  11902. }
  11903. tmp_rh =
  11904. (struct mg_handler_info *)mg_calloc_ctx(1,
  11905. sizeof(struct mg_handler_info),
  11906. phys_ctx);
  11907. if (tmp_rh == NULL) {
  11908. mg_unlock_context(phys_ctx);
  11909. mg_cry_ctx_internal(phys_ctx,
  11910. "%s",
  11911. "Cannot create new request handler struct, OOM");
  11912. return;
  11913. }
  11914. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11915. if (!tmp_rh->uri) {
  11916. mg_unlock_context(phys_ctx);
  11917. mg_free(tmp_rh);
  11918. mg_cry_ctx_internal(phys_ctx,
  11919. "%s",
  11920. "Cannot create new request handler struct, OOM");
  11921. return;
  11922. }
  11923. tmp_rh->uri_len = urilen;
  11924. if (handler_type == REQUEST_HANDLER) {
  11925. tmp_rh->refcount = 0;
  11926. tmp_rh->removing = 0;
  11927. tmp_rh->handler = handler;
  11928. } else if (handler_type == WEBSOCKET_HANDLER) {
  11929. tmp_rh->subprotocols = subprotocols;
  11930. tmp_rh->connect_handler = connect_handler;
  11931. tmp_rh->ready_handler = ready_handler;
  11932. tmp_rh->data_handler = data_handler;
  11933. tmp_rh->close_handler = close_handler;
  11934. } else { /* AUTH_HANDLER */
  11935. tmp_rh->auth_handler = auth_handler;
  11936. }
  11937. tmp_rh->cbdata = cbdata;
  11938. tmp_rh->handler_type = handler_type;
  11939. tmp_rh->next = NULL;
  11940. *lastref = tmp_rh;
  11941. mg_unlock_context(phys_ctx);
  11942. }
  11943. void
  11944. mg_set_request_handler(struct mg_context *ctx,
  11945. const char *uri,
  11946. mg_request_handler handler,
  11947. void *cbdata)
  11948. {
  11949. mg_set_handler_type(ctx,
  11950. &(ctx->dd),
  11951. uri,
  11952. REQUEST_HANDLER,
  11953. handler == NULL,
  11954. handler,
  11955. NULL,
  11956. NULL,
  11957. NULL,
  11958. NULL,
  11959. NULL,
  11960. NULL,
  11961. cbdata);
  11962. }
  11963. void
  11964. mg_set_websocket_handler(struct mg_context *ctx,
  11965. const char *uri,
  11966. mg_websocket_connect_handler connect_handler,
  11967. mg_websocket_ready_handler ready_handler,
  11968. mg_websocket_data_handler data_handler,
  11969. mg_websocket_close_handler close_handler,
  11970. void *cbdata)
  11971. {
  11972. mg_set_websocket_handler_with_subprotocols(ctx,
  11973. uri,
  11974. NULL,
  11975. connect_handler,
  11976. ready_handler,
  11977. data_handler,
  11978. close_handler,
  11979. cbdata);
  11980. }
  11981. void
  11982. mg_set_websocket_handler_with_subprotocols(
  11983. struct mg_context *ctx,
  11984. const char *uri,
  11985. struct mg_websocket_subprotocols *subprotocols,
  11986. mg_websocket_connect_handler connect_handler,
  11987. mg_websocket_ready_handler ready_handler,
  11988. mg_websocket_data_handler data_handler,
  11989. mg_websocket_close_handler close_handler,
  11990. void *cbdata)
  11991. {
  11992. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11993. && (data_handler == NULL)
  11994. && (close_handler == NULL);
  11995. mg_set_handler_type(ctx,
  11996. &(ctx->dd),
  11997. uri,
  11998. WEBSOCKET_HANDLER,
  11999. is_delete_request,
  12000. NULL,
  12001. subprotocols,
  12002. connect_handler,
  12003. ready_handler,
  12004. data_handler,
  12005. close_handler,
  12006. NULL,
  12007. cbdata);
  12008. }
  12009. void
  12010. mg_set_auth_handler(struct mg_context *ctx,
  12011. const char *uri,
  12012. mg_authorization_handler handler,
  12013. void *cbdata)
  12014. {
  12015. mg_set_handler_type(ctx,
  12016. &(ctx->dd),
  12017. uri,
  12018. AUTH_HANDLER,
  12019. handler == NULL,
  12020. NULL,
  12021. NULL,
  12022. NULL,
  12023. NULL,
  12024. NULL,
  12025. NULL,
  12026. handler,
  12027. cbdata);
  12028. }
  12029. static int
  12030. get_request_handler(struct mg_connection *conn,
  12031. int handler_type,
  12032. mg_request_handler *handler,
  12033. struct mg_websocket_subprotocols **subprotocols,
  12034. mg_websocket_connect_handler *connect_handler,
  12035. mg_websocket_ready_handler *ready_handler,
  12036. mg_websocket_data_handler *data_handler,
  12037. mg_websocket_close_handler *close_handler,
  12038. mg_authorization_handler *auth_handler,
  12039. void **cbdata,
  12040. struct mg_handler_info **handler_info)
  12041. {
  12042. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12043. if (request_info) {
  12044. const char *uri = request_info->local_uri;
  12045. size_t urilen = strlen(uri);
  12046. struct mg_handler_info *tmp_rh;
  12047. int step, matched;
  12048. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12049. return 0;
  12050. }
  12051. mg_lock_context(conn->phys_ctx);
  12052. for (step = 0; step < 3; step++) {
  12053. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12054. tmp_rh = tmp_rh->next) {
  12055. if (tmp_rh->handler_type != handler_type) {
  12056. continue;
  12057. }
  12058. if (step == 0) {
  12059. /* first try for an exact match */
  12060. matched = (tmp_rh->uri_len == urilen)
  12061. && (strcmp(tmp_rh->uri, uri) == 0);
  12062. } else if (step == 1) {
  12063. /* next try for a partial match, we will accept
  12064. uri/something */
  12065. matched = (tmp_rh->uri_len < urilen)
  12066. && (uri[tmp_rh->uri_len] == '/')
  12067. && (memcmp(tmp_rh->uri, uri,
  12068. tmp_rh->uri_len) == 0);
  12069. } else {
  12070. /* finally try for pattern match */
  12071. matched = match_prefix(tmp_rh->uri,
  12072. tmp_rh->uri_len, uri) > 0;
  12073. }
  12074. if (matched) {
  12075. if (handler_type == WEBSOCKET_HANDLER) {
  12076. *subprotocols = tmp_rh->subprotocols;
  12077. *connect_handler = tmp_rh->connect_handler;
  12078. *ready_handler = tmp_rh->ready_handler;
  12079. *data_handler = tmp_rh->data_handler;
  12080. *close_handler = tmp_rh->close_handler;
  12081. } else if (handler_type == REQUEST_HANDLER) {
  12082. if (tmp_rh->removing) {
  12083. /* Treat as none found */
  12084. step = 2;
  12085. break;
  12086. }
  12087. *handler = tmp_rh->handler;
  12088. /* Acquire handler and give it back */
  12089. tmp_rh->refcount++;
  12090. *handler_info = tmp_rh;
  12091. } else { /* AUTH_HANDLER */
  12092. *auth_handler = tmp_rh->auth_handler;
  12093. }
  12094. *cbdata = tmp_rh->cbdata;
  12095. mg_unlock_context(conn->phys_ctx);
  12096. return 1;
  12097. }
  12098. }
  12099. }
  12100. mg_unlock_context(conn->phys_ctx);
  12101. }
  12102. return 0; /* none found */
  12103. }
  12104. /* Check if the script file is in a path, allowed for script files.
  12105. * This can be used if uploading files is possible not only for the server
  12106. * admin, and the upload mechanism does not check the file extension.
  12107. */
  12108. static int
  12109. is_in_script_path(const struct mg_connection *conn, const char *path)
  12110. {
  12111. /* TODO (Feature): Add config value for allowed script path.
  12112. * Default: All allowed. */
  12113. (void)conn;
  12114. (void)path;
  12115. return 1;
  12116. }
  12117. #if defined(USE_WEBSOCKET) \
  12118. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12119. static int
  12120. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12121. void *cbdata)
  12122. {
  12123. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12124. if (pcallbacks->websocket_connect) {
  12125. return pcallbacks->websocket_connect(conn);
  12126. }
  12127. /* No handler set - assume "OK" */
  12128. return 0;
  12129. }
  12130. static void
  12131. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12132. {
  12133. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12134. if (pcallbacks->websocket_ready) {
  12135. pcallbacks->websocket_ready(conn);
  12136. }
  12137. }
  12138. static int
  12139. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12140. int bits,
  12141. char *data,
  12142. size_t len,
  12143. void *cbdata)
  12144. {
  12145. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12146. if (pcallbacks->websocket_data) {
  12147. return pcallbacks->websocket_data(conn, bits, data, len);
  12148. }
  12149. /* No handler set - assume "OK" */
  12150. return 1;
  12151. }
  12152. static void
  12153. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12154. void *cbdata)
  12155. {
  12156. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12157. if (pcallbacks->connection_close) {
  12158. pcallbacks->connection_close(conn);
  12159. }
  12160. }
  12161. #endif
  12162. /* This is the heart of the Civetweb's logic.
  12163. * This function is called when the request is read, parsed and validated,
  12164. * and Civetweb must decide what action to take: serve a file, or
  12165. * a directory, or call embedded function, etcetera. */
  12166. static void
  12167. handle_request(struct mg_connection *conn)
  12168. {
  12169. struct mg_request_info *ri = &conn->request_info;
  12170. char path[PATH_MAX];
  12171. int uri_len, ssl_index;
  12172. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12173. is_put_or_delete_request = 0, is_callback_resource = 0;
  12174. int i;
  12175. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12176. mg_request_handler callback_handler = NULL;
  12177. struct mg_handler_info *handler_info = NULL;
  12178. struct mg_websocket_subprotocols *subprotocols;
  12179. mg_websocket_connect_handler ws_connect_handler = NULL;
  12180. mg_websocket_ready_handler ws_ready_handler = NULL;
  12181. mg_websocket_data_handler ws_data_handler = NULL;
  12182. mg_websocket_close_handler ws_close_handler = NULL;
  12183. void *callback_data = NULL;
  12184. mg_authorization_handler auth_handler = NULL;
  12185. void *auth_callback_data = NULL;
  12186. int handler_type;
  12187. time_t curtime = time(NULL);
  12188. char date[64];
  12189. path[0] = 0;
  12190. /* 1. get the request url */
  12191. /* 1.1. split into url and query string */
  12192. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12193. != NULL) {
  12194. *((char *)conn->request_info.query_string++) = '\0';
  12195. }
  12196. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12197. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12198. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12199. if (ssl_index >= 0) {
  12200. redirect_to_https_port(conn, ssl_index);
  12201. } else {
  12202. /* A http to https forward port has been specified,
  12203. * but no https port to forward to. */
  12204. mg_send_http_error(conn,
  12205. 503,
  12206. "%s",
  12207. "Error: SSL forward not configured properly");
  12208. mg_cry_internal(conn,
  12209. "%s",
  12210. "Can not redirect to SSL, no SSL port available");
  12211. }
  12212. return;
  12213. }
  12214. uri_len = (int)strlen(ri->local_uri);
  12215. /* 1.3. decode url (if config says so) */
  12216. if (should_decode_url(conn)) {
  12217. mg_url_decode(
  12218. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12219. }
  12220. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12221. * not possible */
  12222. remove_dot_segments((char *)ri->local_uri);
  12223. /* step 1. completed, the url is known now */
  12224. uri_len = (int)strlen(ri->local_uri);
  12225. DEBUG_TRACE("URL: %s", ri->local_uri);
  12226. /* 2. if this ip has limited speed, set it for this connection */
  12227. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12228. get_remote_ip(conn),
  12229. ri->local_uri);
  12230. /* 3. call a "handle everything" callback, if registered */
  12231. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12232. /* Note that since V1.7 the "begin_request" function is called
  12233. * before an authorization check. If an authorization check is
  12234. * required, use a request_handler instead. */
  12235. i = conn->phys_ctx->callbacks.begin_request(conn);
  12236. if (i > 0) {
  12237. /* callback already processed the request. Store the
  12238. return value as a status code for the access log. */
  12239. conn->status_code = i;
  12240. if (!conn->must_close) {
  12241. discard_unread_request_data(conn);
  12242. }
  12243. return;
  12244. } else if (i == 0) {
  12245. /* civetweb should process the request */
  12246. } else {
  12247. /* unspecified - may change with the next version */
  12248. return;
  12249. }
  12250. }
  12251. /* request not yet handled by a handler or redirect, so the request
  12252. * is processed here */
  12253. /* 4. Check for CORS preflight requests and handle them (if configured).
  12254. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12255. */
  12256. if (!strcmp(ri->request_method, "OPTIONS")) {
  12257. /* Send a response to CORS preflights only if
  12258. * access_control_allow_methods is not NULL and not an empty string.
  12259. * In this case, scripts can still handle CORS. */
  12260. const char *cors_meth_cfg =
  12261. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12262. const char *cors_orig_cfg =
  12263. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12264. const char *cors_origin =
  12265. get_header(ri->http_headers, ri->num_headers, "Origin");
  12266. const char *cors_acrm = get_header(ri->http_headers,
  12267. ri->num_headers,
  12268. "Access-Control-Request-Method");
  12269. /* Todo: check if cors_origin is in cors_orig_cfg.
  12270. * Or, let the client check this. */
  12271. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12272. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12273. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12274. /* This is a valid CORS preflight, and the server is configured
  12275. * to
  12276. * handle it automatically. */
  12277. const char *cors_acrh =
  12278. get_header(ri->http_headers,
  12279. ri->num_headers,
  12280. "Access-Control-Request-Headers");
  12281. gmt_time_string(date, sizeof(date), &curtime);
  12282. mg_printf(conn,
  12283. "HTTP/1.1 200 OK\r\n"
  12284. "Date: %s\r\n"
  12285. "Access-Control-Allow-Origin: %s\r\n"
  12286. "Access-Control-Allow-Methods: %s\r\n"
  12287. "Content-Length: 0\r\n"
  12288. "Connection: %s\r\n",
  12289. date,
  12290. cors_orig_cfg,
  12291. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12292. suggest_connection_header(conn));
  12293. if (cors_acrh != NULL) {
  12294. /* CORS request is asking for additional headers */
  12295. const char *cors_hdr_cfg =
  12296. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12297. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12298. /* Allow only if access_control_allow_headers is
  12299. * not NULL and not an empty string. If this
  12300. * configuration is set to *, allow everything.
  12301. * Otherwise this configuration must be a list
  12302. * of allowed HTTP header names. */
  12303. mg_printf(conn,
  12304. "Access-Control-Allow-Headers: %s\r\n",
  12305. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12306. : cors_hdr_cfg));
  12307. }
  12308. }
  12309. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12310. mg_printf(conn, "\r\n");
  12311. return;
  12312. }
  12313. }
  12314. /* 5. interpret the url to find out how the request must be handled
  12315. */
  12316. /* 5.1. first test, if the request targets the regular http(s)://
  12317. * protocol namespace or the websocket ws(s):// protocol namespace.
  12318. */
  12319. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12320. #if defined(USE_WEBSOCKET)
  12321. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12322. #else
  12323. handler_type = REQUEST_HANDLER;
  12324. #endif /* defined(USE_WEBSOCKET) */
  12325. /* 5.2. check if the request will be handled by a callback */
  12326. if (get_request_handler(conn,
  12327. handler_type,
  12328. &callback_handler,
  12329. &subprotocols,
  12330. &ws_connect_handler,
  12331. &ws_ready_handler,
  12332. &ws_data_handler,
  12333. &ws_close_handler,
  12334. NULL,
  12335. &callback_data,
  12336. &handler_info)) {
  12337. /* 5.2.1. A callback will handle this request. All requests
  12338. * handled
  12339. * by a callback have to be considered as requests to a script
  12340. * resource. */
  12341. is_callback_resource = 1;
  12342. is_script_resource = 1;
  12343. is_put_or_delete_request = is_put_or_delete_method(conn);
  12344. } else {
  12345. no_callback_resource:
  12346. /* 5.2.2. No callback is responsible for this request. The URI
  12347. * addresses a file based resource (static content or Lua/cgi
  12348. * scripts in the file system). */
  12349. is_callback_resource = 0;
  12350. interpret_uri(conn,
  12351. path,
  12352. sizeof(path),
  12353. &file.stat,
  12354. &is_found,
  12355. &is_script_resource,
  12356. &is_websocket_request,
  12357. &is_put_or_delete_request);
  12358. }
  12359. /* 6. authorization check */
  12360. /* 6.1. a custom authorization handler is installed */
  12361. if (get_request_handler(conn,
  12362. AUTH_HANDLER,
  12363. NULL,
  12364. NULL,
  12365. NULL,
  12366. NULL,
  12367. NULL,
  12368. NULL,
  12369. &auth_handler,
  12370. &auth_callback_data,
  12371. NULL)) {
  12372. if (!auth_handler(conn, auth_callback_data)) {
  12373. return;
  12374. }
  12375. } else if (is_put_or_delete_request && !is_script_resource
  12376. && !is_callback_resource) {
  12377. /* 6.2. this request is a PUT/DELETE to a real file */
  12378. /* 6.2.1. thus, the server must have real files */
  12379. #if defined(NO_FILES)
  12380. if (1) {
  12381. #else
  12382. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12383. #endif
  12384. /* This server does not have any real files, thus the
  12385. * PUT/DELETE methods are not valid. */
  12386. mg_send_http_error(conn,
  12387. 405,
  12388. "%s method not allowed",
  12389. conn->request_info.request_method);
  12390. return;
  12391. }
  12392. #if !defined(NO_FILES)
  12393. /* 6.2.2. Check if put authorization for static files is
  12394. * available.
  12395. */
  12396. if (!is_authorized_for_put(conn)) {
  12397. send_authorization_request(conn, NULL);
  12398. return;
  12399. }
  12400. #endif
  12401. } else {
  12402. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12403. * or it is a PUT or DELETE request to a resource that does not
  12404. * correspond to a file. Check authorization. */
  12405. if (!check_authorization(conn, path)) {
  12406. send_authorization_request(conn, NULL);
  12407. return;
  12408. }
  12409. }
  12410. /* request is authorized or does not need authorization */
  12411. /* 7. check if there are request handlers for this uri */
  12412. if (is_callback_resource) {
  12413. if (!is_websocket_request) {
  12414. i = callback_handler(conn, callback_data);
  12415. /* Callback handler will not be used anymore. Release it */
  12416. mg_lock_context(conn->phys_ctx);
  12417. handler_info->refcount--;
  12418. mg_unlock_context(conn->phys_ctx);
  12419. if (i > 0) {
  12420. /* Do nothing, callback has served the request. Store
  12421. * then return value as status code for the log and discard
  12422. * all data from the client not used by the callback. */
  12423. conn->status_code = i;
  12424. if (!conn->must_close) {
  12425. discard_unread_request_data(conn);
  12426. }
  12427. } else {
  12428. /* The handler did NOT handle the request. */
  12429. /* Some proper reactions would be:
  12430. * a) close the connections without sending anything
  12431. * b) send a 404 not found
  12432. * c) try if there is a file matching the URI
  12433. * It would be possible to do a, b or c in the callback
  12434. * implementation, and return 1 - we cannot do anything
  12435. * here, that is not possible in the callback.
  12436. *
  12437. * TODO: What would be the best reaction here?
  12438. * (Note: The reaction may change, if there is a better
  12439. *idea.)
  12440. */
  12441. /* For the moment, use option c: We look for a proper file,
  12442. * but since a file request is not always a script resource,
  12443. * the authorization check might be different. */
  12444. interpret_uri(conn,
  12445. path,
  12446. sizeof(path),
  12447. &file.stat,
  12448. &is_found,
  12449. &is_script_resource,
  12450. &is_websocket_request,
  12451. &is_put_or_delete_request);
  12452. callback_handler = NULL;
  12453. /* Here we are at a dead end:
  12454. * According to URI matching, a callback should be
  12455. * responsible for handling the request,
  12456. * we called it, but the callback declared itself
  12457. * not responsible.
  12458. * We use a goto here, to get out of this dead end,
  12459. * and continue with the default handling.
  12460. * A goto here is simpler and better to understand
  12461. * than some curious loop. */
  12462. goto no_callback_resource;
  12463. }
  12464. } else {
  12465. #if defined(USE_WEBSOCKET)
  12466. handle_websocket_request(conn,
  12467. path,
  12468. is_callback_resource,
  12469. subprotocols,
  12470. ws_connect_handler,
  12471. ws_ready_handler,
  12472. ws_data_handler,
  12473. ws_close_handler,
  12474. callback_data);
  12475. #endif
  12476. }
  12477. return;
  12478. }
  12479. /* 8. handle websocket requests */
  12480. #if defined(USE_WEBSOCKET)
  12481. if (is_websocket_request) {
  12482. if (is_script_resource) {
  12483. if (is_in_script_path(conn, path)) {
  12484. /* Websocket Lua script */
  12485. handle_websocket_request(conn,
  12486. path,
  12487. 0 /* Lua Script */,
  12488. NULL,
  12489. NULL,
  12490. NULL,
  12491. NULL,
  12492. NULL,
  12493. conn->phys_ctx->user_data);
  12494. } else {
  12495. /* Script was in an illegal path */
  12496. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12497. }
  12498. } else {
  12499. #if defined(MG_LEGACY_INTERFACE)
  12500. handle_websocket_request(
  12501. conn,
  12502. path,
  12503. !is_script_resource /* could be deprecated global callback
  12504. */
  12505. ,
  12506. NULL,
  12507. deprecated_websocket_connect_wrapper,
  12508. deprecated_websocket_ready_wrapper,
  12509. deprecated_websocket_data_wrapper,
  12510. NULL,
  12511. conn->phys_ctx->callbacks);
  12512. #else
  12513. mg_send_http_error(conn, 404, "%s", "Not found");
  12514. #endif
  12515. }
  12516. return;
  12517. } else
  12518. #endif
  12519. #if defined(NO_FILES)
  12520. /* 9a. In case the server uses only callbacks, this uri is
  12521. * unknown.
  12522. * Then, all request handling ends here. */
  12523. mg_send_http_error(conn, 404, "%s", "Not Found");
  12524. #else
  12525. /* 9b. This request is either for a static file or resource handled
  12526. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12527. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12528. mg_send_http_error(conn, 404, "%s", "Not Found");
  12529. return;
  12530. }
  12531. /* 10. Request is handled by a script */
  12532. if (is_script_resource) {
  12533. handle_file_based_request(conn, path, &file);
  12534. return;
  12535. }
  12536. /* 11. Handle put/delete/mkcol requests */
  12537. if (is_put_or_delete_request) {
  12538. /* 11.1. PUT method */
  12539. if (!strcmp(ri->request_method, "PUT")) {
  12540. put_file(conn, path);
  12541. return;
  12542. }
  12543. /* 11.2. DELETE method */
  12544. if (!strcmp(ri->request_method, "DELETE")) {
  12545. delete_file(conn, path);
  12546. return;
  12547. }
  12548. /* 11.3. MKCOL method */
  12549. if (!strcmp(ri->request_method, "MKCOL")) {
  12550. mkcol(conn, path);
  12551. return;
  12552. }
  12553. /* 11.4. PATCH method
  12554. * This method is not supported for static resources,
  12555. * only for scripts (Lua, CGI) and callbacks. */
  12556. mg_send_http_error(conn,
  12557. 405,
  12558. "%s method not allowed",
  12559. conn->request_info.request_method);
  12560. return;
  12561. }
  12562. /* 11. File does not exist, or it was configured that it should be
  12563. * hidden */
  12564. if (!is_found || (must_hide_file(conn, path))) {
  12565. mg_send_http_error(conn, 404, "%s", "Not found");
  12566. return;
  12567. }
  12568. /* 12. Directory uris should end with a slash */
  12569. if (file.stat.is_directory && (uri_len > 0)
  12570. && (ri->local_uri[uri_len - 1] != '/')) {
  12571. gmt_time_string(date, sizeof(date), &curtime);
  12572. mg_printf(conn,
  12573. "HTTP/1.1 301 Moved Permanently\r\n"
  12574. "Location: %s/\r\n"
  12575. "Date: %s\r\n"
  12576. /* "Cache-Control: private\r\n" (= default) */
  12577. "Content-Length: 0\r\n"
  12578. "Connection: %s\r\n",
  12579. ri->request_uri,
  12580. date,
  12581. suggest_connection_header(conn));
  12582. send_additional_header(conn);
  12583. mg_printf(conn, "\r\n");
  12584. return;
  12585. }
  12586. /* 13. Handle other methods than GET/HEAD */
  12587. /* 13.1. Handle PROPFIND */
  12588. if (!strcmp(ri->request_method, "PROPFIND")) {
  12589. handle_propfind(conn, path, &file.stat);
  12590. return;
  12591. }
  12592. /* 13.2. Handle OPTIONS for files */
  12593. if (!strcmp(ri->request_method, "OPTIONS")) {
  12594. /* This standard handler is only used for real files.
  12595. * Scripts should support the OPTIONS method themselves, to allow a
  12596. * maximum flexibility.
  12597. * Lua and CGI scripts may fully support CORS this way (including
  12598. * preflights). */
  12599. send_options(conn);
  12600. return;
  12601. }
  12602. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12603. if ((0 != strcmp(ri->request_method, "GET"))
  12604. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12605. mg_send_http_error(conn,
  12606. 405,
  12607. "%s method not allowed",
  12608. conn->request_info.request_method);
  12609. return;
  12610. }
  12611. /* 14. directories */
  12612. if (file.stat.is_directory) {
  12613. /* Substitute files have already been handled above. */
  12614. /* Here we can either generate and send a directory listing,
  12615. * or send an "access denied" error. */
  12616. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12617. "yes")) {
  12618. handle_directory_request(conn, path);
  12619. } else {
  12620. mg_send_http_error(conn,
  12621. 403,
  12622. "%s",
  12623. "Error: Directory listing denied");
  12624. }
  12625. return;
  12626. }
  12627. /* 15. read a normal file with GET or HEAD */
  12628. handle_file_based_request(conn, path, &file);
  12629. #endif /* !defined(NO_FILES) */
  12630. }
  12631. /* Include HTTP/2 modules */
  12632. #ifdef USE_HTTP2
  12633. #if defined(NO_SSL)
  12634. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12635. #endif
  12636. #include "mod_http2.inl"
  12637. #endif
  12638. #if !defined(NO_FILESYSTEMS)
  12639. static void
  12640. handle_file_based_request(struct mg_connection *conn,
  12641. const char *path,
  12642. struct mg_file *file)
  12643. {
  12644. if (!conn || !conn->dom_ctx) {
  12645. return;
  12646. }
  12647. if (0) {
  12648. #if defined(USE_LUA)
  12649. } else if (match_prefix(
  12650. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12651. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12652. path)
  12653. > 0) {
  12654. if (is_in_script_path(conn, path)) {
  12655. /* Lua server page: an SSI like page containing mostly plain
  12656. * html
  12657. * code
  12658. * plus some tags with server generated contents. */
  12659. handle_lsp_request(conn, path, file, NULL);
  12660. } else {
  12661. /* Script was in an illegal path */
  12662. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12663. }
  12664. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12665. strlen(
  12666. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12667. path)
  12668. > 0) {
  12669. if (is_in_script_path(conn, path)) {
  12670. /* Lua in-server module script: a CGI like script used to
  12671. * generate
  12672. * the
  12673. * entire reply. */
  12674. mg_exec_lua_script(conn, path, NULL);
  12675. } else {
  12676. /* Script was in an illegal path */
  12677. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12678. }
  12679. #endif
  12680. #if defined(USE_DUKTAPE)
  12681. } else if (match_prefix(
  12682. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12683. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12684. path)
  12685. > 0) {
  12686. if (is_in_script_path(conn, path)) {
  12687. /* Call duktape to generate the page */
  12688. mg_exec_duktape_script(conn, path);
  12689. } else {
  12690. /* Script was in an illegal path */
  12691. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12692. }
  12693. #endif
  12694. #if !defined(NO_CGI)
  12695. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12696. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12697. path)
  12698. > 0) {
  12699. if (is_in_script_path(conn, path)) {
  12700. /* CGI scripts may support all HTTP methods */
  12701. handle_cgi_request(conn, path);
  12702. } else {
  12703. /* Script was in an illegal path */
  12704. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12705. }
  12706. #endif /* !NO_CGI */
  12707. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12708. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12709. path)
  12710. > 0) {
  12711. if (is_in_script_path(conn, path)) {
  12712. handle_ssi_file_request(conn, path, file);
  12713. } else {
  12714. /* Script was in an illegal path */
  12715. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12716. }
  12717. #if !defined(NO_CACHING)
  12718. } else if ((!conn->in_error_handler)
  12719. && is_not_modified(conn, &file->stat)) {
  12720. /* Send 304 "Not Modified" - this must not send any body data */
  12721. handle_not_modified_static_file_request(conn, file);
  12722. #endif /* !NO_CACHING */
  12723. } else {
  12724. handle_static_file_request(conn, path, file, NULL, NULL);
  12725. }
  12726. }
  12727. #endif /* NO_FILESYSTEMS */
  12728. static void
  12729. close_all_listening_sockets(struct mg_context *ctx)
  12730. {
  12731. unsigned int i;
  12732. if (!ctx) {
  12733. return;
  12734. }
  12735. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12736. closesocket(ctx->listening_sockets[i].sock);
  12737. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12738. }
  12739. mg_free(ctx->listening_sockets);
  12740. ctx->listening_sockets = NULL;
  12741. mg_free(ctx->listening_socket_fds);
  12742. ctx->listening_socket_fds = NULL;
  12743. }
  12744. /* Valid listening port specification is: [ip_address:]port[s]
  12745. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12746. * Examples for IPv6: [::]:80, [::1]:80,
  12747. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12748. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12749. * In order to bind to both, IPv4 and IPv6, you can either add
  12750. * both ports using 8080,[::]:8080, or the short form +8080.
  12751. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12752. * one only accepting IPv4 the other only IPv6. +8080 creates
  12753. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12754. * environment, they might work differently, or might not work
  12755. * at all - it must be tested what options work best in the
  12756. * relevant network environment.
  12757. */
  12758. static int
  12759. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12760. {
  12761. unsigned int a, b, c, d;
  12762. unsigned port;
  12763. unsigned long portUL;
  12764. int ch, len;
  12765. const char *cb;
  12766. char *endptr;
  12767. #if defined(USE_IPV6)
  12768. char buf[100] = {0};
  12769. #endif
  12770. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12771. * Also, all-zeroes in the socket address means binding to all addresses
  12772. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12773. memset(so, 0, sizeof(*so));
  12774. so->lsa.sin.sin_family = AF_INET;
  12775. *ip_version = 0;
  12776. /* Initialize port and len as invalid. */
  12777. port = 0;
  12778. len = 0;
  12779. /* Test for different ways to format this string */
  12780. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12781. == 5) {
  12782. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12783. so->lsa.sin.sin_addr.s_addr =
  12784. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12785. so->lsa.sin.sin_port = htons((uint16_t)port);
  12786. *ip_version = 4;
  12787. #if defined(USE_IPV6)
  12788. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12789. && mg_inet_pton(
  12790. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12791. /* IPv6 address, examples: see above */
  12792. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12793. */
  12794. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12795. *ip_version = 6;
  12796. #endif
  12797. } else if ((vec->ptr[0] == '+')
  12798. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12799. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12800. /* Add 1 to len for the + character we skipped before */
  12801. len++;
  12802. #if defined(USE_IPV6)
  12803. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12804. so->lsa.sin6.sin6_family = AF_INET6;
  12805. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12806. *ip_version = 4 + 6;
  12807. #else
  12808. /* Bind to IPv4 only, since IPv6 is not built in. */
  12809. so->lsa.sin.sin_port = htons((uint16_t)port);
  12810. *ip_version = 4;
  12811. #endif
  12812. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12813. && (vec->ptr != endptr)) {
  12814. len = (int)(endptr - vec->ptr);
  12815. port = (uint16_t)portUL;
  12816. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12817. so->lsa.sin.sin_port = htons((uint16_t)port);
  12818. *ip_version = 4;
  12819. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12820. /* String could be a hostname. This check algotithm
  12821. * will only work for RFC 952 compliant hostnames,
  12822. * starting with a letter, containing only letters,
  12823. * digits and hyphen ('-'). Newer specs may allow
  12824. * more, but this is not guaranteed here, since it
  12825. * may interfere with rules for port option lists. */
  12826. /* According to RFC 1035, hostnames are restricted to 255 characters
  12827. * in total (63 between two dots). */
  12828. char hostname[256];
  12829. size_t hostnlen = (size_t)(cb - vec->ptr);
  12830. if (hostnlen >= sizeof(hostname)) {
  12831. /* This would be invalid in any case */
  12832. *ip_version = 0;
  12833. return 0;
  12834. }
  12835. memcpy(hostname, vec->ptr, hostnlen);
  12836. hostname[hostnlen] = 0;
  12837. if (mg_inet_pton(
  12838. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12839. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12840. *ip_version = 4;
  12841. so->lsa.sin.sin_family = AF_INET;
  12842. so->lsa.sin.sin_port = htons((uint16_t)port);
  12843. len += (int)(hostnlen + 1);
  12844. } else {
  12845. port = 0;
  12846. len = 0;
  12847. }
  12848. #if defined(USE_IPV6)
  12849. } else if (mg_inet_pton(AF_INET6,
  12850. hostname,
  12851. &so->lsa.sin6,
  12852. sizeof(so->lsa.sin6))) {
  12853. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12854. *ip_version = 6;
  12855. so->lsa.sin6.sin6_family = AF_INET6;
  12856. so->lsa.sin.sin_port = htons((uint16_t)port);
  12857. len += (int)(hostnlen + 1);
  12858. } else {
  12859. port = 0;
  12860. len = 0;
  12861. }
  12862. #endif
  12863. }
  12864. } else {
  12865. /* Parsing failure. */
  12866. }
  12867. /* sscanf and the option splitting code ensure the following condition
  12868. */
  12869. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12870. *ip_version = 0;
  12871. return 0;
  12872. }
  12873. ch = vec->ptr[len]; /* Next character after the port number */
  12874. so->is_ssl = (ch == 's');
  12875. so->ssl_redir = (ch == 'r');
  12876. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12877. if (is_valid_port(port)
  12878. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12879. return 1;
  12880. }
  12881. /* Reset ip_version to 0 if there is an error */
  12882. *ip_version = 0;
  12883. return 0;
  12884. }
  12885. /* Is there any SSL port in use? */
  12886. static int
  12887. is_ssl_port_used(const char *ports)
  12888. {
  12889. if (ports) {
  12890. /* There are several different allowed syntax variants:
  12891. * - "80" for a single port using every network interface
  12892. * - "localhost:80" for a single port using only localhost
  12893. * - "80,localhost:8080" for two ports, one bound to localhost
  12894. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12895. * to IPv4 localhost, one to IPv6 localhost
  12896. * - "+80" use port 80 for IPv4 and IPv6
  12897. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12898. * for both: IPv4 and IPv4
  12899. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12900. * additionally port 8080 bound to localhost connections
  12901. *
  12902. * If we just look for 's' anywhere in the string, "localhost:80"
  12903. * will be detected as SSL (false positive).
  12904. * Looking for 's' after a digit may cause false positives in
  12905. * "my24service:8080".
  12906. * Looking from 's' backward if there are only ':' and numbers
  12907. * before will not work for "24service:8080" (non SSL, port 8080)
  12908. * or "24s" (SSL, port 24).
  12909. *
  12910. * Remark: Initially hostnames were not allowed to start with a
  12911. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12912. * Section 2.1).
  12913. *
  12914. * To get this correct, the entire string must be parsed as a whole,
  12915. * reading it as a list element for element and parsing with an
  12916. * algorithm equivalent to parse_port_string.
  12917. *
  12918. * In fact, we use local interface names here, not arbitrary
  12919. * hostnames, so in most cases the only name will be "localhost".
  12920. *
  12921. * So, for now, we use this simple algorithm, that may still return
  12922. * a false positive in bizarre cases.
  12923. */
  12924. int i;
  12925. int portslen = (int)strlen(ports);
  12926. char prevIsNumber = 0;
  12927. for (i = 0; i < portslen; i++) {
  12928. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12929. return 1;
  12930. }
  12931. if (ports[i] >= '0' && ports[i] <= '9') {
  12932. prevIsNumber = 1;
  12933. } else {
  12934. prevIsNumber = 0;
  12935. }
  12936. }
  12937. }
  12938. return 0;
  12939. }
  12940. static int
  12941. set_ports_option(struct mg_context *phys_ctx)
  12942. {
  12943. const char *list;
  12944. int on = 1;
  12945. #if defined(USE_IPV6)
  12946. int off = 0;
  12947. #endif
  12948. struct vec vec;
  12949. struct socket so, *ptr;
  12950. struct mg_pollfd *pfd;
  12951. union usa usa;
  12952. socklen_t len;
  12953. int ip_version;
  12954. int portsTotal = 0;
  12955. int portsOk = 0;
  12956. const char *opt_txt;
  12957. long opt_listen_backlog;
  12958. if (!phys_ctx) {
  12959. return 0;
  12960. }
  12961. memset(&so, 0, sizeof(so));
  12962. memset(&usa, 0, sizeof(usa));
  12963. len = sizeof(usa);
  12964. list = phys_ctx->dd.config[LISTENING_PORTS];
  12965. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12966. portsTotal++;
  12967. if (!parse_port_string(&vec, &so, &ip_version)) {
  12968. mg_cry_ctx_internal(
  12969. phys_ctx,
  12970. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12971. (int)vec.len,
  12972. vec.ptr,
  12973. portsTotal,
  12974. "[IP_ADDRESS:]PORT[s|r]");
  12975. continue;
  12976. }
  12977. #if !defined(NO_SSL)
  12978. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12979. mg_cry_ctx_internal(phys_ctx,
  12980. "Cannot add SSL socket (entry %i)",
  12981. portsTotal);
  12982. continue;
  12983. }
  12984. #endif
  12985. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12986. == INVALID_SOCKET) {
  12987. mg_cry_ctx_internal(phys_ctx,
  12988. "cannot create socket (entry %i)",
  12989. portsTotal);
  12990. continue;
  12991. }
  12992. #if defined(_WIN32)
  12993. /* Windows SO_REUSEADDR lets many procs binds to a
  12994. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12995. * if someone already has the socket -- DTL */
  12996. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12997. * Windows might need a few seconds before
  12998. * the same port can be used again in the
  12999. * same process, so a short Sleep may be
  13000. * required between mg_stop and mg_start.
  13001. */
  13002. if (setsockopt(so.sock,
  13003. SOL_SOCKET,
  13004. SO_EXCLUSIVEADDRUSE,
  13005. (SOCK_OPT_TYPE)&on,
  13006. sizeof(on))
  13007. != 0) {
  13008. /* Set reuse option, but don't abort on errors. */
  13009. mg_cry_ctx_internal(
  13010. phys_ctx,
  13011. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13012. portsTotal);
  13013. }
  13014. #else
  13015. if (setsockopt(so.sock,
  13016. SOL_SOCKET,
  13017. SO_REUSEADDR,
  13018. (SOCK_OPT_TYPE)&on,
  13019. sizeof(on))
  13020. != 0) {
  13021. /* Set reuse option, but don't abort on errors. */
  13022. mg_cry_ctx_internal(
  13023. phys_ctx,
  13024. "cannot set socket option SO_REUSEADDR (entry %i)",
  13025. portsTotal);
  13026. }
  13027. #endif
  13028. if (ip_version > 4) {
  13029. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13030. #if defined(USE_IPV6)
  13031. if (ip_version > 6) {
  13032. if (so.lsa.sa.sa_family == AF_INET6
  13033. && setsockopt(so.sock,
  13034. IPPROTO_IPV6,
  13035. IPV6_V6ONLY,
  13036. (void *)&off,
  13037. sizeof(off))
  13038. != 0) {
  13039. /* Set IPv6 only option, but don't abort on errors. */
  13040. mg_cry_ctx_internal(phys_ctx,
  13041. "cannot set socket option "
  13042. "IPV6_V6ONLY=off (entry %i)",
  13043. portsTotal);
  13044. }
  13045. } else {
  13046. if (so.lsa.sa.sa_family == AF_INET6
  13047. && setsockopt(so.sock,
  13048. IPPROTO_IPV6,
  13049. IPV6_V6ONLY,
  13050. (void *)&on,
  13051. sizeof(on))
  13052. != 0) {
  13053. /* Set IPv6 only option, but don't abort on errors. */
  13054. mg_cry_ctx_internal(phys_ctx,
  13055. "cannot set socket option "
  13056. "IPV6_V6ONLY=on (entry %i)",
  13057. portsTotal);
  13058. }
  13059. }
  13060. #else
  13061. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13062. closesocket(so.sock);
  13063. so.sock = INVALID_SOCKET;
  13064. continue;
  13065. #endif
  13066. }
  13067. if (so.lsa.sa.sa_family == AF_INET) {
  13068. len = sizeof(so.lsa.sin);
  13069. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13070. mg_cry_ctx_internal(phys_ctx,
  13071. "cannot bind to %.*s: %d (%s)",
  13072. (int)vec.len,
  13073. vec.ptr,
  13074. (int)ERRNO,
  13075. strerror(errno));
  13076. closesocket(so.sock);
  13077. so.sock = INVALID_SOCKET;
  13078. continue;
  13079. }
  13080. }
  13081. #if defined(USE_IPV6)
  13082. else if (so.lsa.sa.sa_family == AF_INET6) {
  13083. len = sizeof(so.lsa.sin6);
  13084. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13085. mg_cry_ctx_internal(phys_ctx,
  13086. "cannot bind to IPv6 %.*s: %d (%s)",
  13087. (int)vec.len,
  13088. vec.ptr,
  13089. (int)ERRNO,
  13090. strerror(errno));
  13091. closesocket(so.sock);
  13092. so.sock = INVALID_SOCKET;
  13093. continue;
  13094. }
  13095. }
  13096. #endif
  13097. else {
  13098. mg_cry_ctx_internal(
  13099. phys_ctx,
  13100. "cannot bind: address family not supported (entry %i)",
  13101. portsTotal);
  13102. closesocket(so.sock);
  13103. so.sock = INVALID_SOCKET;
  13104. continue;
  13105. }
  13106. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13107. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13108. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13109. mg_cry_ctx_internal(phys_ctx,
  13110. "%s value \"%s\" is invalid",
  13111. config_options[LISTEN_BACKLOG_SIZE].name,
  13112. opt_txt);
  13113. closesocket(so.sock);
  13114. so.sock = INVALID_SOCKET;
  13115. continue;
  13116. }
  13117. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13118. mg_cry_ctx_internal(phys_ctx,
  13119. "cannot listen to %.*s: %d (%s)",
  13120. (int)vec.len,
  13121. vec.ptr,
  13122. (int)ERRNO,
  13123. strerror(errno));
  13124. closesocket(so.sock);
  13125. so.sock = INVALID_SOCKET;
  13126. continue;
  13127. }
  13128. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13129. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13130. int err = (int)ERRNO;
  13131. mg_cry_ctx_internal(phys_ctx,
  13132. "call to getsockname failed %.*s: %d (%s)",
  13133. (int)vec.len,
  13134. vec.ptr,
  13135. err,
  13136. strerror(errno));
  13137. closesocket(so.sock);
  13138. so.sock = INVALID_SOCKET;
  13139. continue;
  13140. }
  13141. /* Update lsa port in case of random free ports */
  13142. #if defined(USE_IPV6)
  13143. if (so.lsa.sa.sa_family == AF_INET6) {
  13144. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13145. } else
  13146. #endif
  13147. {
  13148. so.lsa.sin.sin_port = usa.sin.sin_port;
  13149. }
  13150. if ((ptr = (struct socket *)
  13151. mg_realloc_ctx(phys_ctx->listening_sockets,
  13152. (phys_ctx->num_listening_sockets + 1)
  13153. * sizeof(phys_ctx->listening_sockets[0]),
  13154. phys_ctx))
  13155. == NULL) {
  13156. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13157. closesocket(so.sock);
  13158. so.sock = INVALID_SOCKET;
  13159. continue;
  13160. }
  13161. if ((pfd = (struct mg_pollfd *)
  13162. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13163. (phys_ctx->num_listening_sockets + 1)
  13164. * sizeof(phys_ctx->listening_socket_fds[0]),
  13165. phys_ctx))
  13166. == NULL) {
  13167. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13168. closesocket(so.sock);
  13169. so.sock = INVALID_SOCKET;
  13170. mg_free(ptr);
  13171. continue;
  13172. }
  13173. set_close_on_exec(so.sock, NULL, phys_ctx);
  13174. phys_ctx->listening_sockets = ptr;
  13175. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13176. phys_ctx->listening_socket_fds = pfd;
  13177. phys_ctx->num_listening_sockets++;
  13178. portsOk++;
  13179. }
  13180. if (portsOk != portsTotal) {
  13181. close_all_listening_sockets(phys_ctx);
  13182. portsOk = 0;
  13183. }
  13184. return portsOk;
  13185. }
  13186. static const char *
  13187. header_val(const struct mg_connection *conn, const char *header)
  13188. {
  13189. const char *header_value;
  13190. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13191. return "-";
  13192. } else {
  13193. return header_value;
  13194. }
  13195. }
  13196. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13197. static void log_access(const struct mg_connection *conn);
  13198. #include "external_log_access.inl"
  13199. #elif !defined(NO_FILESYSTEMS)
  13200. static void
  13201. log_access(const struct mg_connection *conn)
  13202. {
  13203. const struct mg_request_info *ri;
  13204. struct mg_file fi;
  13205. char date[64], src_addr[IP_ADDR_STR_LEN];
  13206. struct tm *tm;
  13207. const char *referer;
  13208. const char *user_agent;
  13209. char buf[4096];
  13210. if (!conn || !conn->dom_ctx) {
  13211. return;
  13212. }
  13213. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13214. if (mg_fopen(conn,
  13215. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13216. MG_FOPEN_MODE_APPEND,
  13217. &fi)
  13218. == 0) {
  13219. fi.access.fp = NULL;
  13220. }
  13221. } else {
  13222. fi.access.fp = NULL;
  13223. }
  13224. /* Log is written to a file and/or a callback. If both are not set,
  13225. * executing the rest of the function is pointless. */
  13226. if ((fi.access.fp == NULL)
  13227. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13228. return;
  13229. }
  13230. tm = localtime(&conn->conn_birth_time);
  13231. if (tm != NULL) {
  13232. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13233. } else {
  13234. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13235. date[sizeof(date) - 1] = '\0';
  13236. }
  13237. ri = &conn->request_info;
  13238. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13239. referer = header_val(conn, "Referer");
  13240. user_agent = header_val(conn, "User-Agent");
  13241. mg_snprintf(conn,
  13242. NULL, /* Ignore truncation in access log */
  13243. buf,
  13244. sizeof(buf),
  13245. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13246. src_addr,
  13247. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13248. date,
  13249. ri->request_method ? ri->request_method : "-",
  13250. ri->request_uri ? ri->request_uri : "-",
  13251. ri->query_string ? "?" : "",
  13252. ri->query_string ? ri->query_string : "",
  13253. ri->http_version,
  13254. conn->status_code,
  13255. conn->num_bytes_sent,
  13256. referer,
  13257. user_agent);
  13258. if (conn->phys_ctx->callbacks.log_access) {
  13259. conn->phys_ctx->callbacks.log_access(conn, buf);
  13260. }
  13261. if (fi.access.fp) {
  13262. int ok = 1;
  13263. flockfile(fi.access.fp);
  13264. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13265. ok = 0;
  13266. }
  13267. if (fflush(fi.access.fp) != 0) {
  13268. ok = 0;
  13269. }
  13270. funlockfile(fi.access.fp);
  13271. if (mg_fclose(&fi.access) != 0) {
  13272. ok = 0;
  13273. }
  13274. if (!ok) {
  13275. mg_cry_internal(conn,
  13276. "Error writing log file %s",
  13277. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13278. }
  13279. }
  13280. }
  13281. #else
  13282. #error Must either enable filesystems or provide a custom log_access implementation
  13283. #endif /* Externally provided function */
  13284. /* Verify given socket address against the ACL.
  13285. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13286. */
  13287. static int
  13288. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13289. {
  13290. int allowed, flag;
  13291. uint32_t net, mask;
  13292. struct vec vec;
  13293. if (phys_ctx) {
  13294. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13295. /* If any ACL is set, deny by default */
  13296. allowed = (list == NULL) ? '+' : '-';
  13297. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13298. flag = vec.ptr[0];
  13299. if ((flag != '+' && flag != '-')
  13300. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13301. mg_cry_ctx_internal(phys_ctx,
  13302. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13303. __func__);
  13304. return -1;
  13305. }
  13306. if (net == (remote_ip & mask)) {
  13307. allowed = flag;
  13308. }
  13309. }
  13310. return allowed == '+';
  13311. }
  13312. return -1;
  13313. }
  13314. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13315. static int
  13316. set_uid_option(struct mg_context *phys_ctx)
  13317. {
  13318. int success = 0;
  13319. if (phys_ctx) {
  13320. /* We are currently running as curr_uid. */
  13321. const uid_t curr_uid = getuid();
  13322. /* If set, we want to run as run_as_user. */
  13323. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13324. const struct passwd *to_pw = NULL;
  13325. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13326. /* run_as_user does not exist on the system. We can't proceed
  13327. * further. */
  13328. mg_cry_ctx_internal(phys_ctx,
  13329. "%s: unknown user [%s]",
  13330. __func__,
  13331. run_as_user);
  13332. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13333. /* There was either no request to change user, or we're already
  13334. * running as run_as_user. Nothing else to do.
  13335. */
  13336. success = 1;
  13337. } else {
  13338. /* Valid change request. */
  13339. if (setgid(to_pw->pw_gid) == -1) {
  13340. mg_cry_ctx_internal(phys_ctx,
  13341. "%s: setgid(%s): %s",
  13342. __func__,
  13343. run_as_user,
  13344. strerror(errno));
  13345. } else if (setgroups(0, NULL) == -1) {
  13346. mg_cry_ctx_internal(phys_ctx,
  13347. "%s: setgroups(): %s",
  13348. __func__,
  13349. strerror(errno));
  13350. } else if (setuid(to_pw->pw_uid) == -1) {
  13351. mg_cry_ctx_internal(phys_ctx,
  13352. "%s: setuid(%s): %s",
  13353. __func__,
  13354. run_as_user,
  13355. strerror(errno));
  13356. } else {
  13357. success = 1;
  13358. }
  13359. }
  13360. }
  13361. return success;
  13362. }
  13363. #endif /* !_WIN32 */
  13364. static void
  13365. tls_dtor(void *key)
  13366. {
  13367. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13368. /* key == pthread_getspecific(sTlsKey); */
  13369. if (tls) {
  13370. if (tls->is_master == 2) {
  13371. tls->is_master = -3; /* Mark memory as dead */
  13372. mg_free(tls);
  13373. }
  13374. }
  13375. pthread_setspecific(sTlsKey, NULL);
  13376. }
  13377. #if !defined(NO_SSL)
  13378. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13379. struct mg_domain_context *dom_ctx,
  13380. const char *pem,
  13381. const char *chain);
  13382. static const char *ssl_error(void);
  13383. static int
  13384. refresh_trust(struct mg_connection *conn)
  13385. {
  13386. struct stat cert_buf;
  13387. int64_t t = 0;
  13388. const char *pem;
  13389. const char *chain;
  13390. int should_verify_peer;
  13391. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13392. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13393. * refresh_trust still can not work. */
  13394. return 0;
  13395. }
  13396. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13397. if (chain == NULL) {
  13398. /* pem is not NULL here */
  13399. chain = pem;
  13400. }
  13401. if (*chain == 0) {
  13402. chain = NULL;
  13403. }
  13404. if (stat(pem, &cert_buf) != -1) {
  13405. t = (int64_t)cert_buf.st_mtime;
  13406. }
  13407. mg_lock_context(conn->phys_ctx);
  13408. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13409. conn->dom_ctx->ssl_cert_last_mtime = t;
  13410. should_verify_peer = 0;
  13411. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13412. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13413. == 0) {
  13414. should_verify_peer = 1;
  13415. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13416. "optional")
  13417. == 0) {
  13418. should_verify_peer = 1;
  13419. }
  13420. }
  13421. if (should_verify_peer) {
  13422. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13423. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13424. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13425. ca_file,
  13426. ca_path)
  13427. != 1) {
  13428. mg_unlock_context(conn->phys_ctx);
  13429. mg_cry_ctx_internal(
  13430. conn->phys_ctx,
  13431. "SSL_CTX_load_verify_locations error: %s "
  13432. "ssl_verify_peer requires setting "
  13433. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13434. "present in "
  13435. "the .conf file?",
  13436. ssl_error());
  13437. return 0;
  13438. }
  13439. }
  13440. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13441. == 0) {
  13442. mg_unlock_context(conn->phys_ctx);
  13443. return 0;
  13444. }
  13445. }
  13446. mg_unlock_context(conn->phys_ctx);
  13447. return 1;
  13448. }
  13449. #if defined(OPENSSL_API_1_1)
  13450. #else
  13451. static pthread_mutex_t *ssl_mutexes;
  13452. #endif /* OPENSSL_API_1_1 */
  13453. static int
  13454. sslize(struct mg_connection *conn,
  13455. int (*func)(SSL *),
  13456. const struct mg_client_options *client_options)
  13457. {
  13458. int ret, err;
  13459. int short_trust;
  13460. unsigned timeout = 1024;
  13461. unsigned i;
  13462. if (!conn) {
  13463. return 0;
  13464. }
  13465. short_trust =
  13466. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13467. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13468. if (short_trust) {
  13469. int trust_ret = refresh_trust(conn);
  13470. if (!trust_ret) {
  13471. return trust_ret;
  13472. }
  13473. }
  13474. mg_lock_context(conn->phys_ctx);
  13475. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13476. mg_unlock_context(conn->phys_ctx);
  13477. if (conn->ssl == NULL) {
  13478. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13479. OPENSSL_REMOVE_THREAD_STATE();
  13480. return 0;
  13481. }
  13482. SSL_set_app_data(conn->ssl, (char *)conn);
  13483. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13484. if (ret != 1) {
  13485. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13486. SSL_free(conn->ssl);
  13487. conn->ssl = NULL;
  13488. OPENSSL_REMOVE_THREAD_STATE();
  13489. return 0;
  13490. }
  13491. if (client_options) {
  13492. if (client_options->host_name) {
  13493. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13494. }
  13495. }
  13496. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13497. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13498. /* NOTE: The loop below acts as a back-off, so we can end
  13499. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13500. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13501. if (to >= 0) {
  13502. timeout = (unsigned)to;
  13503. }
  13504. }
  13505. /* SSL functions may fail and require to be called again:
  13506. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13507. * Here "func" could be SSL_connect or SSL_accept. */
  13508. for (i = 0; i <= timeout; i += 50) {
  13509. ERR_clear_error();
  13510. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13511. ret = func(conn->ssl);
  13512. if (ret != 1) {
  13513. err = SSL_get_error(conn->ssl, ret);
  13514. if ((err == SSL_ERROR_WANT_CONNECT)
  13515. || (err == SSL_ERROR_WANT_ACCEPT)
  13516. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13517. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13518. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13519. /* Don't wait if the server is going to be stopped. */
  13520. break;
  13521. }
  13522. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13523. /* Simply retry the function call. */
  13524. mg_sleep(50);
  13525. } else {
  13526. /* Need to retry the function call "later".
  13527. * See https://linux.die.net/man/3/ssl_get_error
  13528. * This is typical for non-blocking sockets. */
  13529. struct mg_pollfd pfd;
  13530. int pollres;
  13531. pfd.fd = conn->client.sock;
  13532. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13533. || (err == SSL_ERROR_WANT_WRITE))
  13534. ? POLLOUT
  13535. : POLLIN;
  13536. pollres = mg_poll(&pfd, 1, 50,
  13537. &(conn->phys_ctx->stop_flag));
  13538. if (pollres < 0) {
  13539. /* Break if error occured (-1)
  13540. * or server shutdown (-2) */
  13541. break;
  13542. }
  13543. }
  13544. } else if (err == SSL_ERROR_SYSCALL) {
  13545. /* This is an IO error. Look at errno. */
  13546. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13547. break;
  13548. } else {
  13549. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13550. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13551. break;
  13552. }
  13553. } else {
  13554. /* success */
  13555. break;
  13556. }
  13557. }
  13558. ERR_clear_error();
  13559. if (ret != 1) {
  13560. SSL_free(conn->ssl);
  13561. conn->ssl = NULL;
  13562. OPENSSL_REMOVE_THREAD_STATE();
  13563. return 0;
  13564. }
  13565. return 1;
  13566. }
  13567. /* Return OpenSSL error message (from CRYPTO lib) */
  13568. static const char *
  13569. ssl_error(void)
  13570. {
  13571. unsigned long err;
  13572. err = ERR_get_error();
  13573. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13574. }
  13575. static int
  13576. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13577. {
  13578. int i;
  13579. const char hexdigit[] = "0123456789abcdef";
  13580. if ((memlen <= 0) || (buflen <= 0)) {
  13581. return 0;
  13582. }
  13583. if (buflen < (3 * memlen)) {
  13584. return 0;
  13585. }
  13586. for (i = 0; i < memlen; i++) {
  13587. if (i > 0) {
  13588. buf[3 * i - 1] = ' ';
  13589. }
  13590. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13591. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13592. }
  13593. buf[3 * memlen - 1] = 0;
  13594. return 1;
  13595. }
  13596. static int
  13597. ssl_get_client_cert_info(const struct mg_connection *conn,
  13598. struct mg_client_cert *client_cert)
  13599. {
  13600. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13601. if (cert) {
  13602. char str_buf[1024];
  13603. unsigned char buf[256];
  13604. char *str_serial = NULL;
  13605. unsigned int ulen;
  13606. int ilen;
  13607. unsigned char *tmp_buf;
  13608. unsigned char *tmp_p;
  13609. /* Handle to algorithm used for fingerprint */
  13610. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13611. /* Get Subject and issuer */
  13612. X509_NAME *subj = X509_get_subject_name(cert);
  13613. X509_NAME *iss = X509_get_issuer_name(cert);
  13614. /* Get serial number */
  13615. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13616. /* Translate serial number to a hex string */
  13617. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13618. if (serial_bn) {
  13619. str_serial = BN_bn2hex(serial_bn);
  13620. BN_free(serial_bn);
  13621. }
  13622. client_cert->serial =
  13623. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13624. /* Translate subject and issuer to a string */
  13625. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13626. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13627. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13628. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13629. /* Calculate SHA1 fingerprint and store as a hex string */
  13630. ulen = 0;
  13631. /* ASN1_digest is deprecated. Do the calculation manually,
  13632. * using EVP_Digest. */
  13633. ilen = i2d_X509(cert, NULL);
  13634. tmp_buf = (ilen > 0)
  13635. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13636. conn->phys_ctx)
  13637. : NULL;
  13638. if (tmp_buf) {
  13639. tmp_p = tmp_buf;
  13640. (void)i2d_X509(cert, &tmp_p);
  13641. if (!EVP_Digest(
  13642. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13643. ulen = 0;
  13644. }
  13645. mg_free(tmp_buf);
  13646. }
  13647. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13648. *str_buf = 0;
  13649. }
  13650. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13651. client_cert->peer_cert = (void *)cert;
  13652. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13653. * see https://linux.die.net/man/3/bn_bn2hex */
  13654. OPENSSL_free(str_serial);
  13655. return 1;
  13656. }
  13657. return 0;
  13658. }
  13659. #if defined(OPENSSL_API_1_1)
  13660. #else
  13661. static void
  13662. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13663. {
  13664. (void)line;
  13665. (void)file;
  13666. if (mode & 1) {
  13667. /* 1 is CRYPTO_LOCK */
  13668. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13669. } else {
  13670. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13671. }
  13672. }
  13673. #endif /* OPENSSL_API_1_1 */
  13674. #if !defined(NO_SSL_DL)
  13675. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13676. static void *
  13677. load_tls_dll(char *ebuf,
  13678. size_t ebuf_len,
  13679. const char *dll_name,
  13680. struct ssl_func *sw)
  13681. {
  13682. union {
  13683. void *p;
  13684. void (*fp)(void);
  13685. } u;
  13686. void *dll_handle;
  13687. struct ssl_func *fp;
  13688. int ok;
  13689. int truncated = 0;
  13690. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13691. mg_snprintf(NULL,
  13692. NULL, /* No truncation check for ebuf */
  13693. ebuf,
  13694. ebuf_len,
  13695. "%s: cannot load %s",
  13696. __func__,
  13697. dll_name);
  13698. return NULL;
  13699. }
  13700. ok = 1;
  13701. for (fp = sw; fp->name != NULL; fp++) {
  13702. enum ssl_func_category req = fp->required;
  13703. #if defined(_WIN32)
  13704. /* GetProcAddress() returns pointer to function */
  13705. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13706. #else
  13707. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13708. * pointers to function pointers. We need to use a union to make a
  13709. * cast. */
  13710. u.p = dlsym(dll_handle, fp->name);
  13711. #endif /* _WIN32 */
  13712. /* Set pointer (might be NULL) */
  13713. fp->ptr = u.fp;
  13714. if (u.fp == NULL) {
  13715. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13716. tls_feature_missing[req]++;
  13717. if (req == TLS_Mandatory) {
  13718. /* Mandatory function is missing */
  13719. if (ok) {
  13720. /* This is the first missing function.
  13721. * Create a new error message. */
  13722. mg_snprintf(NULL,
  13723. &truncated,
  13724. ebuf,
  13725. ebuf_len,
  13726. "%s: %s: cannot find %s",
  13727. __func__,
  13728. dll_name,
  13729. fp->name);
  13730. ok = 0;
  13731. } else {
  13732. /* This is yet anothermissing function.
  13733. * Append existing error message. */
  13734. size_t cur_len = strlen(ebuf);
  13735. if (!truncated) {
  13736. mg_snprintf(NULL,
  13737. &truncated,
  13738. ebuf + cur_len,
  13739. ebuf_len - cur_len - 3,
  13740. ", %s",
  13741. fp->name);
  13742. if (truncated) {
  13743. /* If truncated, add "..." */
  13744. strcat(ebuf, "...");
  13745. }
  13746. }
  13747. }
  13748. }
  13749. }
  13750. }
  13751. if (!ok) {
  13752. (void)dlclose(dll_handle);
  13753. return NULL;
  13754. }
  13755. return dll_handle;
  13756. }
  13757. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13758. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13759. #endif /* NO_SSL_DL */
  13760. #if defined(SSL_ALREADY_INITIALIZED)
  13761. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13762. #else
  13763. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13764. #endif
  13765. static int
  13766. initialize_ssl(char *ebuf, size_t ebuf_len)
  13767. {
  13768. #if defined(OPENSSL_API_1_1)
  13769. if (ebuf_len > 0) {
  13770. ebuf[0] = 0;
  13771. }
  13772. #if !defined(NO_SSL_DL)
  13773. if (!cryptolib_dll_handle) {
  13774. cryptolib_dll_handle =
  13775. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13776. if (!cryptolib_dll_handle) {
  13777. mg_snprintf(NULL,
  13778. NULL, /* No truncation check for ebuf */
  13779. ebuf,
  13780. ebuf_len,
  13781. "%s: error loading library %s",
  13782. __func__,
  13783. CRYPTO_LIB);
  13784. DEBUG_TRACE("%s", ebuf);
  13785. return 0;
  13786. }
  13787. }
  13788. #endif /* NO_SSL_DL */
  13789. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13790. return 1;
  13791. }
  13792. #else /* not OPENSSL_API_1_1 */
  13793. int i, num_locks;
  13794. size_t size;
  13795. if (ebuf_len > 0) {
  13796. ebuf[0] = 0;
  13797. }
  13798. #if !defined(NO_SSL_DL)
  13799. if (!cryptolib_dll_handle) {
  13800. cryptolib_dll_handle =
  13801. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13802. if (!cryptolib_dll_handle) {
  13803. mg_snprintf(NULL,
  13804. NULL, /* No truncation check for ebuf */
  13805. ebuf,
  13806. ebuf_len,
  13807. "%s: error loading library %s",
  13808. __func__,
  13809. CRYPTO_LIB);
  13810. DEBUG_TRACE("%s", ebuf);
  13811. return 0;
  13812. }
  13813. }
  13814. #endif /* NO_SSL_DL */
  13815. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13816. return 1;
  13817. }
  13818. /* Initialize locking callbacks, needed for thread safety.
  13819. * http://www.openssl.org/support/faq.html#PROG1
  13820. */
  13821. num_locks = CRYPTO_num_locks();
  13822. if (num_locks < 0) {
  13823. num_locks = 0;
  13824. }
  13825. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13826. /* allocate mutex array, if required */
  13827. if (num_locks == 0) {
  13828. /* No mutex array required */
  13829. ssl_mutexes = NULL;
  13830. } else {
  13831. /* Mutex array required - allocate it */
  13832. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13833. /* Check OOM */
  13834. if (ssl_mutexes == NULL) {
  13835. mg_snprintf(NULL,
  13836. NULL, /* No truncation check for ebuf */
  13837. ebuf,
  13838. ebuf_len,
  13839. "%s: cannot allocate mutexes: %s",
  13840. __func__,
  13841. ssl_error());
  13842. DEBUG_TRACE("%s", ebuf);
  13843. return 0;
  13844. }
  13845. /* initialize mutex array */
  13846. for (i = 0; i < num_locks; i++) {
  13847. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13848. mg_snprintf(NULL,
  13849. NULL, /* No truncation check for ebuf */
  13850. ebuf,
  13851. ebuf_len,
  13852. "%s: error initializing mutex %i of %i",
  13853. __func__,
  13854. i,
  13855. num_locks);
  13856. DEBUG_TRACE("%s", ebuf);
  13857. mg_free(ssl_mutexes);
  13858. return 0;
  13859. }
  13860. }
  13861. }
  13862. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13863. CRYPTO_set_id_callback(&mg_current_thread_id);
  13864. #endif /* OPENSSL_API_1_1 */
  13865. #if !defined(NO_SSL_DL)
  13866. if (!ssllib_dll_handle) {
  13867. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13868. if (!ssllib_dll_handle) {
  13869. #if !defined(OPENSSL_API_1_1)
  13870. mg_free(ssl_mutexes);
  13871. #endif
  13872. DEBUG_TRACE("%s", ebuf);
  13873. return 0;
  13874. }
  13875. }
  13876. #endif /* NO_SSL_DL */
  13877. #if defined(OPENSSL_API_1_1)
  13878. /* Initialize SSL library */
  13879. OPENSSL_init_ssl(0, NULL);
  13880. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13881. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13882. NULL);
  13883. #else
  13884. /* Initialize SSL library */
  13885. SSL_library_init();
  13886. SSL_load_error_strings();
  13887. #endif
  13888. return 1;
  13889. }
  13890. static int
  13891. ssl_use_pem_file(struct mg_context *phys_ctx,
  13892. struct mg_domain_context *dom_ctx,
  13893. const char *pem,
  13894. const char *chain)
  13895. {
  13896. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13897. mg_cry_ctx_internal(phys_ctx,
  13898. "%s: cannot open certificate file %s: %s",
  13899. __func__,
  13900. pem,
  13901. ssl_error());
  13902. return 0;
  13903. }
  13904. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13905. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13906. mg_cry_ctx_internal(phys_ctx,
  13907. "%s: cannot open private key file %s: %s",
  13908. __func__,
  13909. pem,
  13910. ssl_error());
  13911. return 0;
  13912. }
  13913. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13914. mg_cry_ctx_internal(phys_ctx,
  13915. "%s: certificate and private key do not match: %s",
  13916. __func__,
  13917. pem);
  13918. return 0;
  13919. }
  13920. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13921. * chain files that contain private keys and certificates in
  13922. * SSL_CTX_use_certificate_chain_file.
  13923. * The CivetWeb-Server used pem-Files that contained both information.
  13924. * In order to make wolfSSL work, it is split in two files.
  13925. * One file that contains key and certificate used by the server and
  13926. * an optional chain file for the ssl stack.
  13927. */
  13928. if (chain) {
  13929. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13930. mg_cry_ctx_internal(phys_ctx,
  13931. "%s: cannot use certificate chain file %s: %s",
  13932. __func__,
  13933. chain,
  13934. ssl_error());
  13935. return 0;
  13936. }
  13937. }
  13938. return 1;
  13939. }
  13940. #if defined(OPENSSL_API_1_1)
  13941. static unsigned long
  13942. ssl_get_protocol(int version_id)
  13943. {
  13944. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13945. if (version_id > 0)
  13946. ret |= SSL_OP_NO_SSLv2;
  13947. if (version_id > 1)
  13948. ret |= SSL_OP_NO_SSLv3;
  13949. if (version_id > 2)
  13950. ret |= SSL_OP_NO_TLSv1;
  13951. if (version_id > 3)
  13952. ret |= SSL_OP_NO_TLSv1_1;
  13953. if (version_id > 4)
  13954. ret |= SSL_OP_NO_TLSv1_2;
  13955. #if defined(SSL_OP_NO_TLSv1_3)
  13956. if (version_id > 5)
  13957. ret |= SSL_OP_NO_TLSv1_3;
  13958. #endif
  13959. return ret;
  13960. }
  13961. #else
  13962. static long
  13963. ssl_get_protocol(int version_id)
  13964. {
  13965. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13966. if (version_id > 0)
  13967. ret |= SSL_OP_NO_SSLv2;
  13968. if (version_id > 1)
  13969. ret |= SSL_OP_NO_SSLv3;
  13970. if (version_id > 2)
  13971. ret |= SSL_OP_NO_TLSv1;
  13972. if (version_id > 3)
  13973. ret |= SSL_OP_NO_TLSv1_1;
  13974. if (version_id > 4)
  13975. ret |= SSL_OP_NO_TLSv1_2;
  13976. #if defined(SSL_OP_NO_TLSv1_3)
  13977. if (version_id > 5)
  13978. ret |= SSL_OP_NO_TLSv1_3;
  13979. #endif
  13980. return (long)ret;
  13981. }
  13982. #endif /* OPENSSL_API_1_1 */
  13983. /* SSL callback documentation:
  13984. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13985. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13986. * https://linux.die.net/man/3/ssl_set_info_callback */
  13987. /* Note: There is no "const" for the first argument in the documentation
  13988. * examples, however some (maybe most, but not all) headers of OpenSSL
  13989. * versions / OpenSSL compatibility layers have it. Having a different
  13990. * definition will cause a warning in C and an error in C++. Use "const SSL
  13991. * *", while automatical conversion from "SSL *" works for all compilers,
  13992. * but not other way around */
  13993. static void
  13994. ssl_info_callback(const SSL *ssl, int what, int ret)
  13995. {
  13996. (void)ret;
  13997. if (what & SSL_CB_HANDSHAKE_START) {
  13998. SSL_get_app_data(ssl);
  13999. }
  14000. if (what & SSL_CB_HANDSHAKE_DONE) {
  14001. /* TODO: check for openSSL 1.1 */
  14002. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14003. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14004. }
  14005. }
  14006. static int
  14007. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14008. {
  14009. #if defined(GCC_DIAGNOSTIC)
  14010. #pragma GCC diagnostic push
  14011. #pragma GCC diagnostic ignored "-Wcast-align"
  14012. #endif /* defined(GCC_DIAGNOSTIC) */
  14013. /* We used an aligned pointer in SSL_set_app_data */
  14014. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14015. #if defined(GCC_DIAGNOSTIC)
  14016. #pragma GCC diagnostic pop
  14017. #endif /* defined(GCC_DIAGNOSTIC) */
  14018. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14019. (void)ad;
  14020. (void)arg;
  14021. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14022. DEBUG_ASSERT(0);
  14023. return SSL_TLSEXT_ERR_NOACK;
  14024. }
  14025. conn->dom_ctx = &(conn->phys_ctx->dd);
  14026. /* Old clients (Win XP) will not support SNI. Then, there
  14027. * is no server name available in the request - we can
  14028. * only work with the default certificate.
  14029. * Multiple HTTPS hosts on one IP+port are only possible
  14030. * with a certificate containing all alternative names.
  14031. */
  14032. if ((servername == NULL) || (*servername == 0)) {
  14033. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14034. mg_lock_context(conn->phys_ctx);
  14035. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14036. mg_unlock_context(conn->phys_ctx);
  14037. return SSL_TLSEXT_ERR_NOACK;
  14038. }
  14039. DEBUG_TRACE("TLS connection to host %s", servername);
  14040. while (conn->dom_ctx) {
  14041. if (!mg_strcasecmp(servername,
  14042. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14043. /* Found matching domain */
  14044. DEBUG_TRACE("TLS domain %s found",
  14045. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14046. break;
  14047. }
  14048. mg_lock_context(conn->phys_ctx);
  14049. conn->dom_ctx = conn->dom_ctx->next;
  14050. mg_unlock_context(conn->phys_ctx);
  14051. }
  14052. if (conn->dom_ctx == NULL) {
  14053. /* Default domain */
  14054. DEBUG_TRACE("TLS default domain %s used",
  14055. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14056. conn->dom_ctx = &(conn->phys_ctx->dd);
  14057. }
  14058. mg_lock_context(conn->phys_ctx);
  14059. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14060. mg_unlock_context(conn->phys_ctx);
  14061. return SSL_TLSEXT_ERR_OK;
  14062. }
  14063. #if defined(USE_HTTP2)
  14064. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14065. static const char *alpn_proto_order[] = {alpn_proto_list,
  14066. alpn_proto_list + 3,
  14067. alpn_proto_list + 3 + 8,
  14068. NULL};
  14069. #else
  14070. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14071. static const char *alpn_proto_order[] = {alpn_proto_list,
  14072. alpn_proto_list + 8,
  14073. NULL};
  14074. #endif
  14075. static int
  14076. alpn_select_cb(SSL *ssl,
  14077. const unsigned char **out,
  14078. unsigned char *outlen,
  14079. const unsigned char *in,
  14080. unsigned int inlen,
  14081. void *arg)
  14082. {
  14083. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14084. unsigned int i, j;
  14085. struct mg_workerTLS *tls =
  14086. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14087. (void)ssl;
  14088. (void)dom_ctx;
  14089. if (tls == NULL) {
  14090. /* Need to store protocol in Thread Local Storage */
  14091. /* If there is no Thread Local Storage, don't use ALPN */
  14092. return SSL_TLSEXT_ERR_NOACK;
  14093. }
  14094. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14095. /* check all accepted protocols in this order */
  14096. const char *alpn_proto = alpn_proto_order[j];
  14097. /* search input for matching protocol */
  14098. for (i = 0; i < inlen; i++) {
  14099. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14100. *out = in + i + 1;
  14101. *outlen = in[i];
  14102. tls->alpn_proto = alpn_proto;
  14103. return SSL_TLSEXT_ERR_OK;
  14104. }
  14105. }
  14106. }
  14107. /* Nothing found */
  14108. return SSL_TLSEXT_ERR_NOACK;
  14109. }
  14110. static int
  14111. next_protos_advertised_cb(SSL *ssl,
  14112. const unsigned char **data,
  14113. unsigned int *len,
  14114. void *arg)
  14115. {
  14116. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14117. *data = (const unsigned char *)alpn_proto_list;
  14118. *len = (unsigned int)strlen((const char *)data);
  14119. (void)ssl;
  14120. (void)dom_ctx;
  14121. return SSL_TLSEXT_ERR_OK;
  14122. }
  14123. static int
  14124. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14125. {
  14126. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14127. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14128. (const unsigned char *)alpn_proto_list,
  14129. alpn_len);
  14130. if (ret != 0) {
  14131. mg_cry_ctx_internal(phys_ctx,
  14132. "SSL_CTX_set_alpn_protos error: %s",
  14133. ssl_error());
  14134. }
  14135. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14136. alpn_select_cb,
  14137. (void *)dom_ctx);
  14138. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14139. next_protos_advertised_cb,
  14140. (void *)dom_ctx);
  14141. return ret;
  14142. }
  14143. /* Setup SSL CTX as required by CivetWeb */
  14144. static int
  14145. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14146. struct mg_domain_context *dom_ctx,
  14147. const char *pem,
  14148. const char *chain)
  14149. {
  14150. int callback_ret;
  14151. int should_verify_peer;
  14152. int peer_certificate_optional;
  14153. const char *ca_path;
  14154. const char *ca_file;
  14155. int use_default_verify_paths;
  14156. int verify_depth;
  14157. struct timespec now_mt;
  14158. md5_byte_t ssl_context_id[16];
  14159. md5_state_t md5state;
  14160. int protocol_ver;
  14161. #if defined(OPENSSL_API_1_1)
  14162. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14163. mg_cry_ctx_internal(phys_ctx,
  14164. "SSL_CTX_new (server) error: %s",
  14165. ssl_error());
  14166. return 0;
  14167. }
  14168. #else
  14169. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14170. mg_cry_ctx_internal(phys_ctx,
  14171. "SSL_CTX_new (server) error: %s",
  14172. ssl_error());
  14173. return 0;
  14174. }
  14175. #endif /* OPENSSL_API_1_1 */
  14176. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14177. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14178. | SSL_OP_NO_TLSv1_1);
  14179. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14180. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14181. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14182. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14183. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14184. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14185. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14186. #if defined(SSL_OP_NO_RENEGOTIATION)
  14187. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14188. #endif
  14189. #if !defined(NO_SSL_DL)
  14190. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14191. #endif /* NO_SSL_DL */
  14192. /* In SSL documentation examples callback defined without const
  14193. * specifier 'void (*)(SSL *, int, int)' See:
  14194. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14195. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14196. * But in the source code const SSL is used:
  14197. * 'void (*)(const SSL *, int, int)' See:
  14198. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14199. * Problem about wrong documentation described, but not resolved:
  14200. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14201. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14202. * But when compiled with modern C++ compiler, correct const should be
  14203. * provided
  14204. */
  14205. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14206. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14207. ssl_servername_callback);
  14208. /* If a callback has been specified, call it. */
  14209. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14210. ? 0
  14211. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14212. phys_ctx->user_data));
  14213. /* If callback returns 0, civetweb sets up the SSL certificate.
  14214. * If it returns 1, civetweb assumes the calback already did this.
  14215. * If it returns -1, initializing ssl fails. */
  14216. if (callback_ret < 0) {
  14217. mg_cry_ctx_internal(phys_ctx,
  14218. "SSL callback returned error: %i",
  14219. callback_ret);
  14220. return 0;
  14221. }
  14222. if (callback_ret > 0) {
  14223. /* Callback did everything. */
  14224. return 1;
  14225. }
  14226. /* If a domain callback has been specified, call it. */
  14227. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14228. ? 0
  14229. : (phys_ctx->callbacks.init_ssl_domain(
  14230. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14231. dom_ctx->ssl_ctx,
  14232. phys_ctx->user_data));
  14233. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14234. * If it returns 1, civetweb assumes the calback already did this.
  14235. * If it returns -1, initializing ssl fails. */
  14236. if (callback_ret < 0) {
  14237. mg_cry_ctx_internal(phys_ctx,
  14238. "Domain SSL callback returned error: %i",
  14239. callback_ret);
  14240. return 0;
  14241. }
  14242. if (callback_ret > 0) {
  14243. /* Domain callback did everything. */
  14244. return 1;
  14245. }
  14246. /* Use some combination of start time, domain and port as a SSL
  14247. * context ID. This should be unique on the current machine. */
  14248. md5_init(&md5state);
  14249. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14250. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14251. md5_append(&md5state,
  14252. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14253. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14254. md5_append(&md5state,
  14255. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14256. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14257. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14258. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14259. md5_finish(&md5state, ssl_context_id);
  14260. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14261. (unsigned char *)ssl_context_id,
  14262. sizeof(ssl_context_id));
  14263. if (pem != NULL) {
  14264. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14265. return 0;
  14266. }
  14267. }
  14268. /* Should we support client certificates? */
  14269. /* Default is "no". */
  14270. should_verify_peer = 0;
  14271. peer_certificate_optional = 0;
  14272. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14273. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14274. /* Yes, they are mandatory */
  14275. should_verify_peer = 1;
  14276. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14277. "optional")
  14278. == 0) {
  14279. /* Yes, they are optional */
  14280. should_verify_peer = 1;
  14281. peer_certificate_optional = 1;
  14282. }
  14283. }
  14284. use_default_verify_paths =
  14285. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14286. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14287. == 0);
  14288. if (should_verify_peer) {
  14289. ca_path = dom_ctx->config[SSL_CA_PATH];
  14290. ca_file = dom_ctx->config[SSL_CA_FILE];
  14291. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14292. != 1) {
  14293. mg_cry_ctx_internal(phys_ctx,
  14294. "SSL_CTX_load_verify_locations error: %s "
  14295. "ssl_verify_peer requires setting "
  14296. "either ssl_ca_path or ssl_ca_file. "
  14297. "Is any of them present in the "
  14298. ".conf file?",
  14299. ssl_error());
  14300. return 0;
  14301. }
  14302. if (peer_certificate_optional) {
  14303. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14304. } else {
  14305. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14306. SSL_VERIFY_PEER
  14307. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14308. NULL);
  14309. }
  14310. if (use_default_verify_paths
  14311. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14312. mg_cry_ctx_internal(phys_ctx,
  14313. "SSL_CTX_set_default_verify_paths error: %s",
  14314. ssl_error());
  14315. return 0;
  14316. }
  14317. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14318. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14319. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14320. }
  14321. }
  14322. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14323. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14324. dom_ctx->config[SSL_CIPHER_LIST])
  14325. != 1) {
  14326. mg_cry_ctx_internal(phys_ctx,
  14327. "SSL_CTX_set_cipher_list error: %s",
  14328. ssl_error());
  14329. }
  14330. }
  14331. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14332. #if !defined(NO_SSL_DL)
  14333. if (!tls_feature_missing[TLS_ALPN])
  14334. #endif
  14335. {
  14336. init_alpn(phys_ctx, dom_ctx);
  14337. }
  14338. return 1;
  14339. }
  14340. /* Check if SSL is required.
  14341. * If so, dynamically load SSL library
  14342. * and set up ctx->ssl_ctx pointer. */
  14343. static int
  14344. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14345. {
  14346. void *ssl_ctx = 0;
  14347. int callback_ret;
  14348. const char *pem;
  14349. const char *chain;
  14350. char ebuf[128];
  14351. if (!phys_ctx) {
  14352. return 0;
  14353. }
  14354. if (!dom_ctx) {
  14355. dom_ctx = &(phys_ctx->dd);
  14356. }
  14357. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14358. /* No SSL port is set. No need to setup SSL. */
  14359. return 1;
  14360. }
  14361. /* Check for external SSL_CTX */
  14362. callback_ret =
  14363. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14364. ? 0
  14365. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14366. phys_ctx->user_data));
  14367. if (callback_ret < 0) {
  14368. mg_cry_ctx_internal(phys_ctx,
  14369. "external_ssl_ctx callback returned error: %i",
  14370. callback_ret);
  14371. return 0;
  14372. } else if (callback_ret > 0) {
  14373. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14374. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14375. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14376. return 0;
  14377. }
  14378. return 1;
  14379. }
  14380. /* Check for external domain SSL_CTX */
  14381. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14382. ? 0
  14383. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14384. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14385. &ssl_ctx,
  14386. phys_ctx->user_data));
  14387. if (callback_ret < 0) {
  14388. mg_cry_ctx_internal(
  14389. phys_ctx,
  14390. "external_ssl_ctx_domain callback returned error: %i",
  14391. callback_ret);
  14392. return 0;
  14393. } else if (callback_ret > 0) {
  14394. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14395. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14396. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14397. return 0;
  14398. }
  14399. return 1;
  14400. }
  14401. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14402. * 0, CivetWeb should continue initializing SSL */
  14403. /* If PEM file is not specified and the init_ssl callbacks
  14404. * are not specified, setup will fail. */
  14405. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14406. && (phys_ctx->callbacks.init_ssl == NULL)
  14407. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14408. /* No certificate and no init_ssl callbacks:
  14409. * Essential data to set up TLS is missing.
  14410. */
  14411. mg_cry_ctx_internal(phys_ctx,
  14412. "Initializing SSL failed: -%s is not set",
  14413. config_options[SSL_CERTIFICATE].name);
  14414. return 0;
  14415. }
  14416. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14417. if (chain == NULL) {
  14418. chain = pem;
  14419. }
  14420. if ((chain != NULL) && (*chain == 0)) {
  14421. chain = NULL;
  14422. }
  14423. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14424. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14425. return 0;
  14426. }
  14427. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14428. }
  14429. static void
  14430. uninitialize_ssl(void)
  14431. {
  14432. #if defined(OPENSSL_API_1_1)
  14433. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14434. /* Shutdown according to
  14435. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14436. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14437. */
  14438. CONF_modules_unload(1);
  14439. #else
  14440. int i;
  14441. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14442. /* Shutdown according to
  14443. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14444. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14445. */
  14446. CRYPTO_set_locking_callback(NULL);
  14447. CRYPTO_set_id_callback(NULL);
  14448. ENGINE_cleanup();
  14449. CONF_modules_unload(1);
  14450. ERR_free_strings();
  14451. EVP_cleanup();
  14452. CRYPTO_cleanup_all_ex_data();
  14453. OPENSSL_REMOVE_THREAD_STATE();
  14454. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14455. pthread_mutex_destroy(&ssl_mutexes[i]);
  14456. }
  14457. mg_free(ssl_mutexes);
  14458. ssl_mutexes = NULL;
  14459. #endif /* OPENSSL_API_1_1 */
  14460. }
  14461. }
  14462. #endif /* !NO_SSL */
  14463. #if !defined(NO_FILESYSTEMS)
  14464. static int
  14465. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14466. {
  14467. if (phys_ctx) {
  14468. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14469. const char *path;
  14470. struct mg_connection fc;
  14471. if (!dom_ctx) {
  14472. dom_ctx = &(phys_ctx->dd);
  14473. }
  14474. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14475. if ((path != NULL)
  14476. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14477. mg_cry_ctx_internal(phys_ctx,
  14478. "Cannot open %s: %s",
  14479. path,
  14480. strerror(ERRNO));
  14481. return 0;
  14482. }
  14483. return 1;
  14484. }
  14485. return 0;
  14486. }
  14487. #endif /* NO_FILESYSTEMS */
  14488. static int
  14489. set_acl_option(struct mg_context *phys_ctx)
  14490. {
  14491. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14492. }
  14493. static void
  14494. reset_per_request_attributes(struct mg_connection *conn)
  14495. {
  14496. if (!conn) {
  14497. return;
  14498. }
  14499. conn->connection_type =
  14500. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14501. conn->num_bytes_sent = conn->consumed_content = 0;
  14502. conn->path_info = NULL;
  14503. conn->status_code = -1;
  14504. conn->content_len = -1;
  14505. conn->is_chunked = 0;
  14506. conn->must_close = 0;
  14507. conn->request_len = 0;
  14508. conn->throttle = 0;
  14509. conn->accept_gzip = 0;
  14510. conn->response_info.content_length = conn->request_info.content_length = -1;
  14511. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14512. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14513. conn->response_info.status_text = NULL;
  14514. conn->response_info.status_code = 0;
  14515. conn->request_info.remote_user = NULL;
  14516. conn->request_info.request_method = NULL;
  14517. conn->request_info.request_uri = NULL;
  14518. conn->request_info.local_uri = NULL;
  14519. #if defined(MG_LEGACY_INTERFACE)
  14520. /* Legacy before split into local_uri and request_uri */
  14521. conn->request_info.uri = NULL;
  14522. #endif
  14523. }
  14524. static int
  14525. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14526. {
  14527. if (setsockopt(sock,
  14528. IPPROTO_TCP,
  14529. TCP_NODELAY,
  14530. (SOCK_OPT_TYPE)&nodelay_on,
  14531. sizeof(nodelay_on))
  14532. != 0) {
  14533. /* Error */
  14534. return 1;
  14535. }
  14536. /* OK */
  14537. return 0;
  14538. }
  14539. #if !defined(__ZEPHYR__)
  14540. static void
  14541. close_socket_gracefully(struct mg_connection *conn)
  14542. {
  14543. #if defined(_WIN32)
  14544. char buf[MG_BUF_LEN];
  14545. int n;
  14546. #endif
  14547. struct linger linger;
  14548. int error_code = 0;
  14549. int linger_timeout = -2;
  14550. socklen_t opt_len = sizeof(error_code);
  14551. if (!conn) {
  14552. return;
  14553. }
  14554. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14555. * "Note that enabling a nonzero timeout on a nonblocking socket
  14556. * is not recommended.", so set it to blocking now */
  14557. set_blocking_mode(conn->client.sock);
  14558. /* Send FIN to the client */
  14559. shutdown(conn->client.sock, SHUTDOWN_WR);
  14560. #if defined(_WIN32)
  14561. /* Read and discard pending incoming data. If we do not do that and
  14562. * close
  14563. * the socket, the data in the send buffer may be discarded. This
  14564. * behaviour is seen on Windows, when client keeps sending data
  14565. * when server decides to close the connection; then when client
  14566. * does recv() it gets no data back. */
  14567. do {
  14568. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14569. } while (n > 0);
  14570. #endif
  14571. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14572. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14573. }
  14574. /* Set linger option according to configuration */
  14575. if (linger_timeout >= 0) {
  14576. /* Set linger option to avoid socket hanging out after close. This
  14577. * prevent ephemeral port exhaust problem under high QPS. */
  14578. linger.l_onoff = 1;
  14579. #if defined(_MSC_VER)
  14580. #pragma warning(push)
  14581. #pragma warning(disable : 4244)
  14582. #endif
  14583. #if defined(GCC_DIAGNOSTIC)
  14584. #pragma GCC diagnostic push
  14585. #pragma GCC diagnostic ignored "-Wconversion"
  14586. #endif
  14587. /* Data type of linger structure elements may differ,
  14588. * so we don't know what cast we need here.
  14589. * Disable type conversion warnings. */
  14590. linger.l_linger = (linger_timeout + 999) / 1000;
  14591. #if defined(GCC_DIAGNOSTIC)
  14592. #pragma GCC diagnostic pop
  14593. #endif
  14594. #if defined(_MSC_VER)
  14595. #pragma warning(pop)
  14596. #endif
  14597. } else {
  14598. linger.l_onoff = 0;
  14599. linger.l_linger = 0;
  14600. }
  14601. if (linger_timeout < -1) {
  14602. /* Default: don't configure any linger */
  14603. } else if (getsockopt(conn->client.sock,
  14604. SOL_SOCKET,
  14605. SO_ERROR,
  14606. #if defined(_WIN32) /* WinSock uses different data type here */
  14607. (char *)&error_code,
  14608. #else
  14609. &error_code,
  14610. #endif
  14611. &opt_len)
  14612. != 0) {
  14613. /* Cannot determine if socket is already closed. This should
  14614. * not occur and never did in a test. Log an error message
  14615. * and continue. */
  14616. mg_cry_internal(conn,
  14617. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14618. __func__,
  14619. strerror(ERRNO));
  14620. #if defined(_WIN32)
  14621. } else if (error_code == WSAECONNRESET) {
  14622. #else
  14623. } else if (error_code == ECONNRESET) {
  14624. #endif
  14625. /* Socket already closed by client/peer, close socket without linger
  14626. */
  14627. } else {
  14628. /* Set linger timeout */
  14629. if (setsockopt(conn->client.sock,
  14630. SOL_SOCKET,
  14631. SO_LINGER,
  14632. (char *)&linger,
  14633. sizeof(linger))
  14634. != 0) {
  14635. mg_cry_internal(
  14636. conn,
  14637. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14638. __func__,
  14639. linger.l_onoff,
  14640. linger.l_linger,
  14641. strerror(ERRNO));
  14642. }
  14643. }
  14644. /* Now we know that our FIN is ACK-ed, safe to close */
  14645. closesocket(conn->client.sock);
  14646. conn->client.sock = INVALID_SOCKET;
  14647. }
  14648. #endif
  14649. static void
  14650. close_connection(struct mg_connection *conn)
  14651. {
  14652. #if defined(USE_SERVER_STATS)
  14653. conn->conn_state = 6; /* to close */
  14654. #endif
  14655. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14656. if (conn->lua_websocket_state) {
  14657. lua_websocket_close(conn, conn->lua_websocket_state);
  14658. conn->lua_websocket_state = NULL;
  14659. }
  14660. #endif
  14661. mg_lock_connection(conn);
  14662. /* Set close flag, so keep-alive loops will stop */
  14663. conn->must_close = 1;
  14664. /* call the connection_close callback if assigned */
  14665. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14666. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14667. conn->phys_ctx->callbacks.connection_close(conn);
  14668. }
  14669. }
  14670. /* Reset user data, after close callback is called.
  14671. * Do not reuse it. If the user needs a destructor,
  14672. * it must be done in the connection_close callback. */
  14673. mg_set_user_connection_data(conn, NULL);
  14674. #if defined(USE_SERVER_STATS)
  14675. conn->conn_state = 7; /* closing */
  14676. #endif
  14677. #if !defined(NO_SSL)
  14678. if (conn->ssl != NULL) {
  14679. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14680. */
  14681. SSL_shutdown(conn->ssl);
  14682. SSL_free(conn->ssl);
  14683. OPENSSL_REMOVE_THREAD_STATE();
  14684. conn->ssl = NULL;
  14685. }
  14686. #endif
  14687. if (conn->client.sock != INVALID_SOCKET) {
  14688. #if defined(__ZEPHYR__)
  14689. closesocket(conn->client.sock);
  14690. #else
  14691. close_socket_gracefully(conn);
  14692. #endif
  14693. conn->client.sock = INVALID_SOCKET;
  14694. }
  14695. if (conn->host) {
  14696. mg_free((void *)conn->host);
  14697. conn->host = NULL;
  14698. }
  14699. mg_unlock_connection(conn);
  14700. #if defined(USE_SERVER_STATS)
  14701. conn->conn_state = 8; /* closed */
  14702. #endif
  14703. }
  14704. void
  14705. mg_close_connection(struct mg_connection *conn)
  14706. {
  14707. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14708. return;
  14709. }
  14710. #if defined(USE_WEBSOCKET)
  14711. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14712. if (conn->in_websocket_handling) {
  14713. /* Set close flag, so the server thread can exit. */
  14714. conn->must_close = 1;
  14715. return;
  14716. }
  14717. }
  14718. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14719. unsigned int i;
  14720. /* client context: loops must end */
  14721. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14722. conn->must_close = 1;
  14723. /* We need to get the client thread out of the select/recv call
  14724. * here. */
  14725. /* Since we use a sleep quantum of some seconds to check for recv
  14726. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14727. /* join worker thread */
  14728. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14729. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14730. }
  14731. }
  14732. #endif /* defined(USE_WEBSOCKET) */
  14733. close_connection(conn);
  14734. #if !defined(NO_SSL)
  14735. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14736. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14737. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14738. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14739. }
  14740. #endif
  14741. #if defined(USE_WEBSOCKET)
  14742. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14743. mg_free(conn->phys_ctx->worker_threadids);
  14744. (void)pthread_mutex_destroy(&conn->mutex);
  14745. mg_free(conn);
  14746. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14747. (void)pthread_mutex_destroy(&conn->mutex);
  14748. mg_free(conn);
  14749. }
  14750. #else
  14751. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14752. (void)pthread_mutex_destroy(&conn->mutex);
  14753. mg_free(conn);
  14754. }
  14755. #endif /* defined(USE_WEBSOCKET) */
  14756. }
  14757. static struct mg_connection *
  14758. mg_connect_client_impl(const struct mg_client_options *client_options,
  14759. int use_ssl,
  14760. char *ebuf,
  14761. size_t ebuf_len)
  14762. {
  14763. struct mg_connection *conn = NULL;
  14764. SOCKET sock;
  14765. union usa sa;
  14766. struct sockaddr *psa;
  14767. socklen_t len;
  14768. unsigned max_req_size =
  14769. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14770. /* Size of structures, aligned to 8 bytes */
  14771. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14772. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14773. conn =
  14774. (struct mg_connection *)mg_calloc(1,
  14775. conn_size + ctx_size + max_req_size);
  14776. if (conn == NULL) {
  14777. mg_snprintf(NULL,
  14778. NULL, /* No truncation check for ebuf */
  14779. ebuf,
  14780. ebuf_len,
  14781. "calloc(): %s",
  14782. strerror(ERRNO));
  14783. return NULL;
  14784. }
  14785. #if defined(GCC_DIAGNOSTIC)
  14786. #pragma GCC diagnostic push
  14787. #pragma GCC diagnostic ignored "-Wcast-align"
  14788. #endif /* defined(GCC_DIAGNOSTIC) */
  14789. /* conn_size is aligned to 8 bytes */
  14790. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14791. #if defined(GCC_DIAGNOSTIC)
  14792. #pragma GCC diagnostic pop
  14793. #endif /* defined(GCC_DIAGNOSTIC) */
  14794. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14795. conn->buf_size = (int)max_req_size;
  14796. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14797. conn->dom_ctx = &(conn->phys_ctx->dd);
  14798. if (!connect_socket(conn->phys_ctx,
  14799. client_options->host,
  14800. client_options->port,
  14801. use_ssl,
  14802. ebuf,
  14803. ebuf_len,
  14804. &sock,
  14805. &sa)) {
  14806. /* ebuf is set by connect_socket,
  14807. * free all memory and return NULL; */
  14808. mg_free(conn);
  14809. return NULL;
  14810. }
  14811. #if !defined(NO_SSL)
  14812. #if defined(OPENSSL_API_1_1)
  14813. if (use_ssl
  14814. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14815. == NULL) {
  14816. mg_snprintf(NULL,
  14817. NULL, /* No truncation check for ebuf */
  14818. ebuf,
  14819. ebuf_len,
  14820. "SSL_CTX_new error: %s",
  14821. ssl_error());
  14822. closesocket(sock);
  14823. mg_free(conn);
  14824. return NULL;
  14825. }
  14826. #else
  14827. if (use_ssl
  14828. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14829. == NULL) {
  14830. mg_snprintf(NULL,
  14831. NULL, /* No truncation check for ebuf */
  14832. ebuf,
  14833. ebuf_len,
  14834. "SSL_CTX_new error: %s",
  14835. ssl_error());
  14836. closesocket(sock);
  14837. mg_free(conn);
  14838. return NULL;
  14839. }
  14840. #endif /* OPENSSL_API_1_1 */
  14841. #endif /* NO_SSL */
  14842. #if defined(USE_IPV6)
  14843. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14844. : sizeof(conn->client.rsa.sin6);
  14845. psa = (sa.sa.sa_family == AF_INET)
  14846. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14847. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14848. #else
  14849. len = sizeof(conn->client.rsa.sin);
  14850. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14851. #endif
  14852. conn->client.sock = sock;
  14853. conn->client.lsa = sa;
  14854. if (getsockname(sock, psa, &len) != 0) {
  14855. mg_cry_internal(conn,
  14856. "%s: getsockname() failed: %s",
  14857. __func__,
  14858. strerror(ERRNO));
  14859. }
  14860. conn->client.is_ssl = use_ssl ? 1 : 0;
  14861. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14862. mg_snprintf(NULL,
  14863. NULL, /* No truncation check for ebuf */
  14864. ebuf,
  14865. ebuf_len,
  14866. "Can not create mutex");
  14867. #if !defined(NO_SSL)
  14868. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14869. #endif
  14870. closesocket(sock);
  14871. mg_free(conn);
  14872. return NULL;
  14873. }
  14874. #if !defined(NO_SSL)
  14875. if (use_ssl) {
  14876. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14877. * SSL_CTX_set_verify call is needed to switch off server
  14878. * certificate checking, which is off by default in OpenSSL and
  14879. * on in yaSSL. */
  14880. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14881. * SSL_VERIFY_PEER, verify_ssl_server); */
  14882. if (client_options->client_cert) {
  14883. if (!ssl_use_pem_file(conn->phys_ctx,
  14884. conn->dom_ctx,
  14885. client_options->client_cert,
  14886. NULL)) {
  14887. mg_snprintf(NULL,
  14888. NULL, /* No truncation check for ebuf */
  14889. ebuf,
  14890. ebuf_len,
  14891. "Can not use SSL client certificate");
  14892. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14893. closesocket(sock);
  14894. mg_free(conn);
  14895. return NULL;
  14896. }
  14897. }
  14898. if (client_options->server_cert) {
  14899. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14900. client_options->server_cert,
  14901. NULL)
  14902. != 1) {
  14903. mg_cry_internal(conn,
  14904. "SSL_CTX_load_verify_locations error: %s ",
  14905. ssl_error());
  14906. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14907. closesocket(sock);
  14908. mg_free(conn);
  14909. return NULL;
  14910. }
  14911. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14912. } else {
  14913. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14914. }
  14915. if (!sslize(conn,
  14916. SSL_connect,
  14917. client_options)) {
  14918. mg_snprintf(NULL,
  14919. NULL, /* No truncation check for ebuf */
  14920. ebuf,
  14921. ebuf_len,
  14922. "SSL connection error");
  14923. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14924. closesocket(sock);
  14925. mg_free(conn);
  14926. return NULL;
  14927. }
  14928. }
  14929. #endif
  14930. return conn;
  14931. }
  14932. CIVETWEB_API struct mg_connection *
  14933. mg_connect_client_secure(const struct mg_client_options *client_options,
  14934. char *error_buffer,
  14935. size_t error_buffer_size)
  14936. {
  14937. return mg_connect_client_impl(client_options,
  14938. 1,
  14939. error_buffer,
  14940. error_buffer_size);
  14941. }
  14942. struct mg_connection *
  14943. mg_connect_client(const char *host,
  14944. int port,
  14945. int use_ssl,
  14946. char *error_buffer,
  14947. size_t error_buffer_size)
  14948. {
  14949. struct mg_client_options opts;
  14950. memset(&opts, 0, sizeof(opts));
  14951. opts.host = host;
  14952. opts.port = port;
  14953. return mg_connect_client_impl(&opts,
  14954. use_ssl,
  14955. error_buffer,
  14956. error_buffer_size);
  14957. }
  14958. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14959. struct mg_connection *
  14960. mg_connect_client2(const char *host,
  14961. const char *protocol,
  14962. int port,
  14963. const char *path,
  14964. struct mg_init_data *init,
  14965. struct mg_error_data *error)
  14966. {
  14967. int is_ssl, is_ws;
  14968. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14969. if (error != NULL) {
  14970. error->code = 0;
  14971. if (error->text_buffer_size > 0) {
  14972. *error->text = 0;
  14973. }
  14974. }
  14975. if ((host == NULL) || (protocol == NULL)) {
  14976. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14977. mg_snprintf(NULL,
  14978. NULL, /* No truncation check for error buffers */
  14979. error->text,
  14980. error->text_buffer_size,
  14981. "%s",
  14982. "Invalid parameters");
  14983. }
  14984. return NULL;
  14985. }
  14986. /* check all known protocolls */
  14987. if (!mg_strcasecmp(protocol, "http")) {
  14988. is_ssl = 0;
  14989. is_ws = 0;
  14990. } else if (!mg_strcasecmp(protocol, "https")) {
  14991. is_ssl = 1;
  14992. is_ws = 0;
  14993. #if defined(USE_WEBSOCKET)
  14994. } else if (!mg_strcasecmp(protocol, "ws")) {
  14995. is_ssl = 0;
  14996. is_ws = 1;
  14997. } else if (!mg_strcasecmp(protocol, "wss")) {
  14998. is_ssl = 1;
  14999. is_ws = 1;
  15000. #endif
  15001. } else {
  15002. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15003. mg_snprintf(NULL,
  15004. NULL, /* No truncation check for error buffers */
  15005. error->text,
  15006. error->text_buffer_size,
  15007. "Protocol %s not supported",
  15008. protocol);
  15009. }
  15010. return NULL;
  15011. }
  15012. /* TODO: The current implementation here just calls the old
  15013. * implementations, without using any new options. This is just a first
  15014. * step to test the new interfaces. */
  15015. #if defined(USE_WEBSOCKET)
  15016. if (is_ws) {
  15017. /* TODO: implement all options */
  15018. return mg_connect_websocket_client(
  15019. host,
  15020. port,
  15021. is_ssl,
  15022. ((error != NULL) ? error->text : NULL),
  15023. ((error != NULL) ? error->text_buffer_size : 0),
  15024. (path ? path : ""),
  15025. NULL /* TODO: origin */,
  15026. deprecated_websocket_data_wrapper,
  15027. deprecated_websocket_close_wrapper,
  15028. (void *)init->callbacks);
  15029. }
  15030. #endif
  15031. /* TODO: all additional options */
  15032. struct mg_client_options opts;
  15033. memset(&opts, 0, sizeof(opts));
  15034. opts.host = host;
  15035. opts.port = port;
  15036. return mg_connect_client_impl(&opts,
  15037. is_ssl,
  15038. ((error != NULL) ? error->text : NULL),
  15039. ((error != NULL) ? error->text_buffer_size
  15040. : 0));
  15041. }
  15042. #endif
  15043. static const struct {
  15044. const char *proto;
  15045. size_t proto_len;
  15046. unsigned default_port;
  15047. } abs_uri_protocols[] = {{"http://", 7, 80},
  15048. {"https://", 8, 443},
  15049. {"ws://", 5, 80},
  15050. {"wss://", 6, 443},
  15051. {NULL, 0, 0}};
  15052. /* Check if the uri is valid.
  15053. * return 0 for invalid uri,
  15054. * return 1 for *,
  15055. * return 2 for relative uri,
  15056. * return 3 for absolute uri without port,
  15057. * return 4 for absolute uri with port */
  15058. static int
  15059. get_uri_type(const char *uri)
  15060. {
  15061. int i;
  15062. const char *hostend, *portbegin;
  15063. char *portend;
  15064. unsigned long port;
  15065. /* According to the HTTP standard
  15066. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15067. * URI can be an asterisk (*) or should start with slash (relative uri),
  15068. * or it should start with the protocol (absolute uri). */
  15069. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15070. /* asterisk */
  15071. return 1;
  15072. }
  15073. /* Valid URIs according to RFC 3986
  15074. * (https://www.ietf.org/rfc/rfc3986.txt)
  15075. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15076. * and unreserved characters A-Z a-z 0-9 and -._~
  15077. * and % encoded symbols.
  15078. */
  15079. for (i = 0; uri[i] != 0; i++) {
  15080. if (uri[i] < 33) {
  15081. /* control characters and spaces are invalid */
  15082. return 0;
  15083. }
  15084. if (uri[i] > 126) {
  15085. /* non-ascii characters must be % encoded */
  15086. return 0;
  15087. } else {
  15088. switch (uri[i]) {
  15089. case '"': /* 34 */
  15090. case '<': /* 60 */
  15091. case '>': /* 62 */
  15092. case '\\': /* 92 */
  15093. case '^': /* 94 */
  15094. case '`': /* 96 */
  15095. case '{': /* 123 */
  15096. case '|': /* 124 */
  15097. case '}': /* 125 */
  15098. return 0;
  15099. default:
  15100. /* character is ok */
  15101. break;
  15102. }
  15103. }
  15104. }
  15105. /* A relative uri starts with a / character */
  15106. if (uri[0] == '/') {
  15107. /* relative uri */
  15108. return 2;
  15109. }
  15110. /* It could be an absolute uri: */
  15111. /* This function only checks if the uri is valid, not if it is
  15112. * addressing the current server. So civetweb can also be used
  15113. * as a proxy server. */
  15114. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15115. if (mg_strncasecmp(uri,
  15116. abs_uri_protocols[i].proto,
  15117. abs_uri_protocols[i].proto_len)
  15118. == 0) {
  15119. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15120. if (!hostend) {
  15121. return 0;
  15122. }
  15123. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15124. if (!portbegin) {
  15125. return 3;
  15126. }
  15127. port = strtoul(portbegin + 1, &portend, 10);
  15128. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15129. return 0;
  15130. }
  15131. return 4;
  15132. }
  15133. }
  15134. return 0;
  15135. }
  15136. /* Return NULL or the relative uri at the current server */
  15137. static const char *
  15138. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15139. {
  15140. const char *server_domain;
  15141. size_t server_domain_len;
  15142. size_t request_domain_len = 0;
  15143. unsigned long port = 0;
  15144. int i, auth_domain_check_enabled;
  15145. const char *hostbegin = NULL;
  15146. const char *hostend = NULL;
  15147. const char *portbegin;
  15148. char *portend;
  15149. auth_domain_check_enabled =
  15150. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15151. /* DNS is case insensitive, so use case insensitive string compare here
  15152. */
  15153. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15154. if (mg_strncasecmp(uri,
  15155. abs_uri_protocols[i].proto,
  15156. abs_uri_protocols[i].proto_len)
  15157. == 0) {
  15158. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15159. hostend = strchr(hostbegin, '/');
  15160. if (!hostend) {
  15161. return 0;
  15162. }
  15163. portbegin = strchr(hostbegin, ':');
  15164. if ((!portbegin) || (portbegin > hostend)) {
  15165. port = abs_uri_protocols[i].default_port;
  15166. request_domain_len = (size_t)(hostend - hostbegin);
  15167. } else {
  15168. port = strtoul(portbegin + 1, &portend, 10);
  15169. if ((portend != hostend) || (port <= 0)
  15170. || !is_valid_port(port)) {
  15171. return 0;
  15172. }
  15173. request_domain_len = (size_t)(portbegin - hostbegin);
  15174. }
  15175. /* protocol found, port set */
  15176. break;
  15177. }
  15178. }
  15179. if (!port) {
  15180. /* port remains 0 if the protocol is not found */
  15181. return 0;
  15182. }
  15183. /* Check if the request is directed to a different server. */
  15184. /* First check if the port is the same (IPv4 and IPv6). */
  15185. #if defined(USE_IPV6)
  15186. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15187. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15188. /* Request is directed to a different port */
  15189. return 0;
  15190. }
  15191. } else
  15192. #endif
  15193. {
  15194. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15195. /* Request is directed to a different port */
  15196. return 0;
  15197. }
  15198. }
  15199. /* Finally check if the server corresponds to the authentication
  15200. * domain of the server (the server domain).
  15201. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15202. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15203. * but do not allow substrings (like
  15204. * http://notmydomain.com/path/file.ext
  15205. * or http://mydomain.com.fake/path/file.ext).
  15206. */
  15207. if (auth_domain_check_enabled) {
  15208. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15209. server_domain_len = strlen(server_domain);
  15210. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15211. return 0;
  15212. }
  15213. if ((request_domain_len == server_domain_len)
  15214. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15215. /* Request is directed to this server - full name match. */
  15216. } else {
  15217. if (request_domain_len < (server_domain_len + 2)) {
  15218. /* Request is directed to another server: The server name
  15219. * is longer than the request name.
  15220. * Drop this case here to avoid overflows in the
  15221. * following checks. */
  15222. return 0;
  15223. }
  15224. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15225. /* Request is directed to another server: It could be a
  15226. * substring
  15227. * like notmyserver.com */
  15228. return 0;
  15229. }
  15230. if (0
  15231. != memcmp(server_domain,
  15232. hostbegin + request_domain_len - server_domain_len,
  15233. server_domain_len)) {
  15234. /* Request is directed to another server:
  15235. * The server name is different. */
  15236. return 0;
  15237. }
  15238. }
  15239. }
  15240. return hostend;
  15241. }
  15242. static int
  15243. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15244. {
  15245. if (ebuf_len > 0) {
  15246. ebuf[0] = '\0';
  15247. }
  15248. *err = 0;
  15249. reset_per_request_attributes(conn);
  15250. if (!conn) {
  15251. mg_snprintf(conn,
  15252. NULL, /* No truncation check for ebuf */
  15253. ebuf,
  15254. ebuf_len,
  15255. "%s",
  15256. "Internal error");
  15257. *err = 500;
  15258. return 0;
  15259. }
  15260. /* Set the time the request was received. This value should be used for
  15261. * timeouts. */
  15262. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15263. conn->request_len =
  15264. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15265. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15266. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15267. mg_snprintf(conn,
  15268. NULL, /* No truncation check for ebuf */
  15269. ebuf,
  15270. ebuf_len,
  15271. "%s",
  15272. "Invalid message size");
  15273. *err = 500;
  15274. return 0;
  15275. }
  15276. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15277. mg_snprintf(conn,
  15278. NULL, /* No truncation check for ebuf */
  15279. ebuf,
  15280. ebuf_len,
  15281. "%s",
  15282. "Message too large");
  15283. *err = 413;
  15284. return 0;
  15285. }
  15286. if (conn->request_len <= 0) {
  15287. if (conn->data_len > 0) {
  15288. mg_snprintf(conn,
  15289. NULL, /* No truncation check for ebuf */
  15290. ebuf,
  15291. ebuf_len,
  15292. "%s",
  15293. "Malformed message");
  15294. *err = 400;
  15295. } else {
  15296. /* Server did not recv anything -> just close the connection */
  15297. conn->must_close = 1;
  15298. mg_snprintf(conn,
  15299. NULL, /* No truncation check for ebuf */
  15300. ebuf,
  15301. ebuf_len,
  15302. "%s",
  15303. "No data received");
  15304. *err = 0;
  15305. }
  15306. return 0;
  15307. }
  15308. return 1;
  15309. }
  15310. static int
  15311. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15312. {
  15313. const char *cl;
  15314. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15315. return 0;
  15316. }
  15317. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15318. <= 0) {
  15319. mg_snprintf(conn,
  15320. NULL, /* No truncation check for ebuf */
  15321. ebuf,
  15322. ebuf_len,
  15323. "%s",
  15324. "Bad request");
  15325. *err = 400;
  15326. return 0;
  15327. }
  15328. /* Message is a valid request */
  15329. /* Is there a "host" ? */
  15330. if (conn->host != NULL) {
  15331. mg_free((void *)conn->host);
  15332. }
  15333. conn->host = alloc_get_host(conn);
  15334. if (!conn->host) {
  15335. mg_snprintf(conn,
  15336. NULL, /* No truncation check for ebuf */
  15337. ebuf,
  15338. ebuf_len,
  15339. "%s",
  15340. "Bad request: Host mismatch");
  15341. *err = 400;
  15342. return 0;
  15343. }
  15344. if (((cl = get_header(conn->request_info.http_headers,
  15345. conn->request_info.num_headers,
  15346. "Transfer-Encoding"))
  15347. != NULL)
  15348. && mg_strcasecmp(cl, "identity")) {
  15349. if (mg_strcasecmp(cl, "chunked")) {
  15350. mg_snprintf(conn,
  15351. NULL, /* No truncation check for ebuf */
  15352. ebuf,
  15353. ebuf_len,
  15354. "%s",
  15355. "Bad request");
  15356. *err = 400;
  15357. return 0;
  15358. }
  15359. conn->is_chunked = 1;
  15360. conn->content_len = 0; /* not yet read */
  15361. } else if ((cl = get_header(conn->request_info.http_headers,
  15362. conn->request_info.num_headers,
  15363. "Content-Length"))
  15364. != NULL) {
  15365. /* Request has content length set */
  15366. char *endptr = NULL;
  15367. conn->content_len = strtoll(cl, &endptr, 10);
  15368. if ((endptr == cl) || (conn->content_len < 0)) {
  15369. mg_snprintf(conn,
  15370. NULL, /* No truncation check for ebuf */
  15371. ebuf,
  15372. ebuf_len,
  15373. "%s",
  15374. "Bad request");
  15375. *err = 411;
  15376. return 0;
  15377. }
  15378. /* Publish the content length back to the request info. */
  15379. conn->request_info.content_length = conn->content_len;
  15380. } else {
  15381. /* There is no exception, see RFC7230. */
  15382. conn->content_len = 0;
  15383. }
  15384. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15385. return 1;
  15386. }
  15387. /* conn is assumed to be valid in this internal function */
  15388. static int
  15389. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15390. {
  15391. const char *cl;
  15392. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15393. return 0;
  15394. }
  15395. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15396. <= 0) {
  15397. mg_snprintf(conn,
  15398. NULL, /* No truncation check for ebuf */
  15399. ebuf,
  15400. ebuf_len,
  15401. "%s",
  15402. "Bad response");
  15403. *err = 400;
  15404. return 0;
  15405. }
  15406. /* Message is a valid response */
  15407. if (((cl = get_header(conn->response_info.http_headers,
  15408. conn->response_info.num_headers,
  15409. "Transfer-Encoding"))
  15410. != NULL)
  15411. && mg_strcasecmp(cl, "identity")) {
  15412. if (mg_strcasecmp(cl, "chunked")) {
  15413. mg_snprintf(conn,
  15414. NULL, /* No truncation check for ebuf */
  15415. ebuf,
  15416. ebuf_len,
  15417. "%s",
  15418. "Bad request");
  15419. *err = 400;
  15420. return 0;
  15421. }
  15422. conn->is_chunked = 1;
  15423. conn->content_len = 0; /* not yet read */
  15424. } else if ((cl = get_header(conn->response_info.http_headers,
  15425. conn->response_info.num_headers,
  15426. "Content-Length"))
  15427. != NULL) {
  15428. char *endptr = NULL;
  15429. conn->content_len = strtoll(cl, &endptr, 10);
  15430. if ((endptr == cl) || (conn->content_len < 0)) {
  15431. mg_snprintf(conn,
  15432. NULL, /* No truncation check for ebuf */
  15433. ebuf,
  15434. ebuf_len,
  15435. "%s",
  15436. "Bad request");
  15437. *err = 411;
  15438. return 0;
  15439. }
  15440. /* Publish the content length back to the response info. */
  15441. conn->response_info.content_length = conn->content_len;
  15442. /* TODO: check if it is still used in response_info */
  15443. conn->request_info.content_length = conn->content_len;
  15444. /* TODO: we should also consider HEAD method */
  15445. if (conn->response_info.status_code == 304) {
  15446. conn->content_len = 0;
  15447. }
  15448. } else {
  15449. /* TODO: we should also consider HEAD method */
  15450. if (((conn->response_info.status_code >= 100)
  15451. && (conn->response_info.status_code <= 199))
  15452. || (conn->response_info.status_code == 204)
  15453. || (conn->response_info.status_code == 304)) {
  15454. conn->content_len = 0;
  15455. } else {
  15456. conn->content_len = -1; /* unknown content length */
  15457. }
  15458. }
  15459. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15460. return 1;
  15461. }
  15462. int
  15463. mg_get_response(struct mg_connection *conn,
  15464. char *ebuf,
  15465. size_t ebuf_len,
  15466. int timeout)
  15467. {
  15468. int err, ret;
  15469. char txt[32]; /* will not overflow */
  15470. char *save_timeout;
  15471. char *new_timeout;
  15472. if (ebuf_len > 0) {
  15473. ebuf[0] = '\0';
  15474. }
  15475. if (!conn) {
  15476. mg_snprintf(conn,
  15477. NULL, /* No truncation check for ebuf */
  15478. ebuf,
  15479. ebuf_len,
  15480. "%s",
  15481. "Parameter error");
  15482. return -1;
  15483. }
  15484. /* Reset the previous responses */
  15485. conn->data_len = 0;
  15486. /* Implementation of API function for HTTP clients */
  15487. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15488. if (timeout >= 0) {
  15489. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15490. new_timeout = txt;
  15491. } else {
  15492. new_timeout = NULL;
  15493. }
  15494. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15495. ret = get_response(conn, ebuf, ebuf_len, &err);
  15496. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15497. #if defined(MG_LEGACY_INTERFACE)
  15498. /* TODO: 1) uri is deprecated;
  15499. * 2) here, ri.uri is the http response code */
  15500. conn->request_info.uri = conn->request_info.request_uri;
  15501. #endif
  15502. conn->request_info.local_uri = conn->request_info.request_uri;
  15503. /* TODO (mid): Define proper return values - maybe return length?
  15504. * For the first test use <0 for error and >0 for OK */
  15505. return (ret == 0) ? -1 : +1;
  15506. }
  15507. struct mg_connection *
  15508. mg_download(const char *host,
  15509. int port,
  15510. int use_ssl,
  15511. char *ebuf,
  15512. size_t ebuf_len,
  15513. const char *fmt,
  15514. ...)
  15515. {
  15516. struct mg_connection *conn;
  15517. va_list ap;
  15518. int i;
  15519. int reqerr;
  15520. if (ebuf_len > 0) {
  15521. ebuf[0] = '\0';
  15522. }
  15523. va_start(ap, fmt);
  15524. /* open a connection */
  15525. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15526. if (conn != NULL) {
  15527. i = mg_vprintf(conn, fmt, ap);
  15528. if (i <= 0) {
  15529. mg_snprintf(conn,
  15530. NULL, /* No truncation check for ebuf */
  15531. ebuf,
  15532. ebuf_len,
  15533. "%s",
  15534. "Error sending request");
  15535. } else {
  15536. /* make sure the buffer is clear */
  15537. conn->data_len = 0;
  15538. get_response(conn, ebuf, ebuf_len, &reqerr);
  15539. #if defined(MG_LEGACY_INTERFACE)
  15540. /* TODO: 1) uri is deprecated;
  15541. * 2) here, ri.uri is the http response code */
  15542. conn->request_info.uri = conn->request_info.request_uri;
  15543. #endif
  15544. conn->request_info.local_uri = conn->request_info.request_uri;
  15545. }
  15546. }
  15547. /* if an error occurred, close the connection */
  15548. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15549. mg_close_connection(conn);
  15550. conn = NULL;
  15551. }
  15552. va_end(ap);
  15553. return conn;
  15554. }
  15555. struct websocket_client_thread_data {
  15556. struct mg_connection *conn;
  15557. mg_websocket_data_handler data_handler;
  15558. mg_websocket_close_handler close_handler;
  15559. void *callback_data;
  15560. };
  15561. #if defined(USE_WEBSOCKET)
  15562. #if defined(_WIN32)
  15563. static unsigned __stdcall websocket_client_thread(void *data)
  15564. #else
  15565. static void *
  15566. websocket_client_thread(void *data)
  15567. #endif
  15568. {
  15569. struct websocket_client_thread_data *cdata =
  15570. (struct websocket_client_thread_data *)data;
  15571. void *user_thread_ptr = NULL;
  15572. #if !defined(_WIN32)
  15573. struct sigaction sa;
  15574. /* Ignore SIGPIPE */
  15575. memset(&sa, 0, sizeof(sa));
  15576. sa.sa_handler = SIG_IGN;
  15577. sigaction(SIGPIPE, &sa, NULL);
  15578. #endif
  15579. mg_set_thread_name("ws-clnt");
  15580. if (cdata->conn->phys_ctx) {
  15581. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15582. /* 3 indicates a websocket client thread */
  15583. /* TODO: check if conn->phys_ctx can be set */
  15584. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15585. cdata->conn->phys_ctx, 3);
  15586. }
  15587. }
  15588. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15589. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15590. if (cdata->close_handler != NULL) {
  15591. cdata->close_handler(cdata->conn, cdata->callback_data);
  15592. }
  15593. /* The websocket_client context has only this thread. If it runs out,
  15594. set the stop_flag to 2 (= "stopped"). */
  15595. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15596. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15597. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15598. 3,
  15599. user_thread_ptr);
  15600. }
  15601. mg_free((void *)cdata);
  15602. #if defined(_WIN32)
  15603. return 0;
  15604. #else
  15605. return NULL;
  15606. #endif
  15607. }
  15608. #endif
  15609. static struct mg_connection *
  15610. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15611. int use_ssl,
  15612. char *error_buffer,
  15613. size_t error_buffer_size,
  15614. const char *path,
  15615. const char *origin,
  15616. mg_websocket_data_handler data_func,
  15617. mg_websocket_close_handler close_func,
  15618. void *user_data)
  15619. {
  15620. struct mg_connection *conn = NULL;
  15621. #if defined(USE_WEBSOCKET)
  15622. struct websocket_client_thread_data *thread_data;
  15623. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15624. const char *handshake_req;
  15625. int port = client_options->port;
  15626. const char *host = client_options->host;
  15627. int i;
  15628. if (origin != NULL) {
  15629. handshake_req = "GET %s HTTP/1.1\r\n"
  15630. "Host: %s\r\n"
  15631. "Upgrade: websocket\r\n"
  15632. "Connection: Upgrade\r\n"
  15633. "Sec-WebSocket-Key: %s\r\n"
  15634. "Sec-WebSocket-Version: 13\r\n"
  15635. "Origin: %s\r\n"
  15636. "\r\n";
  15637. } else {
  15638. handshake_req = "GET %s HTTP/1.1\r\n"
  15639. "Host: %s\r\n"
  15640. "Upgrade: websocket\r\n"
  15641. "Connection: Upgrade\r\n"
  15642. "Sec-WebSocket-Key: %s\r\n"
  15643. "Sec-WebSocket-Version: 13\r\n"
  15644. "\r\n";
  15645. }
  15646. #if defined(__clang__)
  15647. #pragma clang diagnostic push
  15648. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15649. #endif
  15650. /* Establish the client connection and request upgrade */
  15651. conn =
  15652. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15653. if (conn == NULL) {
  15654. /* error_buffer already filled */
  15655. return NULL;
  15656. }
  15657. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15658. if (i <= 0) {
  15659. mg_snprintf(conn,
  15660. NULL, /* No truncation check for ebuf */
  15661. error_buffer,
  15662. error_buffer_size,
  15663. "%s",
  15664. "Error sending request");
  15665. mg_close_connection(conn);
  15666. return NULL;
  15667. }
  15668. conn->data_len = 0;
  15669. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15670. mg_close_connection(conn);
  15671. return NULL;
  15672. }
  15673. conn->request_info.local_uri = conn->request_info.request_uri;
  15674. #if defined(__clang__)
  15675. #pragma clang diagnostic pop
  15676. #endif
  15677. /* Connection object will be null if something goes wrong */
  15678. if (conn == NULL) {
  15679. if (!*error_buffer) {
  15680. /* There should be already an error message */
  15681. mg_snprintf(conn,
  15682. NULL, /* No truncation check for ebuf */
  15683. error_buffer,
  15684. error_buffer_size,
  15685. "Unexpected error");
  15686. }
  15687. return NULL;
  15688. }
  15689. if (conn->response_info.status_code != 101) {
  15690. /* We sent an "upgrade" request. For a correct websocket
  15691. * protocol handshake, we expect a "101 Continue" response.
  15692. * Otherwise it is a protocol violation. Maybe the HTTP
  15693. * Server does not know websockets. */
  15694. if (!*error_buffer) {
  15695. /* set an error, if not yet set */
  15696. mg_snprintf(conn,
  15697. NULL, /* No truncation check for ebuf */
  15698. error_buffer,
  15699. error_buffer_size,
  15700. "Unexpected server reply");
  15701. }
  15702. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15703. mg_close_connection(conn);
  15704. return NULL;
  15705. }
  15706. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15707. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15708. if (!thread_data) {
  15709. DEBUG_TRACE("%s\r\n", "Out of memory");
  15710. mg_close_connection(conn);
  15711. return NULL;
  15712. }
  15713. thread_data->conn = conn;
  15714. thread_data->data_handler = data_func;
  15715. thread_data->close_handler = close_func;
  15716. thread_data->callback_data = user_data;
  15717. conn->phys_ctx->worker_threadids =
  15718. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15719. if (!conn->phys_ctx->worker_threadids) {
  15720. DEBUG_TRACE("%s\r\n", "Out of memory");
  15721. mg_free(thread_data);
  15722. mg_close_connection(conn);
  15723. return NULL;
  15724. }
  15725. /* Now upgrade to ws/wss client context */
  15726. conn->phys_ctx->user_data = user_data;
  15727. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15728. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15729. /* Start a thread to read the websocket client connection
  15730. * This thread will automatically stop when mg_disconnect is
  15731. * called on the client connection */
  15732. if (mg_start_thread_with_id(websocket_client_thread,
  15733. thread_data,
  15734. conn->phys_ctx->worker_threadids)
  15735. != 0) {
  15736. conn->phys_ctx->cfg_worker_threads = 0;
  15737. mg_free(thread_data);
  15738. mg_close_connection(conn);
  15739. conn = NULL;
  15740. DEBUG_TRACE("%s",
  15741. "Websocket client connect thread could not be started\r\n");
  15742. }
  15743. #else
  15744. /* Appease "unused parameter" warnings */
  15745. (void)client_options;
  15746. (void)use_ssl;
  15747. (void)error_buffer;
  15748. (void)error_buffer_size;
  15749. (void)path;
  15750. (void)origin;
  15751. (void)user_data;
  15752. (void)data_func;
  15753. (void)close_func;
  15754. #endif
  15755. return conn;
  15756. }
  15757. struct mg_connection *
  15758. mg_connect_websocket_client(const char *host,
  15759. int port,
  15760. int use_ssl,
  15761. char *error_buffer,
  15762. size_t error_buffer_size,
  15763. const char *path,
  15764. const char *origin,
  15765. mg_websocket_data_handler data_func,
  15766. mg_websocket_close_handler close_func,
  15767. void *user_data)
  15768. {
  15769. struct mg_client_options client_options;
  15770. memset(&client_options, 0, sizeof(client_options));
  15771. client_options.host = host;
  15772. client_options.port = port;
  15773. return mg_connect_websocket_client_impl(&client_options,
  15774. use_ssl,
  15775. error_buffer,
  15776. error_buffer_size,
  15777. path,
  15778. origin,
  15779. data_func,
  15780. close_func,
  15781. user_data);
  15782. }
  15783. struct mg_connection *
  15784. mg_connect_websocket_client_secure(
  15785. const struct mg_client_options *client_options,
  15786. char *error_buffer,
  15787. size_t error_buffer_size,
  15788. const char *path,
  15789. const char *origin,
  15790. mg_websocket_data_handler data_func,
  15791. mg_websocket_close_handler close_func,
  15792. void *user_data)
  15793. {
  15794. if (!client_options) {
  15795. return NULL;
  15796. }
  15797. return mg_connect_websocket_client_impl(client_options,
  15798. 1,
  15799. error_buffer,
  15800. error_buffer_size,
  15801. path,
  15802. origin,
  15803. data_func,
  15804. close_func,
  15805. user_data);
  15806. }
  15807. /* Prepare connection data structure */
  15808. static void
  15809. init_connection(struct mg_connection *conn)
  15810. {
  15811. /* Is keep alive allowed by the server */
  15812. int keep_alive_enabled =
  15813. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15814. if (!keep_alive_enabled) {
  15815. conn->must_close = 1;
  15816. }
  15817. /* Important: on new connection, reset the receiving buffer. Credit
  15818. * goes to crule42. */
  15819. conn->data_len = 0;
  15820. conn->handled_requests = 0;
  15821. mg_set_user_connection_data(conn, NULL);
  15822. #if defined(USE_SERVER_STATS)
  15823. conn->conn_state = 2; /* init */
  15824. #endif
  15825. /* call the init_connection callback if assigned */
  15826. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15827. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15828. void *conn_data = NULL;
  15829. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15830. mg_set_user_connection_data(conn, conn_data);
  15831. }
  15832. }
  15833. }
  15834. /* Process a connection - may handle multiple requests
  15835. * using the same connection.
  15836. * Must be called with a valid connection (conn and
  15837. * conn->phys_ctx must be valid).
  15838. */
  15839. static void
  15840. process_new_connection(struct mg_connection *conn)
  15841. {
  15842. struct mg_request_info *ri = &conn->request_info;
  15843. int keep_alive, discard_len;
  15844. char ebuf[100];
  15845. const char *hostend;
  15846. int reqerr, uri_type;
  15847. #if defined(USE_SERVER_STATS)
  15848. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15849. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15850. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15851. /* could use atomic compare exchange, but this
  15852. * seems overkill for statistics data */
  15853. conn->phys_ctx->max_active_connections = mcon;
  15854. }
  15855. #endif
  15856. init_connection(conn);
  15857. DEBUG_TRACE("Start processing connection from %s",
  15858. conn->request_info.remote_addr);
  15859. /* Loop over multiple requests sent using the same connection
  15860. * (while "keep alive"). */
  15861. do {
  15862. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15863. conn->handled_requests + 1);
  15864. #if defined(USE_SERVER_STATS)
  15865. conn->conn_state = 3; /* ready */
  15866. #endif
  15867. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15868. /* The request sent by the client could not be understood by
  15869. * the server, or it was incomplete or a timeout. Send an
  15870. * error message and close the connection. */
  15871. if (reqerr > 0) {
  15872. DEBUG_ASSERT(ebuf[0] != '\0');
  15873. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15874. }
  15875. } else if (strcmp(ri->http_version, "1.0")
  15876. && strcmp(ri->http_version, "1.1")) {
  15877. /* HTTP/2 is not allowed here */
  15878. mg_snprintf(conn,
  15879. NULL, /* No truncation check for ebuf */
  15880. ebuf,
  15881. sizeof(ebuf),
  15882. "Bad HTTP version: [%s]",
  15883. ri->http_version);
  15884. mg_send_http_error(conn, 505, "%s", ebuf);
  15885. }
  15886. if (ebuf[0] == '\0') {
  15887. uri_type = get_uri_type(conn->request_info.request_uri);
  15888. switch (uri_type) {
  15889. case 1:
  15890. /* Asterisk */
  15891. conn->request_info.local_uri = 0;
  15892. /* TODO: Deal with '*'. */
  15893. break;
  15894. case 2:
  15895. /* relative uri */
  15896. conn->request_info.local_uri = conn->request_info.request_uri;
  15897. break;
  15898. case 3:
  15899. case 4:
  15900. /* absolute uri (with/without port) */
  15901. hostend = get_rel_url_at_current_server(
  15902. conn->request_info.request_uri, conn);
  15903. if (hostend) {
  15904. conn->request_info.local_uri = hostend;
  15905. } else {
  15906. conn->request_info.local_uri = NULL;
  15907. }
  15908. break;
  15909. default:
  15910. mg_snprintf(conn,
  15911. NULL, /* No truncation check for ebuf */
  15912. ebuf,
  15913. sizeof(ebuf),
  15914. "Invalid URI");
  15915. mg_send_http_error(conn, 400, "%s", ebuf);
  15916. conn->request_info.local_uri = NULL;
  15917. break;
  15918. }
  15919. #if defined(MG_LEGACY_INTERFACE)
  15920. /* Legacy before split into local_uri and request_uri */
  15921. conn->request_info.uri = conn->request_info.local_uri;
  15922. #endif
  15923. }
  15924. if (ebuf[0] != '\0') {
  15925. conn->protocol_type = -1;
  15926. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15927. /* HTTP/1 allows protocol upgrade */
  15928. conn->protocol_type = should_switch_to_protocol(conn);
  15929. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15930. /* This will occur, if a HTTP/1.1 request should be upgraded
  15931. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15932. * Since most (all?) major browsers only support HTTP/2 using
  15933. * ALPN, this is hard to test and very low priority.
  15934. * Deactivate it (at least for now).
  15935. */
  15936. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15937. }
  15938. }
  15939. DEBUG_TRACE("http: %s, error: %s",
  15940. (ri->http_version ? ri->http_version : "none"),
  15941. (ebuf[0] ? ebuf : "none"));
  15942. if (ebuf[0] == '\0') {
  15943. if (conn->request_info.local_uri) {
  15944. /* handle request to local server */
  15945. #if defined(USE_SERVER_STATS)
  15946. conn->conn_state = 4; /* processing */
  15947. #endif
  15948. handle_request(conn);
  15949. #if defined(USE_SERVER_STATS)
  15950. conn->conn_state = 5; /* processed */
  15951. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15952. conn->consumed_content);
  15953. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15954. conn->num_bytes_sent);
  15955. #endif
  15956. DEBUG_TRACE("%s", "handle_request done");
  15957. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15958. conn->phys_ctx->callbacks.end_request(conn,
  15959. conn->status_code);
  15960. DEBUG_TRACE("%s", "end_request callback done");
  15961. }
  15962. log_access(conn);
  15963. } else {
  15964. /* TODO: handle non-local request (PROXY) */
  15965. conn->must_close = 1;
  15966. }
  15967. } else {
  15968. conn->must_close = 1;
  15969. }
  15970. if (ri->remote_user != NULL) {
  15971. mg_free((void *)ri->remote_user);
  15972. /* Important! When having connections with and without auth
  15973. * would cause double free and then crash */
  15974. ri->remote_user = NULL;
  15975. }
  15976. /* NOTE(lsm): order is important here. should_keep_alive() call
  15977. * is using parsed request, which will be invalid after
  15978. * memmove's below.
  15979. * Therefore, memorize should_keep_alive() result now for later
  15980. * use in loop exit condition. */
  15981. /* Enable it only if this request is completely discardable. */
  15982. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  15983. && should_keep_alive(conn) && (conn->content_len >= 0)
  15984. && (conn->request_len > 0)
  15985. && ((conn->is_chunked == 4)
  15986. || (!conn->is_chunked
  15987. && ((conn->consumed_content == conn->content_len)
  15988. || ((conn->request_len + conn->content_len)
  15989. <= conn->data_len))))
  15990. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  15991. if (keep_alive) {
  15992. /* Discard all buffered data for this request */
  15993. discard_len =
  15994. ((conn->request_len + conn->content_len) < conn->data_len)
  15995. ? (int)(conn->request_len + conn->content_len)
  15996. : conn->data_len;
  15997. conn->data_len -= discard_len;
  15998. if (conn->data_len > 0) {
  15999. DEBUG_TRACE("discard_len = %d", discard_len);
  16000. memmove(conn->buf,
  16001. conn->buf + discard_len,
  16002. (size_t)conn->data_len);
  16003. }
  16004. }
  16005. DEBUG_ASSERT(conn->data_len >= 0);
  16006. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16007. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16008. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16009. (long int)conn->data_len,
  16010. (long int)conn->buf_size);
  16011. break;
  16012. }
  16013. conn->handled_requests++;
  16014. } while (keep_alive);
  16015. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16016. conn->request_info.remote_addr,
  16017. difftime(time(NULL), conn->conn_birth_time));
  16018. close_connection(conn);
  16019. #if defined(USE_SERVER_STATS)
  16020. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16021. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16022. #endif
  16023. }
  16024. #if defined(ALTERNATIVE_QUEUE)
  16025. static void
  16026. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16027. {
  16028. unsigned int i;
  16029. while (!ctx->stop_flag) {
  16030. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16031. /* find a free worker slot and signal it */
  16032. if (ctx->client_socks[i].in_use == 2) {
  16033. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16034. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16035. ctx->client_socks[i] = *sp;
  16036. ctx->client_socks[i].in_use = 1;
  16037. /* socket has been moved to the consumer */
  16038. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16039. (void)event_signal(ctx->client_wait_events[i]);
  16040. return;
  16041. }
  16042. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16043. }
  16044. }
  16045. /* queue is full */
  16046. mg_sleep(1);
  16047. }
  16048. /* must consume */
  16049. set_blocking_mode(sp->sock);
  16050. closesocket(sp->sock);
  16051. }
  16052. static int
  16053. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16054. {
  16055. DEBUG_TRACE("%s", "going idle");
  16056. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16057. ctx->client_socks[thread_index].in_use = 2;
  16058. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16059. event_wait(ctx->client_wait_events[thread_index]);
  16060. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16061. *sp = ctx->client_socks[thread_index];
  16062. if (ctx->stop_flag) {
  16063. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16064. if (sp->in_use == 1) {
  16065. /* must consume */
  16066. set_blocking_mode(sp->sock);
  16067. closesocket(sp->sock);
  16068. }
  16069. return 0;
  16070. }
  16071. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16072. if (sp->in_use == 1) {
  16073. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16074. return 1;
  16075. }
  16076. /* must not reach here */
  16077. DEBUG_ASSERT(0);
  16078. return 0;
  16079. }
  16080. #else /* ALTERNATIVE_QUEUE */
  16081. /* Worker threads take accepted socket from the queue */
  16082. static int
  16083. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16084. {
  16085. (void)thread_index;
  16086. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16087. DEBUG_TRACE("%s", "going idle");
  16088. /* If the queue is empty, wait. We're idle at this point. */
  16089. while ((ctx->sq_head == ctx->sq_tail)
  16090. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16091. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16092. }
  16093. /* If we're stopping, sq_head may be equal to sq_tail. */
  16094. if (ctx->sq_head > ctx->sq_tail) {
  16095. /* Copy socket from the queue and increment tail */
  16096. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16097. ctx->sq_tail++;
  16098. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16099. /* Wrap pointers if needed */
  16100. while (ctx->sq_tail > ctx->sq_size) {
  16101. ctx->sq_tail -= ctx->sq_size;
  16102. ctx->sq_head -= ctx->sq_size;
  16103. }
  16104. }
  16105. (void)pthread_cond_signal(&ctx->sq_empty);
  16106. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16107. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16108. }
  16109. /* Master thread adds accepted socket to a queue */
  16110. static void
  16111. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16112. {
  16113. int queue_filled;
  16114. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16115. queue_filled = ctx->sq_head - ctx->sq_tail;
  16116. /* If the queue is full, wait */
  16117. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16118. && (queue_filled >= ctx->sq_size)) {
  16119. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16120. #if defined(USE_SERVER_STATS)
  16121. if (queue_filled > ctx->sq_max_fill) {
  16122. ctx->sq_max_fill = queue_filled;
  16123. }
  16124. #endif
  16125. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16126. ctx->sq_blocked = 0; /* Not blocked now */
  16127. queue_filled = ctx->sq_head - ctx->sq_tail;
  16128. }
  16129. if (queue_filled < ctx->sq_size) {
  16130. /* Copy socket to the queue and increment head */
  16131. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16132. ctx->sq_head++;
  16133. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16134. }
  16135. queue_filled = ctx->sq_head - ctx->sq_tail;
  16136. #if defined(USE_SERVER_STATS)
  16137. if (queue_filled > ctx->sq_max_fill) {
  16138. ctx->sq_max_fill = queue_filled;
  16139. }
  16140. #endif
  16141. (void)pthread_cond_signal(&ctx->sq_full);
  16142. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16143. }
  16144. #endif /* ALTERNATIVE_QUEUE */
  16145. static void
  16146. worker_thread_run(struct mg_connection *conn)
  16147. {
  16148. struct mg_context *ctx = conn->phys_ctx;
  16149. int thread_index;
  16150. struct mg_workerTLS tls;
  16151. #if defined(MG_LEGACY_INTERFACE)
  16152. uint32_t addr;
  16153. #endif
  16154. mg_set_thread_name("worker");
  16155. tls.is_master = 0;
  16156. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16157. #if defined(_WIN32)
  16158. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16159. #endif
  16160. /* Initialize thread local storage before calling any callback */
  16161. pthread_setspecific(sTlsKey, &tls);
  16162. /* Check if there is a user callback */
  16163. if (ctx->callbacks.init_thread) {
  16164. /* call init_thread for a worker thread (type 1), and store the
  16165. * return value */
  16166. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16167. } else {
  16168. /* No callback: set user pointer to NULL */
  16169. tls.user_ptr = NULL;
  16170. }
  16171. /* Connection structure has been pre-allocated */
  16172. thread_index = (int)(conn - ctx->worker_connections);
  16173. if ((thread_index < 0)
  16174. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16175. mg_cry_ctx_internal(ctx,
  16176. "Internal error: Invalid worker index %i",
  16177. thread_index);
  16178. return;
  16179. }
  16180. /* Request buffers are not pre-allocated. They are private to the
  16181. * request and do not contain any state information that might be
  16182. * of interest to anyone observing a server status. */
  16183. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16184. if (conn->buf == NULL) {
  16185. mg_cry_ctx_internal(
  16186. ctx,
  16187. "Out of memory: Cannot allocate buffer for worker %i",
  16188. thread_index);
  16189. return;
  16190. }
  16191. conn->buf_size = (int)ctx->max_request_size;
  16192. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16193. conn->host = NULL; /* until we have more information. */
  16194. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16195. conn->request_info.user_data = ctx->user_data;
  16196. /* Allocate a mutex for this connection to allow communication both
  16197. * within the request handler and from elsewhere in the application
  16198. */
  16199. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16200. mg_free(conn->buf);
  16201. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16202. return;
  16203. }
  16204. #if defined(USE_SERVER_STATS)
  16205. conn->conn_state = 1; /* not consumed */
  16206. #endif
  16207. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16208. * signal sq_empty condvar to wake up the master waiting in
  16209. * produce_socket() */
  16210. while (consume_socket(ctx, &conn->client, thread_index)) {
  16211. /* New connections must start with new protocol negotiation */
  16212. tls.alpn_proto = NULL;
  16213. #if defined(USE_SERVER_STATS)
  16214. conn->conn_close_time = 0;
  16215. #endif
  16216. conn->conn_birth_time = time(NULL);
  16217. /* Fill in IP, port info early so even if SSL setup below fails,
  16218. * error handler would have the corresponding info.
  16219. * Thanks to Johannes Winkelmann for the patch.
  16220. */
  16221. #if defined(USE_IPV6)
  16222. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16223. conn->request_info.remote_port =
  16224. ntohs(conn->client.rsa.sin6.sin6_port);
  16225. } else
  16226. #endif
  16227. {
  16228. conn->request_info.remote_port =
  16229. ntohs(conn->client.rsa.sin.sin_port);
  16230. }
  16231. sockaddr_to_string(conn->request_info.remote_addr,
  16232. sizeof(conn->request_info.remote_addr),
  16233. &conn->client.rsa);
  16234. DEBUG_TRACE("Start processing connection from %s",
  16235. conn->request_info.remote_addr);
  16236. conn->request_info.is_ssl = conn->client.is_ssl;
  16237. if (conn->client.is_ssl) {
  16238. #if !defined(NO_SSL)
  16239. /* HTTPS connection */
  16240. if (sslize(conn,
  16241. SSL_accept,
  16242. NULL)) {
  16243. /* conn->dom_ctx is set in get_request */
  16244. /* Get SSL client certificate information (if set) */
  16245. struct mg_client_cert client_cert;
  16246. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16247. conn->request_info.client_cert = &client_cert;
  16248. }
  16249. /* process HTTPS connection */
  16250. #if defined(USE_HTTP2)
  16251. if ((tls.alpn_proto != NULL)
  16252. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16253. /* process HTTPS/2 connection */
  16254. init_connection(conn);
  16255. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16256. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16257. conn->content_len = -1;
  16258. conn->is_chunked = 0;
  16259. process_new_http2_connection(conn);
  16260. } else
  16261. #endif
  16262. {
  16263. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16264. process_new_connection(conn);
  16265. }
  16266. /* Free client certificate info */
  16267. if (conn->request_info.client_cert) {
  16268. mg_free((void *)(conn->request_info.client_cert->subject));
  16269. mg_free((void *)(conn->request_info.client_cert->issuer));
  16270. mg_free((void *)(conn->request_info.client_cert->serial));
  16271. mg_free((void *)(conn->request_info.client_cert->finger));
  16272. /* Free certificate memory */
  16273. X509_free(
  16274. (X509 *)conn->request_info.client_cert->peer_cert);
  16275. conn->request_info.client_cert->peer_cert = 0;
  16276. conn->request_info.client_cert->subject = 0;
  16277. conn->request_info.client_cert->issuer = 0;
  16278. conn->request_info.client_cert->serial = 0;
  16279. conn->request_info.client_cert->finger = 0;
  16280. conn->request_info.client_cert = 0;
  16281. }
  16282. } else {
  16283. /* make sure the connection is cleaned up on SSL failure */
  16284. close_connection(conn);
  16285. }
  16286. #endif
  16287. } else {
  16288. /* process HTTP connection */
  16289. process_new_connection(conn);
  16290. }
  16291. DEBUG_TRACE("%s", "Connection closed");
  16292. #if defined(USE_SERVER_STATS)
  16293. conn->conn_close_time = time(NULL);
  16294. #endif
  16295. }
  16296. /* Call exit thread user callback */
  16297. if (ctx->callbacks.exit_thread) {
  16298. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16299. }
  16300. /* delete thread local storage objects */
  16301. pthread_setspecific(sTlsKey, NULL);
  16302. #if defined(_WIN32)
  16303. CloseHandle(tls.pthread_cond_helper_mutex);
  16304. #endif
  16305. pthread_mutex_destroy(&conn->mutex);
  16306. /* Free the request buffer. */
  16307. conn->buf_size = 0;
  16308. mg_free(conn->buf);
  16309. conn->buf = NULL;
  16310. #if defined(USE_SERVER_STATS)
  16311. conn->conn_state = 9; /* done */
  16312. #endif
  16313. DEBUG_TRACE("%s", "exiting");
  16314. }
  16315. /* Threads have different return types on Windows and Unix. */
  16316. #if defined(_WIN32)
  16317. static unsigned __stdcall worker_thread(void *thread_func_param)
  16318. {
  16319. worker_thread_run((struct mg_connection *)thread_func_param);
  16320. return 0;
  16321. }
  16322. #else
  16323. static void *
  16324. worker_thread(void *thread_func_param)
  16325. {
  16326. #if !defined(__ZEPHYR__)
  16327. struct sigaction sa;
  16328. /* Ignore SIGPIPE */
  16329. memset(&sa, 0, sizeof(sa));
  16330. sa.sa_handler = SIG_IGN;
  16331. sigaction(SIGPIPE, &sa, NULL);
  16332. #endif
  16333. worker_thread_run((struct mg_connection *)thread_func_param);
  16334. return NULL;
  16335. }
  16336. #endif /* _WIN32 */
  16337. /* This is an internal function, thus all arguments are expected to be
  16338. * valid - a NULL check is not required. */
  16339. static void
  16340. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16341. {
  16342. struct socket so;
  16343. char src_addr[IP_ADDR_STR_LEN];
  16344. socklen_t len = sizeof(so.rsa);
  16345. #if !defined(__ZEPHYR__)
  16346. int on = 1;
  16347. #endif
  16348. memset(&so, 0, sizeof(so));
  16349. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16350. == INVALID_SOCKET) {
  16351. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16352. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16353. mg_cry_ctx_internal(ctx,
  16354. "%s: %s is not allowed to connect",
  16355. __func__,
  16356. src_addr);
  16357. closesocket(so.sock);
  16358. } else {
  16359. /* Put so socket structure into the queue */
  16360. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16361. set_close_on_exec(so.sock, NULL, ctx);
  16362. so.is_ssl = listener->is_ssl;
  16363. so.ssl_redir = listener->ssl_redir;
  16364. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16365. mg_cry_ctx_internal(ctx,
  16366. "%s: getsockname() failed: %s",
  16367. __func__,
  16368. strerror(ERRNO));
  16369. }
  16370. #if !defined(__ZEPHYR__)
  16371. /* Set TCP keep-alive. This is needed because if HTTP-level
  16372. * keep-alive
  16373. * is enabled, and client resets the connection, server won't get
  16374. * TCP FIN or RST and will keep the connection open forever. With
  16375. * TCP keep-alive, next keep-alive handshake will figure out that
  16376. * the client is down and will close the server end.
  16377. * Thanks to Igor Klopov who suggested the patch. */
  16378. if (setsockopt(so.sock,
  16379. SOL_SOCKET,
  16380. SO_KEEPALIVE,
  16381. (SOCK_OPT_TYPE)&on,
  16382. sizeof(on))
  16383. != 0) {
  16384. mg_cry_ctx_internal(
  16385. ctx,
  16386. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16387. __func__,
  16388. strerror(ERRNO));
  16389. }
  16390. #endif
  16391. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16392. * to effectively fill up the underlying IP packet payload and
  16393. * reduce the overhead of sending lots of small buffers. However
  16394. * this hurts the server's throughput (ie. operations per second)
  16395. * when HTTP 1.1 persistent connections are used and the responses
  16396. * are relatively small (eg. less than 1400 bytes).
  16397. */
  16398. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16399. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16400. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16401. mg_cry_ctx_internal(
  16402. ctx,
  16403. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16404. __func__,
  16405. strerror(ERRNO));
  16406. }
  16407. }
  16408. /* The "non blocking" property should already be
  16409. * inherited from the parent socket. Set it for
  16410. * non-compliant socket implementations. */
  16411. set_non_blocking_mode(so.sock);
  16412. so.in_use = 0;
  16413. produce_socket(ctx, &so);
  16414. }
  16415. }
  16416. static void
  16417. master_thread_run(struct mg_context *ctx)
  16418. {
  16419. struct mg_workerTLS tls;
  16420. struct mg_pollfd *pfd;
  16421. unsigned int i;
  16422. unsigned int workerthreadcount;
  16423. if (!ctx) {
  16424. return;
  16425. }
  16426. mg_set_thread_name("master");
  16427. /* Increase priority of the master thread */
  16428. #if defined(_WIN32)
  16429. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16430. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16431. int min_prio = sched_get_priority_min(SCHED_RR);
  16432. int max_prio = sched_get_priority_max(SCHED_RR);
  16433. if ((min_prio >= 0) && (max_prio >= 0)
  16434. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16435. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16436. struct sched_param sched_param = {0};
  16437. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16438. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16439. }
  16440. #endif
  16441. /* Initialize thread local storage */
  16442. #if defined(_WIN32)
  16443. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16444. #endif
  16445. tls.is_master = 1;
  16446. pthread_setspecific(sTlsKey, &tls);
  16447. if (ctx->callbacks.init_thread) {
  16448. /* Callback for the master thread (type 0) */
  16449. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16450. } else {
  16451. tls.user_ptr = NULL;
  16452. }
  16453. /* Server starts *now* */
  16454. ctx->start_time = time(NULL);
  16455. /* Start the server */
  16456. pfd = ctx->listening_socket_fds;
  16457. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16458. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16459. pfd[i].fd = ctx->listening_sockets[i].sock;
  16460. pfd[i].events = POLLIN;
  16461. }
  16462. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16463. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16464. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16465. * successful poll, and POLLIN is defined as
  16466. * (POLLRDNORM | POLLRDBAND)
  16467. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16468. * pfd[i].revents == POLLIN. */
  16469. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16470. && (pfd[i].revents & POLLIN)) {
  16471. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16472. }
  16473. }
  16474. }
  16475. }
  16476. /* Here stop_flag is 1 - Initiate shutdown. */
  16477. DEBUG_TRACE("%s", "stopping workers");
  16478. /* Stop signal received: somebody called mg_stop. Quit. */
  16479. close_all_listening_sockets(ctx);
  16480. /* Wakeup workers that are waiting for connections to handle. */
  16481. #if defined(ALTERNATIVE_QUEUE)
  16482. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16483. event_signal(ctx->client_wait_events[i]);
  16484. }
  16485. #else
  16486. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16487. pthread_cond_broadcast(&ctx->sq_full);
  16488. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16489. #endif
  16490. /* Join all worker threads to avoid leaking threads. */
  16491. workerthreadcount = ctx->cfg_worker_threads;
  16492. for (i = 0; i < workerthreadcount; i++) {
  16493. if (ctx->worker_threadids[i] != 0) {
  16494. mg_join_thread(ctx->worker_threadids[i]);
  16495. }
  16496. }
  16497. #if defined(USE_LUA)
  16498. /* Free Lua state of lua background task */
  16499. if (ctx->lua_background_state) {
  16500. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16501. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16502. if (lua_istable(lstate, -1)) {
  16503. reg_boolean(lstate, "shutdown", 1);
  16504. lua_pop(lstate, 1);
  16505. mg_sleep(2);
  16506. }
  16507. lua_close(lstate);
  16508. ctx->lua_background_state = 0;
  16509. }
  16510. #endif
  16511. DEBUG_TRACE("%s", "exiting");
  16512. /* call exit thread callback */
  16513. if (ctx->callbacks.exit_thread) {
  16514. /* Callback for the master thread (type 0) */
  16515. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16516. }
  16517. #if defined(_WIN32)
  16518. CloseHandle(tls.pthread_cond_helper_mutex);
  16519. #endif
  16520. pthread_setspecific(sTlsKey, NULL);
  16521. /* Signal mg_stop() that we're done.
  16522. * WARNING: This must be the very last thing this
  16523. * thread does, as ctx becomes invalid after this line. */
  16524. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16525. }
  16526. /* Threads have different return types on Windows and Unix. */
  16527. #if defined(_WIN32)
  16528. static unsigned __stdcall master_thread(void *thread_func_param)
  16529. {
  16530. master_thread_run((struct mg_context *)thread_func_param);
  16531. return 0;
  16532. }
  16533. #else
  16534. static void *
  16535. master_thread(void *thread_func_param)
  16536. {
  16537. #if !defined(__ZEPHYR__)
  16538. struct sigaction sa;
  16539. /* Ignore SIGPIPE */
  16540. memset(&sa, 0, sizeof(sa));
  16541. sa.sa_handler = SIG_IGN;
  16542. sigaction(SIGPIPE, &sa, NULL);
  16543. #endif
  16544. master_thread_run((struct mg_context *)thread_func_param);
  16545. return NULL;
  16546. }
  16547. #endif /* _WIN32 */
  16548. static void
  16549. free_context(struct mg_context *ctx)
  16550. {
  16551. int i;
  16552. struct mg_handler_info *tmp_rh;
  16553. if (ctx == NULL) {
  16554. return;
  16555. }
  16556. if (ctx->callbacks.exit_context) {
  16557. ctx->callbacks.exit_context(ctx);
  16558. }
  16559. /* All threads exited, no sync is needed. Destroy thread mutex and
  16560. * condvars
  16561. */
  16562. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16563. #if defined(ALTERNATIVE_QUEUE)
  16564. mg_free(ctx->client_socks);
  16565. if (ctx->client_wait_events != NULL) {
  16566. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16567. event_destroy(ctx->client_wait_events[i]);
  16568. }
  16569. mg_free(ctx->client_wait_events);
  16570. }
  16571. #else
  16572. (void)pthread_cond_destroy(&ctx->sq_empty);
  16573. (void)pthread_cond_destroy(&ctx->sq_full);
  16574. mg_free(ctx->squeue);
  16575. #endif
  16576. /* Destroy other context global data structures mutex */
  16577. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16578. #if defined(USE_TIMERS)
  16579. timers_exit(ctx);
  16580. #endif
  16581. /* Deallocate config parameters */
  16582. for (i = 0; i < NUM_OPTIONS; i++) {
  16583. if (ctx->dd.config[i] != NULL) {
  16584. #if defined(_MSC_VER)
  16585. #pragma warning(suppress : 6001)
  16586. #endif
  16587. mg_free(ctx->dd.config[i]);
  16588. }
  16589. }
  16590. /* Deallocate request handlers */
  16591. while (ctx->dd.handlers) {
  16592. tmp_rh = ctx->dd.handlers;
  16593. ctx->dd.handlers = tmp_rh->next;
  16594. mg_free(tmp_rh->uri);
  16595. mg_free(tmp_rh);
  16596. }
  16597. #if !defined(NO_SSL)
  16598. /* Deallocate SSL context */
  16599. if (ctx->dd.ssl_ctx != NULL) {
  16600. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16601. int callback_ret =
  16602. (ctx->callbacks.external_ssl_ctx == NULL)
  16603. ? 0
  16604. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16605. if (callback_ret == 0) {
  16606. SSL_CTX_free(ctx->dd.ssl_ctx);
  16607. }
  16608. /* else: ignore error and ommit SSL_CTX_free in case
  16609. * callback_ret is 1 */
  16610. }
  16611. #endif /* !NO_SSL */
  16612. /* Deallocate worker thread ID array */
  16613. mg_free(ctx->worker_threadids);
  16614. /* Deallocate worker thread ID array */
  16615. mg_free(ctx->worker_connections);
  16616. /* deallocate system name string */
  16617. mg_free(ctx->systemName);
  16618. /* Deallocate context itself */
  16619. mg_free(ctx);
  16620. }
  16621. void
  16622. mg_stop(struct mg_context *ctx)
  16623. {
  16624. pthread_t mt;
  16625. if (!ctx) {
  16626. return;
  16627. }
  16628. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16629. * two threads is not allowed. */
  16630. mt = ctx->masterthreadid;
  16631. if (mt == 0) {
  16632. return;
  16633. }
  16634. ctx->masterthreadid = 0;
  16635. /* Set stop flag, so all threads know they have to exit. */
  16636. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16637. /* Wait until everything has stopped. */
  16638. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16639. (void)mg_sleep(10);
  16640. }
  16641. mg_join_thread(mt);
  16642. free_context(ctx);
  16643. #if defined(_WIN32)
  16644. (void)WSACleanup();
  16645. #endif /* _WIN32 */
  16646. }
  16647. static void
  16648. get_system_name(char **sysName)
  16649. {
  16650. #if defined(_WIN32)
  16651. #if defined(_WIN32_WCE)
  16652. *sysName = mg_strdup("WinCE");
  16653. #else
  16654. char name[128];
  16655. DWORD dwVersion = 0;
  16656. DWORD dwMajorVersion = 0;
  16657. DWORD dwMinorVersion = 0;
  16658. DWORD dwBuild = 0;
  16659. BOOL wowRet, isWoW = FALSE;
  16660. #if defined(_MSC_VER)
  16661. #pragma warning(push)
  16662. /* GetVersion was declared deprecated */
  16663. #pragma warning(disable : 4996)
  16664. #endif
  16665. dwVersion = GetVersion();
  16666. #if defined(_MSC_VER)
  16667. #pragma warning(pop)
  16668. #endif
  16669. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16670. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16671. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16672. (void)dwBuild;
  16673. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16674. sprintf(name,
  16675. "Windows %u.%u%s",
  16676. (unsigned)dwMajorVersion,
  16677. (unsigned)dwMinorVersion,
  16678. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16679. *sysName = mg_strdup(name);
  16680. #endif
  16681. #elif defined(__ZEPHYR__)
  16682. *sysName = mg_strdup("Zephyr OS");
  16683. #else
  16684. struct utsname name;
  16685. memset(&name, 0, sizeof(name));
  16686. uname(&name);
  16687. *sysName = mg_strdup(name.sysname);
  16688. #endif
  16689. }
  16690. static void
  16691. legacy_init(const char **options)
  16692. {
  16693. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16694. if (options) {
  16695. const char **run_options = options;
  16696. const char *optname = config_options[LISTENING_PORTS].name;
  16697. /* Try to find the "listening_ports" option */
  16698. while (*run_options) {
  16699. if (!strcmp(*run_options, optname)) {
  16700. ports_option = run_options[1];
  16701. }
  16702. run_options += 2;
  16703. }
  16704. }
  16705. if (is_ssl_port_used(ports_option)) {
  16706. /* Initialize with SSL support */
  16707. mg_init_library(MG_FEATURES_TLS);
  16708. } else {
  16709. /* Initialize without SSL support */
  16710. mg_init_library(MG_FEATURES_DEFAULT);
  16711. }
  16712. }
  16713. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16714. static
  16715. #endif
  16716. struct mg_context *
  16717. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16718. {
  16719. struct mg_context *ctx;
  16720. const char *name, *value, *default_value;
  16721. int idx, ok, workerthreadcount;
  16722. unsigned int i;
  16723. int itmp;
  16724. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16725. const char **options =
  16726. ((init != NULL) ? (init->configuration_options) : (NULL));
  16727. struct mg_workerTLS tls;
  16728. #if defined(_WIN32)
  16729. WSADATA data;
  16730. WSAStartup(MAKEWORD(2, 2), &data);
  16731. #endif /* _WIN32 */
  16732. if (error != NULL) {
  16733. error->code = 0;
  16734. if (error->text_buffer_size > 0) {
  16735. *error->text = 0;
  16736. }
  16737. }
  16738. if (mg_init_library_called == 0) {
  16739. /* Legacy INIT, if mg_start is called without mg_init_library.
  16740. * Note: This will cause a memory leak when unloading the library.
  16741. */
  16742. legacy_init(options);
  16743. }
  16744. if (mg_init_library_called == 0) {
  16745. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16746. mg_snprintf(NULL,
  16747. NULL, /* No truncation check for error buffers */
  16748. error->text,
  16749. error->text_buffer_size,
  16750. "%s",
  16751. "Library uninitialized");
  16752. }
  16753. return NULL;
  16754. }
  16755. /* Allocate context and initialize reasonable general case defaults. */
  16756. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16757. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16758. mg_snprintf(NULL,
  16759. NULL, /* No truncation check for error buffers */
  16760. error->text,
  16761. error->text_buffer_size,
  16762. "%s",
  16763. "Out of memory");
  16764. }
  16765. return NULL;
  16766. }
  16767. /* Random number generator will initialize at the first call */
  16768. ctx->dd.auth_nonce_mask =
  16769. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16770. /* Save started thread index to reuse in other external API calls
  16771. * For the sake of thread synchronization all non-civetweb threads
  16772. * can be considered as single external thread */
  16773. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16774. tls.is_master = -1; /* Thread calling mg_start */
  16775. tls.thread_idx = ctx->starter_thread_idx;
  16776. #if defined(_WIN32)
  16777. tls.pthread_cond_helper_mutex = NULL;
  16778. #endif
  16779. pthread_setspecific(sTlsKey, &tls);
  16780. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16781. #if !defined(ALTERNATIVE_QUEUE)
  16782. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16783. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16784. ctx->sq_blocked = 0;
  16785. #endif
  16786. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16787. if (!ok) {
  16788. const char *err_msg =
  16789. "Cannot initialize thread synchronization objects";
  16790. /* Fatal error - abort start. However, this situation should never
  16791. * occur in practice. */
  16792. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16793. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16794. mg_snprintf(NULL,
  16795. NULL, /* No truncation check for error buffers */
  16796. error->text,
  16797. error->text_buffer_size,
  16798. "%s",
  16799. err_msg);
  16800. }
  16801. mg_free(ctx);
  16802. pthread_setspecific(sTlsKey, NULL);
  16803. return NULL;
  16804. }
  16805. if ((init != NULL) && (init->callbacks != NULL)) {
  16806. /* Set all callbacks except exit_context. */
  16807. ctx->callbacks = *init->callbacks;
  16808. exit_callback = init->callbacks->exit_context;
  16809. /* The exit callback is activated once the context is successfully
  16810. * created. It should not be called, if an incomplete context object
  16811. * is deleted during a failed initialization. */
  16812. ctx->callbacks.exit_context = 0;
  16813. }
  16814. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16815. ctx->dd.handlers = NULL;
  16816. ctx->dd.next = NULL;
  16817. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16818. ctx->dd.shared_lua_websockets = NULL;
  16819. #endif
  16820. /* Store options */
  16821. while (options && (name = *options++) != NULL) {
  16822. if ((idx = get_option_index(name)) == -1) {
  16823. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16824. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16825. mg_snprintf(NULL,
  16826. NULL, /* No truncation check for error buffers */
  16827. error->text,
  16828. error->text_buffer_size,
  16829. "Invalid configuration option: %s",
  16830. name);
  16831. }
  16832. free_context(ctx);
  16833. pthread_setspecific(sTlsKey, NULL);
  16834. return NULL;
  16835. } else if ((value = *options++) == NULL) {
  16836. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16837. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16838. mg_snprintf(NULL,
  16839. NULL, /* No truncation check for error buffers */
  16840. error->text,
  16841. error->text_buffer_size,
  16842. "Invalid configuration option value: %s",
  16843. name);
  16844. }
  16845. free_context(ctx);
  16846. pthread_setspecific(sTlsKey, NULL);
  16847. return NULL;
  16848. }
  16849. if (ctx->dd.config[idx] != NULL) {
  16850. /* A duplicate configuration option is not an error - the last
  16851. * option value will be used. */
  16852. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16853. mg_free(ctx->dd.config[idx]);
  16854. }
  16855. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16856. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16857. }
  16858. /* Set default value if needed */
  16859. for (i = 0; config_options[i].name != NULL; i++) {
  16860. default_value = config_options[i].default_value;
  16861. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16862. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16863. }
  16864. }
  16865. /* Request size option */
  16866. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16867. if (itmp < 1024) {
  16868. mg_cry_ctx_internal(ctx,
  16869. "%s too small",
  16870. config_options[MAX_REQUEST_SIZE].name);
  16871. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16872. mg_snprintf(NULL,
  16873. NULL, /* No truncation check for error buffers */
  16874. error->text,
  16875. error->text_buffer_size,
  16876. "Invalid configuration option value: %s",
  16877. config_options[MAX_REQUEST_SIZE].name);
  16878. }
  16879. free_context(ctx);
  16880. pthread_setspecific(sTlsKey, NULL);
  16881. return NULL;
  16882. }
  16883. ctx->max_request_size = (unsigned)itmp;
  16884. /* Queue length */
  16885. #if !defined(ALTERNATIVE_QUEUE)
  16886. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16887. if (itmp < 1) {
  16888. mg_cry_ctx_internal(ctx,
  16889. "%s too small",
  16890. config_options[CONNECTION_QUEUE_SIZE].name);
  16891. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16892. mg_snprintf(NULL,
  16893. NULL, /* No truncation check for error buffers */
  16894. error->text,
  16895. error->text_buffer_size,
  16896. "Invalid configuration option value: %s",
  16897. config_options[CONNECTION_QUEUE_SIZE].name);
  16898. }
  16899. free_context(ctx);
  16900. pthread_setspecific(sTlsKey, NULL);
  16901. return NULL;
  16902. }
  16903. ctx->squeue =
  16904. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16905. if (ctx->squeue == NULL) {
  16906. mg_cry_ctx_internal(ctx,
  16907. "Out of memory: Cannot allocate %s",
  16908. config_options[CONNECTION_QUEUE_SIZE].name);
  16909. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16910. mg_snprintf(NULL,
  16911. NULL, /* No truncation check for error buffers */
  16912. error->text,
  16913. error->text_buffer_size,
  16914. "Out of memory: Cannot allocate %s",
  16915. config_options[CONNECTION_QUEUE_SIZE].name);
  16916. }
  16917. free_context(ctx);
  16918. pthread_setspecific(sTlsKey, NULL);
  16919. return NULL;
  16920. }
  16921. ctx->sq_size = itmp;
  16922. #endif
  16923. /* Worker thread count option */
  16924. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16925. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16926. if (workerthreadcount <= 0) {
  16927. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16928. } else {
  16929. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16930. }
  16931. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16932. mg_snprintf(NULL,
  16933. NULL, /* No truncation check for error buffers */
  16934. error->text,
  16935. error->text_buffer_size,
  16936. "Invalid configuration option value: %s",
  16937. config_options[NUM_THREADS].name);
  16938. }
  16939. free_context(ctx);
  16940. pthread_setspecific(sTlsKey, NULL);
  16941. return NULL;
  16942. }
  16943. /* Document root */
  16944. #if defined(NO_FILES)
  16945. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16946. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16947. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16948. mg_snprintf(NULL,
  16949. NULL, /* No truncation check for error buffers */
  16950. error->text,
  16951. error->text_buffer_size,
  16952. "Invalid configuration option value: %s",
  16953. config_options[DOCUMENT_ROOT].name);
  16954. }
  16955. free_context(ctx);
  16956. pthread_setspecific(sTlsKey, NULL);
  16957. return NULL;
  16958. }
  16959. #endif
  16960. get_system_name(&ctx->systemName);
  16961. #if defined(USE_LUA)
  16962. /* If a Lua background script has been configured, start it. */
  16963. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16964. char ebuf[256];
  16965. struct vec opt_vec;
  16966. struct vec eq_vec;
  16967. const char *sparams;
  16968. lua_State *state = mg_prepare_lua_context_script(
  16969. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16970. if (!state) {
  16971. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16972. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16973. mg_snprintf(NULL,
  16974. NULL, /* No truncation check for error buffers */
  16975. error->text,
  16976. error->text_buffer_size,
  16977. "Error in script %s: %s",
  16978. config_options[DOCUMENT_ROOT].name,
  16979. ebuf);
  16980. }
  16981. free_context(ctx);
  16982. pthread_setspecific(sTlsKey, NULL);
  16983. return NULL;
  16984. }
  16985. ctx->lua_background_state = (void *)state;
  16986. lua_newtable(state);
  16987. reg_boolean(state, "shutdown", 0);
  16988. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16989. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16990. reg_llstring(
  16991. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16992. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16993. break;
  16994. }
  16995. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16996. } else {
  16997. ctx->lua_background_state = 0;
  16998. }
  16999. #endif
  17000. /* Step by step initialization of ctx - depending on build options */
  17001. #if !defined(NO_FILESYSTEMS)
  17002. if (!set_gpass_option(ctx, NULL)) {
  17003. const char *err_msg = "Invalid global password file";
  17004. /* Fatal error - abort start. */
  17005. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17006. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17007. mg_snprintf(NULL,
  17008. NULL, /* No truncation check for error buffers */
  17009. error->text,
  17010. error->text_buffer_size,
  17011. "%s",
  17012. err_msg);
  17013. }
  17014. free_context(ctx);
  17015. pthread_setspecific(sTlsKey, NULL);
  17016. return NULL;
  17017. }
  17018. #endif
  17019. #if !defined(NO_SSL)
  17020. if (!init_ssl_ctx(ctx, NULL)) {
  17021. const char *err_msg = "Error initializing SSL context";
  17022. /* Fatal error - abort start. */
  17023. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17024. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17025. mg_snprintf(NULL,
  17026. NULL, /* No truncation check for error buffers */
  17027. error->text,
  17028. error->text_buffer_size,
  17029. "%s",
  17030. err_msg);
  17031. }
  17032. free_context(ctx);
  17033. pthread_setspecific(sTlsKey, NULL);
  17034. return NULL;
  17035. }
  17036. #endif
  17037. if (!set_ports_option(ctx)) {
  17038. const char *err_msg = "Failed to setup server ports";
  17039. /* Fatal error - abort start. */
  17040. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17041. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17042. mg_snprintf(NULL,
  17043. NULL, /* No truncation check for error buffers */
  17044. error->text,
  17045. error->text_buffer_size,
  17046. "%s",
  17047. err_msg);
  17048. }
  17049. free_context(ctx);
  17050. pthread_setspecific(sTlsKey, NULL);
  17051. return NULL;
  17052. }
  17053. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17054. if (!set_uid_option(ctx)) {
  17055. const char *err_msg = "Failed to run as configured user";
  17056. /* Fatal error - abort start. */
  17057. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17058. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17059. mg_snprintf(NULL,
  17060. NULL, /* No truncation check for error buffers */
  17061. error->text,
  17062. error->text_buffer_size,
  17063. "%s",
  17064. err_msg);
  17065. }
  17066. free_context(ctx);
  17067. pthread_setspecific(sTlsKey, NULL);
  17068. return NULL;
  17069. }
  17070. #endif
  17071. if (!set_acl_option(ctx)) {
  17072. const char *err_msg = "Failed to setup access control list";
  17073. /* Fatal error - abort start. */
  17074. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17075. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17076. mg_snprintf(NULL,
  17077. NULL, /* No truncation check for error buffers */
  17078. error->text,
  17079. error->text_buffer_size,
  17080. "%s",
  17081. err_msg);
  17082. }
  17083. free_context(ctx);
  17084. pthread_setspecific(sTlsKey, NULL);
  17085. return NULL;
  17086. }
  17087. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17088. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17089. sizeof(pthread_t),
  17090. ctx);
  17091. if (ctx->worker_threadids == NULL) {
  17092. const char *err_msg = "Not enough memory for worker thread ID array";
  17093. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17094. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17095. mg_snprintf(NULL,
  17096. NULL, /* No truncation check for error buffers */
  17097. error->text,
  17098. error->text_buffer_size,
  17099. "%s",
  17100. err_msg);
  17101. }
  17102. free_context(ctx);
  17103. pthread_setspecific(sTlsKey, NULL);
  17104. return NULL;
  17105. }
  17106. ctx->worker_connections =
  17107. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17108. sizeof(struct mg_connection),
  17109. ctx);
  17110. if (ctx->worker_connections == NULL) {
  17111. const char *err_msg =
  17112. "Not enough memory for worker thread connection array";
  17113. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17114. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17115. mg_snprintf(NULL,
  17116. NULL, /* No truncation check for error buffers */
  17117. error->text,
  17118. error->text_buffer_size,
  17119. "%s",
  17120. err_msg);
  17121. }
  17122. free_context(ctx);
  17123. pthread_setspecific(sTlsKey, NULL);
  17124. return NULL;
  17125. }
  17126. #if defined(ALTERNATIVE_QUEUE)
  17127. ctx->client_wait_events =
  17128. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17129. sizeof(ctx->client_wait_events[0]),
  17130. ctx);
  17131. if (ctx->client_wait_events == NULL) {
  17132. const char *err_msg = "Not enough memory for worker event array";
  17133. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17134. mg_free(ctx->worker_threadids);
  17135. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17136. mg_snprintf(NULL,
  17137. NULL, /* No truncation check for error buffers */
  17138. error->text,
  17139. error->text_buffer_size,
  17140. "%s",
  17141. err_msg);
  17142. }
  17143. free_context(ctx);
  17144. pthread_setspecific(sTlsKey, NULL);
  17145. return NULL;
  17146. }
  17147. ctx->client_socks =
  17148. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17149. sizeof(ctx->client_socks[0]),
  17150. ctx);
  17151. if (ctx->client_socks == NULL) {
  17152. const char *err_msg = "Not enough memory for worker socket array";
  17153. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17154. mg_free(ctx->client_wait_events);
  17155. mg_free(ctx->worker_threadids);
  17156. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17157. mg_snprintf(NULL,
  17158. NULL, /* No truncation check for error buffers */
  17159. error->text,
  17160. error->text_buffer_size,
  17161. "%s",
  17162. err_msg);
  17163. }
  17164. free_context(ctx);
  17165. pthread_setspecific(sTlsKey, NULL);
  17166. return NULL;
  17167. }
  17168. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17169. ctx->client_wait_events[i] = event_create();
  17170. if (ctx->client_wait_events[i] == 0) {
  17171. const char *err_msg = "Error creating worker event %i";
  17172. mg_cry_ctx_internal(ctx, err_msg, i);
  17173. while (i > 0) {
  17174. i--;
  17175. event_destroy(ctx->client_wait_events[i]);
  17176. }
  17177. mg_free(ctx->client_socks);
  17178. mg_free(ctx->client_wait_events);
  17179. mg_free(ctx->worker_threadids);
  17180. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17181. mg_snprintf(NULL,
  17182. NULL, /* No truncation check for error buffers */
  17183. error->text,
  17184. error->text_buffer_size,
  17185. err_msg,
  17186. i);
  17187. }
  17188. free_context(ctx);
  17189. pthread_setspecific(sTlsKey, NULL);
  17190. return NULL;
  17191. }
  17192. }
  17193. #endif
  17194. #if defined(USE_TIMERS)
  17195. if (timers_init(ctx) != 0) {
  17196. const char *err_msg = "Error creating timers";
  17197. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17198. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17199. mg_snprintf(NULL,
  17200. NULL, /* No truncation check for error buffers */
  17201. error->text,
  17202. error->text_buffer_size,
  17203. "%s",
  17204. err_msg);
  17205. }
  17206. free_context(ctx);
  17207. pthread_setspecific(sTlsKey, NULL);
  17208. return NULL;
  17209. }
  17210. #endif
  17211. /* Context has been created - init user libraries */
  17212. if (ctx->callbacks.init_context) {
  17213. ctx->callbacks.init_context(ctx);
  17214. }
  17215. /* From now, the context is successfully created.
  17216. * When it is destroyed, the exit callback should be called. */
  17217. ctx->callbacks.exit_context = exit_callback;
  17218. ctx->context_type = CONTEXT_SERVER; /* server context */
  17219. /* Start worker threads */
  17220. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17221. /* worker_thread sets up the other fields */
  17222. ctx->worker_connections[i].phys_ctx = ctx;
  17223. if (mg_start_thread_with_id(worker_thread,
  17224. &ctx->worker_connections[i],
  17225. &ctx->worker_threadids[i])
  17226. != 0) {
  17227. long error_no = (long)ERRNO;
  17228. /* thread was not created */
  17229. if (i > 0) {
  17230. /* If the second, third, ... thread cannot be created, set a
  17231. * warning, but keep running. */
  17232. mg_cry_ctx_internal(ctx,
  17233. "Cannot start worker thread %i: error %ld",
  17234. i + 1,
  17235. error_no);
  17236. /* If the server initialization should stop here, all
  17237. * threads that have already been created must be stopped
  17238. * first, before any free_context(ctx) call.
  17239. */
  17240. } else {
  17241. /* If the first worker thread cannot be created, stop
  17242. * initialization and free the entire server context. */
  17243. mg_cry_ctx_internal(ctx,
  17244. "Cannot create threads: error %ld",
  17245. error_no);
  17246. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17247. mg_snprintf(
  17248. NULL,
  17249. NULL, /* No truncation check for error buffers */
  17250. error->text,
  17251. error->text_buffer_size,
  17252. "Cannot create first worker thread: error %ld",
  17253. error_no);
  17254. }
  17255. free_context(ctx);
  17256. pthread_setspecific(sTlsKey, NULL);
  17257. return NULL;
  17258. }
  17259. break;
  17260. }
  17261. }
  17262. /* Start master (listening) thread */
  17263. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17264. pthread_setspecific(sTlsKey, NULL);
  17265. return ctx;
  17266. }
  17267. struct mg_context *
  17268. mg_start(const struct mg_callbacks *callbacks,
  17269. void *user_data,
  17270. const char **options)
  17271. {
  17272. struct mg_init_data init = {0};
  17273. init.callbacks = callbacks;
  17274. init.user_data = user_data;
  17275. init.configuration_options = options;
  17276. return mg_start2(&init, NULL);
  17277. }
  17278. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17279. /* Add an additional domain to an already running web server. */
  17280. int
  17281. mg_start_domain2(struct mg_context *ctx,
  17282. const char **options,
  17283. struct mg_error_data *error)
  17284. {
  17285. const char *name;
  17286. const char *value;
  17287. const char *default_value;
  17288. struct mg_domain_context *new_dom;
  17289. struct mg_domain_context *dom;
  17290. int idx, i;
  17291. if (error != NULL) {
  17292. error->code = 0;
  17293. if (error->text_buffer_size > 0) {
  17294. *error->text = 0;
  17295. }
  17296. }
  17297. if ((ctx == NULL) || (options == NULL)) {
  17298. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17299. mg_snprintf(NULL,
  17300. NULL, /* No truncation check for error buffers */
  17301. error->text,
  17302. error->text_buffer_size,
  17303. "%s",
  17304. "Invalid parameters");
  17305. }
  17306. return -1;
  17307. }
  17308. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17309. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17310. mg_snprintf(NULL,
  17311. NULL, /* No truncation check for error buffers */
  17312. error->text,
  17313. error->text_buffer_size,
  17314. "%s",
  17315. "Server already stopped");
  17316. }
  17317. return -1;
  17318. }
  17319. new_dom = (struct mg_domain_context *)
  17320. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17321. if (!new_dom) {
  17322. /* Out of memory */
  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. "Out or memory");
  17330. }
  17331. return -6;
  17332. }
  17333. /* Store options - TODO: unite duplicate code */
  17334. while (options && (name = *options++) != NULL) {
  17335. if ((idx = get_option_index(name)) == -1) {
  17336. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17337. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17338. mg_snprintf(NULL,
  17339. NULL, /* No truncation check for error buffers */
  17340. error->text,
  17341. error->text_buffer_size,
  17342. "Invalid option: %s",
  17343. name);
  17344. }
  17345. mg_free(new_dom);
  17346. return -2;
  17347. } else if ((value = *options++) == NULL) {
  17348. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17349. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17350. mg_snprintf(NULL,
  17351. NULL, /* No truncation check for error buffers */
  17352. error->text,
  17353. error->text_buffer_size,
  17354. "Invalid option value: %s",
  17355. name);
  17356. }
  17357. mg_free(new_dom);
  17358. return -2;
  17359. }
  17360. if (new_dom->config[idx] != NULL) {
  17361. /* Duplicate option: Later values overwrite earlier ones. */
  17362. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17363. mg_free(new_dom->config[idx]);
  17364. }
  17365. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17366. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17367. }
  17368. /* Authentication domain is mandatory */
  17369. /* TODO: Maybe use a new option hostname? */
  17370. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17371. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17372. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17373. mg_snprintf(NULL,
  17374. NULL, /* No truncation check for error buffers */
  17375. error->text,
  17376. error->text_buffer_size,
  17377. "Mandatory option %s missing",
  17378. config_options[AUTHENTICATION_DOMAIN].name);
  17379. }
  17380. mg_free(new_dom);
  17381. return -4;
  17382. }
  17383. /* Set default value if needed. Take the config value from
  17384. * ctx as a default value. */
  17385. for (i = 0; config_options[i].name != NULL; i++) {
  17386. default_value = ctx->dd.config[i];
  17387. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17388. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17389. }
  17390. }
  17391. new_dom->handlers = NULL;
  17392. new_dom->next = NULL;
  17393. new_dom->nonce_count = 0;
  17394. new_dom->auth_nonce_mask =
  17395. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17396. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17397. new_dom->shared_lua_websockets = NULL;
  17398. #endif
  17399. if (!init_ssl_ctx(ctx, new_dom)) {
  17400. /* Init SSL failed */
  17401. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17402. mg_snprintf(NULL,
  17403. NULL, /* No truncation check for error buffers */
  17404. error->text,
  17405. error->text_buffer_size,
  17406. "%s",
  17407. "Initializing SSL context failed");
  17408. }
  17409. mg_free(new_dom);
  17410. return -3;
  17411. }
  17412. /* Add element to linked list. */
  17413. mg_lock_context(ctx);
  17414. idx = 0;
  17415. dom = &(ctx->dd);
  17416. for (;;) {
  17417. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17418. dom->config[AUTHENTICATION_DOMAIN])) {
  17419. /* Domain collision */
  17420. mg_cry_ctx_internal(ctx,
  17421. "domain %s already in use",
  17422. new_dom->config[AUTHENTICATION_DOMAIN]);
  17423. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17424. mg_snprintf(NULL,
  17425. NULL, /* No truncation check for error buffers */
  17426. error->text,
  17427. error->text_buffer_size,
  17428. "Domain %s specified by %s is already in use",
  17429. new_dom->config[AUTHENTICATION_DOMAIN],
  17430. config_options[AUTHENTICATION_DOMAIN].name);
  17431. }
  17432. mg_free(new_dom);
  17433. mg_unlock_context(ctx);
  17434. return -5;
  17435. }
  17436. /* Count number of domains */
  17437. idx++;
  17438. if (dom->next == NULL) {
  17439. dom->next = new_dom;
  17440. break;
  17441. }
  17442. dom = dom->next;
  17443. }
  17444. mg_unlock_context(ctx);
  17445. /* Return domain number */
  17446. return idx;
  17447. }
  17448. int
  17449. mg_start_domain(struct mg_context *ctx, const char **options)
  17450. {
  17451. return mg_start_domain2(ctx, options, NULL);
  17452. }
  17453. #endif
  17454. /* Feature check API function */
  17455. unsigned
  17456. mg_check_feature(unsigned feature)
  17457. {
  17458. static const unsigned feature_set = 0
  17459. /* Set bits for available features according to API documentation.
  17460. * This bit mask is created at compile time, according to the active
  17461. * preprocessor defines. It is a single const value at runtime. */
  17462. #if !defined(NO_FILES)
  17463. | MG_FEATURES_FILES
  17464. #endif
  17465. #if !defined(NO_SSL)
  17466. | MG_FEATURES_SSL
  17467. #endif
  17468. #if !defined(NO_CGI)
  17469. | MG_FEATURES_CGI
  17470. #endif
  17471. #if defined(USE_IPV6)
  17472. | MG_FEATURES_IPV6
  17473. #endif
  17474. #if defined(USE_WEBSOCKET)
  17475. | MG_FEATURES_WEBSOCKET
  17476. #endif
  17477. #if defined(USE_LUA)
  17478. | MG_FEATURES_LUA
  17479. #endif
  17480. #if defined(USE_DUKTAPE)
  17481. | MG_FEATURES_SSJS
  17482. #endif
  17483. #if !defined(NO_CACHING)
  17484. | MG_FEATURES_CACHE
  17485. #endif
  17486. #if defined(USE_SERVER_STATS)
  17487. | MG_FEATURES_STATS
  17488. #endif
  17489. #if defined(USE_ZLIB)
  17490. | MG_FEATURES_COMPRESSION
  17491. #endif
  17492. /* Set some extra bits not defined in the API documentation.
  17493. * These bits may change without further notice. */
  17494. #if defined(MG_LEGACY_INTERFACE)
  17495. | 0x00008000u
  17496. #endif
  17497. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17498. | 0x00004000u
  17499. #endif
  17500. #if defined(MEMORY_DEBUGGING)
  17501. | 0x00001000u
  17502. #endif
  17503. #if defined(USE_TIMERS)
  17504. | 0x00020000u
  17505. #endif
  17506. #if !defined(NO_NONCE_CHECK)
  17507. | 0x00040000u
  17508. #endif
  17509. #if !defined(NO_POPEN)
  17510. | 0x00080000u
  17511. #endif
  17512. ;
  17513. return (feature & feature_set);
  17514. }
  17515. static size_t
  17516. mg_str_append(char **dst, char *end, const char *src)
  17517. {
  17518. size_t len = strlen(src);
  17519. if (*dst != end) {
  17520. /* Append src if enough space, or close dst. */
  17521. if ((size_t)(end - *dst) > len) {
  17522. strcpy(*dst, src);
  17523. *dst += len;
  17524. } else {
  17525. *dst = end;
  17526. }
  17527. }
  17528. return len;
  17529. }
  17530. /* Get system information. It can be printed or stored by the caller.
  17531. * Return the size of available information. */
  17532. int
  17533. mg_get_system_info(char *buffer, int buflen)
  17534. {
  17535. char *end, *append_eoobj = NULL, block[256];
  17536. size_t system_info_length = 0;
  17537. #if defined(_WIN32)
  17538. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17539. #else
  17540. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17541. #endif
  17542. if ((buffer == NULL) || (buflen < 1)) {
  17543. buflen = 0;
  17544. end = buffer;
  17545. } else {
  17546. *buffer = 0;
  17547. end = buffer + buflen;
  17548. }
  17549. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17550. /* has enough space to append eoobj */
  17551. append_eoobj = buffer;
  17552. if (end) {
  17553. end -= sizeof(eoobj) - 1;
  17554. }
  17555. }
  17556. system_info_length += mg_str_append(&buffer, end, "{");
  17557. /* Server version */
  17558. {
  17559. const char *version = mg_version();
  17560. mg_snprintf(NULL,
  17561. NULL,
  17562. block,
  17563. sizeof(block),
  17564. "%s\"version\" : \"%s\"",
  17565. eol,
  17566. version);
  17567. system_info_length += mg_str_append(&buffer, end, block);
  17568. }
  17569. /* System info */
  17570. {
  17571. #if defined(_WIN32)
  17572. DWORD dwVersion = 0;
  17573. DWORD dwMajorVersion = 0;
  17574. DWORD dwMinorVersion = 0;
  17575. SYSTEM_INFO si;
  17576. GetSystemInfo(&si);
  17577. #if defined(_MSC_VER)
  17578. #pragma warning(push)
  17579. /* GetVersion was declared deprecated */
  17580. #pragma warning(disable : 4996)
  17581. #endif
  17582. dwVersion = GetVersion();
  17583. #if defined(_MSC_VER)
  17584. #pragma warning(pop)
  17585. #endif
  17586. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17587. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17588. mg_snprintf(NULL,
  17589. NULL,
  17590. block,
  17591. sizeof(block),
  17592. ",%s\"os\" : \"Windows %u.%u\"",
  17593. eol,
  17594. (unsigned)dwMajorVersion,
  17595. (unsigned)dwMinorVersion);
  17596. system_info_length += mg_str_append(&buffer, end, block);
  17597. mg_snprintf(NULL,
  17598. NULL,
  17599. block,
  17600. sizeof(block),
  17601. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17602. eol,
  17603. (unsigned)si.wProcessorArchitecture,
  17604. (unsigned)si.dwNumberOfProcessors,
  17605. (unsigned)si.dwActiveProcessorMask);
  17606. system_info_length += mg_str_append(&buffer, end, block);
  17607. #elif defined(__ZEPHYR__)
  17608. mg_snprintf(NULL,
  17609. NULL,
  17610. block,
  17611. sizeof(block),
  17612. ",%s\"os\" : \"%s %s\"",
  17613. eol,
  17614. "Zephyr OS",
  17615. ZEPHYR_VERSION);
  17616. system_info_length += mg_str_append(&buffer, end, block);
  17617. #else
  17618. struct utsname name;
  17619. memset(&name, 0, sizeof(name));
  17620. uname(&name);
  17621. mg_snprintf(NULL,
  17622. NULL,
  17623. block,
  17624. sizeof(block),
  17625. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17626. eol,
  17627. name.sysname,
  17628. name.version,
  17629. name.release,
  17630. name.machine);
  17631. system_info_length += mg_str_append(&buffer, end, block);
  17632. #endif
  17633. }
  17634. /* Features */
  17635. {
  17636. mg_snprintf(NULL,
  17637. NULL,
  17638. block,
  17639. sizeof(block),
  17640. ",%s\"features\" : %lu"
  17641. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17642. eol,
  17643. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17644. eol,
  17645. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17646. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17647. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17648. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17649. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17650. : "",
  17651. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17652. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17653. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17654. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17655. system_info_length += mg_str_append(&buffer, end, block);
  17656. #if defined(USE_LUA)
  17657. mg_snprintf(NULL,
  17658. NULL,
  17659. block,
  17660. sizeof(block),
  17661. ",%s\"lua_version\" : \"%u (%s)\"",
  17662. eol,
  17663. (unsigned)LUA_VERSION_NUM,
  17664. LUA_RELEASE);
  17665. system_info_length += mg_str_append(&buffer, end, block);
  17666. #endif
  17667. #if defined(USE_DUKTAPE)
  17668. mg_snprintf(NULL,
  17669. NULL,
  17670. block,
  17671. sizeof(block),
  17672. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17673. eol,
  17674. (unsigned)DUK_VERSION / 10000,
  17675. ((unsigned)DUK_VERSION / 100) % 100,
  17676. (unsigned)DUK_VERSION % 100);
  17677. system_info_length += mg_str_append(&buffer, end, block);
  17678. #endif
  17679. }
  17680. /* Build date */
  17681. {
  17682. #if defined(GCC_DIAGNOSTIC)
  17683. #if GCC_VERSION >= 40900
  17684. #pragma GCC diagnostic push
  17685. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17686. #pragma GCC diagnostic ignored "-Wdate-time"
  17687. #endif
  17688. #endif
  17689. mg_snprintf(NULL,
  17690. NULL,
  17691. block,
  17692. sizeof(block),
  17693. ",%s\"build\" : \"%s\"",
  17694. eol,
  17695. __DATE__);
  17696. #if defined(GCC_DIAGNOSTIC)
  17697. #if GCC_VERSION >= 40900
  17698. #pragma GCC diagnostic pop
  17699. #endif
  17700. #endif
  17701. system_info_length += mg_str_append(&buffer, end, block);
  17702. }
  17703. /* Compiler information */
  17704. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17705. {
  17706. #if defined(_MSC_VER)
  17707. mg_snprintf(NULL,
  17708. NULL,
  17709. block,
  17710. sizeof(block),
  17711. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17712. eol,
  17713. (unsigned)_MSC_VER,
  17714. (unsigned)_MSC_FULL_VER);
  17715. system_info_length += mg_str_append(&buffer, end, block);
  17716. #elif defined(__MINGW64__)
  17717. mg_snprintf(NULL,
  17718. NULL,
  17719. block,
  17720. sizeof(block),
  17721. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17722. eol,
  17723. (unsigned)__MINGW64_VERSION_MAJOR,
  17724. (unsigned)__MINGW64_VERSION_MINOR);
  17725. system_info_length += mg_str_append(&buffer, end, block);
  17726. mg_snprintf(NULL,
  17727. NULL,
  17728. block,
  17729. sizeof(block),
  17730. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17731. eol,
  17732. (unsigned)__MINGW32_MAJOR_VERSION,
  17733. (unsigned)__MINGW32_MINOR_VERSION);
  17734. system_info_length += mg_str_append(&buffer, end, block);
  17735. #elif defined(__MINGW32__)
  17736. mg_snprintf(NULL,
  17737. NULL,
  17738. block,
  17739. sizeof(block),
  17740. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17741. eol,
  17742. (unsigned)__MINGW32_MAJOR_VERSION,
  17743. (unsigned)__MINGW32_MINOR_VERSION);
  17744. system_info_length += mg_str_append(&buffer, end, block);
  17745. #elif defined(__clang__)
  17746. mg_snprintf(NULL,
  17747. NULL,
  17748. block,
  17749. sizeof(block),
  17750. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17751. eol,
  17752. __clang_major__,
  17753. __clang_minor__,
  17754. __clang_patchlevel__,
  17755. __clang_version__);
  17756. system_info_length += mg_str_append(&buffer, end, block);
  17757. #elif defined(__GNUC__)
  17758. mg_snprintf(NULL,
  17759. NULL,
  17760. block,
  17761. sizeof(block),
  17762. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17763. eol,
  17764. (unsigned)__GNUC__,
  17765. (unsigned)__GNUC_MINOR__,
  17766. (unsigned)__GNUC_PATCHLEVEL__);
  17767. system_info_length += mg_str_append(&buffer, end, block);
  17768. #elif defined(__INTEL_COMPILER)
  17769. mg_snprintf(NULL,
  17770. NULL,
  17771. block,
  17772. sizeof(block),
  17773. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17774. eol,
  17775. (unsigned)__INTEL_COMPILER);
  17776. system_info_length += mg_str_append(&buffer, end, block);
  17777. #elif defined(__BORLANDC__)
  17778. mg_snprintf(NULL,
  17779. NULL,
  17780. block,
  17781. sizeof(block),
  17782. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17783. eol,
  17784. (unsigned)__BORLANDC__);
  17785. system_info_length += mg_str_append(&buffer, end, block);
  17786. #elif defined(__SUNPRO_C)
  17787. mg_snprintf(NULL,
  17788. NULL,
  17789. block,
  17790. sizeof(block),
  17791. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17792. eol,
  17793. (unsigned)__SUNPRO_C);
  17794. system_info_length += mg_str_append(&buffer, end, block);
  17795. #else
  17796. mg_snprintf(NULL,
  17797. NULL,
  17798. block,
  17799. sizeof(block),
  17800. ",%s\"compiler\" : \"other\"",
  17801. eol);
  17802. system_info_length += mg_str_append(&buffer, end, block);
  17803. #endif
  17804. }
  17805. /* Determine 32/64 bit data mode.
  17806. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17807. {
  17808. mg_snprintf(NULL,
  17809. NULL,
  17810. block,
  17811. sizeof(block),
  17812. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17813. "char:%u/%u, "
  17814. "ptr:%u, size:%u, time:%u\"",
  17815. eol,
  17816. (unsigned)sizeof(short),
  17817. (unsigned)sizeof(int),
  17818. (unsigned)sizeof(long),
  17819. (unsigned)sizeof(long long),
  17820. (unsigned)sizeof(float),
  17821. (unsigned)sizeof(double),
  17822. (unsigned)sizeof(long double),
  17823. (unsigned)sizeof(char),
  17824. (unsigned)sizeof(wchar_t),
  17825. (unsigned)sizeof(void *),
  17826. (unsigned)sizeof(size_t),
  17827. (unsigned)sizeof(time_t));
  17828. system_info_length += mg_str_append(&buffer, end, block);
  17829. }
  17830. /* Terminate string */
  17831. if (append_eoobj) {
  17832. strcat(append_eoobj, eoobj);
  17833. }
  17834. system_info_length += sizeof(eoobj) - 1;
  17835. return (int)system_info_length;
  17836. }
  17837. /* Get context information. It can be printed or stored by the caller.
  17838. * Return the size of available information. */
  17839. int
  17840. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17841. {
  17842. #if defined(USE_SERVER_STATS)
  17843. char *end, *append_eoobj = NULL, block[256];
  17844. size_t context_info_length = 0;
  17845. #if defined(_WIN32)
  17846. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17847. #else
  17848. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17849. #endif
  17850. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17851. if ((buffer == NULL) || (buflen < 1)) {
  17852. buflen = 0;
  17853. end = buffer;
  17854. } else {
  17855. *buffer = 0;
  17856. end = buffer + buflen;
  17857. }
  17858. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17859. /* has enough space to append eoobj */
  17860. append_eoobj = buffer;
  17861. end -= sizeof(eoobj) - 1;
  17862. }
  17863. context_info_length += mg_str_append(&buffer, end, "{");
  17864. if (ms) { /* <-- should be always true */
  17865. /* Memory information */
  17866. mg_snprintf(NULL,
  17867. NULL,
  17868. block,
  17869. sizeof(block),
  17870. "%s\"memory\" : {%s"
  17871. "\"blocks\" : %i,%s"
  17872. "\"used\" : %" INT64_FMT ",%s"
  17873. "\"maxUsed\" : %" INT64_FMT "%s"
  17874. "}",
  17875. eol,
  17876. eol,
  17877. ms->blockCount,
  17878. eol,
  17879. ms->totalMemUsed,
  17880. eol,
  17881. ms->maxMemUsed,
  17882. eol);
  17883. context_info_length += mg_str_append(&buffer, end, block);
  17884. }
  17885. if (ctx) {
  17886. /* Declare all variables at begin of the block, to comply
  17887. * with old C standards. */
  17888. char start_time_str[64] = {0};
  17889. char now_str[64] = {0};
  17890. time_t start_time = ctx->start_time;
  17891. time_t now = time(NULL);
  17892. /* Connections information */
  17893. mg_snprintf(NULL,
  17894. NULL,
  17895. block,
  17896. sizeof(block),
  17897. ",%s\"connections\" : {%s"
  17898. "\"active\" : %i,%s"
  17899. "\"maxActive\" : %i,%s"
  17900. "\"total\" : %" INT64_FMT "%s"
  17901. "}",
  17902. eol,
  17903. eol,
  17904. ctx->active_connections,
  17905. eol,
  17906. ctx->max_active_connections,
  17907. eol,
  17908. ctx->total_connections,
  17909. eol);
  17910. context_info_length += mg_str_append(&buffer, end, block);
  17911. /* Queue information */
  17912. #if !defined(ALTERNATIVE_QUEUE)
  17913. mg_snprintf(NULL,
  17914. NULL,
  17915. block,
  17916. sizeof(block),
  17917. ",%s\"queue\" : {%s"
  17918. "\"length\" : %i,%s"
  17919. "\"filled\" : %i,%s"
  17920. "\"maxFilled\" : %i,%s"
  17921. "\"full\" : %s%s"
  17922. "}",
  17923. eol,
  17924. eol,
  17925. ctx->sq_size,
  17926. eol,
  17927. ctx->sq_head - ctx->sq_tail,
  17928. eol,
  17929. ctx->sq_max_fill,
  17930. eol,
  17931. (ctx->sq_blocked ? "true" : "false"),
  17932. eol);
  17933. context_info_length += mg_str_append(&buffer, end, block);
  17934. #endif
  17935. /* Requests information */
  17936. mg_snprintf(NULL,
  17937. NULL,
  17938. block,
  17939. sizeof(block),
  17940. ",%s\"requests\" : {%s"
  17941. "\"total\" : %" INT64_FMT "%s"
  17942. "}",
  17943. eol,
  17944. eol,
  17945. ctx->total_requests,
  17946. eol);
  17947. context_info_length += mg_str_append(&buffer, end, block);
  17948. /* Data information */
  17949. mg_snprintf(NULL,
  17950. NULL,
  17951. block,
  17952. sizeof(block),
  17953. ",%s\"data\" : {%s"
  17954. "\"read\" : %" INT64_FMT ",%s"
  17955. "\"written\" : %" INT64_FMT "%s"
  17956. "}",
  17957. eol,
  17958. eol,
  17959. ctx->total_data_read,
  17960. eol,
  17961. ctx->total_data_written,
  17962. eol);
  17963. context_info_length += mg_str_append(&buffer, end, block);
  17964. /* Execution time information */
  17965. gmt_time_string(start_time_str,
  17966. sizeof(start_time_str) - 1,
  17967. &start_time);
  17968. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17969. mg_snprintf(NULL,
  17970. NULL,
  17971. block,
  17972. sizeof(block),
  17973. ",%s\"time\" : {%s"
  17974. "\"uptime\" : %.0f,%s"
  17975. "\"start\" : \"%s\",%s"
  17976. "\"now\" : \"%s\"%s"
  17977. "}",
  17978. eol,
  17979. eol,
  17980. difftime(now, start_time),
  17981. eol,
  17982. start_time_str,
  17983. eol,
  17984. now_str,
  17985. eol);
  17986. context_info_length += mg_str_append(&buffer, end, block);
  17987. }
  17988. /* Terminate string */
  17989. if (append_eoobj) {
  17990. strcat(append_eoobj, eoobj);
  17991. }
  17992. context_info_length += sizeof(eoobj) - 1;
  17993. return (int)context_info_length;
  17994. #else
  17995. (void)ctx;
  17996. if ((buffer != NULL) && (buflen > 0)) {
  17997. *buffer = 0;
  17998. }
  17999. return 0;
  18000. #endif
  18001. }
  18002. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18003. /* Get connection information. It can be printed or stored by the caller.
  18004. * Return the size of available information. */
  18005. int
  18006. mg_get_connection_info(const struct mg_context *ctx,
  18007. int idx,
  18008. char *buffer,
  18009. int buflen)
  18010. {
  18011. const struct mg_connection *conn;
  18012. const struct mg_request_info *ri;
  18013. char *end, *append_eoobj = NULL, block[256];
  18014. size_t connection_info_length = 0;
  18015. int state = 0;
  18016. const char *state_str = "unknown";
  18017. #if defined(_WIN32)
  18018. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18019. #else
  18020. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18021. #endif
  18022. if ((buffer == NULL) || (buflen < 1)) {
  18023. buflen = 0;
  18024. end = buffer;
  18025. } else {
  18026. *buffer = 0;
  18027. end = buffer + buflen;
  18028. }
  18029. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18030. /* has enough space to append eoobj */
  18031. append_eoobj = buffer;
  18032. end -= sizeof(eoobj) - 1;
  18033. }
  18034. if ((ctx == NULL) || (idx < 0)) {
  18035. /* Parameter error */
  18036. return 0;
  18037. }
  18038. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18039. /* Out of range */
  18040. return 0;
  18041. }
  18042. /* Take connection [idx]. This connection is not locked in
  18043. * any way, so some other thread might use it. */
  18044. conn = (ctx->worker_connections) + idx;
  18045. /* Initialize output string */
  18046. connection_info_length += mg_str_append(&buffer, end, "{");
  18047. /* Init variables */
  18048. ri = &(conn->request_info);
  18049. #if defined(USE_SERVER_STATS)
  18050. state = conn->conn_state;
  18051. /* State as string */
  18052. switch (state) {
  18053. case 0:
  18054. state_str = "undefined";
  18055. break;
  18056. case 1:
  18057. state_str = "not used";
  18058. break;
  18059. case 2:
  18060. state_str = "init";
  18061. break;
  18062. case 3:
  18063. state_str = "ready";
  18064. break;
  18065. case 4:
  18066. state_str = "processing";
  18067. break;
  18068. case 5:
  18069. state_str = "processed";
  18070. break;
  18071. case 6:
  18072. state_str = "to close";
  18073. break;
  18074. case 7:
  18075. state_str = "closing";
  18076. break;
  18077. case 8:
  18078. state_str = "closed";
  18079. break;
  18080. case 9:
  18081. state_str = "done";
  18082. break;
  18083. }
  18084. #endif
  18085. /* Connection info */
  18086. if ((state >= 3) && (state < 9)) {
  18087. mg_snprintf(NULL,
  18088. NULL,
  18089. block,
  18090. sizeof(block),
  18091. "%s\"connection\" : {%s"
  18092. "\"remote\" : {%s"
  18093. "\"protocol\" : \"%s\",%s"
  18094. "\"addr\" : \"%s\",%s"
  18095. "\"port\" : %u%s"
  18096. "},%s"
  18097. "\"handled_requests\" : %u%s"
  18098. "}",
  18099. eol,
  18100. eol,
  18101. eol,
  18102. get_proto_name(conn),
  18103. eol,
  18104. ri->remote_addr,
  18105. eol,
  18106. ri->remote_port,
  18107. eol,
  18108. eol,
  18109. conn->handled_requests,
  18110. eol);
  18111. connection_info_length += mg_str_append(&buffer, end, block);
  18112. }
  18113. /* Request info */
  18114. if ((state >= 4) && (state < 6)) {
  18115. mg_snprintf(NULL,
  18116. NULL,
  18117. block,
  18118. sizeof(block),
  18119. "%s%s\"request_info\" : {%s"
  18120. "\"method\" : \"%s\",%s"
  18121. "\"uri\" : \"%s\",%s"
  18122. "\"query\" : %s%s%s%s"
  18123. "}",
  18124. (connection_info_length > 1 ? "," : ""),
  18125. eol,
  18126. eol,
  18127. ri->request_method,
  18128. eol,
  18129. ri->request_uri,
  18130. eol,
  18131. ri->query_string ? "\"" : "",
  18132. ri->query_string ? ri->query_string : "null",
  18133. ri->query_string ? "\"" : "",
  18134. eol);
  18135. connection_info_length += mg_str_append(&buffer, end, block);
  18136. }
  18137. /* Execution time information */
  18138. if ((state >= 2) && (state < 9)) {
  18139. char start_time_str[64] = {0};
  18140. char close_time_str[64] = {0};
  18141. time_t start_time = conn->conn_birth_time;
  18142. time_t close_time = conn->conn_close_time;
  18143. double time_diff;
  18144. gmt_time_string(start_time_str,
  18145. sizeof(start_time_str) - 1,
  18146. &start_time);
  18147. if (close_time != 0) {
  18148. time_diff = difftime(close_time, start_time);
  18149. gmt_time_string(close_time_str,
  18150. sizeof(close_time_str) - 1,
  18151. &close_time);
  18152. } else {
  18153. time_t now = time(NULL);
  18154. time_diff = difftime(now, start_time);
  18155. close_time_str[0] = 0; /* or use "now" ? */
  18156. }
  18157. mg_snprintf(NULL,
  18158. NULL,
  18159. block,
  18160. sizeof(block),
  18161. "%s%s\"time\" : {%s"
  18162. "\"uptime\" : %.0f,%s"
  18163. "\"start\" : \"%s\",%s"
  18164. "\"closed\" : \"%s\"%s"
  18165. "}",
  18166. (connection_info_length > 1 ? "," : ""),
  18167. eol,
  18168. eol,
  18169. time_diff,
  18170. eol,
  18171. start_time_str,
  18172. eol,
  18173. close_time_str,
  18174. eol);
  18175. connection_info_length += mg_str_append(&buffer, end, block);
  18176. }
  18177. /* Remote user name */
  18178. if ((ri->remote_user) && (state < 9)) {
  18179. mg_snprintf(NULL,
  18180. NULL,
  18181. block,
  18182. sizeof(block),
  18183. "%s%s\"user\" : {%s"
  18184. "\"name\" : \"%s\",%s"
  18185. "}",
  18186. (connection_info_length > 1 ? "," : ""),
  18187. eol,
  18188. eol,
  18189. ri->remote_user,
  18190. eol);
  18191. connection_info_length += mg_str_append(&buffer, end, block);
  18192. }
  18193. /* Data block */
  18194. if (state >= 3) {
  18195. mg_snprintf(NULL,
  18196. NULL,
  18197. block,
  18198. sizeof(block),
  18199. "%s%s\"data\" : {%s"
  18200. "\"read\" : %" INT64_FMT ",%s"
  18201. "\"written\" : %" INT64_FMT "%s"
  18202. "}",
  18203. (connection_info_length > 1 ? "," : ""),
  18204. eol,
  18205. eol,
  18206. conn->consumed_content,
  18207. eol,
  18208. conn->num_bytes_sent,
  18209. eol);
  18210. connection_info_length += mg_str_append(&buffer, end, block);
  18211. }
  18212. /* State */
  18213. mg_snprintf(NULL,
  18214. NULL,
  18215. block,
  18216. sizeof(block),
  18217. "%s%s\"state\" : \"%s\"",
  18218. (connection_info_length > 1 ? "," : ""),
  18219. eol,
  18220. state_str);
  18221. connection_info_length += mg_str_append(&buffer, end, block);
  18222. /* Terminate string */
  18223. if (append_eoobj) {
  18224. strcat(append_eoobj, eoobj);
  18225. }
  18226. connection_info_length += sizeof(eoobj) - 1;
  18227. return (int)connection_info_length;
  18228. }
  18229. #endif
  18230. /* Initialize this library. This function does not need to be thread safe.
  18231. */
  18232. unsigned
  18233. mg_init_library(unsigned features)
  18234. {
  18235. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18236. unsigned features_inited = features_to_init;
  18237. if (mg_init_library_called <= 0) {
  18238. /* Not initialized yet */
  18239. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18240. return 0;
  18241. }
  18242. }
  18243. mg_global_lock();
  18244. if (mg_init_library_called <= 0) {
  18245. #if defined(_WIN32)
  18246. int file_mutex_init = 1;
  18247. int wsa = 1;
  18248. #else
  18249. int mutexattr_init = 1;
  18250. #endif
  18251. int failed = 1;
  18252. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18253. if (key_create == 0) {
  18254. #if defined(_WIN32)
  18255. file_mutex_init = pthread_mutex_init(&global_log_file_lock,
  18256. &pthread_mutex_attr);
  18257. if (file_mutex_init == 0) {
  18258. /* Start WinSock */
  18259. WSADATA data;
  18260. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18261. }
  18262. #else
  18263. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18264. if (mutexattr_init == 0) {
  18265. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18266. PTHREAD_MUTEX_RECURSIVE);
  18267. }
  18268. #endif
  18269. }
  18270. if (failed) {
  18271. #if defined(_WIN32)
  18272. if (wsa == 0) {
  18273. (void)WSACleanup();
  18274. }
  18275. if (file_mutex_init == 0) {
  18276. (void)pthread_mutex_destroy(&global_log_file_lock);
  18277. }
  18278. #else
  18279. if (mutexattr_init == 0) {
  18280. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18281. }
  18282. #endif
  18283. if (key_create == 0) {
  18284. (void)pthread_key_delete(sTlsKey);
  18285. }
  18286. mg_global_unlock();
  18287. (void)pthread_mutex_destroy(&global_lock_mutex);
  18288. return 0;
  18289. }
  18290. #if defined(USE_LUA)
  18291. lua_init_optional_libraries();
  18292. #endif
  18293. }
  18294. mg_global_unlock();
  18295. #if !defined(NO_SSL)
  18296. if (features_to_init & MG_FEATURES_SSL) {
  18297. if (!mg_ssl_initialized) {
  18298. char ebuf[128];
  18299. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18300. mg_ssl_initialized = 1;
  18301. } else {
  18302. (void)ebuf;
  18303. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18304. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18305. }
  18306. } else {
  18307. /* ssl already initialized */
  18308. }
  18309. }
  18310. #endif
  18311. mg_global_lock();
  18312. if (mg_init_library_called <= 0) {
  18313. mg_init_library_called = 1;
  18314. } else {
  18315. mg_init_library_called++;
  18316. }
  18317. mg_global_unlock();
  18318. return features_inited;
  18319. }
  18320. /* Un-initialize this library. */
  18321. unsigned
  18322. mg_exit_library(void)
  18323. {
  18324. if (mg_init_library_called <= 0) {
  18325. return 0;
  18326. }
  18327. mg_global_lock();
  18328. mg_init_library_called--;
  18329. if (mg_init_library_called == 0) {
  18330. #if !defined(NO_SSL)
  18331. if (mg_ssl_initialized) {
  18332. uninitialize_ssl();
  18333. mg_ssl_initialized = 0;
  18334. }
  18335. #endif
  18336. #if defined(_WIN32)
  18337. (void)WSACleanup();
  18338. (void)pthread_mutex_destroy(&global_log_file_lock);
  18339. #else
  18340. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18341. #endif
  18342. (void)pthread_key_delete(sTlsKey);
  18343. #if defined(USE_LUA)
  18344. lua_exit_optional_libraries();
  18345. #endif
  18346. mg_global_unlock();
  18347. (void)pthread_mutex_destroy(&global_lock_mutex);
  18348. return 1;
  18349. }
  18350. mg_global_unlock();
  18351. return 1;
  18352. }
  18353. /* End of civetweb.c */