civetweb.c 569 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204
  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(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(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(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. FUNCTION_MAY_BE_UNUSED
  1073. static int
  1074. mg_atomic_compare_and_swap(int *addr, int oldval, int newval)
  1075. {
  1076. int ret;
  1077. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1078. /* Depending on the SDK, this function uses either
  1079. * (volatile unsigned int *) or (volatile LONG *),
  1080. * so whatever you use, the other SDK is likely to raise a warning. */
  1081. ret = InterlockedCompareExchange((volatile long *)addr, newval, oldval);
  1082. #elif defined(__GNUC__) \
  1083. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1084. && !defined(NO_ATOMICS)
  1085. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1086. #else
  1087. mg_global_lock();
  1088. ret = *addr;
  1089. if ((ret != newval) && (ret == oldval)) {
  1090. *addr = newval;
  1091. }
  1092. mg_global_unlock();
  1093. #endif
  1094. return ret;
  1095. }
  1096. #if defined(GCC_DIAGNOSTIC)
  1097. /* Show no warning in case system functions are not used. */
  1098. #pragma GCC diagnostic pop
  1099. #endif /* defined(GCC_DIAGNOSTIC) */
  1100. #if defined(__clang__)
  1101. /* Show no warning in case system functions are not used. */
  1102. #pragma clang diagnostic pop
  1103. #endif
  1104. #if defined(USE_SERVER_STATS)
  1105. static pthread_mutex_t global_stats_mutex;
  1106. struct mg_memory_stat {
  1107. int64_t totalMemUsed;
  1108. int64_t maxMemUsed;
  1109. int blockCount;
  1110. };
  1111. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1112. static void *
  1113. mg_malloc_ex(size_t size,
  1114. struct mg_context *ctx,
  1115. const char *file,
  1116. unsigned line)
  1117. {
  1118. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1119. void *memory = 0;
  1120. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1121. #if defined(MEMORY_DEBUGGING)
  1122. char mallocStr[256];
  1123. #else
  1124. (void)file;
  1125. (void)line;
  1126. #endif
  1127. if (data) {
  1128. (void)pthread_mutex_lock(&global_stats_mutex);
  1129. mstat->totalMemUsed += (int64_t)size;
  1130. if (mstat->totalMemUsed > mstat->maxMemUsed) {
  1131. mstat->maxMemUsed = mstat->totalMemUsed;
  1132. }
  1133. mstat->blockCount++;
  1134. (void)pthread_mutex_unlock(&global_stats_mutex);
  1135. ((uintptr_t *)data)[0] = size;
  1136. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1137. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1138. }
  1139. #if defined(MEMORY_DEBUGGING)
  1140. (void)pthread_mutex_lock(&global_stats_mutex);
  1141. sprintf(mallocStr,
  1142. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1143. memory,
  1144. (unsigned long)size,
  1145. (unsigned long)mstat->totalMemUsed,
  1146. (unsigned long)mstat->blockCount,
  1147. file,
  1148. line);
  1149. (void)pthread_mutex_unlock(&global_stats_mutex);
  1150. #if defined(_WIN32)
  1151. OutputDebugStringA(mallocStr);
  1152. #else
  1153. DEBUG_TRACE("%s", mallocStr);
  1154. #endif
  1155. #endif
  1156. return memory;
  1157. }
  1158. static void *
  1159. mg_calloc_ex(size_t count,
  1160. size_t size,
  1161. struct mg_context *ctx,
  1162. const char *file,
  1163. unsigned line)
  1164. {
  1165. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1166. if (data) {
  1167. memset(data, 0, size * count);
  1168. }
  1169. return data;
  1170. }
  1171. static void
  1172. mg_free_ex(void *memory, const char *file, unsigned line)
  1173. {
  1174. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1175. #if defined(MEMORY_DEBUGGING)
  1176. char mallocStr[256];
  1177. #else
  1178. (void)file;
  1179. (void)line;
  1180. #endif
  1181. if (memory) {
  1182. uintptr_t size = ((uintptr_t *)data)[0];
  1183. struct mg_memory_stat *mstat =
  1184. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1185. (void)pthread_mutex_lock(&global_stats_mutex);
  1186. mstat->totalMemUsed -= (int64_t)size;
  1187. mstat->blockCount--;
  1188. (void)pthread_mutex_unlock(&global_stats_mutex);
  1189. #if defined(MEMORY_DEBUGGING)
  1190. (void)pthread_mutex_lock(&global_stats_mutex);
  1191. sprintf(mallocStr,
  1192. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1193. memory,
  1194. (unsigned long)size,
  1195. (unsigned long)mstat->totalMemUsed,
  1196. (unsigned long)mstat->blockCount,
  1197. file,
  1198. line);
  1199. (void)pthread_mutex_unlock(&global_stats_mutex);
  1200. #if defined(_WIN32)
  1201. OutputDebugStringA(mallocStr);
  1202. #else
  1203. DEBUG_TRACE("%s", mallocStr);
  1204. #endif
  1205. #endif
  1206. free(data);
  1207. }
  1208. }
  1209. static void *
  1210. mg_realloc_ex(void *memory,
  1211. size_t newsize,
  1212. struct mg_context *ctx,
  1213. const char *file,
  1214. unsigned line)
  1215. {
  1216. void *data;
  1217. void *_realloc;
  1218. uintptr_t oldsize;
  1219. #if defined(MEMORY_DEBUGGING)
  1220. char mallocStr[256];
  1221. #else
  1222. (void)file;
  1223. (void)line;
  1224. #endif
  1225. if (newsize) {
  1226. if (memory) {
  1227. /* Reallocate existing block */
  1228. struct mg_memory_stat *mstat;
  1229. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1230. oldsize = ((uintptr_t *)data)[0];
  1231. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1232. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1233. if (_realloc) {
  1234. data = _realloc;
  1235. (void)pthread_mutex_lock(&global_stats_mutex);
  1236. mstat->totalMemUsed -= (int64_t)oldsize;
  1237. (void)pthread_mutex_unlock(&global_stats_mutex);
  1238. #if defined(MEMORY_DEBUGGING)
  1239. (void)pthread_mutex_lock(&global_stats_mutex);
  1240. sprintf(mallocStr,
  1241. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1242. memory,
  1243. (unsigned long)oldsize,
  1244. (unsigned long)mstat->totalMemUsed,
  1245. (unsigned long)mstat->blockCount,
  1246. file,
  1247. line);
  1248. (void)pthread_mutex_unlock(&global_stats_mutex);
  1249. #if defined(_WIN32)
  1250. OutputDebugStringA(mallocStr);
  1251. #else
  1252. DEBUG_TRACE("%s", mallocStr);
  1253. #endif
  1254. #endif
  1255. (void)pthread_mutex_lock(&global_stats_mutex);
  1256. mstat->totalMemUsed += (int64_t)newsize;
  1257. (void)pthread_mutex_unlock(&global_stats_mutex);
  1258. #if defined(MEMORY_DEBUGGING)
  1259. (void)pthread_mutex_lock(&global_stats_mutex);
  1260. sprintf(mallocStr,
  1261. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1262. memory,
  1263. (unsigned long)newsize,
  1264. (unsigned long)mstat->totalMemUsed,
  1265. (unsigned long)mstat->blockCount,
  1266. file,
  1267. line);
  1268. (void)pthread_mutex_unlock(&global_stats_mutex);
  1269. #if defined(_WIN32)
  1270. OutputDebugStringA(mallocStr);
  1271. #else
  1272. DEBUG_TRACE("%s", mallocStr);
  1273. #endif
  1274. #endif
  1275. *(uintptr_t *)data = newsize;
  1276. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1277. } else {
  1278. #if defined(MEMORY_DEBUGGING)
  1279. #if defined(_WIN32)
  1280. OutputDebugStringA("MEM: realloc failed\n");
  1281. #else
  1282. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1283. #endif
  1284. #endif
  1285. return _realloc;
  1286. }
  1287. } else {
  1288. /* Allocate new block */
  1289. data = mg_malloc_ex(newsize, ctx, file, line);
  1290. }
  1291. } else {
  1292. /* Free existing block */
  1293. data = 0;
  1294. mg_free_ex(memory, file, line);
  1295. }
  1296. return data;
  1297. }
  1298. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1299. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1300. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1301. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1302. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1303. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1304. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1305. #else /* USE_SERVER_STATS */
  1306. static __inline void *
  1307. mg_malloc(size_t a)
  1308. {
  1309. return malloc(a);
  1310. }
  1311. static __inline void *
  1312. mg_calloc(size_t a, size_t b)
  1313. {
  1314. return calloc(a, b);
  1315. }
  1316. static __inline void *
  1317. mg_realloc(void *a, size_t b)
  1318. {
  1319. return realloc(a, b);
  1320. }
  1321. static __inline void
  1322. mg_free(void *a)
  1323. {
  1324. free(a);
  1325. }
  1326. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1327. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1328. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1329. #define mg_free_ctx(a, c) mg_free(a)
  1330. #endif /* USE_SERVER_STATS */
  1331. static void mg_vsnprintf(const struct mg_connection *conn,
  1332. int *truncated,
  1333. char *buf,
  1334. size_t buflen,
  1335. const char *fmt,
  1336. va_list ap);
  1337. static void mg_snprintf(const struct mg_connection *conn,
  1338. int *truncated,
  1339. char *buf,
  1340. size_t buflen,
  1341. PRINTF_FORMAT_STRING(const char *fmt),
  1342. ...) PRINTF_ARGS(5, 6);
  1343. /* This following lines are just meant as a reminder to use the mg-functions
  1344. * for memory management */
  1345. #if defined(malloc)
  1346. #undef malloc
  1347. #endif
  1348. #if defined(calloc)
  1349. #undef calloc
  1350. #endif
  1351. #if defined(realloc)
  1352. #undef realloc
  1353. #endif
  1354. #if defined(free)
  1355. #undef free
  1356. #endif
  1357. #if defined(snprintf)
  1358. #undef snprintf
  1359. #endif
  1360. #if defined(vsnprintf)
  1361. #undef vsnprintf
  1362. #endif
  1363. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1364. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1365. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1366. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1367. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1368. #if defined(_WIN32)
  1369. /* vsnprintf must not be used in any system,
  1370. * but this define only works well for Windows. */
  1371. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1372. #endif
  1373. /* mg_init_library counter */
  1374. static int mg_init_library_called = 0;
  1375. #if !defined(NO_SSL)
  1376. static int mg_ssl_initialized = 0;
  1377. #endif
  1378. static pthread_key_t sTlsKey; /* Thread local storage index */
  1379. static int thread_idx_max = 0;
  1380. #if defined(MG_LEGACY_INTERFACE)
  1381. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1382. #endif
  1383. struct mg_workerTLS {
  1384. int is_master;
  1385. unsigned long thread_idx;
  1386. void *user_ptr;
  1387. #if defined(_WIN32)
  1388. HANDLE pthread_cond_helper_mutex;
  1389. struct mg_workerTLS *next_waiting_thread;
  1390. #endif
  1391. const char *alpn_proto;
  1392. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1393. char txtbuf[4];
  1394. #endif
  1395. };
  1396. #if defined(GCC_DIAGNOSTIC)
  1397. /* Show no warning in case system functions are not used. */
  1398. #pragma GCC diagnostic push
  1399. #pragma GCC diagnostic ignored "-Wunused-function"
  1400. #endif /* defined(GCC_DIAGNOSTIC) */
  1401. #if defined(__clang__)
  1402. /* Show no warning in case system functions are not used. */
  1403. #pragma clang diagnostic push
  1404. #pragma clang diagnostic ignored "-Wunused-function"
  1405. #endif
  1406. /* Get a unique thread ID as unsigned long, independent from the data type
  1407. * of thread IDs defined by the operating system API.
  1408. * If two calls to mg_current_thread_id return the same value, they calls
  1409. * are done from the same thread. If they return different values, they are
  1410. * done from different threads. (Provided this function is used in the same
  1411. * process context and threads are not repeatedly created and deleted, but
  1412. * CivetWeb does not do that).
  1413. * This function must match the signature required for SSL id callbacks:
  1414. * CRYPTO_set_id_callback
  1415. */
  1416. FUNCTION_MAY_BE_UNUSED
  1417. static unsigned long
  1418. mg_current_thread_id(void)
  1419. {
  1420. #if defined(_WIN32)
  1421. return GetCurrentThreadId();
  1422. #else
  1423. #if defined(__clang__)
  1424. #pragma clang diagnostic push
  1425. #pragma clang diagnostic ignored "-Wunreachable-code"
  1426. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1427. * or not, so one of the two conditions will be unreachable by construction.
  1428. * Unfortunately the C standard does not define a way to check this at
  1429. * compile time, since the #if preprocessor conditions can not use the sizeof
  1430. * operator as an argument. */
  1431. #endif
  1432. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1433. /* This is the problematic case for CRYPTO_set_id_callback:
  1434. * The OS pthread_t can not be cast to unsigned long. */
  1435. struct mg_workerTLS *tls =
  1436. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1437. if (tls == NULL) {
  1438. /* SSL called from an unknown thread: Create some thread index.
  1439. */
  1440. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1441. tls->is_master = -2; /* -2 means "3rd party thread" */
  1442. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1443. pthread_setspecific(sTlsKey, tls);
  1444. }
  1445. return tls->thread_idx;
  1446. } else {
  1447. /* pthread_t may be any data type, so a simple cast to unsigned long
  1448. * can rise a warning/error, depending on the platform.
  1449. * Here memcpy is used as an anything-to-anything cast. */
  1450. unsigned long ret = 0;
  1451. pthread_t t = pthread_self();
  1452. memcpy(&ret, &t, sizeof(pthread_t));
  1453. return ret;
  1454. }
  1455. #if defined(__clang__)
  1456. #pragma clang diagnostic pop
  1457. #endif
  1458. #endif
  1459. }
  1460. FUNCTION_MAY_BE_UNUSED
  1461. static uint64_t
  1462. mg_get_current_time_ns(void)
  1463. {
  1464. struct timespec tsnow;
  1465. clock_gettime(CLOCK_REALTIME, &tsnow);
  1466. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1467. }
  1468. #if defined(GCC_DIAGNOSTIC)
  1469. /* Show no warning in case system functions are not used. */
  1470. #pragma GCC diagnostic pop
  1471. #endif /* defined(GCC_DIAGNOSTIC) */
  1472. #if defined(__clang__)
  1473. /* Show no warning in case system functions are not used. */
  1474. #pragma clang diagnostic pop
  1475. #endif
  1476. #if defined(NEED_DEBUG_TRACE_FUNC)
  1477. static void
  1478. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1479. {
  1480. va_list args;
  1481. struct timespec tsnow;
  1482. /* Get some operating system independent thread id */
  1483. unsigned long thread_id = mg_current_thread_id();
  1484. clock_gettime(CLOCK_REALTIME, &tsnow);
  1485. flockfile(DEBUG_TRACE_STREAM);
  1486. fprintf(DEBUG_TRACE_STREAM,
  1487. "*** %lu.%09lu %lu %s:%u: ",
  1488. (unsigned long)tsnow.tv_sec,
  1489. (unsigned long)tsnow.tv_nsec,
  1490. thread_id,
  1491. func,
  1492. line);
  1493. va_start(args, fmt);
  1494. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1495. va_end(args);
  1496. putc('\n', DEBUG_TRACE_STREAM);
  1497. fflush(DEBUG_TRACE_STREAM);
  1498. funlockfile(DEBUG_TRACE_STREAM);
  1499. }
  1500. #endif /* NEED_DEBUG_TRACE_FUNC */
  1501. #define MD5_STATIC static
  1502. #include "md5.inl"
  1503. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1504. #if defined(NO_SOCKLEN_T)
  1505. typedef int socklen_t;
  1506. #endif /* NO_SOCKLEN_T */
  1507. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1508. #if !defined(MSG_NOSIGNAL)
  1509. #define MSG_NOSIGNAL (0)
  1510. #endif
  1511. #if defined(NO_SSL)
  1512. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1513. typedef struct SSL_CTX SSL_CTX;
  1514. #else
  1515. #if defined(NO_SSL_DL)
  1516. #include <openssl/bn.h>
  1517. #include <openssl/conf.h>
  1518. #include <openssl/crypto.h>
  1519. #include <openssl/dh.h>
  1520. #include <openssl/engine.h>
  1521. #include <openssl/err.h>
  1522. #include <openssl/opensslv.h>
  1523. #include <openssl/pem.h>
  1524. #include <openssl/ssl.h>
  1525. #include <openssl/tls1.h>
  1526. #include <openssl/x509.h>
  1527. #if defined(WOLFSSL_VERSION)
  1528. /* Additional defines for WolfSSL, see
  1529. * https://github.com/civetweb/civetweb/issues/583 */
  1530. #include "wolfssl_extras.inl"
  1531. #endif
  1532. #if defined(OPENSSL_IS_BORINGSSL)
  1533. /* From boringssl/src/include/openssl/mem.h:
  1534. *
  1535. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1536. * However, that was written in a time before Valgrind and ASAN. Since we now
  1537. * have those tools, the OpenSSL allocation functions are simply macros around
  1538. * the standard memory functions.
  1539. *
  1540. * #define OPENSSL_free free */
  1541. #define free free
  1542. // disable for boringssl
  1543. #define CONF_modules_unload(a) ((void)0)
  1544. #define ENGINE_cleanup() ((void)0)
  1545. #endif
  1546. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1547. /* If OpenSSL headers are included, automatically select the API version */
  1548. #if !defined(OPENSSL_API_1_1)
  1549. #define OPENSSL_API_1_1
  1550. #endif
  1551. #define OPENSSL_REMOVE_THREAD_STATE()
  1552. #else
  1553. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1554. #endif
  1555. #else
  1556. /* SSL loaded dynamically from DLL.
  1557. * I put the prototypes here to be independent from OpenSSL source
  1558. * installation. */
  1559. typedef struct ssl_st SSL;
  1560. typedef struct ssl_method_st SSL_METHOD;
  1561. typedef struct ssl_ctx_st SSL_CTX;
  1562. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1563. typedef struct x509_name X509_NAME;
  1564. typedef struct asn1_integer ASN1_INTEGER;
  1565. typedef struct bignum BIGNUM;
  1566. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1567. typedef struct evp_md EVP_MD;
  1568. typedef struct x509 X509;
  1569. #define SSL_CTRL_OPTIONS (32)
  1570. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1571. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1572. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1573. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1574. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1575. #define SSL_VERIFY_NONE (0)
  1576. #define SSL_VERIFY_PEER (1)
  1577. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1578. #define SSL_VERIFY_CLIENT_ONCE (4)
  1579. #define SSL_OP_ALL (0x80000BFFul)
  1580. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1581. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1582. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1583. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1584. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1585. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1586. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1587. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1588. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1589. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1590. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1591. #define SSL_CB_HANDSHAKE_START (0x10)
  1592. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1593. #define SSL_ERROR_NONE (0)
  1594. #define SSL_ERROR_SSL (1)
  1595. #define SSL_ERROR_WANT_READ (2)
  1596. #define SSL_ERROR_WANT_WRITE (3)
  1597. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1598. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1599. #define SSL_ERROR_ZERO_RETURN (6)
  1600. #define SSL_ERROR_WANT_CONNECT (7)
  1601. #define SSL_ERROR_WANT_ACCEPT (8)
  1602. #define TLSEXT_TYPE_server_name (0)
  1603. #define TLSEXT_NAMETYPE_host_name (0)
  1604. #define SSL_TLSEXT_ERR_OK (0)
  1605. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1606. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1607. #define SSL_TLSEXT_ERR_NOACK (3)
  1608. enum ssl_func_category {
  1609. TLS_Mandatory, /* required for HTTPS */
  1610. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1611. TLS_END_OF_LIST
  1612. };
  1613. /* Check if all TLS functions/features are available */
  1614. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1615. struct ssl_func {
  1616. const char *name; /* SSL function name */
  1617. union {
  1618. enum ssl_func_category required; /* Mandatory or optional */
  1619. void (*ptr)(void); /* Function pointer */
  1620. };
  1621. };
  1622. #if defined(OPENSSL_API_1_1)
  1623. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1624. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1625. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1626. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1627. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1628. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1629. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1630. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1631. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1632. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1633. #define OPENSSL_init_ssl \
  1634. (*(int (*)(uint64_t opts, \
  1635. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1636. .ptr)
  1637. #define SSL_CTX_use_PrivateKey_file \
  1638. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1639. #define SSL_CTX_use_certificate_file \
  1640. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1641. #define SSL_CTX_set_default_passwd_cb \
  1642. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1643. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1644. #define SSL_CTX_use_certificate_chain_file \
  1645. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1646. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1647. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1648. #define SSL_CTX_set_verify \
  1649. (*(void (*)(SSL_CTX *, \
  1650. int, \
  1651. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1652. .ptr)
  1653. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1654. #define SSL_CTX_load_verify_locations \
  1655. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1656. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1657. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1658. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1659. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1660. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1661. #define SSL_CIPHER_get_name \
  1662. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1663. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1664. #define SSL_CTX_set_session_id_context \
  1665. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1666. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1667. #define SSL_CTX_set_cipher_list \
  1668. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1669. #define SSL_CTX_set_options \
  1670. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1671. #define SSL_CTX_set_info_callback \
  1672. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1673. ssl_sw[32] \
  1674. .ptr)
  1675. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1676. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1677. #define SSL_CTX_callback_ctrl \
  1678. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1679. #define SSL_get_servername \
  1680. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1681. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1682. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1683. #define SSL_CTX_set_alpn_protos \
  1684. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1685. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1686. const unsigned char **out,
  1687. unsigned char *outlen,
  1688. const unsigned char *in,
  1689. unsigned int inlen,
  1690. void *arg);
  1691. #define SSL_CTX_set_alpn_select_cb \
  1692. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1693. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1694. const unsigned char **out,
  1695. unsigned int *outlen,
  1696. void *arg);
  1697. #define SSL_CTX_set_next_protos_advertised_cb \
  1698. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1699. .ptr)
  1700. #define SSL_CTX_clear_options(ctx, op) \
  1701. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1702. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1703. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1704. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1705. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1706. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1707. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1708. SSL_CTX_callback_ctrl(ctx, \
  1709. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1710. (void (*)(void))cb)
  1711. #define SSL_set_tlsext_host_name(ctx, arg) \
  1712. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1713. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1714. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1715. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1716. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1717. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1718. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1719. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1720. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1721. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1722. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1723. #define X509_NAME_oneline \
  1724. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1725. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1726. #define EVP_get_digestbyname \
  1727. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1728. #define EVP_Digest \
  1729. (*(int (*)( \
  1730. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1731. crypto_sw[9] \
  1732. .ptr)
  1733. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1734. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1735. #define ASN1_INTEGER_to_BN \
  1736. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1737. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1738. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1739. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1740. #define OPENSSL_free(a) CRYPTO_free(a)
  1741. #define OPENSSL_REMOVE_THREAD_STATE()
  1742. /* init_ssl_ctx() function updates this array.
  1743. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1744. * of respective functions. The macros above (like SSL_connect()) are really
  1745. * just calling these functions indirectly via the pointer. */
  1746. static struct ssl_func ssl_sw[] = {
  1747. {"SSL_free", {TLS_Mandatory}},
  1748. {"SSL_accept", {TLS_Mandatory}},
  1749. {"SSL_connect", {TLS_Mandatory}},
  1750. {"SSL_read", {TLS_Mandatory}},
  1751. {"SSL_write", {TLS_Mandatory}},
  1752. {"SSL_get_error", {TLS_Mandatory}},
  1753. {"SSL_set_fd", {TLS_Mandatory}},
  1754. {"SSL_new", {TLS_Mandatory}},
  1755. {"SSL_CTX_new", {TLS_Mandatory}},
  1756. {"TLS_server_method", {TLS_Mandatory}},
  1757. {"OPENSSL_init_ssl", {TLS_Mandatory}},
  1758. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1759. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1760. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1761. {"SSL_CTX_free", {TLS_Mandatory}},
  1762. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1763. {"TLS_client_method", {TLS_Mandatory}},
  1764. {"SSL_pending", {TLS_Mandatory}},
  1765. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1766. {"SSL_shutdown", {TLS_Mandatory}},
  1767. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1768. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1769. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1770. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1771. {"SSL_get_version", {TLS_Mandatory}},
  1772. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1773. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1774. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1775. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1776. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1777. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1778. {"SSL_CTX_set_options", {TLS_Mandatory}},
  1779. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1780. {"SSL_get_ex_data", {TLS_Mandatory}},
  1781. {"SSL_set_ex_data", {TLS_Mandatory}},
  1782. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1783. {"SSL_get_servername", {TLS_Mandatory}},
  1784. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1785. {"SSL_ctrl", {TLS_Mandatory}},
  1786. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1787. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1788. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1789. {NULL, {TLS_END_OF_LIST}}};
  1790. /* Similar array as ssl_sw. These functions could be located in different
  1791. * lib. */
  1792. static struct ssl_func crypto_sw[] = {{"ERR_get_error", {TLS_Mandatory}},
  1793. {"ERR_error_string", {TLS_Mandatory}},
  1794. {"CONF_modules_unload", {TLS_Mandatory}},
  1795. {"X509_free", {TLS_Mandatory}},
  1796. {"X509_get_subject_name",
  1797. {TLS_Mandatory}},
  1798. {"X509_get_issuer_name", {TLS_Mandatory}},
  1799. {"X509_NAME_oneline", {TLS_Mandatory}},
  1800. {"X509_get_serialNumber",
  1801. {TLS_Mandatory}},
  1802. {"EVP_get_digestbyname", {TLS_Mandatory}},
  1803. {"EVP_Digest", {TLS_Mandatory}},
  1804. {"i2d_X509", {TLS_Mandatory}},
  1805. {"BN_bn2hex", {TLS_Mandatory}},
  1806. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  1807. {"BN_free", {TLS_Mandatory}},
  1808. {"CRYPTO_free", {TLS_Mandatory}},
  1809. {"ERR_clear_error", {TLS_Mandatory}},
  1810. {NULL, {TLS_END_OF_LIST}}};
  1811. #else
  1812. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1813. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1814. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1815. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1816. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1817. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1818. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1819. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1820. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1821. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1822. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1823. #define SSL_CTX_use_PrivateKey_file \
  1824. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1825. #define SSL_CTX_use_certificate_file \
  1826. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1827. #define SSL_CTX_set_default_passwd_cb \
  1828. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1829. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1830. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1831. #define SSL_CTX_use_certificate_chain_file \
  1832. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1833. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1834. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1835. #define SSL_CTX_set_verify \
  1836. (*(void (*)(SSL_CTX *, \
  1837. int, \
  1838. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1839. .ptr)
  1840. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1841. #define SSL_CTX_load_verify_locations \
  1842. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1843. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1844. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1845. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1846. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1847. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1848. #define SSL_CIPHER_get_name \
  1849. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1850. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1851. #define SSL_CTX_set_session_id_context \
  1852. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1853. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1854. #define SSL_CTX_set_cipher_list \
  1855. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1856. #define SSL_CTX_set_info_callback \
  1857. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1858. .ptr)
  1859. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1860. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1861. #define SSL_CTX_callback_ctrl \
  1862. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1863. #define SSL_get_servername \
  1864. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1865. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1866. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1867. #define SSL_CTX_set_alpn_protos \
  1868. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1869. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1870. const unsigned char **out,
  1871. unsigned char *outlen,
  1872. const unsigned char *in,
  1873. unsigned int inlen,
  1874. void *arg);
  1875. #define SSL_CTX_set_alpn_select_cb \
  1876. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1877. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1878. const unsigned char **out,
  1879. unsigned int *outlen,
  1880. void *arg);
  1881. #define SSL_CTX_set_next_protos_advertised_cb \
  1882. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1883. .ptr)
  1884. #define SSL_CTX_set_options(ctx, op) \
  1885. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1886. #define SSL_CTX_clear_options(ctx, op) \
  1887. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1888. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1889. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1890. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1891. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1892. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1893. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1894. SSL_CTX_callback_ctrl(ctx, \
  1895. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1896. (void (*)(void))cb)
  1897. #define SSL_set_tlsext_host_name(ctx, arg) \
  1898. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1899. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1900. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1901. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1902. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1903. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1904. #define CRYPTO_set_locking_callback \
  1905. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1906. #define CRYPTO_set_id_callback \
  1907. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1908. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1909. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1910. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1911. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1912. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1913. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1914. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1915. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1916. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1917. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1918. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1919. #define X509_NAME_oneline \
  1920. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1921. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1922. #define i2c_ASN1_INTEGER \
  1923. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1924. #define EVP_get_digestbyname \
  1925. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1926. #define EVP_Digest \
  1927. (*(int (*)( \
  1928. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1929. crypto_sw[18] \
  1930. .ptr)
  1931. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1932. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1933. #define ASN1_INTEGER_to_BN \
  1934. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1935. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1936. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1937. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1938. #define OPENSSL_free(a) CRYPTO_free(a)
  1939. /* use here ERR_remove_state,
  1940. * while on some platforms function is not included into library due to
  1941. * deprication */
  1942. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1943. /* init_ssl_ctx() function updates this array.
  1944. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1945. * of respective functions. The macros above (like SSL_connect()) are really
  1946. * just calling these functions indirectly via the pointer. */
  1947. static struct ssl_func ssl_sw[] = {
  1948. {"SSL_free", {TLS_Mandatory}},
  1949. {"SSL_accept", {TLS_Mandatory}},
  1950. {"SSL_connect", {TLS_Mandatory}},
  1951. {"SSL_read", {TLS_Mandatory}},
  1952. {"SSL_write", {TLS_Mandatory}},
  1953. {"SSL_get_error", {TLS_Mandatory}},
  1954. {"SSL_set_fd", {TLS_Mandatory}},
  1955. {"SSL_new", {TLS_Mandatory}},
  1956. {"SSL_CTX_new", {TLS_Mandatory}},
  1957. {"SSLv23_server_method", {TLS_Mandatory}},
  1958. {"SSL_library_init", {TLS_Mandatory}},
  1959. {"SSL_CTX_use_PrivateKey_file", {TLS_Mandatory}},
  1960. {"SSL_CTX_use_certificate_file", {TLS_Mandatory}},
  1961. {"SSL_CTX_set_default_passwd_cb", {TLS_Mandatory}},
  1962. {"SSL_CTX_free", {TLS_Mandatory}},
  1963. {"SSL_load_error_strings", {TLS_Mandatory}},
  1964. {"SSL_CTX_use_certificate_chain_file", {TLS_Mandatory}},
  1965. {"SSLv23_client_method", {TLS_Mandatory}},
  1966. {"SSL_pending", {TLS_Mandatory}},
  1967. {"SSL_CTX_set_verify", {TLS_Mandatory}},
  1968. {"SSL_shutdown", {TLS_Mandatory}},
  1969. {"SSL_CTX_load_verify_locations", {TLS_Mandatory}},
  1970. {"SSL_CTX_set_default_verify_paths", {TLS_Mandatory}},
  1971. {"SSL_CTX_set_verify_depth", {TLS_Mandatory}},
  1972. {"SSL_get_peer_certificate", {TLS_Mandatory}},
  1973. {"SSL_get_version", {TLS_Mandatory}},
  1974. {"SSL_get_current_cipher", {TLS_Mandatory}},
  1975. {"SSL_CIPHER_get_name", {TLS_Mandatory}},
  1976. {"SSL_CTX_check_private_key", {TLS_Mandatory}},
  1977. {"SSL_CTX_set_session_id_context", {TLS_Mandatory}},
  1978. {"SSL_CTX_ctrl", {TLS_Mandatory}},
  1979. {"SSL_CTX_set_cipher_list", {TLS_Mandatory}},
  1980. {"SSL_CTX_set_info_callback", {TLS_Mandatory}},
  1981. {"SSL_get_ex_data", {TLS_Mandatory}},
  1982. {"SSL_set_ex_data", {TLS_Mandatory}},
  1983. {"SSL_CTX_callback_ctrl", {TLS_Mandatory}},
  1984. {"SSL_get_servername", {TLS_Mandatory}},
  1985. {"SSL_set_SSL_CTX", {TLS_Mandatory}},
  1986. {"SSL_ctrl", {TLS_Mandatory}},
  1987. {"SSL_CTX_set_alpn_protos", {TLS_ALPN}},
  1988. {"SSL_CTX_set_alpn_select_cb", {TLS_ALPN}},
  1989. {"SSL_CTX_set_next_protos_advertised_cb", {TLS_ALPN}},
  1990. {NULL, {TLS_END_OF_LIST}}};
  1991. /* Similar array as ssl_sw. These functions could be located in different
  1992. * lib. */
  1993. static struct ssl_func crypto_sw[] = {
  1994. {"CRYPTO_num_locks", {TLS_Mandatory}},
  1995. {"CRYPTO_set_locking_callback", {TLS_Mandatory}},
  1996. {"CRYPTO_set_id_callback", {TLS_Mandatory}},
  1997. {"ERR_get_error", {TLS_Mandatory}},
  1998. {"ERR_error_string", {TLS_Mandatory}},
  1999. {"ERR_remove_state", {TLS_Mandatory}},
  2000. {"ERR_free_strings", {TLS_Mandatory}},
  2001. {"ENGINE_cleanup", {TLS_Mandatory}},
  2002. {"CONF_modules_unload", {TLS_Mandatory}},
  2003. {"CRYPTO_cleanup_all_ex_data", {TLS_Mandatory}},
  2004. {"EVP_cleanup", {TLS_Mandatory}},
  2005. {"X509_free", {TLS_Mandatory}},
  2006. {"X509_get_subject_name", {TLS_Mandatory}},
  2007. {"X509_get_issuer_name", {TLS_Mandatory}},
  2008. {"X509_NAME_oneline", {TLS_Mandatory}},
  2009. {"X509_get_serialNumber", {TLS_Mandatory}},
  2010. {"i2c_ASN1_INTEGER", {TLS_Mandatory}},
  2011. {"EVP_get_digestbyname", {TLS_Mandatory}},
  2012. {"EVP_Digest", {TLS_Mandatory}},
  2013. {"i2d_X509", {TLS_Mandatory}},
  2014. {"BN_bn2hex", {TLS_Mandatory}},
  2015. {"ASN1_INTEGER_to_BN", {TLS_Mandatory}},
  2016. {"BN_free", {TLS_Mandatory}},
  2017. {"CRYPTO_free", {TLS_Mandatory}},
  2018. {"ERR_clear_error", {TLS_Mandatory}},
  2019. {NULL, {TLS_END_OF_LIST}}};
  2020. #endif /* OPENSSL_API_1_1 */
  2021. #endif /* NO_SSL_DL */
  2022. #endif /* NO_SSL */
  2023. #if !defined(NO_CACHING)
  2024. static const char month_names[][4] = {"Jan",
  2025. "Feb",
  2026. "Mar",
  2027. "Apr",
  2028. "May",
  2029. "Jun",
  2030. "Jul",
  2031. "Aug",
  2032. "Sep",
  2033. "Oct",
  2034. "Nov",
  2035. "Dec"};
  2036. #endif /* !NO_CACHING */
  2037. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2038. * the union u. */
  2039. union usa {
  2040. struct sockaddr sa;
  2041. struct sockaddr_in sin;
  2042. #if defined(USE_IPV6)
  2043. struct sockaddr_in6 sin6;
  2044. #endif
  2045. };
  2046. /* Describes a string (chunk of memory). */
  2047. struct vec {
  2048. const char *ptr;
  2049. size_t len;
  2050. };
  2051. struct mg_file_stat {
  2052. /* File properties filled by mg_stat: */
  2053. uint64_t size;
  2054. time_t last_modified;
  2055. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2056. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2057. * case we need a "Content-Eencoding: gzip" header */
  2058. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2059. };
  2060. struct mg_file_in_memory {
  2061. char *p;
  2062. uint32_t pos;
  2063. char mode;
  2064. };
  2065. struct mg_file_access {
  2066. /* File properties filled by mg_fopen: */
  2067. FILE *fp;
  2068. #if defined(MG_USE_OPEN_FILE)
  2069. /* TODO (low): Remove obsolete "file in memory" implementation.
  2070. * In an "early 2017" discussion at Google groups
  2071. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2072. * we decided to get rid of this feature (after some fade-out
  2073. * phase). */
  2074. const char *membuf;
  2075. #endif
  2076. };
  2077. struct mg_file {
  2078. struct mg_file_stat stat;
  2079. struct mg_file_access access;
  2080. };
  2081. #if defined(MG_USE_OPEN_FILE)
  2082. #define STRUCT_FILE_INITIALIZER \
  2083. { \
  2084. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2085. { \
  2086. (FILE *)NULL, (const char *)NULL \
  2087. } \
  2088. }
  2089. #else
  2090. #define STRUCT_FILE_INITIALIZER \
  2091. { \
  2092. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2093. { \
  2094. (FILE *)NULL \
  2095. } \
  2096. }
  2097. #endif
  2098. /* Describes listening socket, or socket which was accept()-ed by the master
  2099. * thread and queued for future handling by the worker thread. */
  2100. struct socket {
  2101. SOCKET sock; /* Listening socket */
  2102. union usa lsa; /* Local socket address */
  2103. union usa rsa; /* Remote socket address */
  2104. unsigned char is_ssl; /* Is port SSL-ed */
  2105. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2106. * port */
  2107. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2108. };
  2109. /* Enum const for all options must be in sync with
  2110. * static struct mg_option config_options[]
  2111. * This is tested in the unit test (test/private.c)
  2112. * "Private Config Options"
  2113. */
  2114. enum {
  2115. /* Once for each server */
  2116. LISTENING_PORTS,
  2117. NUM_THREADS,
  2118. RUN_AS_USER,
  2119. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2120. * socket option typedef TCP_NODELAY. */
  2121. MAX_REQUEST_SIZE,
  2122. LINGER_TIMEOUT,
  2123. CONNECTION_QUEUE_SIZE,
  2124. LISTEN_BACKLOG_SIZE,
  2125. #if defined(__linux__)
  2126. ALLOW_SENDFILE_CALL,
  2127. #endif
  2128. #if defined(_WIN32)
  2129. CASE_SENSITIVE_FILES,
  2130. #endif
  2131. THROTTLE,
  2132. ACCESS_LOG_FILE,
  2133. ERROR_LOG_FILE,
  2134. ENABLE_KEEP_ALIVE,
  2135. REQUEST_TIMEOUT,
  2136. KEEP_ALIVE_TIMEOUT,
  2137. #if defined(USE_WEBSOCKET)
  2138. WEBSOCKET_TIMEOUT,
  2139. ENABLE_WEBSOCKET_PING_PONG,
  2140. #endif
  2141. DECODE_URL,
  2142. #if defined(USE_LUA)
  2143. LUA_BACKGROUND_SCRIPT,
  2144. LUA_BACKGROUND_SCRIPT_PARAMS,
  2145. #endif
  2146. #if defined(USE_TIMERS)
  2147. CGI_TIMEOUT,
  2148. #endif
  2149. /* Once for each domain */
  2150. DOCUMENT_ROOT,
  2151. CGI_EXTENSIONS,
  2152. CGI_ENVIRONMENT,
  2153. PUT_DELETE_PASSWORDS_FILE,
  2154. CGI_INTERPRETER,
  2155. CGI_INTERPRETER_ARGS,
  2156. PROTECT_URI,
  2157. AUTHENTICATION_DOMAIN,
  2158. ENABLE_AUTH_DOMAIN_CHECK,
  2159. SSI_EXTENSIONS,
  2160. ENABLE_DIRECTORY_LISTING,
  2161. GLOBAL_PASSWORDS_FILE,
  2162. INDEX_FILES,
  2163. ACCESS_CONTROL_LIST,
  2164. EXTRA_MIME_TYPES,
  2165. SSL_CERTIFICATE,
  2166. SSL_CERTIFICATE_CHAIN,
  2167. URL_REWRITE_PATTERN,
  2168. HIDE_FILES,
  2169. SSL_DO_VERIFY_PEER,
  2170. SSL_CA_PATH,
  2171. SSL_CA_FILE,
  2172. SSL_VERIFY_DEPTH,
  2173. SSL_DEFAULT_VERIFY_PATHS,
  2174. SSL_CIPHER_LIST,
  2175. SSL_PROTOCOL_VERSION,
  2176. SSL_SHORT_TRUST,
  2177. #if defined(USE_LUA)
  2178. LUA_PRELOAD_FILE,
  2179. LUA_SCRIPT_EXTENSIONS,
  2180. LUA_SERVER_PAGE_EXTENSIONS,
  2181. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2182. LUA_DEBUG_PARAMS,
  2183. #endif
  2184. #endif
  2185. #if defined(USE_DUKTAPE)
  2186. DUKTAPE_SCRIPT_EXTENSIONS,
  2187. #endif
  2188. #if defined(USE_WEBSOCKET)
  2189. WEBSOCKET_ROOT,
  2190. #endif
  2191. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2192. LUA_WEBSOCKET_EXTENSIONS,
  2193. #endif
  2194. ACCESS_CONTROL_ALLOW_ORIGIN,
  2195. ACCESS_CONTROL_ALLOW_METHODS,
  2196. ACCESS_CONTROL_ALLOW_HEADERS,
  2197. ERROR_PAGES,
  2198. #if !defined(NO_CACHING)
  2199. STATIC_FILE_MAX_AGE,
  2200. STATIC_FILE_CACHE_CONTROL,
  2201. #endif
  2202. #if !defined(NO_SSL)
  2203. STRICT_HTTPS_MAX_AGE,
  2204. #endif
  2205. ADDITIONAL_HEADER,
  2206. ALLOW_INDEX_SCRIPT_SUB_RES,
  2207. #if defined(DAEMONIZE)
  2208. ENABLE_DAEMONIZE,
  2209. #endif
  2210. NUM_OPTIONS
  2211. };
  2212. /* Config option name, config types, default value.
  2213. * Must be in the same order as the enum const above.
  2214. */
  2215. static const struct mg_option config_options[] = {
  2216. /* Once for each server */
  2217. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2218. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2219. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2220. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2221. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2222. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2223. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2224. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2225. #if defined(__linux__)
  2226. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2227. #endif
  2228. #if defined(_WIN32)
  2229. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2230. #endif
  2231. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2232. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2233. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2234. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2235. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2236. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2237. #if defined(USE_WEBSOCKET)
  2238. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2239. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2240. #endif
  2241. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2242. #if defined(USE_LUA)
  2243. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2244. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2245. #endif
  2246. #if defined(USE_TIMERS)
  2247. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2248. #endif
  2249. /* Once for each domain */
  2250. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2251. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2252. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2253. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2254. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2255. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2256. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2257. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2258. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2259. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2260. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2261. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2262. {"index_files",
  2263. MG_CONFIG_TYPE_STRING_LIST,
  2264. #if defined(USE_LUA)
  2265. "index.xhtml,index.html,index.htm,"
  2266. "index.lp,index.lsp,index.lua,index.cgi,"
  2267. "index.shtml,index.php"},
  2268. #else
  2269. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2270. #endif
  2271. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2272. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2273. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2274. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2275. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2276. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2277. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2278. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2279. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2280. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2281. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2282. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2283. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2284. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2285. #if defined(USE_LUA)
  2286. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2287. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2288. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2289. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2290. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2291. #endif
  2292. #endif
  2293. #if defined(USE_DUKTAPE)
  2294. /* The support for duktape is still in alpha version state.
  2295. * The name of this config option might change. */
  2296. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2297. #endif
  2298. #if defined(USE_WEBSOCKET)
  2299. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2300. #endif
  2301. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2302. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2303. #endif
  2304. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2305. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2306. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2307. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2308. #if !defined(NO_CACHING)
  2309. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2310. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2311. #endif
  2312. #if !defined(NO_SSL)
  2313. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2314. #endif
  2315. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2316. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2317. #if defined(DAEMONIZE)
  2318. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2319. #endif
  2320. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2321. /* Check if the config_options and the corresponding enum have compatible
  2322. * sizes. */
  2323. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2324. == (NUM_OPTIONS + 1),
  2325. "config_options and enum not sync");
  2326. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2327. struct mg_handler_info {
  2328. /* Name/Pattern of the URI. */
  2329. char *uri;
  2330. size_t uri_len;
  2331. /* handler type */
  2332. int handler_type;
  2333. /* Handler for http/https or authorization requests. */
  2334. mg_request_handler handler;
  2335. unsigned int refcount;
  2336. int removing;
  2337. /* Handler for ws/wss (websocket) requests. */
  2338. mg_websocket_connect_handler connect_handler;
  2339. mg_websocket_ready_handler ready_handler;
  2340. mg_websocket_data_handler data_handler;
  2341. mg_websocket_close_handler close_handler;
  2342. /* accepted subprotocols for ws/wss requests. */
  2343. struct mg_websocket_subprotocols *subprotocols;
  2344. /* Handler for authorization requests */
  2345. mg_authorization_handler auth_handler;
  2346. /* User supplied argument for the handler function. */
  2347. void *cbdata;
  2348. /* next handler in a linked list */
  2349. struct mg_handler_info *next;
  2350. };
  2351. enum {
  2352. CONTEXT_INVALID,
  2353. CONTEXT_SERVER,
  2354. CONTEXT_HTTP_CLIENT,
  2355. CONTEXT_WS_CLIENT
  2356. };
  2357. struct mg_domain_context {
  2358. SSL_CTX *ssl_ctx; /* SSL context */
  2359. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2360. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2361. int64_t ssl_cert_last_mtime;
  2362. /* Server nonce */
  2363. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2364. unsigned long nonce_count; /* Used nonces, used for authentication */
  2365. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2366. /* linked list of shared lua websockets */
  2367. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2368. #endif
  2369. /* Linked list of domains */
  2370. struct mg_domain_context *next;
  2371. };
  2372. /* Stop flag can be "volatile" or require atomic access */
  2373. #if !defined(STOP_FLAG_NO_ATOMICS)
  2374. typedef int stop_flag_t;
  2375. #define STOP_FLAG_IS_ZERO(f) (mg_atomic_compare_and_swap((f), 0, 0) == 0)
  2376. #define STOP_FLAG_IS_TWO(f) (mg_atomic_compare_and_swap((f), 0, 0) == 2)
  2377. static void
  2378. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2379. {
  2380. /* This only increments *f to v, never decrements. */
  2381. int i;
  2382. for (i = 0; i < v; i++) {
  2383. (void)mg_atomic_compare_and_swap(f, i, i + 1);
  2384. }
  2385. }
  2386. #else /* STOP_FLAG_NO_ATOMICS */
  2387. typedef int volatile stop_flag_t;
  2388. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2389. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2390. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2391. #endif /* STOP_FLAG_NO_ATOMICS */
  2392. struct mg_context {
  2393. /* Part 1 - Physical context:
  2394. * This holds threads, ports, timeouts, ...
  2395. * set for the entire server, independent from the
  2396. * addressed hostname.
  2397. */
  2398. /* Connection related */
  2399. int context_type; /* See CONTEXT_* above */
  2400. struct socket *listening_sockets;
  2401. struct mg_pollfd *listening_socket_fds;
  2402. unsigned int num_listening_sockets;
  2403. struct mg_connection *worker_connections; /* The connection struct, pre-
  2404. * allocated for each worker */
  2405. #if defined(USE_SERVER_STATS)
  2406. int active_connections;
  2407. int max_active_connections;
  2408. int64_t total_connections;
  2409. int64_t total_requests;
  2410. int64_t total_data_read;
  2411. int64_t total_data_written;
  2412. #endif
  2413. /* Thread related */
  2414. stop_flag_t stop_flag; /* Should we stop event loop */
  2415. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2416. pthread_t masterthreadid; /* The master thread ID */
  2417. unsigned int
  2418. cfg_worker_threads; /* The number of configured worker threads. */
  2419. pthread_t *worker_threadids; /* The worker thread IDs */
  2420. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2421. /* Connection to thread dispatching */
  2422. #if defined(ALTERNATIVE_QUEUE)
  2423. struct socket *client_socks;
  2424. void **client_wait_events;
  2425. #else
  2426. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2427. worker thread */
  2428. int sq_head; /* Head of the socket queue */
  2429. int sq_tail; /* Tail of the socket queue */
  2430. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2431. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2432. int sq_size; /* No of elements in socket queue */
  2433. #if defined(USE_SERVER_STATS)
  2434. int sq_blocked; /* Status information: sq is full */
  2435. int sq_filled; /* Status information: sq_head - sq_tail */
  2436. int sq_max_fill;
  2437. #endif /* USE_SERVER_STATS */
  2438. #endif /* ALTERNATIVE_QUEUE */
  2439. /* Memory related */
  2440. unsigned int max_request_size; /* The max request size */
  2441. #if defined(USE_SERVER_STATS)
  2442. struct mg_memory_stat ctx_memory;
  2443. #endif
  2444. /* Operating system related */
  2445. char *systemName; /* What operating system is running */
  2446. time_t start_time; /* Server start time, used for authentication
  2447. * and for diagnstics. */
  2448. #if defined(USE_TIMERS)
  2449. struct ttimers *timers;
  2450. #endif
  2451. /* Lua specific: Background operations and shared websockets */
  2452. #if defined(USE_LUA)
  2453. void *lua_background_state;
  2454. #endif
  2455. /* Server nonce */
  2456. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2457. * ssl_cert_last_mtime, nonce_count, and
  2458. * next (linked list) */
  2459. /* Server callbacks */
  2460. struct mg_callbacks callbacks; /* User-defined callback function */
  2461. void *user_data; /* User-defined data */
  2462. /* Part 2 - Logical domain:
  2463. * This holds hostname, TLS certificate, document root, ...
  2464. * set for a domain hosted at the server.
  2465. * There may be multiple domains hosted at one physical server.
  2466. * The default domain "dd" is the first element of a list of
  2467. * domains.
  2468. */
  2469. struct mg_domain_context dd; /* default domain */
  2470. };
  2471. #if defined(USE_SERVER_STATS)
  2472. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2473. static struct mg_memory_stat *
  2474. get_memory_stat(struct mg_context *ctx)
  2475. {
  2476. if (ctx) {
  2477. return &(ctx->ctx_memory);
  2478. }
  2479. return &mg_common_memory;
  2480. }
  2481. #endif
  2482. enum {
  2483. CONNECTION_TYPE_INVALID,
  2484. CONNECTION_TYPE_REQUEST,
  2485. CONNECTION_TYPE_RESPONSE
  2486. };
  2487. enum {
  2488. PROTOCOL_TYPE_HTTP1 = 0,
  2489. PROTOCOL_TYPE_WEBSOCKET = 1,
  2490. PROTOCOL_TYPE_HTTP2 = 2
  2491. };
  2492. struct mg_connection {
  2493. int connection_type; /* see CONNECTION_TYPE_* above */
  2494. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2495. struct mg_request_info request_info;
  2496. struct mg_response_info response_info;
  2497. struct mg_context *phys_ctx;
  2498. struct mg_domain_context *dom_ctx;
  2499. #if defined(USE_SERVER_STATS)
  2500. int conn_state; /* 0 = undef, numerical value may change in different
  2501. * versions. For the current definition, see
  2502. * mg_get_connection_info_impl */
  2503. #endif
  2504. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2505. SSL *ssl; /* SSL descriptor */
  2506. struct socket client; /* Connected client */
  2507. time_t conn_birth_time; /* Time (wall clock) when connection was
  2508. * established */
  2509. #if defined(USE_SERVER_STATS)
  2510. time_t conn_close_time; /* Time (wall clock) when connection was
  2511. * closed (or 0 if still open) */
  2512. #endif
  2513. struct timespec req_time; /* Time (since system start) when the request
  2514. * was received */
  2515. int64_t num_bytes_sent; /* Total bytes sent to client */
  2516. int64_t content_len; /* How many bytes of content can be read
  2517. * !is_chunked: Content-Length header value
  2518. * or -1 (until connection closed,
  2519. * not allowed for a request)
  2520. * is_chunked: >= 0, appended gradually
  2521. */
  2522. int64_t consumed_content; /* How many bytes of content have been read */
  2523. int is_chunked; /* Transfer-Encoding is chunked:
  2524. * 0 = not chunked,
  2525. * 1 = chunked, not yet, or some data read,
  2526. * 2 = chunked, has error,
  2527. * 3 = chunked, all data read except trailer,
  2528. * 4 = chunked, all data read
  2529. */
  2530. char *buf; /* Buffer for received data */
  2531. char *path_info; /* PATH_INFO part of the URL */
  2532. int must_close; /* 1 if connection must be closed */
  2533. int accept_gzip; /* 1 if gzip encoding is accepted */
  2534. int in_error_handler; /* 1 if in handler for user defined error
  2535. * pages */
  2536. #if defined(USE_WEBSOCKET)
  2537. int in_websocket_handling; /* 1 if in read_websocket */
  2538. #endif
  2539. int handled_requests; /* Number of requests handled by this connection
  2540. */
  2541. int buf_size; /* Buffer size */
  2542. int request_len; /* Size of the request + headers in a buffer */
  2543. int data_len; /* Total size of data in a buffer */
  2544. int status_code; /* HTTP reply status code, e.g. 200 */
  2545. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2546. * throttle */
  2547. time_t last_throttle_time; /* Last time throttled data was sent */
  2548. int last_throttle_bytes; /* Bytes sent this second */
  2549. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2550. * atomic transmissions for websockets */
  2551. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2552. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2553. #endif
  2554. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2555. * for quick access */
  2556. };
  2557. /* Directory entry */
  2558. struct de {
  2559. struct mg_connection *conn;
  2560. char *file_name;
  2561. struct mg_file_stat file;
  2562. };
  2563. #define mg_cry_internal(conn, fmt, ...) \
  2564. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2565. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2566. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2567. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2568. struct mg_context *ctx,
  2569. const char *func,
  2570. unsigned line,
  2571. const char *fmt,
  2572. ...) PRINTF_ARGS(5, 6);
  2573. #if !defined(NO_THREAD_NAME)
  2574. #if defined(_WIN32) && defined(_MSC_VER)
  2575. /* Set the thread name for debugging purposes in Visual Studio
  2576. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2577. */
  2578. #pragma pack(push, 8)
  2579. typedef struct tagTHREADNAME_INFO {
  2580. DWORD dwType; /* Must be 0x1000. */
  2581. LPCSTR szName; /* Pointer to name (in user addr space). */
  2582. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2583. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2584. } THREADNAME_INFO;
  2585. #pragma pack(pop)
  2586. #elif defined(__linux__)
  2587. #include <sys/prctl.h>
  2588. #include <sys/sendfile.h>
  2589. #if defined(ALTERNATIVE_QUEUE)
  2590. #include <sys/eventfd.h>
  2591. #endif /* ALTERNATIVE_QUEUE */
  2592. #if defined(ALTERNATIVE_QUEUE)
  2593. static void *
  2594. event_create(void)
  2595. {
  2596. int evhdl = eventfd(0, EFD_CLOEXEC);
  2597. int *ret;
  2598. if (evhdl == -1) {
  2599. /* Linux uses -1 on error, Windows NULL. */
  2600. /* However, Linux does not return 0 on success either. */
  2601. return 0;
  2602. }
  2603. ret = (int *)mg_malloc(sizeof(int));
  2604. if (ret) {
  2605. *ret = evhdl;
  2606. } else {
  2607. (void)close(evhdl);
  2608. }
  2609. return (void *)ret;
  2610. }
  2611. static int
  2612. event_wait(void *eventhdl)
  2613. {
  2614. uint64_t u;
  2615. int evhdl, s;
  2616. if (!eventhdl) {
  2617. /* error */
  2618. return 0;
  2619. }
  2620. evhdl = *(int *)eventhdl;
  2621. s = (int)read(evhdl, &u, sizeof(u));
  2622. if (s != sizeof(u)) {
  2623. /* error */
  2624. return 0;
  2625. }
  2626. (void)u; /* the value is not required */
  2627. return 1;
  2628. }
  2629. static int
  2630. event_signal(void *eventhdl)
  2631. {
  2632. uint64_t u = 1;
  2633. int evhdl, s;
  2634. if (!eventhdl) {
  2635. /* error */
  2636. return 0;
  2637. }
  2638. evhdl = *(int *)eventhdl;
  2639. s = (int)write(evhdl, &u, sizeof(u));
  2640. if (s != sizeof(u)) {
  2641. /* error */
  2642. return 0;
  2643. }
  2644. return 1;
  2645. }
  2646. static void
  2647. event_destroy(void *eventhdl)
  2648. {
  2649. int evhdl;
  2650. if (!eventhdl) {
  2651. /* error */
  2652. return;
  2653. }
  2654. evhdl = *(int *)eventhdl;
  2655. close(evhdl);
  2656. mg_free(eventhdl);
  2657. }
  2658. #endif
  2659. #endif
  2660. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2661. struct posix_event {
  2662. pthread_mutex_t mutex;
  2663. pthread_cond_t cond;
  2664. int signaled;
  2665. };
  2666. static void *
  2667. event_create(void)
  2668. {
  2669. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2670. if (ret == 0) {
  2671. /* out of memory */
  2672. return 0;
  2673. }
  2674. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2675. /* pthread mutex not available */
  2676. mg_free(ret);
  2677. return 0;
  2678. }
  2679. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2680. /* pthread cond not available */
  2681. pthread_mutex_destroy(&(ret->mutex));
  2682. mg_free(ret);
  2683. return 0;
  2684. }
  2685. ret->signaled = 0;
  2686. return (void *)ret;
  2687. }
  2688. static int
  2689. event_wait(void *eventhdl)
  2690. {
  2691. struct posix_event *ev = (struct posix_event *)eventhdl;
  2692. pthread_mutex_lock(&(ev->mutex));
  2693. while (!ev->signaled) {
  2694. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2695. }
  2696. ev->signaled = 0;
  2697. pthread_mutex_unlock(&(ev->mutex));
  2698. return 1;
  2699. }
  2700. static int
  2701. event_signal(void *eventhdl)
  2702. {
  2703. struct posix_event *ev = (struct posix_event *)eventhdl;
  2704. pthread_mutex_lock(&(ev->mutex));
  2705. pthread_cond_signal(&(ev->cond));
  2706. ev->signaled = 1;
  2707. pthread_mutex_unlock(&(ev->mutex));
  2708. return 1;
  2709. }
  2710. static void
  2711. event_destroy(void *eventhdl)
  2712. {
  2713. struct posix_event *ev = (struct posix_event *)eventhdl;
  2714. pthread_cond_destroy(&(ev->cond));
  2715. pthread_mutex_destroy(&(ev->mutex));
  2716. mg_free(ev);
  2717. }
  2718. #endif
  2719. static void
  2720. mg_set_thread_name(const char *name)
  2721. {
  2722. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2723. mg_snprintf(
  2724. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2725. #if defined(_WIN32)
  2726. #if defined(_MSC_VER)
  2727. /* Windows and Visual Studio Compiler */
  2728. __try {
  2729. THREADNAME_INFO info;
  2730. info.dwType = 0x1000;
  2731. info.szName = threadName;
  2732. info.dwThreadID = ~0U;
  2733. info.dwFlags = 0;
  2734. RaiseException(0x406D1388,
  2735. 0,
  2736. sizeof(info) / sizeof(ULONG_PTR),
  2737. (ULONG_PTR *)&info);
  2738. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2739. }
  2740. #elif defined(__MINGW32__)
  2741. /* No option known to set thread name for MinGW known */
  2742. #endif
  2743. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2744. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2745. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2746. #if defined(__MACH__)
  2747. /* OS X only current thread name can be changed */
  2748. (void)pthread_setname_np(threadName);
  2749. #else
  2750. (void)pthread_setname_np(pthread_self(), threadName);
  2751. #endif
  2752. #elif defined(__linux__)
  2753. /* On Linux we can use the prctl function.
  2754. * When building for Linux Standard Base (LSB) use
  2755. * NO_THREAD_NAME. However, thread names are a big
  2756. * help for debugging, so the stadard is to set them.
  2757. */
  2758. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2759. #endif
  2760. }
  2761. #else /* !defined(NO_THREAD_NAME) */
  2762. void
  2763. mg_set_thread_name(const char *threadName)
  2764. {
  2765. }
  2766. #endif
  2767. #if defined(MG_LEGACY_INTERFACE)
  2768. const char **
  2769. mg_get_valid_option_names(void)
  2770. {
  2771. /* This function is deprecated. Use mg_get_valid_options instead. */
  2772. static const char
  2773. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2774. int i;
  2775. for (i = 0; config_options[i].name != NULL; i++) {
  2776. data[i * 2] = config_options[i].name;
  2777. data[i * 2 + 1] = config_options[i].default_value;
  2778. }
  2779. return data;
  2780. }
  2781. #endif
  2782. const struct mg_option *
  2783. mg_get_valid_options(void)
  2784. {
  2785. return config_options;
  2786. }
  2787. /* Do not open file (used in is_file_in_memory) */
  2788. #define MG_FOPEN_MODE_NONE (0)
  2789. /* Open file for read only access */
  2790. #define MG_FOPEN_MODE_READ (1)
  2791. /* Open file for writing, create and overwrite */
  2792. #define MG_FOPEN_MODE_WRITE (2)
  2793. /* Open file for writing, create and append */
  2794. #define MG_FOPEN_MODE_APPEND (4)
  2795. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2796. * output filep and return 1, otherwise return 0 and don't modify anything.
  2797. */
  2798. static int
  2799. open_file_in_memory(const struct mg_connection *conn,
  2800. const char *path,
  2801. struct mg_file *filep,
  2802. int mode)
  2803. {
  2804. #if defined(MG_USE_OPEN_FILE)
  2805. size_t size = 0;
  2806. const char *buf = NULL;
  2807. if (!conn) {
  2808. return 0;
  2809. }
  2810. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2811. return 0;
  2812. }
  2813. if (conn->phys_ctx->callbacks.open_file) {
  2814. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2815. if (buf != NULL) {
  2816. if (filep == NULL) {
  2817. /* This is a file in memory, but we cannot store the
  2818. * properties
  2819. * now.
  2820. * Called from "is_file_in_memory" function. */
  2821. return 1;
  2822. }
  2823. /* NOTE: override filep->size only on success. Otherwise, it
  2824. * might
  2825. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2826. filep->access.membuf = buf;
  2827. filep->access.fp = NULL;
  2828. /* Size was set by the callback */
  2829. filep->stat.size = size;
  2830. /* Assume the data may change during runtime by setting
  2831. * last_modified = now */
  2832. filep->stat.last_modified = time(NULL);
  2833. filep->stat.is_directory = 0;
  2834. filep->stat.is_gzipped = 0;
  2835. }
  2836. }
  2837. return (buf != NULL);
  2838. #else
  2839. (void)conn;
  2840. (void)path;
  2841. (void)filep;
  2842. (void)mode;
  2843. return 0;
  2844. #endif
  2845. }
  2846. static int
  2847. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2848. {
  2849. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2850. }
  2851. static int
  2852. is_file_opened(const struct mg_file_access *fileacc)
  2853. {
  2854. if (!fileacc) {
  2855. return 0;
  2856. }
  2857. #if defined(MG_USE_OPEN_FILE)
  2858. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2859. #else
  2860. return (fileacc->fp != NULL);
  2861. #endif
  2862. }
  2863. #if !defined(NO_FILESYSTEMS)
  2864. static int mg_stat(const struct mg_connection *conn,
  2865. const char *path,
  2866. struct mg_file_stat *filep);
  2867. /* mg_fopen will open a file either in memory or on the disk.
  2868. * The input parameter path is a string in UTF-8 encoding.
  2869. * The input parameter mode is MG_FOPEN_MODE_*
  2870. * On success, either fp or membuf will be set in the output
  2871. * struct file. All status members will also be set.
  2872. * The function returns 1 on success, 0 on error. */
  2873. static int
  2874. mg_fopen(const struct mg_connection *conn,
  2875. const char *path,
  2876. int mode,
  2877. struct mg_file *filep)
  2878. {
  2879. int found;
  2880. if (!filep) {
  2881. return 0;
  2882. }
  2883. filep->access.fp = NULL;
  2884. #if defined(MG_USE_OPEN_FILE)
  2885. filep->access.membuf = NULL;
  2886. #endif
  2887. if (!is_file_in_memory(conn, path)) {
  2888. /* filep is initialized in mg_stat: all fields with memset to,
  2889. * some fields like size and modification date with values */
  2890. found = mg_stat(conn, path, &(filep->stat));
  2891. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2892. /* file does not exist and will not be created */
  2893. return 0;
  2894. }
  2895. #if defined(_WIN32)
  2896. {
  2897. wchar_t wbuf[W_PATH_MAX];
  2898. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2899. switch (mode) {
  2900. case MG_FOPEN_MODE_READ:
  2901. filep->access.fp = _wfopen(wbuf, L"rb");
  2902. break;
  2903. case MG_FOPEN_MODE_WRITE:
  2904. filep->access.fp = _wfopen(wbuf, L"wb");
  2905. break;
  2906. case MG_FOPEN_MODE_APPEND:
  2907. filep->access.fp = _wfopen(wbuf, L"ab");
  2908. break;
  2909. }
  2910. }
  2911. #else
  2912. /* Linux et al already use unicode. No need to convert. */
  2913. switch (mode) {
  2914. case MG_FOPEN_MODE_READ:
  2915. filep->access.fp = fopen(path, "r");
  2916. break;
  2917. case MG_FOPEN_MODE_WRITE:
  2918. filep->access.fp = fopen(path, "w");
  2919. break;
  2920. case MG_FOPEN_MODE_APPEND:
  2921. filep->access.fp = fopen(path, "a");
  2922. break;
  2923. }
  2924. #endif
  2925. if (!found) {
  2926. /* File did not exist before fopen was called.
  2927. * Maybe it has been created now. Get stat info
  2928. * like creation time now. */
  2929. found = mg_stat(conn, path, &(filep->stat));
  2930. (void)found;
  2931. }
  2932. /* file is on disk */
  2933. return (filep->access.fp != NULL);
  2934. } else {
  2935. #if defined(MG_USE_OPEN_FILE)
  2936. /* is_file_in_memory returned true */
  2937. if (open_file_in_memory(conn, path, filep, mode)) {
  2938. /* file is in memory */
  2939. return (filep->access.membuf != NULL);
  2940. }
  2941. #endif
  2942. }
  2943. /* Open failed */
  2944. return 0;
  2945. }
  2946. /* return 0 on success, just like fclose */
  2947. static int
  2948. mg_fclose(struct mg_file_access *fileacc)
  2949. {
  2950. int ret = -1;
  2951. if (fileacc != NULL) {
  2952. if (fileacc->fp != NULL) {
  2953. ret = fclose(fileacc->fp);
  2954. #if defined(MG_USE_OPEN_FILE)
  2955. } else if (fileacc->membuf != NULL) {
  2956. ret = 0;
  2957. #endif
  2958. }
  2959. /* reset all members of fileacc */
  2960. memset(fileacc, 0, sizeof(*fileacc));
  2961. }
  2962. return ret;
  2963. }
  2964. #endif /* NO_FILESYSTEMS */
  2965. static void
  2966. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2967. {
  2968. for (; *src != '\0' && n > 1; n--) {
  2969. *dst++ = *src++;
  2970. }
  2971. *dst = '\0';
  2972. }
  2973. static int
  2974. lowercase(const char *s)
  2975. {
  2976. return tolower((unsigned char)*s);
  2977. }
  2978. int
  2979. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2980. {
  2981. int diff = 0;
  2982. if (len > 0) {
  2983. do {
  2984. diff = lowercase(s1++) - lowercase(s2++);
  2985. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2986. }
  2987. return diff;
  2988. }
  2989. int
  2990. mg_strcasecmp(const char *s1, const char *s2)
  2991. {
  2992. int diff;
  2993. do {
  2994. diff = lowercase(s1++) - lowercase(s2++);
  2995. } while (diff == 0 && s1[-1] != '\0');
  2996. return diff;
  2997. }
  2998. static char *
  2999. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3000. {
  3001. char *p;
  3002. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3003. * defined */
  3004. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3005. mg_strlcpy(p, ptr, len + 1);
  3006. }
  3007. return p;
  3008. }
  3009. static char *
  3010. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3011. {
  3012. return mg_strndup_ctx(str, strlen(str), ctx);
  3013. }
  3014. static char *
  3015. mg_strdup(const char *str)
  3016. {
  3017. return mg_strndup_ctx(str, strlen(str), NULL);
  3018. }
  3019. static const char *
  3020. mg_strcasestr(const char *big_str, const char *small_str)
  3021. {
  3022. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3023. if (big_len >= small_len) {
  3024. for (i = 0; i <= (big_len - small_len); i++) {
  3025. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3026. return big_str + i;
  3027. }
  3028. }
  3029. }
  3030. return NULL;
  3031. }
  3032. /* Return null terminated string of given maximum length.
  3033. * Report errors if length is exceeded. */
  3034. static void
  3035. mg_vsnprintf(const struct mg_connection *conn,
  3036. int *truncated,
  3037. char *buf,
  3038. size_t buflen,
  3039. const char *fmt,
  3040. va_list ap)
  3041. {
  3042. int n, ok;
  3043. if (buflen == 0) {
  3044. if (truncated) {
  3045. *truncated = 1;
  3046. }
  3047. return;
  3048. }
  3049. #if defined(__clang__)
  3050. #pragma clang diagnostic push
  3051. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3052. /* Using fmt as a non-literal is intended here, since it is mostly called
  3053. * indirectly by mg_snprintf */
  3054. #endif
  3055. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3056. ok = (n >= 0) && ((size_t)n < buflen);
  3057. #if defined(__clang__)
  3058. #pragma clang diagnostic pop
  3059. #endif
  3060. if (ok) {
  3061. if (truncated) {
  3062. *truncated = 0;
  3063. }
  3064. } else {
  3065. if (truncated) {
  3066. *truncated = 1;
  3067. }
  3068. mg_cry_internal(conn,
  3069. "truncating vsnprintf buffer: [%.*s]",
  3070. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3071. buf);
  3072. n = (int)buflen - 1;
  3073. }
  3074. buf[n] = '\0';
  3075. }
  3076. static void
  3077. mg_snprintf(const struct mg_connection *conn,
  3078. int *truncated,
  3079. char *buf,
  3080. size_t buflen,
  3081. const char *fmt,
  3082. ...)
  3083. {
  3084. va_list ap;
  3085. va_start(ap, fmt);
  3086. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3087. va_end(ap);
  3088. }
  3089. static int
  3090. get_option_index(const char *name)
  3091. {
  3092. int i;
  3093. for (i = 0; config_options[i].name != NULL; i++) {
  3094. if (strcmp(config_options[i].name, name) == 0) {
  3095. return i;
  3096. }
  3097. }
  3098. return -1;
  3099. }
  3100. const char *
  3101. mg_get_option(const struct mg_context *ctx, const char *name)
  3102. {
  3103. int i;
  3104. if ((i = get_option_index(name)) == -1) {
  3105. return NULL;
  3106. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3107. return "";
  3108. } else {
  3109. return ctx->dd.config[i];
  3110. }
  3111. }
  3112. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3113. struct mg_context *
  3114. mg_get_context(const struct mg_connection *conn)
  3115. {
  3116. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3117. }
  3118. void *
  3119. mg_get_user_data(const struct mg_context *ctx)
  3120. {
  3121. return (ctx == NULL) ? NULL : ctx->user_data;
  3122. }
  3123. void *
  3124. mg_get_user_context_data(const struct mg_connection *conn)
  3125. {
  3126. return mg_get_user_data(mg_get_context(conn));
  3127. }
  3128. void *
  3129. mg_get_thread_pointer(const struct mg_connection *conn)
  3130. {
  3131. /* both methods should return the same pointer */
  3132. if (conn) {
  3133. /* quick access, in case conn is known */
  3134. return conn->tls_user_ptr;
  3135. } else {
  3136. /* otherwise get pointer from thread local storage (TLS) */
  3137. struct mg_workerTLS *tls =
  3138. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3139. return tls->user_ptr;
  3140. }
  3141. }
  3142. void
  3143. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3144. {
  3145. if (conn != NULL) {
  3146. conn->request_info.conn_data = data;
  3147. }
  3148. }
  3149. void *
  3150. mg_get_user_connection_data(const struct mg_connection *conn)
  3151. {
  3152. if (conn != NULL) {
  3153. return conn->request_info.conn_data;
  3154. }
  3155. return NULL;
  3156. }
  3157. #if defined(MG_LEGACY_INTERFACE)
  3158. /* Deprecated: Use mg_get_server_ports instead. */
  3159. size_t
  3160. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3161. {
  3162. size_t i;
  3163. if (!ctx) {
  3164. return 0;
  3165. }
  3166. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3167. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3168. ports[i] =
  3169. #if defined(USE_IPV6)
  3170. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3171. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3172. :
  3173. #endif
  3174. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3175. }
  3176. return i;
  3177. }
  3178. #endif
  3179. int
  3180. mg_get_server_ports(const struct mg_context *ctx,
  3181. int size,
  3182. struct mg_server_port *ports)
  3183. {
  3184. int i, cnt = 0;
  3185. if (size <= 0) {
  3186. return -1;
  3187. }
  3188. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3189. if (!ctx) {
  3190. return -1;
  3191. }
  3192. if (!ctx->listening_sockets) {
  3193. return -1;
  3194. }
  3195. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3196. ports[cnt].port =
  3197. #if defined(USE_IPV6)
  3198. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3199. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3200. :
  3201. #endif
  3202. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3203. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3204. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3205. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3206. /* IPv4 */
  3207. ports[cnt].protocol = 1;
  3208. cnt++;
  3209. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3210. /* IPv6 */
  3211. ports[cnt].protocol = 3;
  3212. cnt++;
  3213. }
  3214. }
  3215. return cnt;
  3216. }
  3217. static void
  3218. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3219. {
  3220. buf[0] = '\0';
  3221. if (!usa) {
  3222. return;
  3223. }
  3224. if (usa->sa.sa_family == AF_INET) {
  3225. getnameinfo(&usa->sa,
  3226. sizeof(usa->sin),
  3227. buf,
  3228. (unsigned)len,
  3229. NULL,
  3230. 0,
  3231. NI_NUMERICHOST);
  3232. }
  3233. #if defined(USE_IPV6)
  3234. else if (usa->sa.sa_family == AF_INET6) {
  3235. getnameinfo(&usa->sa,
  3236. sizeof(usa->sin6),
  3237. buf,
  3238. (unsigned)len,
  3239. NULL,
  3240. 0,
  3241. NI_NUMERICHOST);
  3242. }
  3243. #endif
  3244. }
  3245. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3246. * included in all responses other than 100, 101, 5xx. */
  3247. static void
  3248. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3249. {
  3250. #if !defined(REENTRANT_TIME)
  3251. struct tm *tm;
  3252. tm = ((t != NULL) ? gmtime(t) : NULL);
  3253. if (tm != NULL) {
  3254. #else
  3255. struct tm _tm;
  3256. struct tm *tm = &_tm;
  3257. if (t != NULL) {
  3258. gmtime_r(t, tm);
  3259. #endif
  3260. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3261. } else {
  3262. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3263. buf[buf_len - 1] = '\0';
  3264. }
  3265. }
  3266. /* difftime for struct timespec. Return value is in seconds. */
  3267. static double
  3268. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3269. {
  3270. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3271. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3272. }
  3273. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3274. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3275. const char *func,
  3276. unsigned line,
  3277. const char *fmt,
  3278. va_list ap);
  3279. #include "external_mg_cry_internal_impl.inl"
  3280. #elif !defined(NO_FILESYSTEMS)
  3281. /* Print error message to the opened error log stream. */
  3282. static void
  3283. mg_cry_internal_impl(const struct mg_connection *conn,
  3284. const char *func,
  3285. unsigned line,
  3286. const char *fmt,
  3287. va_list ap)
  3288. {
  3289. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3290. struct mg_file fi;
  3291. time_t timestamp;
  3292. /* Unused, in the RELEASE build */
  3293. (void)func;
  3294. (void)line;
  3295. #if defined(GCC_DIAGNOSTIC)
  3296. #pragma GCC diagnostic push
  3297. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3298. #endif
  3299. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3300. #if defined(GCC_DIAGNOSTIC)
  3301. #pragma GCC diagnostic pop
  3302. #endif
  3303. buf[sizeof(buf) - 1] = 0;
  3304. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3305. if (!conn) {
  3306. puts(buf);
  3307. return;
  3308. }
  3309. /* Do not lock when getting the callback value, here and below.
  3310. * I suppose this is fine, since function cannot disappear in the
  3311. * same way string option can. */
  3312. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3313. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3314. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3315. if (mg_fopen(conn,
  3316. conn->dom_ctx->config[ERROR_LOG_FILE],
  3317. MG_FOPEN_MODE_APPEND,
  3318. &fi)
  3319. == 0) {
  3320. fi.access.fp = NULL;
  3321. }
  3322. } else {
  3323. fi.access.fp = NULL;
  3324. }
  3325. if (fi.access.fp != NULL) {
  3326. flockfile(fi.access.fp);
  3327. timestamp = time(NULL);
  3328. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3329. fprintf(fi.access.fp,
  3330. "[%010lu] [error] [client %s] ",
  3331. (unsigned long)timestamp,
  3332. src_addr);
  3333. if (conn->request_info.request_method != NULL) {
  3334. fprintf(fi.access.fp,
  3335. "%s %s: ",
  3336. conn->request_info.request_method,
  3337. conn->request_info.request_uri
  3338. ? conn->request_info.request_uri
  3339. : "");
  3340. }
  3341. fprintf(fi.access.fp, "%s", buf);
  3342. fputc('\n', fi.access.fp);
  3343. fflush(fi.access.fp);
  3344. funlockfile(fi.access.fp);
  3345. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3346. * mg_cry here anyway ;-) */
  3347. }
  3348. }
  3349. }
  3350. #else
  3351. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3352. #endif /* Externally provided function */
  3353. /* Construct fake connection structure. Used for logging, if connection
  3354. * is not applicable at the moment of logging. */
  3355. static struct mg_connection *
  3356. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3357. {
  3358. static const struct mg_connection conn_zero = {0};
  3359. *fc = conn_zero;
  3360. fc->phys_ctx = ctx;
  3361. fc->dom_ctx = &(ctx->dd);
  3362. return fc;
  3363. }
  3364. static void
  3365. mg_cry_internal_wrap(const struct mg_connection *conn,
  3366. struct mg_context *ctx,
  3367. const char *func,
  3368. unsigned line,
  3369. const char *fmt,
  3370. ...)
  3371. {
  3372. va_list ap;
  3373. va_start(ap, fmt);
  3374. if (!conn && ctx) {
  3375. struct mg_connection fc;
  3376. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3377. } else {
  3378. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3379. }
  3380. va_end(ap);
  3381. }
  3382. void
  3383. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3384. {
  3385. va_list ap;
  3386. va_start(ap, fmt);
  3387. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3388. va_end(ap);
  3389. }
  3390. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3391. const char *
  3392. mg_version(void)
  3393. {
  3394. return CIVETWEB_VERSION;
  3395. }
  3396. const struct mg_request_info *
  3397. mg_get_request_info(const struct mg_connection *conn)
  3398. {
  3399. if (!conn) {
  3400. return NULL;
  3401. }
  3402. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3403. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3404. char txt[16];
  3405. struct mg_workerTLS *tls =
  3406. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3407. sprintf(txt, "%03i", conn->response_info.status_code);
  3408. if (strlen(txt) == 3) {
  3409. memcpy(tls->txtbuf, txt, 4);
  3410. } else {
  3411. strcpy(tls->txtbuf, "ERR");
  3412. }
  3413. ((struct mg_connection *)conn)->request_info.local_uri =
  3414. ((struct mg_connection *)conn)->request_info.request_uri =
  3415. tls->txtbuf; /* use thread safe buffer */
  3416. ((struct mg_connection *)conn)->request_info.num_headers =
  3417. conn->response_info.num_headers;
  3418. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3419. conn->response_info.http_headers,
  3420. sizeof(conn->response_info.http_headers));
  3421. } else
  3422. #endif
  3423. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3424. return NULL;
  3425. }
  3426. return &conn->request_info;
  3427. }
  3428. const struct mg_response_info *
  3429. mg_get_response_info(const struct mg_connection *conn)
  3430. {
  3431. if (!conn) {
  3432. return NULL;
  3433. }
  3434. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3435. return NULL;
  3436. }
  3437. return &conn->response_info;
  3438. }
  3439. static const char *
  3440. get_proto_name(const struct mg_connection *conn)
  3441. {
  3442. #if defined(__clang__)
  3443. #pragma clang diagnostic push
  3444. #pragma clang diagnostic ignored "-Wunreachable-code"
  3445. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3446. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3447. * unreachable, but splitting into four different #ifdef clauses here is more
  3448. * complicated.
  3449. */
  3450. #endif
  3451. const struct mg_request_info *ri = &conn->request_info;
  3452. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3453. ? (ri->is_ssl ? "wss" : "ws")
  3454. : (ri->is_ssl ? "https" : "http"));
  3455. return proto;
  3456. #if defined(__clang__)
  3457. #pragma clang diagnostic pop
  3458. #endif
  3459. }
  3460. int
  3461. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3462. {
  3463. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3464. return -1;
  3465. } else {
  3466. int truncated = 0;
  3467. const struct mg_request_info *ri = &conn->request_info;
  3468. const char *proto = get_proto_name(conn);
  3469. if (ri->local_uri == NULL) {
  3470. return -1;
  3471. }
  3472. if ((ri->request_uri != NULL)
  3473. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3474. /* The request uri is different from the local uri.
  3475. * This is usually if an absolute URI, including server
  3476. * name has been provided. */
  3477. mg_snprintf(conn,
  3478. &truncated,
  3479. buf,
  3480. buflen,
  3481. "%s://%s",
  3482. proto,
  3483. ri->request_uri);
  3484. if (truncated) {
  3485. return -1;
  3486. }
  3487. return 0;
  3488. } else {
  3489. /* The common case is a relative URI, so we have to
  3490. * construct an absolute URI from server name and port */
  3491. #if defined(USE_IPV6)
  3492. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3493. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3494. : htons(conn->client.lsa.sin.sin_port);
  3495. #else
  3496. int port = htons(conn->client.lsa.sin.sin_port);
  3497. #endif
  3498. int def_port = ri->is_ssl ? 443 : 80;
  3499. int auth_domain_check_enabled =
  3500. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3501. && (!mg_strcasecmp(
  3502. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3503. const char *server_domain =
  3504. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3505. char portstr[16];
  3506. char server_ip[48];
  3507. if (port != def_port) {
  3508. sprintf(portstr, ":%u", (unsigned)port);
  3509. } else {
  3510. portstr[0] = 0;
  3511. }
  3512. if (!auth_domain_check_enabled || !server_domain) {
  3513. sockaddr_to_string(server_ip,
  3514. sizeof(server_ip),
  3515. &conn->client.lsa);
  3516. server_domain = server_ip;
  3517. }
  3518. mg_snprintf(conn,
  3519. &truncated,
  3520. buf,
  3521. buflen,
  3522. "%s://%s%s%s",
  3523. proto,
  3524. server_domain,
  3525. portstr,
  3526. ri->local_uri);
  3527. if (truncated) {
  3528. return -1;
  3529. }
  3530. return 0;
  3531. }
  3532. }
  3533. }
  3534. /* Skip the characters until one of the delimiters characters found.
  3535. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3536. * Advance pointer to buffer to the next word. Return found 0-terminated
  3537. * word.
  3538. * Delimiters can be quoted with quotechar. */
  3539. static char *
  3540. skip_quoted(char **buf,
  3541. const char *delimiters,
  3542. const char *whitespace,
  3543. char quotechar)
  3544. {
  3545. char *p, *begin_word, *end_word, *end_whitespace;
  3546. begin_word = *buf;
  3547. end_word = begin_word + strcspn(begin_word, delimiters);
  3548. /* Check for quotechar */
  3549. if (end_word > begin_word) {
  3550. p = end_word - 1;
  3551. while (*p == quotechar) {
  3552. /* While the delimiter is quoted, look for the next delimiter.
  3553. */
  3554. /* This happens, e.g., in calls from parse_auth_header,
  3555. * if the user name contains a " character. */
  3556. /* If there is anything beyond end_word, copy it. */
  3557. if (*end_word != '\0') {
  3558. size_t end_off = strcspn(end_word + 1, delimiters);
  3559. memmove(p, end_word, end_off + 1);
  3560. p += end_off; /* p must correspond to end_word - 1 */
  3561. end_word += end_off + 1;
  3562. } else {
  3563. *p = '\0';
  3564. break;
  3565. }
  3566. }
  3567. for (p++; p < end_word; p++) {
  3568. *p = '\0';
  3569. }
  3570. }
  3571. if (*end_word == '\0') {
  3572. *buf = end_word;
  3573. } else {
  3574. #if defined(GCC_DIAGNOSTIC)
  3575. /* Disable spurious conversion warning for GCC */
  3576. #pragma GCC diagnostic push
  3577. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3578. #endif /* defined(GCC_DIAGNOSTIC) */
  3579. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3580. #if defined(GCC_DIAGNOSTIC)
  3581. #pragma GCC diagnostic pop
  3582. #endif /* defined(GCC_DIAGNOSTIC) */
  3583. for (p = end_word; p < end_whitespace; p++) {
  3584. *p = '\0';
  3585. }
  3586. *buf = end_whitespace;
  3587. }
  3588. return begin_word;
  3589. }
  3590. /* Return HTTP header value, or NULL if not found. */
  3591. static const char *
  3592. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3593. {
  3594. int i;
  3595. for (i = 0; i < num_hdr; i++) {
  3596. if (!mg_strcasecmp(name, hdr[i].name)) {
  3597. return hdr[i].value;
  3598. }
  3599. }
  3600. return NULL;
  3601. }
  3602. #if defined(USE_WEBSOCKET)
  3603. /* Retrieve requested HTTP header multiple values, and return the number of
  3604. * found occurrences */
  3605. static int
  3606. get_req_headers(const struct mg_request_info *ri,
  3607. const char *name,
  3608. const char **output,
  3609. int output_max_size)
  3610. {
  3611. int i;
  3612. int cnt = 0;
  3613. if (ri) {
  3614. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3615. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3616. output[cnt++] = ri->http_headers[i].value;
  3617. }
  3618. }
  3619. }
  3620. return cnt;
  3621. }
  3622. #endif
  3623. const char *
  3624. mg_get_header(const struct mg_connection *conn, const char *name)
  3625. {
  3626. if (!conn) {
  3627. return NULL;
  3628. }
  3629. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3630. return get_header(conn->request_info.http_headers,
  3631. conn->request_info.num_headers,
  3632. name);
  3633. }
  3634. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3635. return get_header(conn->response_info.http_headers,
  3636. conn->response_info.num_headers,
  3637. name);
  3638. }
  3639. return NULL;
  3640. }
  3641. static const char *
  3642. get_http_version(const struct mg_connection *conn)
  3643. {
  3644. if (!conn) {
  3645. return NULL;
  3646. }
  3647. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3648. return conn->request_info.http_version;
  3649. }
  3650. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3651. return conn->response_info.http_version;
  3652. }
  3653. return NULL;
  3654. }
  3655. /* A helper function for traversing a comma separated list of values.
  3656. * It returns a list pointer shifted to the next value, or NULL if the end
  3657. * of the list found.
  3658. * Value is stored in val vector. If value has form "x=y", then eq_val
  3659. * vector is initialized to point to the "y" part, and val vector length
  3660. * is adjusted to point only to "x". */
  3661. static const char *
  3662. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3663. {
  3664. int end;
  3665. reparse:
  3666. if (val == NULL || list == NULL || *list == '\0') {
  3667. /* End of the list */
  3668. return NULL;
  3669. }
  3670. /* Skip over leading LWS */
  3671. while (*list == ' ' || *list == '\t')
  3672. list++;
  3673. val->ptr = list;
  3674. if ((list = strchr(val->ptr, ',')) != NULL) {
  3675. /* Comma found. Store length and shift the list ptr */
  3676. val->len = ((size_t)(list - val->ptr));
  3677. list++;
  3678. } else {
  3679. /* This value is the last one */
  3680. list = val->ptr + strlen(val->ptr);
  3681. val->len = ((size_t)(list - val->ptr));
  3682. }
  3683. /* Adjust length for trailing LWS */
  3684. end = (int)val->len - 1;
  3685. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3686. end--;
  3687. val->len = (size_t)(end) + (size_t)(1);
  3688. if (val->len == 0) {
  3689. /* Ignore any empty entries. */
  3690. goto reparse;
  3691. }
  3692. if (eq_val != NULL) {
  3693. /* Value has form "x=y", adjust pointers and lengths
  3694. * so that val points to "x", and eq_val points to "y". */
  3695. eq_val->len = 0;
  3696. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3697. if (eq_val->ptr != NULL) {
  3698. eq_val->ptr++; /* Skip over '=' character */
  3699. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3700. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3701. }
  3702. }
  3703. return list;
  3704. }
  3705. /* A helper function for checking if a comma separated list of values
  3706. * contains
  3707. * the given option (case insensitvely).
  3708. * 'header' can be NULL, in which case false is returned. */
  3709. static int
  3710. header_has_option(const char *header, const char *option)
  3711. {
  3712. struct vec opt_vec;
  3713. struct vec eq_vec;
  3714. DEBUG_ASSERT(option != NULL);
  3715. DEBUG_ASSERT(option[0] != '\0');
  3716. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3717. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3718. return 1;
  3719. }
  3720. return 0;
  3721. }
  3722. /* Perform case-insensitive match of string against pattern */
  3723. static ptrdiff_t
  3724. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3725. {
  3726. const char *or_str;
  3727. ptrdiff_t i, j, len, res;
  3728. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3729. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3730. return (res > 0) ? res
  3731. : match_prefix(or_str + 1,
  3732. (size_t)((pattern + pattern_len)
  3733. - (or_str + 1)),
  3734. str);
  3735. }
  3736. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3737. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3738. continue;
  3739. } else if (pattern[i] == '$') {
  3740. return (str[j] == '\0') ? j : -1;
  3741. } else if (pattern[i] == '*') {
  3742. i++;
  3743. if (pattern[i] == '*') {
  3744. i++;
  3745. len = (ptrdiff_t)strlen(str + j);
  3746. } else {
  3747. len = (ptrdiff_t)strcspn(str + j, "/");
  3748. }
  3749. if (i == (ptrdiff_t)pattern_len) {
  3750. return j + len;
  3751. }
  3752. do {
  3753. res = match_prefix(pattern + i,
  3754. (pattern_len - (size_t)i),
  3755. str + j + len);
  3756. } while (res == -1 && len-- > 0);
  3757. return (res == -1) ? -1 : j + res + len;
  3758. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3759. return -1;
  3760. }
  3761. }
  3762. return (ptrdiff_t)j;
  3763. }
  3764. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3765. * This function must tolerate situations when connection info is not
  3766. * set up, for example if request parsing failed. */
  3767. static int
  3768. should_keep_alive(const struct mg_connection *conn)
  3769. {
  3770. const char *http_version;
  3771. const char *header;
  3772. /* First satisfy needs of the server */
  3773. if ((conn == NULL) || conn->must_close) {
  3774. /* Close, if civetweb framework needs to close */
  3775. return 0;
  3776. }
  3777. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3778. /* Close, if keep alive is not enabled */
  3779. return 0;
  3780. }
  3781. /* Check explicit wish of the client */
  3782. header = mg_get_header(conn, "Connection");
  3783. if (header) {
  3784. /* If there is a connection header from the client, obey */
  3785. if (header_has_option(header, "keep-alive")) {
  3786. return 1;
  3787. }
  3788. return 0;
  3789. }
  3790. /* Use default of the standard */
  3791. http_version = get_http_version(conn);
  3792. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3793. /* HTTP 1.1 default is keep alive */
  3794. return 1;
  3795. }
  3796. /* HTTP 1.0 (and earlier) default is to close the connection */
  3797. return 0;
  3798. }
  3799. static int
  3800. should_decode_url(const struct mg_connection *conn)
  3801. {
  3802. if (!conn || !conn->dom_ctx) {
  3803. return 0;
  3804. }
  3805. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3806. }
  3807. static const char *
  3808. suggest_connection_header(const struct mg_connection *conn)
  3809. {
  3810. return should_keep_alive(conn) ? "keep-alive" : "close";
  3811. }
  3812. static int
  3813. send_no_cache_header(struct mg_connection *conn)
  3814. {
  3815. /* Send all current and obsolete cache opt-out directives. */
  3816. return mg_printf(conn,
  3817. "Cache-Control: no-cache, no-store, "
  3818. "must-revalidate, private, max-age=0\r\n"
  3819. "Pragma: no-cache\r\n"
  3820. "Expires: 0\r\n");
  3821. }
  3822. static int
  3823. send_static_cache_header(struct mg_connection *conn)
  3824. {
  3825. #if !defined(NO_CACHING)
  3826. int max_age;
  3827. const char *cache_control =
  3828. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3829. if (cache_control != NULL) {
  3830. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3831. }
  3832. /* Read the server config to check how long a file may be cached.
  3833. * The configuration is in seconds. */
  3834. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3835. if (max_age <= 0) {
  3836. /* 0 means "do not cache". All values <0 are reserved
  3837. * and may be used differently in the future. */
  3838. /* If a file should not be cached, do not only send
  3839. * max-age=0, but also pragmas and Expires headers. */
  3840. return send_no_cache_header(conn);
  3841. }
  3842. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3843. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3844. /* See also https://www.mnot.net/cache_docs/ */
  3845. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3846. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3847. * leap
  3848. * year to 31622400 seconds. For the moment, we just send whatever has
  3849. * been configured, still the behavior for >1 year should be considered
  3850. * as undefined. */
  3851. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3852. #else /* NO_CACHING */
  3853. return send_no_cache_header(conn);
  3854. #endif /* !NO_CACHING */
  3855. }
  3856. static int
  3857. send_additional_header(struct mg_connection *conn)
  3858. {
  3859. int i = 0;
  3860. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3861. #if !defined(NO_SSL)
  3862. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3863. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3864. if (max_age >= 0) {
  3865. i += mg_printf(conn,
  3866. "Strict-Transport-Security: max-age=%u\r\n",
  3867. (unsigned)max_age);
  3868. }
  3869. }
  3870. #endif
  3871. if (header && header[0]) {
  3872. i += mg_printf(conn, "%s\r\n", header);
  3873. }
  3874. return i;
  3875. }
  3876. #if !defined(NO_FILESYSTEMS)
  3877. static void handle_file_based_request(struct mg_connection *conn,
  3878. const char *path,
  3879. struct mg_file *filep);
  3880. #endif /* NO_FILESYSTEMS */
  3881. const char *
  3882. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3883. {
  3884. /* See IANA HTTP status code assignment:
  3885. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3886. */
  3887. switch (response_code) {
  3888. /* RFC2616 Section 10.1 - Informational 1xx */
  3889. case 100:
  3890. return "Continue"; /* RFC2616 Section 10.1.1 */
  3891. case 101:
  3892. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3893. case 102:
  3894. return "Processing"; /* RFC2518 Section 10.1 */
  3895. /* RFC2616 Section 10.2 - Successful 2xx */
  3896. case 200:
  3897. return "OK"; /* RFC2616 Section 10.2.1 */
  3898. case 201:
  3899. return "Created"; /* RFC2616 Section 10.2.2 */
  3900. case 202:
  3901. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3902. case 203:
  3903. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3904. case 204:
  3905. return "No Content"; /* RFC2616 Section 10.2.5 */
  3906. case 205:
  3907. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3908. case 206:
  3909. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3910. case 207:
  3911. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3912. */
  3913. case 208:
  3914. return "Already Reported"; /* RFC5842 Section 7.1 */
  3915. case 226:
  3916. return "IM used"; /* RFC3229 Section 10.4.1 */
  3917. /* RFC2616 Section 10.3 - Redirection 3xx */
  3918. case 300:
  3919. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3920. case 301:
  3921. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3922. case 302:
  3923. return "Found"; /* RFC2616 Section 10.3.3 */
  3924. case 303:
  3925. return "See Other"; /* RFC2616 Section 10.3.4 */
  3926. case 304:
  3927. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3928. case 305:
  3929. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3930. case 307:
  3931. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3932. case 308:
  3933. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3934. /* RFC2616 Section 10.4 - Client Error 4xx */
  3935. case 400:
  3936. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3937. case 401:
  3938. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3939. case 402:
  3940. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3941. case 403:
  3942. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3943. case 404:
  3944. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3945. case 405:
  3946. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3947. case 406:
  3948. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3949. case 407:
  3950. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3951. case 408:
  3952. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3953. case 409:
  3954. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3955. case 410:
  3956. return "Gone"; /* RFC2616 Section 10.4.11 */
  3957. case 411:
  3958. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3959. case 412:
  3960. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3961. case 413:
  3962. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3963. case 414:
  3964. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3965. case 415:
  3966. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3967. case 416:
  3968. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3969. */
  3970. case 417:
  3971. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3972. case 421:
  3973. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3974. case 422:
  3975. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3976. * Section 11.2 */
  3977. case 423:
  3978. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3979. case 424:
  3980. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3981. * Section 11.4 */
  3982. case 426:
  3983. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3984. case 428:
  3985. return "Precondition Required"; /* RFC 6585, Section 3 */
  3986. case 429:
  3987. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3988. case 431:
  3989. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3990. case 451:
  3991. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3992. * Section 3 */
  3993. /* RFC2616 Section 10.5 - Server Error 5xx */
  3994. case 500:
  3995. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3996. case 501:
  3997. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3998. case 502:
  3999. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4000. case 503:
  4001. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4002. case 504:
  4003. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4004. case 505:
  4005. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4006. case 506:
  4007. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4008. case 507:
  4009. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4010. * Section 11.5 */
  4011. case 508:
  4012. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4013. case 510:
  4014. return "Not Extended"; /* RFC 2774, Section 7 */
  4015. case 511:
  4016. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4017. /* Other status codes, not shown in the IANA HTTP status code
  4018. * assignment.
  4019. * E.g., "de facto" standards due to common use, ... */
  4020. case 418:
  4021. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4022. case 419:
  4023. return "Authentication Timeout"; /* common use */
  4024. case 420:
  4025. return "Enhance Your Calm"; /* common use */
  4026. case 440:
  4027. return "Login Timeout"; /* common use */
  4028. case 509:
  4029. return "Bandwidth Limit Exceeded"; /* common use */
  4030. default:
  4031. /* This error code is unknown. This should not happen. */
  4032. if (conn) {
  4033. mg_cry_internal(conn,
  4034. "Unknown HTTP response code: %u",
  4035. response_code);
  4036. }
  4037. /* Return at least a category according to RFC 2616 Section 10. */
  4038. if (response_code >= 100 && response_code < 200) {
  4039. /* Unknown informational status code */
  4040. return "Information";
  4041. }
  4042. if (response_code >= 200 && response_code < 300) {
  4043. /* Unknown success code */
  4044. return "Success";
  4045. }
  4046. if (response_code >= 300 && response_code < 400) {
  4047. /* Unknown redirection code */
  4048. return "Redirection";
  4049. }
  4050. if (response_code >= 400 && response_code < 500) {
  4051. /* Unknown request error code */
  4052. return "Client Error";
  4053. }
  4054. if (response_code >= 500 && response_code < 600) {
  4055. /* Unknown server error code */
  4056. return "Server Error";
  4057. }
  4058. /* Response code not even within reasonable range */
  4059. return "";
  4060. }
  4061. }
  4062. static int
  4063. mg_send_http_error_impl(struct mg_connection *conn,
  4064. int status,
  4065. const char *fmt,
  4066. va_list args)
  4067. {
  4068. char errmsg_buf[MG_BUF_LEN];
  4069. va_list ap;
  4070. int has_body;
  4071. char date[64];
  4072. time_t curtime = time(NULL);
  4073. #if !defined(NO_FILESYSTEMS)
  4074. char path_buf[PATH_MAX];
  4075. int len, i, page_handler_found, scope, truncated;
  4076. const char *error_handler = NULL;
  4077. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4078. const char *error_page_file_ext, *tstr;
  4079. #endif /* NO_FILESYSTEMS */
  4080. int handled_by_callback = 0;
  4081. const char *status_text = mg_get_response_code_text(conn, status);
  4082. if ((conn == NULL) || (fmt == NULL)) {
  4083. return -2;
  4084. }
  4085. /* Set status (for log) */
  4086. conn->status_code = status;
  4087. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4088. has_body = ((status > 199) && (status != 204) && (status != 304));
  4089. /* Prepare message in buf, if required */
  4090. if (has_body
  4091. || (!conn->in_error_handler
  4092. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4093. /* Store error message in errmsg_buf */
  4094. va_copy(ap, args);
  4095. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4096. va_end(ap);
  4097. /* In a debug build, print all html errors */
  4098. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4099. }
  4100. /* If there is a http_error callback, call it.
  4101. * But don't do it recursively, if callback calls mg_send_http_error again.
  4102. */
  4103. if (!conn->in_error_handler
  4104. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4105. /* Mark in_error_handler to avoid recursion and call user callback. */
  4106. conn->in_error_handler = 1;
  4107. handled_by_callback =
  4108. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4109. == 0);
  4110. conn->in_error_handler = 0;
  4111. }
  4112. if (!handled_by_callback) {
  4113. /* Check for recursion */
  4114. if (conn->in_error_handler) {
  4115. DEBUG_TRACE(
  4116. "Recursion when handling error %u - fall back to default",
  4117. status);
  4118. #if !defined(NO_FILESYSTEMS)
  4119. } else {
  4120. /* Send user defined error pages, if defined */
  4121. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4122. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4123. page_handler_found = 0;
  4124. if (error_handler != NULL) {
  4125. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4126. switch (scope) {
  4127. case 1: /* Handler for specific error, e.g. 404 error */
  4128. mg_snprintf(conn,
  4129. &truncated,
  4130. path_buf,
  4131. sizeof(path_buf) - 32,
  4132. "%serror%03u.",
  4133. error_handler,
  4134. status);
  4135. break;
  4136. case 2: /* Handler for error group, e.g., 5xx error
  4137. * handler
  4138. * for all server errors (500-599) */
  4139. mg_snprintf(conn,
  4140. &truncated,
  4141. path_buf,
  4142. sizeof(path_buf) - 32,
  4143. "%serror%01uxx.",
  4144. error_handler,
  4145. status / 100);
  4146. break;
  4147. default: /* Handler for all errors */
  4148. mg_snprintf(conn,
  4149. &truncated,
  4150. path_buf,
  4151. sizeof(path_buf) - 32,
  4152. "%serror.",
  4153. error_handler);
  4154. break;
  4155. }
  4156. /* String truncation in buf may only occur if
  4157. * error_handler is too long. This string is
  4158. * from the config, not from a client. */
  4159. (void)truncated;
  4160. /* The following code is redundant, but it should avoid
  4161. * false positives in static source code analyzers and
  4162. * vulnerability scanners.
  4163. */
  4164. path_buf[sizeof(path_buf) - 32] = 0;
  4165. len = (int)strlen(path_buf);
  4166. if (len > (int)sizeof(path_buf) - 32) {
  4167. len = (int)sizeof(path_buf) - 32;
  4168. }
  4169. /* Start with the file extenstion from the configuration. */
  4170. tstr = strchr(error_page_file_ext, '.');
  4171. while (tstr) {
  4172. for (i = 1;
  4173. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4174. i++) {
  4175. /* buffer overrun is not possible here, since
  4176. * (i < 32) && (len < sizeof(path_buf) - 32)
  4177. * ==> (i + len) < sizeof(path_buf) */
  4178. path_buf[len + i - 1] = tstr[i];
  4179. }
  4180. /* buffer overrun is not possible here, since
  4181. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4182. * ==> (i + len) <= sizeof(path_buf) */
  4183. path_buf[len + i - 1] = 0;
  4184. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4185. DEBUG_TRACE("Check error page %s - found",
  4186. path_buf);
  4187. page_handler_found = 1;
  4188. break;
  4189. }
  4190. DEBUG_TRACE("Check error page %s - not found",
  4191. path_buf);
  4192. /* Continue with the next file extenstion from the
  4193. * configuration (if there is a next one). */
  4194. tstr = strchr(tstr + i, '.');
  4195. }
  4196. }
  4197. }
  4198. if (page_handler_found) {
  4199. conn->in_error_handler = 1;
  4200. handle_file_based_request(conn, path_buf, &error_page_file);
  4201. conn->in_error_handler = 0;
  4202. return 0;
  4203. }
  4204. #endif /* NO_FILESYSTEMS */
  4205. }
  4206. /* No custom error page. Send default error page. */
  4207. gmt_time_string(date, sizeof(date), &curtime);
  4208. conn->must_close = 1;
  4209. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4210. send_no_cache_header(conn);
  4211. send_additional_header(conn);
  4212. if (has_body) {
  4213. mg_printf(conn,
  4214. "%s",
  4215. "Content-Type: text/plain; charset=utf-8\r\n");
  4216. }
  4217. mg_printf(conn,
  4218. "Date: %s\r\n"
  4219. "Connection: close\r\n\r\n",
  4220. date);
  4221. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4222. if (has_body) {
  4223. /* For other errors, send a generic error message. */
  4224. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4225. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4226. } else {
  4227. /* No body allowed. Close the connection. */
  4228. DEBUG_TRACE("Error %i", status);
  4229. }
  4230. }
  4231. return 0;
  4232. }
  4233. int
  4234. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4235. {
  4236. va_list ap;
  4237. int ret;
  4238. va_start(ap, fmt);
  4239. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4240. va_end(ap);
  4241. return ret;
  4242. }
  4243. int
  4244. mg_send_http_ok(struct mg_connection *conn,
  4245. const char *mime_type,
  4246. long long content_length)
  4247. {
  4248. char date[64];
  4249. time_t curtime = time(NULL);
  4250. if ((mime_type == NULL) || (*mime_type == 0)) {
  4251. /* No content type defined: default to text/html */
  4252. mime_type = "text/html";
  4253. }
  4254. gmt_time_string(date, sizeof(date), &curtime);
  4255. mg_printf(conn,
  4256. "HTTP/1.1 200 OK\r\n"
  4257. "Content-Type: %s\r\n"
  4258. "Date: %s\r\n"
  4259. "Connection: %s\r\n",
  4260. mime_type,
  4261. date,
  4262. suggest_connection_header(conn));
  4263. send_no_cache_header(conn);
  4264. send_additional_header(conn);
  4265. if (content_length < 0) {
  4266. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4267. } else {
  4268. mg_printf(conn,
  4269. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4270. (uint64_t)content_length);
  4271. }
  4272. return 0;
  4273. }
  4274. int
  4275. mg_send_http_redirect(struct mg_connection *conn,
  4276. const char *target_url,
  4277. int redirect_code)
  4278. {
  4279. /* Send a 30x redirect response.
  4280. *
  4281. * Redirect types (status codes):
  4282. *
  4283. * Status | Perm/Temp | Method | Version
  4284. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4285. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4286. * 303 | temporary | always use GET | HTTP/1.1
  4287. * 307 | temporary | always keep method | HTTP/1.1
  4288. * 308 | permanent | always keep method | HTTP/1.1
  4289. */
  4290. const char *redirect_text;
  4291. int ret;
  4292. size_t content_len = 0;
  4293. char reply[MG_BUF_LEN];
  4294. /* In case redirect_code=0, use 307. */
  4295. if (redirect_code == 0) {
  4296. redirect_code = 307;
  4297. }
  4298. /* In case redirect_code is none of the above, return error. */
  4299. if ((redirect_code != 301) && (redirect_code != 302)
  4300. && (redirect_code != 303) && (redirect_code != 307)
  4301. && (redirect_code != 308)) {
  4302. /* Parameter error */
  4303. return -2;
  4304. }
  4305. /* Get proper text for response code */
  4306. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4307. /* If target_url is not defined, redirect to "/". */
  4308. if ((target_url == NULL) || (*target_url == 0)) {
  4309. target_url = "/";
  4310. }
  4311. #if defined(MG_SEND_REDIRECT_BODY)
  4312. /* TODO: condition name? */
  4313. /* Prepare a response body with a hyperlink.
  4314. *
  4315. * According to RFC2616 (and RFC1945 before):
  4316. * Unless the request method was HEAD, the entity of the
  4317. * response SHOULD contain a short hypertext note with a hyperlink to
  4318. * the new URI(s).
  4319. *
  4320. * However, this response body is not useful in M2M communication.
  4321. * Probably the original reason in the RFC was, clients not supporting
  4322. * a 30x HTTP redirect could still show the HTML page and let the user
  4323. * press the link. Since current browsers support 30x HTTP, the additional
  4324. * HTML body does not seem to make sense anymore.
  4325. *
  4326. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4327. * but it only notes:
  4328. * The server's response payload usually contains a short
  4329. * hypertext note with a hyperlink to the new URI(s).
  4330. *
  4331. * Deactivated by default. If you need the 30x body, set the define.
  4332. */
  4333. mg_snprintf(
  4334. conn,
  4335. NULL /* ignore truncation */,
  4336. reply,
  4337. sizeof(reply),
  4338. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4339. redirect_text,
  4340. target_url,
  4341. target_url);
  4342. content_len = strlen(reply);
  4343. #else
  4344. reply[0] = 0;
  4345. #endif
  4346. /* Do not send any additional header. For all other options,
  4347. * including caching, there are suitable defaults. */
  4348. ret = mg_printf(conn,
  4349. "HTTP/1.1 %i %s\r\n"
  4350. "Location: %s\r\n"
  4351. "Content-Length: %u\r\n"
  4352. "Connection: %s\r\n\r\n",
  4353. redirect_code,
  4354. redirect_text,
  4355. target_url,
  4356. (unsigned int)content_len,
  4357. suggest_connection_header(conn));
  4358. /* Send response body */
  4359. if (ret > 0) {
  4360. /* ... unless it is a HEAD request */
  4361. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4362. ret = mg_write(conn, reply, content_len);
  4363. }
  4364. }
  4365. return (ret > 0) ? ret : -1;
  4366. }
  4367. #if defined(_WIN32)
  4368. /* Create substitutes for POSIX functions in Win32. */
  4369. #if defined(GCC_DIAGNOSTIC)
  4370. /* Show no warning in case system functions are not used. */
  4371. #pragma GCC diagnostic push
  4372. #pragma GCC diagnostic ignored "-Wunused-function"
  4373. #endif
  4374. static int
  4375. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4376. {
  4377. (void)unused;
  4378. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4379. InitializeCriticalSection(&mutex->sec);
  4380. return 0;
  4381. }
  4382. static int
  4383. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4384. {
  4385. DeleteCriticalSection(&mutex->sec);
  4386. return 0;
  4387. }
  4388. static int
  4389. pthread_mutex_lock(pthread_mutex_t *mutex)
  4390. {
  4391. EnterCriticalSection(&mutex->sec);
  4392. return 0;
  4393. }
  4394. static int
  4395. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4396. {
  4397. LeaveCriticalSection(&mutex->sec);
  4398. return 0;
  4399. }
  4400. FUNCTION_MAY_BE_UNUSED
  4401. static int
  4402. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4403. {
  4404. (void)unused;
  4405. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4406. cv->waiting_thread = NULL;
  4407. return 0;
  4408. }
  4409. FUNCTION_MAY_BE_UNUSED
  4410. static int
  4411. pthread_cond_timedwait(pthread_cond_t *cv,
  4412. pthread_mutex_t *mutex,
  4413. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4414. {
  4415. struct mg_workerTLS **ptls,
  4416. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4417. int ok;
  4418. int64_t nsnow, nswaitabs, nswaitrel;
  4419. DWORD mswaitrel;
  4420. pthread_mutex_lock(&cv->threadIdSec);
  4421. /* Add this thread to cv's waiting list */
  4422. ptls = &cv->waiting_thread;
  4423. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4424. ;
  4425. tls->next_waiting_thread = NULL;
  4426. *ptls = tls;
  4427. pthread_mutex_unlock(&cv->threadIdSec);
  4428. if (abstime) {
  4429. nsnow = mg_get_current_time_ns();
  4430. nswaitabs =
  4431. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4432. nswaitrel = nswaitabs - nsnow;
  4433. if (nswaitrel < 0) {
  4434. nswaitrel = 0;
  4435. }
  4436. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4437. } else {
  4438. mswaitrel = (DWORD)INFINITE;
  4439. }
  4440. pthread_mutex_unlock(mutex);
  4441. ok = (WAIT_OBJECT_0
  4442. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4443. if (!ok) {
  4444. ok = 1;
  4445. pthread_mutex_lock(&cv->threadIdSec);
  4446. ptls = &cv->waiting_thread;
  4447. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4448. if (*ptls == tls) {
  4449. *ptls = tls->next_waiting_thread;
  4450. ok = 0;
  4451. break;
  4452. }
  4453. }
  4454. pthread_mutex_unlock(&cv->threadIdSec);
  4455. if (ok) {
  4456. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4457. (DWORD)INFINITE);
  4458. }
  4459. }
  4460. /* This thread has been removed from cv's waiting list */
  4461. pthread_mutex_lock(mutex);
  4462. return ok ? 0 : -1;
  4463. }
  4464. FUNCTION_MAY_BE_UNUSED
  4465. static int
  4466. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4467. {
  4468. return pthread_cond_timedwait(cv, mutex, NULL);
  4469. }
  4470. FUNCTION_MAY_BE_UNUSED
  4471. static int
  4472. pthread_cond_signal(pthread_cond_t *cv)
  4473. {
  4474. HANDLE wkup = NULL;
  4475. BOOL ok = FALSE;
  4476. pthread_mutex_lock(&cv->threadIdSec);
  4477. if (cv->waiting_thread) {
  4478. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4479. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4480. ok = SetEvent(wkup);
  4481. DEBUG_ASSERT(ok);
  4482. }
  4483. pthread_mutex_unlock(&cv->threadIdSec);
  4484. return ok ? 0 : 1;
  4485. }
  4486. FUNCTION_MAY_BE_UNUSED
  4487. static int
  4488. pthread_cond_broadcast(pthread_cond_t *cv)
  4489. {
  4490. pthread_mutex_lock(&cv->threadIdSec);
  4491. while (cv->waiting_thread) {
  4492. pthread_cond_signal(cv);
  4493. }
  4494. pthread_mutex_unlock(&cv->threadIdSec);
  4495. return 0;
  4496. }
  4497. FUNCTION_MAY_BE_UNUSED
  4498. static int
  4499. pthread_cond_destroy(pthread_cond_t *cv)
  4500. {
  4501. pthread_mutex_lock(&cv->threadIdSec);
  4502. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4503. pthread_mutex_unlock(&cv->threadIdSec);
  4504. pthread_mutex_destroy(&cv->threadIdSec);
  4505. return 0;
  4506. }
  4507. #if defined(ALTERNATIVE_QUEUE)
  4508. FUNCTION_MAY_BE_UNUSED
  4509. static void *
  4510. event_create(void)
  4511. {
  4512. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4513. }
  4514. FUNCTION_MAY_BE_UNUSED
  4515. static int
  4516. event_wait(void *eventhdl)
  4517. {
  4518. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4519. return (res == WAIT_OBJECT_0);
  4520. }
  4521. FUNCTION_MAY_BE_UNUSED
  4522. static int
  4523. event_signal(void *eventhdl)
  4524. {
  4525. return (int)SetEvent((HANDLE)eventhdl);
  4526. }
  4527. FUNCTION_MAY_BE_UNUSED
  4528. static void
  4529. event_destroy(void *eventhdl)
  4530. {
  4531. CloseHandle((HANDLE)eventhdl);
  4532. }
  4533. #endif
  4534. #if defined(GCC_DIAGNOSTIC)
  4535. /* Enable unused function warning again */
  4536. #pragma GCC diagnostic pop
  4537. #endif
  4538. /* For Windows, change all slashes to backslashes in path names. */
  4539. static void
  4540. change_slashes_to_backslashes(char *path)
  4541. {
  4542. int i;
  4543. for (i = 0; path[i] != '\0'; i++) {
  4544. if (path[i] == '/') {
  4545. path[i] = '\\';
  4546. }
  4547. /* remove double backslash (check i > 0 to preserve UNC paths,
  4548. * like \\server\file.txt) */
  4549. if ((i > 0) && (path[i] == '\\')) {
  4550. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4551. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4552. }
  4553. }
  4554. }
  4555. }
  4556. static int
  4557. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4558. {
  4559. int diff;
  4560. do {
  4561. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4562. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4563. s1++;
  4564. s2++;
  4565. } while ((diff == 0) && (s1[-1] != L'\0'));
  4566. return diff;
  4567. }
  4568. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4569. * wbuf and wbuf_len is a target buffer and its length. */
  4570. static void
  4571. path_to_unicode(const struct mg_connection *conn,
  4572. const char *path,
  4573. wchar_t *wbuf,
  4574. size_t wbuf_len)
  4575. {
  4576. char buf[PATH_MAX], buf2[PATH_MAX];
  4577. wchar_t wbuf2[W_PATH_MAX + 1];
  4578. DWORD long_len, err;
  4579. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4580. mg_strlcpy(buf, path, sizeof(buf));
  4581. change_slashes_to_backslashes(buf);
  4582. /* Convert to Unicode and back. If doubly-converted string does not
  4583. * match the original, something is fishy, reject. */
  4584. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4585. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4586. WideCharToMultiByte(
  4587. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4588. if (strcmp(buf, buf2) != 0) {
  4589. wbuf[0] = L'\0';
  4590. }
  4591. /* Windows file systems are not case sensitive, but you can still use
  4592. * uppercase and lowercase letters (on all modern file systems).
  4593. * The server can check if the URI uses the same upper/lowercase
  4594. * letters an the file system, effectively making Windows servers
  4595. * case sensitive (like Linux servers are). It is still not possible
  4596. * to use two files with the same name in different cases on Windows
  4597. * (like /a and /A) - this would be possible in Linux.
  4598. * As a default, Windows is not case sensitive, but the case sensitive
  4599. * file name check can be activated by an additional configuration. */
  4600. if (conn) {
  4601. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4602. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4603. "yes")) {
  4604. /* Use case sensitive compare function */
  4605. fcompare = wcscmp;
  4606. }
  4607. }
  4608. (void)conn; /* conn is currently unused */
  4609. #if !defined(_WIN32_WCE)
  4610. /* Only accept a full file path, not a Windows short (8.3) path. */
  4611. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4612. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4613. if (long_len == 0) {
  4614. err = GetLastError();
  4615. if (err == ERROR_FILE_NOT_FOUND) {
  4616. /* File does not exist. This is not always a problem here. */
  4617. return;
  4618. }
  4619. }
  4620. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4621. /* Short name is used. */
  4622. wbuf[0] = L'\0';
  4623. }
  4624. #else
  4625. (void)long_len;
  4626. (void)wbuf2;
  4627. (void)err;
  4628. if (strchr(path, '~')) {
  4629. wbuf[0] = L'\0';
  4630. }
  4631. #endif
  4632. }
  4633. #if !defined(NO_FILESYSTEMS)
  4634. static int
  4635. mg_stat(const struct mg_connection *conn,
  4636. const char *path,
  4637. struct mg_file_stat *filep)
  4638. {
  4639. wchar_t wbuf[W_PATH_MAX];
  4640. WIN32_FILE_ATTRIBUTE_DATA info;
  4641. time_t creation_time;
  4642. size_t len;
  4643. if (!filep) {
  4644. return 0;
  4645. }
  4646. memset(filep, 0, sizeof(*filep));
  4647. if (conn && is_file_in_memory(conn, path)) {
  4648. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4649. * memset */
  4650. /* Quick fix (for 1.9.x): */
  4651. /* mg_stat must fill all fields, also for files in memory */
  4652. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4653. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4654. filep->size = tmp_file.stat.size;
  4655. filep->location = 2;
  4656. /* TODO: for 1.10: restructure how files in memory are handled */
  4657. /* The "file in memory" feature is a candidate for deletion.
  4658. * Please join the discussion at
  4659. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4660. */
  4661. filep->last_modified = time(NULL); /* TODO */
  4662. /* last_modified = now ... assumes the file may change during
  4663. * runtime,
  4664. * so every mg_fopen call may return different data */
  4665. /* last_modified = conn->phys_ctx.start_time;
  4666. * May be used it the data does not change during runtime. This
  4667. * allows
  4668. * browser caching. Since we do not know, we have to assume the file
  4669. * in memory may change. */
  4670. return 1;
  4671. }
  4672. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4673. /* Windows happily opens files with some garbage at the end of file name.
  4674. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4675. * "a.cgi", despite one would expect an error back. */
  4676. len = strlen(path);
  4677. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4678. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4679. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4680. filep->last_modified =
  4681. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4682. info.ftLastWriteTime.dwHighDateTime);
  4683. /* On Windows, the file creation time can be higher than the
  4684. * modification time, e.g. when a file is copied.
  4685. * Since the Last-Modified timestamp is used for caching
  4686. * it should be based on the most recent timestamp. */
  4687. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4688. info.ftCreationTime.dwHighDateTime);
  4689. if (creation_time > filep->last_modified) {
  4690. filep->last_modified = creation_time;
  4691. }
  4692. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4693. return 1;
  4694. }
  4695. return 0;
  4696. }
  4697. #endif
  4698. static int
  4699. mg_remove(const struct mg_connection *conn, const char *path)
  4700. {
  4701. wchar_t wbuf[W_PATH_MAX];
  4702. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4703. return DeleteFileW(wbuf) ? 0 : -1;
  4704. }
  4705. static int
  4706. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4707. {
  4708. wchar_t wbuf[W_PATH_MAX];
  4709. (void)mode;
  4710. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4711. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4712. }
  4713. /* Create substitutes for POSIX functions in Win32. */
  4714. #if defined(GCC_DIAGNOSTIC)
  4715. /* Show no warning in case system functions are not used. */
  4716. #pragma GCC diagnostic push
  4717. #pragma GCC diagnostic ignored "-Wunused-function"
  4718. #endif
  4719. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4720. FUNCTION_MAY_BE_UNUSED
  4721. static DIR *
  4722. mg_opendir(const struct mg_connection *conn, const char *name)
  4723. {
  4724. DIR *dir = NULL;
  4725. wchar_t wpath[W_PATH_MAX];
  4726. DWORD attrs;
  4727. if (name == NULL) {
  4728. SetLastError(ERROR_BAD_ARGUMENTS);
  4729. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4730. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4731. } else {
  4732. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4733. attrs = GetFileAttributesW(wpath);
  4734. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4735. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4736. (void)wcscat(wpath, L"\\*");
  4737. dir->handle = FindFirstFileW(wpath, &dir->info);
  4738. dir->result.d_name[0] = '\0';
  4739. } else {
  4740. mg_free(dir);
  4741. dir = NULL;
  4742. }
  4743. }
  4744. return dir;
  4745. }
  4746. FUNCTION_MAY_BE_UNUSED
  4747. static int
  4748. mg_closedir(DIR *dir)
  4749. {
  4750. int result = 0;
  4751. if (dir != NULL) {
  4752. if (dir->handle != INVALID_HANDLE_VALUE)
  4753. result = FindClose(dir->handle) ? 0 : -1;
  4754. mg_free(dir);
  4755. } else {
  4756. result = -1;
  4757. SetLastError(ERROR_BAD_ARGUMENTS);
  4758. }
  4759. return result;
  4760. }
  4761. FUNCTION_MAY_BE_UNUSED
  4762. static struct dirent *
  4763. mg_readdir(DIR *dir)
  4764. {
  4765. struct dirent *result = 0;
  4766. if (dir) {
  4767. if (dir->handle != INVALID_HANDLE_VALUE) {
  4768. result = &dir->result;
  4769. (void)WideCharToMultiByte(CP_UTF8,
  4770. 0,
  4771. dir->info.cFileName,
  4772. -1,
  4773. result->d_name,
  4774. sizeof(result->d_name),
  4775. NULL,
  4776. NULL);
  4777. if (!FindNextFileW(dir->handle, &dir->info)) {
  4778. (void)FindClose(dir->handle);
  4779. dir->handle = INVALID_HANDLE_VALUE;
  4780. }
  4781. } else {
  4782. SetLastError(ERROR_FILE_NOT_FOUND);
  4783. }
  4784. } else {
  4785. SetLastError(ERROR_BAD_ARGUMENTS);
  4786. }
  4787. return result;
  4788. }
  4789. #if !defined(HAVE_POLL)
  4790. #undef POLLIN
  4791. #undef POLLPRI
  4792. #undef POLLOUT
  4793. #define POLLIN (1) /* Data ready - read will not block. */
  4794. #define POLLPRI (2) /* Priority data ready. */
  4795. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4796. FUNCTION_MAY_BE_UNUSED
  4797. static int
  4798. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4799. {
  4800. struct timeval tv;
  4801. fd_set rset;
  4802. fd_set wset;
  4803. unsigned int i;
  4804. int result;
  4805. SOCKET maxfd = 0;
  4806. memset(&tv, 0, sizeof(tv));
  4807. tv.tv_sec = milliseconds / 1000;
  4808. tv.tv_usec = (milliseconds % 1000) * 1000;
  4809. FD_ZERO(&rset);
  4810. FD_ZERO(&wset);
  4811. for (i = 0; i < n; i++) {
  4812. if (pfd[i].events & POLLIN) {
  4813. FD_SET(pfd[i].fd, &rset);
  4814. }
  4815. if (pfd[i].events & POLLOUT) {
  4816. FD_SET(pfd[i].fd, &wset);
  4817. }
  4818. pfd[i].revents = 0;
  4819. if (pfd[i].fd > maxfd) {
  4820. maxfd = pfd[i].fd;
  4821. }
  4822. }
  4823. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4824. for (i = 0; i < n; i++) {
  4825. if (FD_ISSET(pfd[i].fd, &rset)) {
  4826. pfd[i].revents |= POLLIN;
  4827. }
  4828. if (FD_ISSET(pfd[i].fd, &wset)) {
  4829. pfd[i].revents |= POLLOUT;
  4830. }
  4831. }
  4832. }
  4833. /* We should subtract the time used in select from remaining
  4834. * "milliseconds", in particular if called from mg_poll with a
  4835. * timeout quantum.
  4836. * Unfortunately, the remaining time is not stored in "tv" in all
  4837. * implementations, so the result in "tv" must be considered undefined.
  4838. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4839. return result;
  4840. }
  4841. #endif /* HAVE_POLL */
  4842. #if defined(GCC_DIAGNOSTIC)
  4843. /* Enable unused function warning again */
  4844. #pragma GCC diagnostic pop
  4845. #endif
  4846. static void
  4847. set_close_on_exec(SOCKET sock,
  4848. const struct mg_connection *conn /* may be null */,
  4849. struct mg_context *ctx /* may be null */)
  4850. {
  4851. (void)conn; /* Unused. */
  4852. (void)ctx;
  4853. #if defined(_WIN32_WCE)
  4854. (void)sock;
  4855. #else
  4856. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4857. #endif
  4858. }
  4859. int
  4860. mg_start_thread(mg_thread_func_t f, void *p)
  4861. {
  4862. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4863. /* Compile-time option to control stack size, e.g.
  4864. * -DUSE_STACK_SIZE=16384
  4865. */
  4866. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4867. == ((uintptr_t)(-1L)))
  4868. ? -1
  4869. : 0);
  4870. #else
  4871. return (
  4872. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4873. ? -1
  4874. : 0);
  4875. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4876. }
  4877. /* Start a thread storing the thread context. */
  4878. static int
  4879. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4880. void *p,
  4881. pthread_t *threadidptr)
  4882. {
  4883. uintptr_t uip;
  4884. HANDLE threadhandle;
  4885. int result = -1;
  4886. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4887. threadhandle = (HANDLE)uip;
  4888. if ((uip != 0) && (threadidptr != NULL)) {
  4889. *threadidptr = threadhandle;
  4890. result = 0;
  4891. }
  4892. return result;
  4893. }
  4894. /* Wait for a thread to finish. */
  4895. static int
  4896. mg_join_thread(pthread_t threadid)
  4897. {
  4898. int result;
  4899. DWORD dwevent;
  4900. result = -1;
  4901. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4902. if (dwevent == WAIT_FAILED) {
  4903. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4904. } else {
  4905. if (dwevent == WAIT_OBJECT_0) {
  4906. CloseHandle(threadid);
  4907. result = 0;
  4908. }
  4909. }
  4910. return result;
  4911. }
  4912. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4913. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4914. /* Create substitutes for POSIX functions in Win32. */
  4915. #if defined(GCC_DIAGNOSTIC)
  4916. /* Show no warning in case system functions are not used. */
  4917. #pragma GCC diagnostic push
  4918. #pragma GCC diagnostic ignored "-Wunused-function"
  4919. #endif
  4920. FUNCTION_MAY_BE_UNUSED
  4921. static HANDLE
  4922. dlopen(const char *dll_name, int flags)
  4923. {
  4924. wchar_t wbuf[W_PATH_MAX];
  4925. (void)flags;
  4926. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4927. return LoadLibraryW(wbuf);
  4928. }
  4929. FUNCTION_MAY_BE_UNUSED
  4930. static int
  4931. dlclose(void *handle)
  4932. {
  4933. int result;
  4934. if (FreeLibrary((HMODULE)handle) != 0) {
  4935. result = 0;
  4936. } else {
  4937. result = -1;
  4938. }
  4939. return result;
  4940. }
  4941. #if defined(GCC_DIAGNOSTIC)
  4942. /* Enable unused function warning again */
  4943. #pragma GCC diagnostic pop
  4944. #endif
  4945. #endif
  4946. #if !defined(NO_CGI)
  4947. #define SIGKILL (0)
  4948. static int
  4949. kill(pid_t pid, int sig_num)
  4950. {
  4951. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4952. (void)CloseHandle((HANDLE)pid);
  4953. return 0;
  4954. }
  4955. #if !defined(WNOHANG)
  4956. #define WNOHANG (1)
  4957. #endif
  4958. static pid_t
  4959. waitpid(pid_t pid, int *status, int flags)
  4960. {
  4961. DWORD timeout = INFINITE;
  4962. DWORD waitres;
  4963. (void)status; /* Currently not used by any client here */
  4964. if ((flags | WNOHANG) == WNOHANG) {
  4965. timeout = 0;
  4966. }
  4967. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4968. if (waitres == WAIT_OBJECT_0) {
  4969. return pid;
  4970. }
  4971. if (waitres == WAIT_TIMEOUT) {
  4972. return 0;
  4973. }
  4974. return (pid_t)-1;
  4975. }
  4976. static void
  4977. trim_trailing_whitespaces(char *s)
  4978. {
  4979. char *e = s + strlen(s);
  4980. while ((e > s) && isspace((unsigned char)e[-1])) {
  4981. *(--e) = '\0';
  4982. }
  4983. }
  4984. static pid_t
  4985. spawn_process(struct mg_connection *conn,
  4986. const char *prog,
  4987. char *envblk,
  4988. char *envp[],
  4989. int fdin[2],
  4990. int fdout[2],
  4991. int fderr[2],
  4992. const char *dir)
  4993. {
  4994. HANDLE me;
  4995. char *p, *interp;
  4996. char *interp_arg = 0;
  4997. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4998. buf[PATH_MAX];
  4999. int truncated;
  5000. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5001. STARTUPINFOA si;
  5002. PROCESS_INFORMATION pi = {0};
  5003. (void)envp;
  5004. memset(&si, 0, sizeof(si));
  5005. si.cb = sizeof(si);
  5006. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5007. si.wShowWindow = SW_HIDE;
  5008. me = GetCurrentProcess();
  5009. DuplicateHandle(me,
  5010. (HANDLE)_get_osfhandle(fdin[0]),
  5011. me,
  5012. &si.hStdInput,
  5013. 0,
  5014. TRUE,
  5015. DUPLICATE_SAME_ACCESS);
  5016. DuplicateHandle(me,
  5017. (HANDLE)_get_osfhandle(fdout[1]),
  5018. me,
  5019. &si.hStdOutput,
  5020. 0,
  5021. TRUE,
  5022. DUPLICATE_SAME_ACCESS);
  5023. DuplicateHandle(me,
  5024. (HANDLE)_get_osfhandle(fderr[1]),
  5025. me,
  5026. &si.hStdError,
  5027. 0,
  5028. TRUE,
  5029. DUPLICATE_SAME_ACCESS);
  5030. /* Mark handles that should not be inherited. See
  5031. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5032. */
  5033. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5034. HANDLE_FLAG_INHERIT,
  5035. 0);
  5036. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5037. HANDLE_FLAG_INHERIT,
  5038. 0);
  5039. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5040. HANDLE_FLAG_INHERIT,
  5041. 0);
  5042. /* First check, if there is a CGI interpreter configured for all CGI
  5043. * scripts. */
  5044. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5045. if (interp != NULL) {
  5046. /* If there is a configured interpreter, check for additional arguments
  5047. */
  5048. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5049. } else {
  5050. /* Otherwise, the interpreter must be stated in the first line of the
  5051. * CGI script file, after a #! (shebang) mark. */
  5052. buf[0] = buf[1] = '\0';
  5053. /* Get the full script path */
  5054. mg_snprintf(
  5055. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5056. if (truncated) {
  5057. pi.hProcess = (pid_t)-1;
  5058. goto spawn_cleanup;
  5059. }
  5060. /* Open the script file, to read the first line */
  5061. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5062. #if defined(MG_USE_OPEN_FILE)
  5063. p = (char *)file.access.membuf;
  5064. #else
  5065. p = (char *)NULL;
  5066. #endif
  5067. /* Read the first line of the script into the buffer */
  5068. mg_fgets(buf, sizeof(buf), &file, &p);
  5069. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5070. buf[sizeof(buf) - 1] = '\0';
  5071. }
  5072. if ((buf[0] == '#') && (buf[1] == '!')) {
  5073. trim_trailing_whitespaces(buf + 2);
  5074. } else {
  5075. buf[2] = '\0';
  5076. }
  5077. interp = buf + 2;
  5078. }
  5079. if (interp[0] != '\0') {
  5080. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5081. interp = full_interp;
  5082. }
  5083. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5084. if (interp[0] != '\0') {
  5085. /* This is an interpreted script file. We must call the interpreter. */
  5086. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5087. mg_snprintf(conn,
  5088. &truncated,
  5089. cmdline,
  5090. sizeof(cmdline),
  5091. "\"%s\" %s \"%s\\%s\"",
  5092. interp,
  5093. interp_arg,
  5094. full_dir,
  5095. prog);
  5096. } else {
  5097. mg_snprintf(conn,
  5098. &truncated,
  5099. cmdline,
  5100. sizeof(cmdline),
  5101. "\"%s\" \"%s\\%s\"",
  5102. interp,
  5103. full_dir,
  5104. prog);
  5105. }
  5106. } else {
  5107. /* This is (probably) a compiled program. We call it directly. */
  5108. mg_snprintf(conn,
  5109. &truncated,
  5110. cmdline,
  5111. sizeof(cmdline),
  5112. "\"%s\\%s\"",
  5113. full_dir,
  5114. prog);
  5115. }
  5116. if (truncated) {
  5117. pi.hProcess = (pid_t)-1;
  5118. goto spawn_cleanup;
  5119. }
  5120. DEBUG_TRACE("Running [%s]", cmdline);
  5121. if (CreateProcessA(NULL,
  5122. cmdline,
  5123. NULL,
  5124. NULL,
  5125. TRUE,
  5126. CREATE_NEW_PROCESS_GROUP,
  5127. envblk,
  5128. NULL,
  5129. &si,
  5130. &pi)
  5131. == 0) {
  5132. mg_cry_internal(
  5133. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5134. pi.hProcess = (pid_t)-1;
  5135. /* goto spawn_cleanup; */
  5136. }
  5137. spawn_cleanup:
  5138. (void)CloseHandle(si.hStdOutput);
  5139. (void)CloseHandle(si.hStdError);
  5140. (void)CloseHandle(si.hStdInput);
  5141. if (pi.hThread != NULL) {
  5142. (void)CloseHandle(pi.hThread);
  5143. }
  5144. return (pid_t)pi.hProcess;
  5145. }
  5146. #endif /* !NO_CGI */
  5147. static int
  5148. set_blocking_mode(SOCKET sock)
  5149. {
  5150. unsigned long non_blocking = 0;
  5151. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5152. }
  5153. static int
  5154. set_non_blocking_mode(SOCKET sock)
  5155. {
  5156. unsigned long non_blocking = 1;
  5157. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5158. }
  5159. #else
  5160. #if !defined(NO_FILESYSTEMS)
  5161. static int
  5162. mg_stat(const struct mg_connection *conn,
  5163. const char *path,
  5164. struct mg_file_stat *filep)
  5165. {
  5166. struct stat st;
  5167. if (!filep) {
  5168. return 0;
  5169. }
  5170. memset(filep, 0, sizeof(*filep));
  5171. if (conn && is_file_in_memory(conn, path)) {
  5172. /* Quick fix (for 1.9.x): */
  5173. /* mg_stat must fill all fields, also for files in memory */
  5174. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5175. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5176. filep->size = tmp_file.stat.size;
  5177. filep->last_modified = time(NULL);
  5178. filep->location = 2;
  5179. /* TODO: remove legacy "files in memory" feature */
  5180. return 1;
  5181. }
  5182. if (0 == stat(path, &st)) {
  5183. filep->size = (uint64_t)(st.st_size);
  5184. filep->last_modified = st.st_mtime;
  5185. filep->is_directory = S_ISDIR(st.st_mode);
  5186. return 1;
  5187. }
  5188. return 0;
  5189. }
  5190. #endif /* NO_FILESYSTEMS */
  5191. static void
  5192. set_close_on_exec(int fd,
  5193. const struct mg_connection *conn /* may be null */,
  5194. struct mg_context *ctx /* may be null */)
  5195. {
  5196. #if defined(__ZEPHYR__)
  5197. (void)fd;
  5198. (void)conn;
  5199. (void)ctx;
  5200. #else
  5201. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5202. if (conn || ctx) {
  5203. struct mg_connection fc;
  5204. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5205. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5206. __func__,
  5207. strerror(ERRNO));
  5208. }
  5209. }
  5210. #endif
  5211. }
  5212. int
  5213. mg_start_thread(mg_thread_func_t func, void *param)
  5214. {
  5215. pthread_t thread_id;
  5216. pthread_attr_t attr;
  5217. int result;
  5218. (void)pthread_attr_init(&attr);
  5219. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5220. #if defined(__ZEPHYR__)
  5221. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5222. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5223. /* Compile-time option to control stack size,
  5224. * e.g. -DUSE_STACK_SIZE=16384 */
  5225. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5226. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5227. result = pthread_create(&thread_id, &attr, func, param);
  5228. pthread_attr_destroy(&attr);
  5229. return result;
  5230. }
  5231. /* Start a thread storing the thread context. */
  5232. static int
  5233. mg_start_thread_with_id(mg_thread_func_t func,
  5234. void *param,
  5235. pthread_t *threadidptr)
  5236. {
  5237. pthread_t thread_id;
  5238. pthread_attr_t attr;
  5239. int result;
  5240. (void)pthread_attr_init(&attr);
  5241. #if defined(__ZEPHYR__)
  5242. pthread_attr_setstack(&attr,
  5243. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5244. ZEPHYR_STACK_SIZE);
  5245. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5246. /* Compile-time option to control stack size,
  5247. * e.g. -DUSE_STACK_SIZE=16384 */
  5248. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5249. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5250. result = pthread_create(&thread_id, &attr, func, param);
  5251. pthread_attr_destroy(&attr);
  5252. if ((result == 0) && (threadidptr != NULL)) {
  5253. *threadidptr = thread_id;
  5254. }
  5255. return result;
  5256. }
  5257. /* Wait for a thread to finish. */
  5258. static int
  5259. mg_join_thread(pthread_t threadid)
  5260. {
  5261. int result;
  5262. result = pthread_join(threadid, NULL);
  5263. return result;
  5264. }
  5265. #if !defined(NO_CGI)
  5266. static pid_t
  5267. spawn_process(struct mg_connection *conn,
  5268. const char *prog,
  5269. char *envblk,
  5270. char *envp[],
  5271. int fdin[2],
  5272. int fdout[2],
  5273. int fderr[2],
  5274. const char *dir)
  5275. {
  5276. pid_t pid;
  5277. const char *interp;
  5278. (void)envblk;
  5279. if ((pid = fork()) == -1) {
  5280. /* Parent */
  5281. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5282. } else if (pid != 0) {
  5283. /* Make sure children close parent-side descriptors.
  5284. * The caller will close the child-side immediately. */
  5285. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5286. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5287. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5288. } else {
  5289. /* Child */
  5290. if (chdir(dir) != 0) {
  5291. mg_cry_internal(
  5292. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5293. } else if (dup2(fdin[0], 0) == -1) {
  5294. mg_cry_internal(conn,
  5295. "%s: dup2(%d, 0): %s",
  5296. __func__,
  5297. fdin[0],
  5298. strerror(ERRNO));
  5299. } else if (dup2(fdout[1], 1) == -1) {
  5300. mg_cry_internal(conn,
  5301. "%s: dup2(%d, 1): %s",
  5302. __func__,
  5303. fdout[1],
  5304. strerror(ERRNO));
  5305. } else if (dup2(fderr[1], 2) == -1) {
  5306. mg_cry_internal(conn,
  5307. "%s: dup2(%d, 2): %s",
  5308. __func__,
  5309. fderr[1],
  5310. strerror(ERRNO));
  5311. } else {
  5312. struct sigaction sa;
  5313. /* Keep stderr and stdout in two different pipes.
  5314. * Stdout will be sent back to the client,
  5315. * stderr should go into a server error log. */
  5316. (void)close(fdin[0]);
  5317. (void)close(fdout[1]);
  5318. (void)close(fderr[1]);
  5319. /* Close write end fdin and read end fdout and fderr */
  5320. (void)close(fdin[1]);
  5321. (void)close(fdout[0]);
  5322. (void)close(fderr[0]);
  5323. /* After exec, all signal handlers are restored to their default
  5324. * values, with one exception of SIGCHLD. According to
  5325. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5326. * will leave unchanged after exec if it was set to be ignored.
  5327. * Restore it to default action. */
  5328. memset(&sa, 0, sizeof(sa));
  5329. sa.sa_handler = SIG_DFL;
  5330. sigaction(SIGCHLD, &sa, NULL);
  5331. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5332. if (interp == NULL) {
  5333. /* no interpreter configured, call the programm directly */
  5334. (void)execle(prog, prog, NULL, envp);
  5335. mg_cry_internal(conn,
  5336. "%s: execle(%s): %s",
  5337. __func__,
  5338. prog,
  5339. strerror(ERRNO));
  5340. } else {
  5341. /* call the configured interpreter */
  5342. const char *interp_args =
  5343. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5344. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5345. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5346. } else {
  5347. (void)execle(interp, interp, prog, NULL, envp);
  5348. }
  5349. mg_cry_internal(conn,
  5350. "%s: execle(%s %s): %s",
  5351. __func__,
  5352. interp,
  5353. prog,
  5354. strerror(ERRNO));
  5355. }
  5356. }
  5357. exit(EXIT_FAILURE);
  5358. }
  5359. return pid;
  5360. }
  5361. #endif /* !NO_CGI */
  5362. static int
  5363. set_non_blocking_mode(SOCKET sock)
  5364. {
  5365. int flags = fcntl(sock, F_GETFL, 0);
  5366. if (flags < 0) {
  5367. return -1;
  5368. }
  5369. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5370. return -1;
  5371. }
  5372. return 0;
  5373. }
  5374. static int
  5375. set_blocking_mode(SOCKET sock)
  5376. {
  5377. int flags = fcntl(sock, F_GETFL, 0);
  5378. if (flags < 0) {
  5379. return -1;
  5380. }
  5381. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5382. return -1;
  5383. }
  5384. return 0;
  5385. }
  5386. #endif /* _WIN32 / else */
  5387. /* End of initial operating system specific define block. */
  5388. /* Get a random number (independent of C rand function) */
  5389. static uint64_t
  5390. get_random(void)
  5391. {
  5392. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5393. static uint64_t lcg = 0; /* Linear congruential generator */
  5394. uint64_t now = mg_get_current_time_ns();
  5395. if (lfsr == 0) {
  5396. /* lfsr will be only 0 if has not been initialized,
  5397. * so this code is called only once. */
  5398. lfsr = mg_get_current_time_ns();
  5399. lcg = mg_get_current_time_ns();
  5400. } else {
  5401. /* Get the next step of both random number generators. */
  5402. lfsr = (lfsr >> 1)
  5403. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5404. << 63);
  5405. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5406. }
  5407. /* Combining two pseudo-random number generators and a high resolution
  5408. * part
  5409. * of the current server time will make it hard (impossible?) to guess
  5410. * the
  5411. * next number. */
  5412. return (lfsr ^ lcg ^ now);
  5413. }
  5414. static int
  5415. mg_poll(struct mg_pollfd *pfd,
  5416. unsigned int n,
  5417. int milliseconds,
  5418. stop_flag_t *stop_flag)
  5419. {
  5420. /* Call poll, but only for a maximum time of a few seconds.
  5421. * This will allow to stop the server after some seconds, instead
  5422. * of having to wait for a long socket timeout. */
  5423. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5424. do {
  5425. int result;
  5426. if (!STOP_FLAG_IS_ZERO(stop_flag)) {
  5427. /* Shut down signal */
  5428. return -2;
  5429. }
  5430. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5431. ms_now = milliseconds;
  5432. }
  5433. result = poll(pfd, n, ms_now);
  5434. if (result != 0) {
  5435. /* Poll returned either success (1) or error (-1).
  5436. * Forward both to the caller. */
  5437. return result;
  5438. }
  5439. /* Poll returned timeout (0). */
  5440. if (milliseconds > 0) {
  5441. milliseconds -= ms_now;
  5442. }
  5443. } while (milliseconds != 0);
  5444. /* timeout: return 0 */
  5445. return 0;
  5446. }
  5447. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5448. * descriptor.
  5449. * Return value:
  5450. * >=0 .. number of bytes successfully written
  5451. * -1 .. timeout
  5452. * -2 .. error
  5453. */
  5454. static int
  5455. push_inner(struct mg_context *ctx,
  5456. FILE *fp,
  5457. SOCKET sock,
  5458. SSL *ssl,
  5459. const char *buf,
  5460. int len,
  5461. double timeout)
  5462. {
  5463. uint64_t start = 0, now = 0, timeout_ns = 0;
  5464. int n, err;
  5465. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5466. #if defined(_WIN32)
  5467. typedef int len_t;
  5468. #else
  5469. typedef size_t len_t;
  5470. #endif
  5471. if (timeout > 0) {
  5472. now = mg_get_current_time_ns();
  5473. start = now;
  5474. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5475. }
  5476. if (ctx == NULL) {
  5477. return -2;
  5478. }
  5479. #if defined(NO_SSL)
  5480. if (ssl) {
  5481. return -2;
  5482. }
  5483. #endif
  5484. /* Try to read until it succeeds, fails, times out, or the server
  5485. * shuts down. */
  5486. for (;;) {
  5487. #if !defined(NO_SSL)
  5488. if (ssl != NULL) {
  5489. ERR_clear_error();
  5490. n = SSL_write(ssl, buf, len);
  5491. if (n <= 0) {
  5492. err = SSL_get_error(ssl, n);
  5493. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5494. err = ERRNO;
  5495. } else if ((err == SSL_ERROR_WANT_READ)
  5496. || (err == SSL_ERROR_WANT_WRITE)) {
  5497. n = 0;
  5498. } else {
  5499. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5500. ERR_clear_error();
  5501. return -2;
  5502. }
  5503. ERR_clear_error();
  5504. } else {
  5505. err = 0;
  5506. }
  5507. } else
  5508. #endif
  5509. if (fp != NULL) {
  5510. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5511. if (ferror(fp)) {
  5512. n = -1;
  5513. err = ERRNO;
  5514. } else {
  5515. err = 0;
  5516. }
  5517. } else {
  5518. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5519. err = (n < 0) ? ERRNO : 0;
  5520. #if defined(_WIN32)
  5521. if (err == WSAEWOULDBLOCK) {
  5522. err = 0;
  5523. n = 0;
  5524. }
  5525. #else
  5526. if (err == EWOULDBLOCK) {
  5527. err = 0;
  5528. n = 0;
  5529. }
  5530. #endif
  5531. if (n < 0) {
  5532. /* shutdown of the socket at client side */
  5533. return -2;
  5534. }
  5535. }
  5536. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5537. return -2;
  5538. }
  5539. if ((n > 0) || ((n == 0) && (len == 0))) {
  5540. /* some data has been read, or no data was requested */
  5541. return n;
  5542. }
  5543. if (n < 0) {
  5544. /* socket error - check errno */
  5545. DEBUG_TRACE("send() failed, error %d", err);
  5546. /* TODO (mid): error handling depending on the error code.
  5547. * These codes are different between Windows and Linux.
  5548. * Currently there is no problem with failing send calls,
  5549. * if there is a reproducible situation, it should be
  5550. * investigated in detail.
  5551. */
  5552. return -2;
  5553. }
  5554. /* Only in case n=0 (timeout), repeat calling the write function */
  5555. /* If send failed, wait before retry */
  5556. if (fp != NULL) {
  5557. /* For files, just wait a fixed time.
  5558. * Maybe it helps, maybe not. */
  5559. mg_sleep(5);
  5560. } else {
  5561. /* For sockets, wait for the socket using poll */
  5562. struct mg_pollfd pfd[1];
  5563. int pollres;
  5564. pfd[0].fd = sock;
  5565. pfd[0].events = POLLOUT;
  5566. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5567. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5568. return -2;
  5569. }
  5570. if (pollres > 0) {
  5571. continue;
  5572. }
  5573. }
  5574. if (timeout > 0) {
  5575. now = mg_get_current_time_ns();
  5576. if ((now - start) > timeout_ns) {
  5577. /* Timeout */
  5578. break;
  5579. }
  5580. }
  5581. }
  5582. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5583. used */
  5584. return -1;
  5585. }
  5586. static int
  5587. push_all(struct mg_context *ctx,
  5588. FILE *fp,
  5589. SOCKET sock,
  5590. SSL *ssl,
  5591. const char *buf,
  5592. int len)
  5593. {
  5594. double timeout = -1.0;
  5595. int n, nwritten = 0;
  5596. if (ctx == NULL) {
  5597. return -1;
  5598. }
  5599. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5600. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5601. }
  5602. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5603. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5604. if (n < 0) {
  5605. if (nwritten == 0) {
  5606. nwritten = -1; /* Propagate the error */
  5607. }
  5608. break;
  5609. } else if (n == 0) {
  5610. break; /* No more data to write */
  5611. } else {
  5612. nwritten += n;
  5613. len -= n;
  5614. }
  5615. }
  5616. return nwritten;
  5617. }
  5618. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5619. * Return value:
  5620. * >=0 .. number of bytes successfully read
  5621. * -1 .. timeout
  5622. * -2 .. error
  5623. */
  5624. static int
  5625. pull_inner(FILE *fp,
  5626. struct mg_connection *conn,
  5627. char *buf,
  5628. int len,
  5629. double timeout)
  5630. {
  5631. int nread, err = 0;
  5632. #if defined(_WIN32)
  5633. typedef int len_t;
  5634. #else
  5635. typedef size_t len_t;
  5636. #endif
  5637. /* We need an additional wait loop around this, because in some cases
  5638. * with TLSwe may get data from the socket but not from SSL_read.
  5639. * In this case we need to repeat at least once.
  5640. */
  5641. if (fp != NULL) {
  5642. #if !defined(_WIN32_WCE)
  5643. /* Use read() instead of fread(), because if we're reading from the
  5644. * CGI pipe, fread() may block until IO buffer is filled up. We
  5645. * cannot afford to block and must pass all read bytes immediately
  5646. * to the client. */
  5647. nread = (int)read(fileno(fp), buf, (size_t)len);
  5648. #else
  5649. /* WinCE does not support CGI pipes */
  5650. nread = (int)fread(buf, 1, (size_t)len, fp);
  5651. #endif
  5652. err = (nread < 0) ? ERRNO : 0;
  5653. if ((nread == 0) && (len > 0)) {
  5654. /* Should get data, but got EOL */
  5655. return -2;
  5656. }
  5657. #if !defined(NO_SSL)
  5658. } else if (conn->ssl != NULL) {
  5659. int ssl_pending;
  5660. struct mg_pollfd pfd[1];
  5661. int pollres;
  5662. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5663. /* We already know there is no more data buffered in conn->buf
  5664. * but there is more available in the SSL layer. So don't poll
  5665. * conn->client.sock yet. */
  5666. if (ssl_pending > len) {
  5667. ssl_pending = len;
  5668. }
  5669. pollres = 1;
  5670. } else {
  5671. pfd[0].fd = conn->client.sock;
  5672. pfd[0].events = POLLIN;
  5673. pollres = mg_poll(pfd,
  5674. 1,
  5675. (int)(timeout * 1000.0),
  5676. &(conn->phys_ctx->stop_flag));
  5677. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5678. return -2;
  5679. }
  5680. }
  5681. if (pollres > 0) {
  5682. ERR_clear_error();
  5683. nread = SSL_read(conn->ssl, buf,
  5684. (ssl_pending > 0) ? ssl_pending : len);
  5685. if (nread <= 0) {
  5686. err = SSL_get_error(conn->ssl, nread);
  5687. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5688. err = ERRNO;
  5689. } else if ((err == SSL_ERROR_WANT_READ)
  5690. || (err == SSL_ERROR_WANT_WRITE)) {
  5691. nread = 0;
  5692. } else {
  5693. /* All errors should return -2 */
  5694. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5695. ERR_clear_error();
  5696. return -2;
  5697. }
  5698. ERR_clear_error();
  5699. } else {
  5700. err = 0;
  5701. }
  5702. } else if (pollres < 0) {
  5703. /* Error */
  5704. return -2;
  5705. } else {
  5706. /* pollres = 0 means timeout */
  5707. nread = 0;
  5708. }
  5709. #endif
  5710. } else {
  5711. struct mg_pollfd pfd[1];
  5712. int pollres;
  5713. pfd[0].fd = conn->client.sock;
  5714. pfd[0].events = POLLIN;
  5715. pollres = mg_poll(pfd,
  5716. 1,
  5717. (int)(timeout * 1000.0),
  5718. &(conn->phys_ctx->stop_flag));
  5719. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5720. return -2;
  5721. }
  5722. if (pollres > 0) {
  5723. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5724. err = (nread < 0) ? ERRNO : 0;
  5725. if (nread <= 0) {
  5726. /* shutdown of the socket at client side */
  5727. return -2;
  5728. }
  5729. } else if (pollres < 0) {
  5730. /* error callint poll */
  5731. return -2;
  5732. } else {
  5733. /* pollres = 0 means timeout */
  5734. nread = 0;
  5735. }
  5736. }
  5737. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5738. return -2;
  5739. }
  5740. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5741. /* some data has been read, or no data was requested */
  5742. return nread;
  5743. }
  5744. if (nread < 0) {
  5745. /* socket error - check errno */
  5746. #if defined(_WIN32)
  5747. if (err == WSAEWOULDBLOCK) {
  5748. /* TODO (low): check if this is still required */
  5749. /* standard case if called from close_socket_gracefully */
  5750. return -2;
  5751. } else if (err == WSAETIMEDOUT) {
  5752. /* TODO (low): check if this is still required */
  5753. /* timeout is handled by the while loop */
  5754. return 0;
  5755. } else if (err == WSAECONNABORTED) {
  5756. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5757. return -2;
  5758. } else {
  5759. DEBUG_TRACE("recv() failed, error %d", err);
  5760. return -2;
  5761. }
  5762. #else
  5763. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5764. * if the timeout is reached and if the socket was set to non-
  5765. * blocking in close_socket_gracefully, so we can not distinguish
  5766. * here. We have to wait for the timeout in both cases for now.
  5767. */
  5768. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5769. /* TODO (low): check if this is still required */
  5770. /* EAGAIN/EWOULDBLOCK:
  5771. * standard case if called from close_socket_gracefully
  5772. * => should return -1 */
  5773. /* or timeout occurred
  5774. * => the code must stay in the while loop */
  5775. /* EINTR can be generated on a socket with a timeout set even
  5776. * when SA_RESTART is effective for all relevant signals
  5777. * (see signal(7)).
  5778. * => stay in the while loop */
  5779. } else {
  5780. DEBUG_TRACE("recv() failed, error %d", err);
  5781. return -2;
  5782. }
  5783. #endif
  5784. }
  5785. /* Timeout occurred, but no data available. */
  5786. return -1;
  5787. }
  5788. static int
  5789. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5790. {
  5791. int n, nread = 0;
  5792. double timeout = -1.0;
  5793. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5794. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5795. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5796. }
  5797. if (timeout >= 0.0) {
  5798. start_time = mg_get_current_time_ns();
  5799. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5800. }
  5801. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5802. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5803. if (n == -2) {
  5804. if (nread == 0) {
  5805. nread = -1; /* Propagate the error */
  5806. }
  5807. break;
  5808. } else if (n == -1) {
  5809. /* timeout */
  5810. if (timeout >= 0.0) {
  5811. now = mg_get_current_time_ns();
  5812. if ((now - start_time) <= timeout_ns) {
  5813. continue;
  5814. }
  5815. }
  5816. break;
  5817. } else if (n == 0) {
  5818. break; /* No more data to read */
  5819. } else {
  5820. nread += n;
  5821. len -= n;
  5822. }
  5823. }
  5824. return nread;
  5825. }
  5826. static void
  5827. discard_unread_request_data(struct mg_connection *conn)
  5828. {
  5829. char buf[MG_BUF_LEN];
  5830. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5831. ;
  5832. }
  5833. static int
  5834. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5835. {
  5836. int64_t content_len, n, buffered_len, nread;
  5837. int64_t len64 =
  5838. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5839. * int, we may not read more
  5840. * bytes */
  5841. const char *body;
  5842. if (conn == NULL) {
  5843. return 0;
  5844. }
  5845. /* If Content-Length is not set for a response with body data,
  5846. * we do not know in advance how much data should be read. */
  5847. content_len = conn->content_len;
  5848. if (content_len < 0) {
  5849. /* The body data is completed when the connection is closed. */
  5850. content_len = INT64_MAX;
  5851. }
  5852. nread = 0;
  5853. if (conn->consumed_content < content_len) {
  5854. /* Adjust number of bytes to read. */
  5855. int64_t left_to_read = content_len - conn->consumed_content;
  5856. if (left_to_read < len64) {
  5857. /* Do not read more than the total content length of the
  5858. * request.
  5859. */
  5860. len64 = left_to_read;
  5861. }
  5862. /* Return buffered data */
  5863. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5864. - conn->consumed_content;
  5865. if (buffered_len > 0) {
  5866. if (len64 < buffered_len) {
  5867. buffered_len = len64;
  5868. }
  5869. body = conn->buf + conn->request_len + conn->consumed_content;
  5870. memcpy(buf, body, (size_t)buffered_len);
  5871. len64 -= buffered_len;
  5872. conn->consumed_content += buffered_len;
  5873. nread += buffered_len;
  5874. buf = (char *)buf + buffered_len;
  5875. }
  5876. /* We have returned all buffered data. Read new data from the remote
  5877. * socket.
  5878. */
  5879. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5880. conn->consumed_content += n;
  5881. nread += n;
  5882. } else {
  5883. nread = ((nread > 0) ? nread : n);
  5884. }
  5885. }
  5886. return (int)nread;
  5887. }
  5888. int
  5889. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5890. {
  5891. if (len > INT_MAX) {
  5892. len = INT_MAX;
  5893. }
  5894. if (conn == NULL) {
  5895. return 0;
  5896. }
  5897. if (conn->is_chunked) {
  5898. size_t all_read = 0;
  5899. while (len > 0) {
  5900. if (conn->is_chunked >= 3) {
  5901. /* No more data left to read */
  5902. return 0;
  5903. }
  5904. if (conn->is_chunked != 1) {
  5905. /* Has error */
  5906. return -1;
  5907. }
  5908. if (conn->consumed_content != conn->content_len) {
  5909. /* copy from the current chunk */
  5910. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5911. if (read_ret < 1) {
  5912. /* read error */
  5913. conn->is_chunked = 2;
  5914. return -1;
  5915. }
  5916. all_read += (size_t)read_ret;
  5917. len -= (size_t)read_ret;
  5918. if (conn->consumed_content == conn->content_len) {
  5919. /* Add data bytes in the current chunk have been read,
  5920. * so we are expecting \r\n now. */
  5921. char x[2];
  5922. conn->content_len += 2;
  5923. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5924. || (x[1] != '\n')) {
  5925. /* Protocol violation */
  5926. conn->is_chunked = 2;
  5927. return -1;
  5928. }
  5929. }
  5930. } else {
  5931. /* fetch a new chunk */
  5932. size_t i;
  5933. char lenbuf[64];
  5934. char *end = NULL;
  5935. unsigned long chunkSize = 0;
  5936. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5937. conn->content_len++;
  5938. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5939. lenbuf[i] = 0;
  5940. }
  5941. if ((i > 0) && (lenbuf[i] == '\r')
  5942. && (lenbuf[i - 1] != '\r')) {
  5943. continue;
  5944. }
  5945. if ((i > 1) && (lenbuf[i] == '\n')
  5946. && (lenbuf[i - 1] == '\r')) {
  5947. lenbuf[i + 1] = 0;
  5948. chunkSize = strtoul(lenbuf, &end, 16);
  5949. if (chunkSize == 0) {
  5950. /* regular end of content */
  5951. conn->is_chunked = 3;
  5952. }
  5953. break;
  5954. }
  5955. if (!isxdigit((unsigned char)lenbuf[i])) {
  5956. /* illegal character for chunk length */
  5957. conn->is_chunked = 2;
  5958. return -1;
  5959. }
  5960. }
  5961. if ((end == NULL) || (*end != '\r')) {
  5962. /* chunksize not set correctly */
  5963. conn->is_chunked = 2;
  5964. return -1;
  5965. }
  5966. if (chunkSize == 0) {
  5967. /* try discarding trailer for keep-alive */
  5968. conn->content_len += 2;
  5969. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5970. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5971. conn->is_chunked = 4;
  5972. }
  5973. break;
  5974. }
  5975. /* append a new chunk */
  5976. conn->content_len += (int64_t)chunkSize;
  5977. }
  5978. }
  5979. return (int)all_read;
  5980. }
  5981. return mg_read_inner(conn, buf, len);
  5982. }
  5983. int
  5984. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5985. {
  5986. time_t now;
  5987. int n, total, allowed;
  5988. if (conn == NULL) {
  5989. return 0;
  5990. }
  5991. if (len > INT_MAX) {
  5992. return -1;
  5993. }
  5994. if (conn->throttle > 0) {
  5995. if ((now = time(NULL)) != conn->last_throttle_time) {
  5996. conn->last_throttle_time = now;
  5997. conn->last_throttle_bytes = 0;
  5998. }
  5999. allowed = conn->throttle - conn->last_throttle_bytes;
  6000. if (allowed > (int)len) {
  6001. allowed = (int)len;
  6002. }
  6003. if ((total = push_all(conn->phys_ctx,
  6004. NULL,
  6005. conn->client.sock,
  6006. conn->ssl,
  6007. (const char *)buf,
  6008. allowed))
  6009. == allowed) {
  6010. buf = (const char *)buf + total;
  6011. conn->last_throttle_bytes += total;
  6012. while ((total < (int)len)
  6013. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6014. allowed = (conn->throttle > ((int)len - total))
  6015. ? (int)len - total
  6016. : conn->throttle;
  6017. if ((n = push_all(conn->phys_ctx,
  6018. NULL,
  6019. conn->client.sock,
  6020. conn->ssl,
  6021. (const char *)buf,
  6022. allowed))
  6023. != allowed) {
  6024. break;
  6025. }
  6026. sleep(1);
  6027. conn->last_throttle_bytes = allowed;
  6028. conn->last_throttle_time = time(NULL);
  6029. buf = (const char *)buf + n;
  6030. total += n;
  6031. }
  6032. }
  6033. } else {
  6034. total = push_all(conn->phys_ctx,
  6035. NULL,
  6036. conn->client.sock,
  6037. conn->ssl,
  6038. (const char *)buf,
  6039. (int)len);
  6040. }
  6041. if (total > 0) {
  6042. conn->num_bytes_sent += total;
  6043. }
  6044. return total;
  6045. }
  6046. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6047. int
  6048. mg_send_chunk(struct mg_connection *conn,
  6049. const char *chunk,
  6050. unsigned int chunk_len)
  6051. {
  6052. char lenbuf[16];
  6053. size_t lenbuf_len;
  6054. int ret;
  6055. int t;
  6056. /* First store the length information in a text buffer. */
  6057. sprintf(lenbuf, "%x\r\n", chunk_len);
  6058. lenbuf_len = strlen(lenbuf);
  6059. /* Then send length information, chunk and terminating \r\n. */
  6060. ret = mg_write(conn, lenbuf, lenbuf_len);
  6061. if (ret != (int)lenbuf_len) {
  6062. return -1;
  6063. }
  6064. t = ret;
  6065. ret = mg_write(conn, chunk, chunk_len);
  6066. if (ret != (int)chunk_len) {
  6067. return -1;
  6068. }
  6069. t += ret;
  6070. ret = mg_write(conn, "\r\n", 2);
  6071. if (ret != 2) {
  6072. return -1;
  6073. }
  6074. t += ret;
  6075. return t;
  6076. }
  6077. #if defined(GCC_DIAGNOSTIC)
  6078. /* This block forwards format strings to printf implementations,
  6079. * so we need to disable the format-nonliteral warning. */
  6080. #pragma GCC diagnostic push
  6081. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6082. #endif
  6083. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6084. static int
  6085. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6086. {
  6087. va_list ap_copy;
  6088. size_t size = MG_BUF_LEN / 4;
  6089. int len = -1;
  6090. *buf = NULL;
  6091. while (len < 0) {
  6092. if (*buf) {
  6093. mg_free(*buf);
  6094. }
  6095. size *= 4;
  6096. *buf = (char *)mg_malloc(size);
  6097. if (!*buf) {
  6098. break;
  6099. }
  6100. va_copy(ap_copy, ap);
  6101. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6102. va_end(ap_copy);
  6103. (*buf)[size - 1] = 0;
  6104. }
  6105. return len;
  6106. }
  6107. /* Print message to buffer. If buffer is large enough to hold the message,
  6108. * return buffer. If buffer is to small, allocate large enough buffer on
  6109. * heap,
  6110. * and return allocated buffer. */
  6111. static int
  6112. alloc_vprintf(char **out_buf,
  6113. char *prealloc_buf,
  6114. size_t prealloc_size,
  6115. const char *fmt,
  6116. va_list ap)
  6117. {
  6118. va_list ap_copy;
  6119. int len;
  6120. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6121. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6122. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6123. * Therefore, we make two passes: on first pass, get required message
  6124. * length.
  6125. * On second pass, actually print the message. */
  6126. va_copy(ap_copy, ap);
  6127. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6128. va_end(ap_copy);
  6129. if (len < 0) {
  6130. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6131. * Switch to alternative code path that uses incremental
  6132. * allocations.
  6133. */
  6134. va_copy(ap_copy, ap);
  6135. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6136. va_end(ap_copy);
  6137. } else if ((size_t)(len) >= prealloc_size) {
  6138. /* The pre-allocated buffer not large enough. */
  6139. /* Allocate a new buffer. */
  6140. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6141. if (!*out_buf) {
  6142. /* Allocation failed. Return -1 as "out of memory" error. */
  6143. return -1;
  6144. }
  6145. /* Buffer allocation successful. Store the string there. */
  6146. va_copy(ap_copy, ap);
  6147. IGNORE_UNUSED_RESULT(
  6148. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6149. va_end(ap_copy);
  6150. } else {
  6151. /* The pre-allocated buffer is large enough.
  6152. * Use it to store the string and return the address. */
  6153. va_copy(ap_copy, ap);
  6154. IGNORE_UNUSED_RESULT(
  6155. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6156. va_end(ap_copy);
  6157. *out_buf = prealloc_buf;
  6158. }
  6159. return len;
  6160. }
  6161. #if defined(GCC_DIAGNOSTIC)
  6162. /* Enable format-nonliteral warning again. */
  6163. #pragma GCC diagnostic pop
  6164. #endif
  6165. static int
  6166. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6167. {
  6168. char mem[MG_BUF_LEN];
  6169. char *buf = NULL;
  6170. int len;
  6171. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6172. len = mg_write(conn, buf, (size_t)len);
  6173. }
  6174. if (buf != mem) {
  6175. mg_free(buf);
  6176. }
  6177. return len;
  6178. }
  6179. int
  6180. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6181. {
  6182. va_list ap;
  6183. int result;
  6184. va_start(ap, fmt);
  6185. result = mg_vprintf(conn, fmt, ap);
  6186. va_end(ap);
  6187. return result;
  6188. }
  6189. int
  6190. mg_url_decode(const char *src,
  6191. int src_len,
  6192. char *dst,
  6193. int dst_len,
  6194. int is_form_url_encoded)
  6195. {
  6196. int i, j, a, b;
  6197. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6198. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6199. if ((i < src_len - 2) && (src[i] == '%')
  6200. && isxdigit((unsigned char)src[i + 1])
  6201. && isxdigit((unsigned char)src[i + 2])) {
  6202. a = tolower((unsigned char)src[i + 1]);
  6203. b = tolower((unsigned char)src[i + 2]);
  6204. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6205. i += 2;
  6206. } else if (is_form_url_encoded && (src[i] == '+')) {
  6207. dst[j] = ' ';
  6208. } else {
  6209. dst[j] = src[i];
  6210. }
  6211. }
  6212. dst[j] = '\0'; /* Null-terminate the destination */
  6213. return (i >= src_len) ? j : -1;
  6214. }
  6215. /* form url decoding of an entire string */
  6216. static void
  6217. url_decode_in_place(char *buf)
  6218. {
  6219. size_t len = strlen(buf);
  6220. while (*buf) {
  6221. if (*buf == '%') {
  6222. if (isxdigit((unsigned char)buf[1])) {
  6223. if (isxdigit((unsigned char)buf[2])) {
  6224. int a = tolower((unsigned char)buf[1]);
  6225. int b = tolower((unsigned char)buf[2]);
  6226. char c = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6227. memmove(buf + 1, buf + 3, len - 2);
  6228. *buf = c;
  6229. len -= 2;
  6230. }
  6231. }
  6232. } else if (*buf == '+') {
  6233. *buf = ' ';
  6234. }
  6235. buf++;
  6236. len--;
  6237. }
  6238. }
  6239. int
  6240. mg_get_var(const char *data,
  6241. size_t data_len,
  6242. const char *name,
  6243. char *dst,
  6244. size_t dst_len)
  6245. {
  6246. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6247. }
  6248. int
  6249. mg_get_var2(const char *data,
  6250. size_t data_len,
  6251. const char *name,
  6252. char *dst,
  6253. size_t dst_len,
  6254. size_t occurrence)
  6255. {
  6256. const char *p, *e, *s;
  6257. size_t name_len;
  6258. int len;
  6259. if ((dst == NULL) || (dst_len == 0)) {
  6260. len = -2;
  6261. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6262. len = -1;
  6263. dst[0] = '\0';
  6264. } else {
  6265. name_len = strlen(name);
  6266. e = data + data_len;
  6267. len = -1;
  6268. dst[0] = '\0';
  6269. /* data is "var1=val1&var2=val2...". Find variable first */
  6270. for (p = data; p + name_len < e; p++) {
  6271. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6272. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6273. /* Point p to variable value */
  6274. p += name_len + 1;
  6275. /* Point s to the end of the value */
  6276. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6277. if (s == NULL) {
  6278. s = e;
  6279. }
  6280. DEBUG_ASSERT(s >= p);
  6281. if (s < p) {
  6282. return -3;
  6283. }
  6284. /* Decode variable into destination buffer */
  6285. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6286. /* Redirect error code from -1 to -2 (destination buffer too
  6287. * small). */
  6288. if (len == -1) {
  6289. len = -2;
  6290. }
  6291. break;
  6292. }
  6293. }
  6294. }
  6295. return len;
  6296. }
  6297. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6298. int
  6299. mg_split_form_urlencoded(char *data,
  6300. struct mg_header *form_fields,
  6301. unsigned num_form_fields)
  6302. {
  6303. char *b;
  6304. int i;
  6305. int num = 0;
  6306. if (data == NULL) {
  6307. /* parameter error */
  6308. return -1;
  6309. }
  6310. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6311. /* determine the number of expected fields */
  6312. if (data[0] == 0) {
  6313. return 0;
  6314. }
  6315. /* count number of & to return the number of key-value-pairs */
  6316. num = 1;
  6317. while (*data) {
  6318. if (*data == '&') {
  6319. num++;
  6320. }
  6321. data++;
  6322. }
  6323. return num;
  6324. }
  6325. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6326. /* parameter error */
  6327. return -1;
  6328. }
  6329. for (i = 0; i < (int)num_form_fields; i++) {
  6330. /* extract key-value pairs from input data */
  6331. while ((*data == ' ') || (*data == '\t')) {
  6332. /* skip initial spaces */
  6333. data++;
  6334. }
  6335. if (*data == 0) {
  6336. /* end of string reached */
  6337. break;
  6338. }
  6339. form_fields[num].name = data;
  6340. /* find & or = */
  6341. b = data;
  6342. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6343. b++;
  6344. }
  6345. if (*b == 0) {
  6346. /* last key without value */
  6347. form_fields[num].value = NULL;
  6348. } else if (*b == '&') {
  6349. /* mid key without value */
  6350. form_fields[num].value = NULL;
  6351. } else {
  6352. /* terminate string */
  6353. *b = 0;
  6354. /* value starts after '=' */
  6355. data = b + 1;
  6356. form_fields[num].value = data;
  6357. }
  6358. /* new field is stored */
  6359. num++;
  6360. /* find a next key */
  6361. b = strchr(data, '&');
  6362. if (b == 0) {
  6363. /* no more data */
  6364. break;
  6365. } else {
  6366. /* terminate value of last field at '&' */
  6367. *b = 0;
  6368. /* next key-value-pairs starts after '&' */
  6369. data = b + 1;
  6370. }
  6371. }
  6372. /* Decode all values */
  6373. for (i = 0; i < num; i++) {
  6374. if (form_fields[i].name) {
  6375. url_decode_in_place((char *)form_fields[i].name);
  6376. }
  6377. if (form_fields[i].value) {
  6378. url_decode_in_place((char *)form_fields[i].value);
  6379. }
  6380. }
  6381. /* return number of fields found */
  6382. return num;
  6383. }
  6384. /* HCP24: some changes to compare hole var_name */
  6385. int
  6386. mg_get_cookie(const char *cookie_header,
  6387. const char *var_name,
  6388. char *dst,
  6389. size_t dst_size)
  6390. {
  6391. const char *s, *p, *end;
  6392. int name_len, len = -1;
  6393. if ((dst == NULL) || (dst_size == 0)) {
  6394. return -2;
  6395. }
  6396. dst[0] = '\0';
  6397. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6398. return -1;
  6399. }
  6400. name_len = (int)strlen(var_name);
  6401. end = s + strlen(s);
  6402. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6403. if (s[name_len] == '=') {
  6404. /* HCP24: now check is it a substring or a full cookie name */
  6405. if ((s == cookie_header) || (s[-1] == ' ')) {
  6406. s += name_len + 1;
  6407. if ((p = strchr(s, ' ')) == NULL) {
  6408. p = end;
  6409. }
  6410. if (p[-1] == ';') {
  6411. p--;
  6412. }
  6413. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6414. s++;
  6415. p--;
  6416. }
  6417. if ((size_t)(p - s) < dst_size) {
  6418. len = (int)(p - s);
  6419. mg_strlcpy(dst, s, (size_t)len + 1);
  6420. } else {
  6421. len = -3;
  6422. }
  6423. break;
  6424. }
  6425. }
  6426. }
  6427. return len;
  6428. }
  6429. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6430. static void
  6431. base64_encode(const unsigned char *src, int src_len, char *dst)
  6432. {
  6433. static const char *b64 =
  6434. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6435. int i, j, a, b, c;
  6436. for (i = j = 0; i < src_len; i += 3) {
  6437. a = src[i];
  6438. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6439. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6440. dst[j++] = b64[a >> 2];
  6441. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6442. if (i + 1 < src_len) {
  6443. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6444. }
  6445. if (i + 2 < src_len) {
  6446. dst[j++] = b64[c & 63];
  6447. }
  6448. }
  6449. while (j % 4 != 0) {
  6450. dst[j++] = '=';
  6451. }
  6452. dst[j++] = '\0';
  6453. }
  6454. #endif
  6455. #if defined(USE_LUA)
  6456. static unsigned char
  6457. b64reverse(char letter)
  6458. {
  6459. if ((letter >= 'A') && (letter <= 'Z')) {
  6460. return letter - 'A';
  6461. }
  6462. if ((letter >= 'a') && (letter <= 'z')) {
  6463. return letter - 'a' + 26;
  6464. }
  6465. if ((letter >= '0') && (letter <= '9')) {
  6466. return letter - '0' + 52;
  6467. }
  6468. if (letter == '+') {
  6469. return 62;
  6470. }
  6471. if (letter == '/') {
  6472. return 63;
  6473. }
  6474. if (letter == '=') {
  6475. return 255; /* normal end */
  6476. }
  6477. return 254; /* error */
  6478. }
  6479. static int
  6480. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6481. {
  6482. int i;
  6483. unsigned char a, b, c, d;
  6484. *dst_len = 0;
  6485. for (i = 0; i < src_len; i += 4) {
  6486. a = b64reverse(src[i]);
  6487. if (a >= 254) {
  6488. return i;
  6489. }
  6490. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6491. if (b >= 254) {
  6492. return i + 1;
  6493. }
  6494. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6495. if (c == 254) {
  6496. return i + 2;
  6497. }
  6498. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6499. if (d == 254) {
  6500. return i + 3;
  6501. }
  6502. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6503. if (c != 255) {
  6504. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6505. if (d != 255) {
  6506. dst[(*dst_len)++] = (c << 6) + d;
  6507. }
  6508. }
  6509. }
  6510. return -1;
  6511. }
  6512. #endif
  6513. static int
  6514. is_put_or_delete_method(const struct mg_connection *conn)
  6515. {
  6516. if (conn) {
  6517. const char *s = conn->request_info.request_method;
  6518. return (s != NULL)
  6519. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6520. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6521. }
  6522. return 0;
  6523. }
  6524. #if !defined(NO_FILES)
  6525. static int
  6526. extention_matches_script(
  6527. struct mg_connection *conn, /* in: request (must be valid) */
  6528. const char *filename /* in: filename (must be valid) */
  6529. )
  6530. {
  6531. #if !defined(NO_CGI)
  6532. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6533. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6534. filename)
  6535. > 0) {
  6536. return 1;
  6537. }
  6538. #endif
  6539. #if defined(USE_LUA)
  6540. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6541. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6542. filename)
  6543. > 0) {
  6544. return 1;
  6545. }
  6546. #endif
  6547. #if defined(USE_DUKTAPE)
  6548. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6549. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6550. filename)
  6551. > 0) {
  6552. return 1;
  6553. }
  6554. #endif
  6555. /* filename and conn could be unused, if all preocessor conditions
  6556. * are false (no script language supported). */
  6557. (void)filename;
  6558. (void)conn;
  6559. return 0;
  6560. }
  6561. /* For given directory path, substitute it to valid index file.
  6562. * Return 1 if index file has been found, 0 if not found.
  6563. * If the file is found, it's stats is returned in stp. */
  6564. static int
  6565. substitute_index_file(struct mg_connection *conn,
  6566. char *path,
  6567. size_t path_len,
  6568. struct mg_file_stat *filestat)
  6569. {
  6570. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6571. struct vec filename_vec;
  6572. size_t n = strlen(path);
  6573. int found = 0;
  6574. /* The 'path' given to us points to the directory. Remove all trailing
  6575. * directory separator characters from the end of the path, and
  6576. * then append single directory separator character. */
  6577. while ((n > 0) && (path[n - 1] == '/')) {
  6578. n--;
  6579. }
  6580. path[n] = '/';
  6581. /* Traverse index files list. For each entry, append it to the given
  6582. * path and see if the file exists. If it exists, break the loop */
  6583. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6584. /* Ignore too long entries that may overflow path buffer */
  6585. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6586. continue;
  6587. }
  6588. /* Prepare full path to the index file */
  6589. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6590. /* Does it exist? */
  6591. if (mg_stat(conn, path, filestat)) {
  6592. /* Yes it does, break the loop */
  6593. found = 1;
  6594. break;
  6595. }
  6596. }
  6597. /* If no index file exists, restore directory path */
  6598. if (!found) {
  6599. path[n] = '\0';
  6600. }
  6601. return found;
  6602. }
  6603. #endif
  6604. static void
  6605. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6606. char *filename, /* out: filename */
  6607. size_t filename_buf_len, /* in: size of filename buffer */
  6608. struct mg_file_stat *filestat, /* out: file status structure */
  6609. int *is_found, /* out: file found (directly) */
  6610. int *is_script_resource, /* out: handled by a script? */
  6611. int *is_websocket_request, /* out: websocket connetion? */
  6612. int *is_put_or_delete_request /* out: put/delete a file? */
  6613. )
  6614. {
  6615. char const *accept_encoding;
  6616. #if !defined(NO_FILES)
  6617. const char *uri = conn->request_info.local_uri;
  6618. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6619. const char *rewrite;
  6620. struct vec a, b;
  6621. ptrdiff_t match_len;
  6622. char gz_path[PATH_MAX];
  6623. int truncated;
  6624. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6625. char *tmp_str;
  6626. size_t tmp_str_len, sep_pos;
  6627. int allow_substitute_script_subresources;
  6628. #endif
  6629. #else
  6630. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6631. #endif
  6632. /* Step 1: Set all initially unknown outputs to zero */
  6633. memset(filestat, 0, sizeof(*filestat));
  6634. *filename = 0;
  6635. *is_found = 0;
  6636. *is_script_resource = 0;
  6637. /* Step 2: Check if the request attempts to modify the file system */
  6638. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6639. /* Step 3: Check if it is a websocket request, and modify the document
  6640. * root if required */
  6641. #if defined(USE_WEBSOCKET)
  6642. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6643. #if !defined(NO_FILES)
  6644. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6645. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6646. }
  6647. #endif /* !NO_FILES */
  6648. #else /* USE_WEBSOCKET */
  6649. *is_websocket_request = 0;
  6650. #endif /* USE_WEBSOCKET */
  6651. /* Step 4: Check if gzip encoded response is allowed */
  6652. conn->accept_gzip = 0;
  6653. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6654. if (strstr(accept_encoding, "gzip") != NULL) {
  6655. conn->accept_gzip = 1;
  6656. }
  6657. }
  6658. #if !defined(NO_FILES)
  6659. /* Step 5: If there is no root directory, don't look for files. */
  6660. /* Note that root == NULL is a regular use case here. This occurs,
  6661. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6662. * config is not required. */
  6663. if (root == NULL) {
  6664. /* all file related outputs have already been set to 0, just return
  6665. */
  6666. return;
  6667. }
  6668. /* Step 6: Determine the local file path from the root path and the
  6669. * request uri. */
  6670. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6671. * part of the path one byte on the right. */
  6672. mg_snprintf(
  6673. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6674. if (truncated) {
  6675. goto interpret_cleanup;
  6676. }
  6677. /* Step 7: URI rewriting */
  6678. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6679. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6680. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6681. mg_snprintf(conn,
  6682. &truncated,
  6683. filename,
  6684. filename_buf_len - 1,
  6685. "%.*s%s",
  6686. (int)b.len,
  6687. b.ptr,
  6688. uri + match_len);
  6689. break;
  6690. }
  6691. }
  6692. if (truncated) {
  6693. goto interpret_cleanup;
  6694. }
  6695. /* Step 8: Check if the file exists at the server */
  6696. /* Local file path and name, corresponding to requested URI
  6697. * is now stored in "filename" variable. */
  6698. if (mg_stat(conn, filename, filestat)) {
  6699. int uri_len = (int)strlen(uri);
  6700. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6701. /* 8.1: File exists. */
  6702. *is_found = 1;
  6703. /* 8.2: Check if it is a script type. */
  6704. if (extention_matches_script(conn, filename)) {
  6705. /* The request addresses a CGI resource, Lua script or
  6706. * server-side javascript.
  6707. * The URI corresponds to the script itself (like
  6708. * /path/script.cgi), and there is no additional resource
  6709. * path (like /path/script.cgi/something).
  6710. * Requests that modify (replace or delete) a resource, like
  6711. * PUT and DELETE requests, should replace/delete the script
  6712. * file.
  6713. * Requests that read or write from/to a resource, like GET and
  6714. * POST requests, should call the script and return the
  6715. * generated response. */
  6716. *is_script_resource = (!*is_put_or_delete_request);
  6717. }
  6718. /* 8.3: If the request target is a directory, there could be
  6719. * a substitute file (index.html, index.cgi, ...). */
  6720. if (filestat->is_directory && is_uri_end_slash) {
  6721. /* Use a local copy here, since substitute_index_file will
  6722. * change the content of the file status */
  6723. struct mg_file_stat tmp_filestat;
  6724. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6725. if (substitute_index_file(
  6726. conn, filename, filename_buf_len, &tmp_filestat)) {
  6727. /* Substitute file found. Copy stat to the output, then
  6728. * check if the file is a script file */
  6729. *filestat = tmp_filestat;
  6730. if (extention_matches_script(conn, filename)) {
  6731. /* Substitute file is a script file */
  6732. *is_script_resource = 1;
  6733. } else {
  6734. /* Substitute file is a regular file */
  6735. *is_script_resource = 0;
  6736. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6737. }
  6738. }
  6739. /* If there is no substitute file, the server could return
  6740. * a directory listing in a later step */
  6741. }
  6742. return;
  6743. }
  6744. /* Step 9: Check for zipped files: */
  6745. /* If we can't find the actual file, look for the file
  6746. * with the same name but a .gz extension. If we find it,
  6747. * use that and set the gzipped flag in the file struct
  6748. * to indicate that the response need to have the content-
  6749. * encoding: gzip header.
  6750. * We can only do this if the browser declares support. */
  6751. if (conn->accept_gzip) {
  6752. mg_snprintf(
  6753. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6754. if (truncated) {
  6755. goto interpret_cleanup;
  6756. }
  6757. if (mg_stat(conn, gz_path, filestat)) {
  6758. if (filestat) {
  6759. filestat->is_gzipped = 1;
  6760. *is_found = 1;
  6761. }
  6762. /* Currently gz files can not be scripts. */
  6763. return;
  6764. }
  6765. }
  6766. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6767. /* Step 10: Script resources may handle sub-resources */
  6768. /* Support PATH_INFO for CGI scripts. */
  6769. tmp_str_len = strlen(filename);
  6770. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6771. if (!tmp_str) {
  6772. /* Out of memory */
  6773. goto interpret_cleanup;
  6774. }
  6775. memcpy(tmp_str, filename, tmp_str_len + 1);
  6776. /* Check config, if index scripts may have sub-resources */
  6777. allow_substitute_script_subresources =
  6778. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6779. "yes");
  6780. sep_pos = tmp_str_len;
  6781. while (sep_pos > 0) {
  6782. sep_pos--;
  6783. if (tmp_str[sep_pos] == '/') {
  6784. int is_script = 0, does_exist = 0;
  6785. tmp_str[sep_pos] = 0;
  6786. if (tmp_str[0]) {
  6787. is_script = extention_matches_script(conn, tmp_str);
  6788. does_exist = mg_stat(conn, tmp_str, filestat);
  6789. }
  6790. if (does_exist && is_script) {
  6791. filename[sep_pos] = 0;
  6792. memmove(filename + sep_pos + 2,
  6793. filename + sep_pos + 1,
  6794. strlen(filename + sep_pos + 1) + 1);
  6795. conn->path_info = filename + sep_pos + 1;
  6796. filename[sep_pos + 1] = '/';
  6797. *is_script_resource = 1;
  6798. *is_found = 1;
  6799. break;
  6800. }
  6801. if (allow_substitute_script_subresources) {
  6802. if (substitute_index_file(
  6803. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6804. /* some intermediate directory has an index file */
  6805. if (extention_matches_script(conn, tmp_str)) {
  6806. DEBUG_TRACE("Substitute script %s serving path %s",
  6807. tmp_str,
  6808. filename);
  6809. /* this index file is a script */
  6810. mg_snprintf(conn,
  6811. &truncated,
  6812. filename,
  6813. filename_buf_len,
  6814. "%s//%s",
  6815. tmp_str,
  6816. filename + sep_pos + 1);
  6817. if (truncated) {
  6818. mg_free(tmp_str);
  6819. goto interpret_cleanup;
  6820. }
  6821. sep_pos = strlen(tmp_str);
  6822. filename[sep_pos] = 0;
  6823. conn->path_info = filename + sep_pos + 1;
  6824. *is_script_resource = 1;
  6825. *is_found = 1;
  6826. break;
  6827. } else {
  6828. DEBUG_TRACE("Substitute file %s serving path %s",
  6829. tmp_str,
  6830. filename);
  6831. /* non-script files will not have sub-resources */
  6832. filename[sep_pos] = 0;
  6833. conn->path_info = 0;
  6834. *is_script_resource = 0;
  6835. *is_found = 0;
  6836. break;
  6837. }
  6838. }
  6839. }
  6840. tmp_str[sep_pos] = '/';
  6841. }
  6842. }
  6843. mg_free(tmp_str);
  6844. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6845. #endif /* !defined(NO_FILES) */
  6846. return;
  6847. #if !defined(NO_FILES)
  6848. /* Reset all outputs */
  6849. interpret_cleanup:
  6850. memset(filestat, 0, sizeof(*filestat));
  6851. *filename = 0;
  6852. *is_found = 0;
  6853. *is_script_resource = 0;
  6854. *is_websocket_request = 0;
  6855. *is_put_or_delete_request = 0;
  6856. #endif /* !defined(NO_FILES) */
  6857. }
  6858. /* Check whether full request is buffered. Return:
  6859. * -1 if request or response is malformed
  6860. * 0 if request or response is not yet fully buffered
  6861. * >0 actual request length, including last \r\n\r\n */
  6862. static int
  6863. get_http_header_len(const char *buf, int buflen)
  6864. {
  6865. int i;
  6866. for (i = 0; i < buflen; i++) {
  6867. /* Do an unsigned comparison in some conditions below */
  6868. const unsigned char c = (unsigned char)buf[i];
  6869. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6870. && !isprint(c)) {
  6871. /* abort scan as soon as one malformed character is found */
  6872. return -1;
  6873. }
  6874. if (i < buflen - 1) {
  6875. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6876. /* Two newline, no carriage return - not standard compliant,
  6877. * but it should be accepted */
  6878. return i + 2;
  6879. }
  6880. }
  6881. if (i < buflen - 3) {
  6882. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6883. && (buf[i + 3] == '\n')) {
  6884. /* Two \r\n - standard compliant */
  6885. return i + 4;
  6886. }
  6887. }
  6888. }
  6889. return 0;
  6890. }
  6891. #if !defined(NO_CACHING)
  6892. /* Convert month to the month number. Return -1 on error, or month number */
  6893. static int
  6894. get_month_index(const char *s)
  6895. {
  6896. size_t i;
  6897. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6898. if (!strcmp(s, month_names[i])) {
  6899. return (int)i;
  6900. }
  6901. }
  6902. return -1;
  6903. }
  6904. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6905. static time_t
  6906. parse_date_string(const char *datetime)
  6907. {
  6908. char month_str[32] = {0};
  6909. int second, minute, hour, day, month, year;
  6910. time_t result = (time_t)0;
  6911. struct tm tm;
  6912. if ((sscanf(datetime,
  6913. "%d/%3s/%d %d:%d:%d",
  6914. &day,
  6915. month_str,
  6916. &year,
  6917. &hour,
  6918. &minute,
  6919. &second)
  6920. == 6)
  6921. || (sscanf(datetime,
  6922. "%d %3s %d %d:%d:%d",
  6923. &day,
  6924. month_str,
  6925. &year,
  6926. &hour,
  6927. &minute,
  6928. &second)
  6929. == 6)
  6930. || (sscanf(datetime,
  6931. "%*3s, %d %3s %d %d:%d:%d",
  6932. &day,
  6933. month_str,
  6934. &year,
  6935. &hour,
  6936. &minute,
  6937. &second)
  6938. == 6)
  6939. || (sscanf(datetime,
  6940. "%d-%3s-%d %d:%d:%d",
  6941. &day,
  6942. month_str,
  6943. &year,
  6944. &hour,
  6945. &minute,
  6946. &second)
  6947. == 6)) {
  6948. month = get_month_index(month_str);
  6949. if ((month >= 0) && (year >= 1970)) {
  6950. memset(&tm, 0, sizeof(tm));
  6951. tm.tm_year = year - 1900;
  6952. tm.tm_mon = month;
  6953. tm.tm_mday = day;
  6954. tm.tm_hour = hour;
  6955. tm.tm_min = minute;
  6956. tm.tm_sec = second;
  6957. result = timegm(&tm);
  6958. }
  6959. }
  6960. return result;
  6961. }
  6962. #endif /* !NO_CACHING */
  6963. /* Pre-process URIs according to RFC + protect against directory disclosure
  6964. * attacks by removing '..', excessive '/' and '\' characters */
  6965. static void
  6966. remove_dot_segments(char *inout)
  6967. {
  6968. /* Windows backend protection
  6969. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6970. * in URI by slash */
  6971. char *out_end = inout;
  6972. char *in = inout;
  6973. if (!in) {
  6974. /* Param error. */
  6975. return;
  6976. }
  6977. while (*in) {
  6978. if (*in == '\\') {
  6979. *in = '/';
  6980. }
  6981. in++;
  6982. }
  6983. /* Algorithm "remove_dot_segments" from
  6984. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6985. /* Step 1:
  6986. * The input buffer is initialized.
  6987. * The output buffer is initialized to the empty string.
  6988. */
  6989. in = inout;
  6990. /* Step 2:
  6991. * While the input buffer is not empty, loop as follows:
  6992. */
  6993. /* Less than out_end of the inout buffer is used as output, so keep
  6994. * condition: out_end <= in */
  6995. while (*in) {
  6996. /* Step 2a:
  6997. * If the input buffer begins with a prefix of "../" or "./",
  6998. * then remove that prefix from the input buffer;
  6999. */
  7000. if (!strncmp(in, "../", 3)) {
  7001. in += 3;
  7002. } else if (!strncmp(in, "./", 2)) {
  7003. in += 2;
  7004. }
  7005. /* otherwise */
  7006. /* Step 2b:
  7007. * if the input buffer begins with a prefix of "/./" or "/.",
  7008. * where "." is a complete path segment, then replace that
  7009. * prefix with "/" in the input buffer;
  7010. */
  7011. else if (!strncmp(in, "/./", 3)) {
  7012. in += 2;
  7013. } else if (!strcmp(in, "/.")) {
  7014. in[1] = 0;
  7015. }
  7016. /* otherwise */
  7017. /* Step 2c:
  7018. * if the input buffer begins with a prefix of "/../" or "/..",
  7019. * where ".." is a complete path segment, then replace that
  7020. * prefix with "/" in the input buffer and remove the last
  7021. * segment and its preceding "/" (if any) from the output
  7022. * buffer;
  7023. */
  7024. else if (!strncmp(in, "/../", 4)) {
  7025. in += 3;
  7026. if (inout != out_end) {
  7027. /* remove last segment */
  7028. do {
  7029. out_end--;
  7030. } while ((inout != out_end) && (*out_end != '/'));
  7031. }
  7032. } else if (!strcmp(in, "/..")) {
  7033. in[1] = 0;
  7034. if (inout != out_end) {
  7035. /* remove last segment */
  7036. do {
  7037. out_end--;
  7038. } while ((inout != out_end) && (*out_end != '/'));
  7039. }
  7040. }
  7041. /* otherwise */
  7042. /* Step 2d:
  7043. * if the input buffer consists only of "." or "..", then remove
  7044. * that from the input buffer;
  7045. */
  7046. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7047. *in = 0;
  7048. }
  7049. /* otherwise */
  7050. /* Step 2e:
  7051. * move the first path segment in the input buffer to the end of
  7052. * the output buffer, including the initial "/" character (if
  7053. * any) and any subsequent characters up to, but not including,
  7054. * the next "/" character or the end of the input buffer.
  7055. */
  7056. else {
  7057. do {
  7058. *out_end = *in;
  7059. out_end++;
  7060. in++;
  7061. } while ((*in != 0) && (*in != '/'));
  7062. }
  7063. }
  7064. /* Step 3:
  7065. * Finally, the output buffer is returned as the result of
  7066. * remove_dot_segments.
  7067. */
  7068. /* Terminate output */
  7069. *out_end = 0;
  7070. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7071. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7072. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7073. * or "//" anymore.
  7074. */
  7075. out_end = in = inout;
  7076. while (*in) {
  7077. if (*in == '.') {
  7078. /* remove . at the end or preceding of / */
  7079. char *in_ahead = in;
  7080. do {
  7081. in_ahead++;
  7082. } while (*in_ahead == '.');
  7083. if (*in_ahead == '/') {
  7084. in = in_ahead;
  7085. if ((out_end != inout) && (out_end[-1] == '/')) {
  7086. /* remove generated // */
  7087. out_end--;
  7088. }
  7089. } else if (*in_ahead == 0) {
  7090. in = in_ahead;
  7091. } else {
  7092. do {
  7093. *out_end++ = '.';
  7094. in++;
  7095. } while (in != in_ahead);
  7096. }
  7097. } else if (*in == '/') {
  7098. /* replace // by / */
  7099. *out_end++ = '/';
  7100. do {
  7101. in++;
  7102. } while (*in == '/');
  7103. } else {
  7104. *out_end++ = *in;
  7105. in++;
  7106. }
  7107. }
  7108. *out_end = 0;
  7109. }
  7110. static const struct {
  7111. const char *extension;
  7112. size_t ext_len;
  7113. const char *mime_type;
  7114. } builtin_mime_types[] = {
  7115. /* IANA registered MIME types
  7116. * (http://www.iana.org/assignments/media-types)
  7117. * application types */
  7118. {".doc", 4, "application/msword"},
  7119. {".eps", 4, "application/postscript"},
  7120. {".exe", 4, "application/octet-stream"},
  7121. {".js", 3, "application/javascript"},
  7122. {".json", 5, "application/json"},
  7123. {".pdf", 4, "application/pdf"},
  7124. {".ps", 3, "application/postscript"},
  7125. {".rtf", 4, "application/rtf"},
  7126. {".xhtml", 6, "application/xhtml+xml"},
  7127. {".xsl", 4, "application/xml"},
  7128. {".xslt", 5, "application/xml"},
  7129. /* fonts */
  7130. {".ttf", 4, "application/font-sfnt"},
  7131. {".cff", 4, "application/font-sfnt"},
  7132. {".otf", 4, "application/font-sfnt"},
  7133. {".aat", 4, "application/font-sfnt"},
  7134. {".sil", 4, "application/font-sfnt"},
  7135. {".pfr", 4, "application/font-tdpfr"},
  7136. {".woff", 5, "application/font-woff"},
  7137. /* audio */
  7138. {".mp3", 4, "audio/mpeg"},
  7139. {".oga", 4, "audio/ogg"},
  7140. {".ogg", 4, "audio/ogg"},
  7141. /* image */
  7142. {".gif", 4, "image/gif"},
  7143. {".ief", 4, "image/ief"},
  7144. {".jpeg", 5, "image/jpeg"},
  7145. {".jpg", 4, "image/jpeg"},
  7146. {".jpm", 4, "image/jpm"},
  7147. {".jpx", 4, "image/jpx"},
  7148. {".png", 4, "image/png"},
  7149. {".svg", 4, "image/svg+xml"},
  7150. {".tif", 4, "image/tiff"},
  7151. {".tiff", 5, "image/tiff"},
  7152. /* model */
  7153. {".wrl", 4, "model/vrml"},
  7154. /* text */
  7155. {".css", 4, "text/css"},
  7156. {".csv", 4, "text/csv"},
  7157. {".htm", 4, "text/html"},
  7158. {".html", 5, "text/html"},
  7159. {".sgm", 4, "text/sgml"},
  7160. {".shtm", 5, "text/html"},
  7161. {".shtml", 6, "text/html"},
  7162. {".txt", 4, "text/plain"},
  7163. {".xml", 4, "text/xml"},
  7164. /* video */
  7165. {".mov", 4, "video/quicktime"},
  7166. {".mp4", 4, "video/mp4"},
  7167. {".mpeg", 5, "video/mpeg"},
  7168. {".mpg", 4, "video/mpeg"},
  7169. {".ogv", 4, "video/ogg"},
  7170. {".qt", 3, "video/quicktime"},
  7171. /* not registered types
  7172. * (http://reference.sitepoint.com/html/mime-types-full,
  7173. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7174. {".arj", 4, "application/x-arj-compressed"},
  7175. {".gz", 3, "application/x-gunzip"},
  7176. {".rar", 4, "application/x-arj-compressed"},
  7177. {".swf", 4, "application/x-shockwave-flash"},
  7178. {".tar", 4, "application/x-tar"},
  7179. {".tgz", 4, "application/x-tar-gz"},
  7180. {".torrent", 8, "application/x-bittorrent"},
  7181. {".ppt", 4, "application/x-mspowerpoint"},
  7182. {".xls", 4, "application/x-msexcel"},
  7183. {".zip", 4, "application/x-zip-compressed"},
  7184. {".aac",
  7185. 4,
  7186. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7187. {".aif", 4, "audio/x-aif"},
  7188. {".m3u", 4, "audio/x-mpegurl"},
  7189. {".mid", 4, "audio/x-midi"},
  7190. {".ra", 3, "audio/x-pn-realaudio"},
  7191. {".ram", 4, "audio/x-pn-realaudio"},
  7192. {".wav", 4, "audio/x-wav"},
  7193. {".bmp", 4, "image/bmp"},
  7194. {".ico", 4, "image/x-icon"},
  7195. {".pct", 4, "image/x-pct"},
  7196. {".pict", 5, "image/pict"},
  7197. {".rgb", 4, "image/x-rgb"},
  7198. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7199. {".asf", 4, "video/x-ms-asf"},
  7200. {".avi", 4, "video/x-msvideo"},
  7201. {".m4v", 4, "video/x-m4v"},
  7202. {NULL, 0, NULL}};
  7203. const char *
  7204. mg_get_builtin_mime_type(const char *path)
  7205. {
  7206. const char *ext;
  7207. size_t i, path_len;
  7208. path_len = strlen(path);
  7209. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7210. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7211. if ((path_len > builtin_mime_types[i].ext_len)
  7212. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7213. return builtin_mime_types[i].mime_type;
  7214. }
  7215. }
  7216. return "text/plain";
  7217. }
  7218. /* Look at the "path" extension and figure what mime type it has.
  7219. * Store mime type in the vector. */
  7220. static void
  7221. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7222. {
  7223. struct vec ext_vec, mime_vec;
  7224. const char *list, *ext;
  7225. size_t path_len;
  7226. path_len = strlen(path);
  7227. if ((conn == NULL) || (vec == NULL)) {
  7228. if (vec != NULL) {
  7229. memset(vec, '\0', sizeof(struct vec));
  7230. }
  7231. return;
  7232. }
  7233. /* Scan user-defined mime types first, in case user wants to
  7234. * override default mime types. */
  7235. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7236. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7237. /* ext now points to the path suffix */
  7238. ext = path + path_len - ext_vec.len;
  7239. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7240. *vec = mime_vec;
  7241. return;
  7242. }
  7243. }
  7244. vec->ptr = mg_get_builtin_mime_type(path);
  7245. vec->len = strlen(vec->ptr);
  7246. }
  7247. /* Stringify binary data. Output buffer must be twice as big as input,
  7248. * because each byte takes 2 bytes in string representation */
  7249. static void
  7250. bin2str(char *to, const unsigned char *p, size_t len)
  7251. {
  7252. static const char *hex = "0123456789abcdef";
  7253. for (; len--; p++) {
  7254. *to++ = hex[p[0] >> 4];
  7255. *to++ = hex[p[0] & 0x0f];
  7256. }
  7257. *to = '\0';
  7258. }
  7259. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7260. */
  7261. char *
  7262. mg_md5(char buf[33], ...)
  7263. {
  7264. md5_byte_t hash[16];
  7265. const char *p;
  7266. va_list ap;
  7267. md5_state_t ctx;
  7268. md5_init(&ctx);
  7269. va_start(ap, buf);
  7270. while ((p = va_arg(ap, const char *)) != NULL) {
  7271. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7272. }
  7273. va_end(ap);
  7274. md5_finish(&ctx, hash);
  7275. bin2str(buf, hash, sizeof(hash));
  7276. return buf;
  7277. }
  7278. /* Check the user's password, return 1 if OK */
  7279. static int
  7280. check_password(const char *method,
  7281. const char *ha1,
  7282. const char *uri,
  7283. const char *nonce,
  7284. const char *nc,
  7285. const char *cnonce,
  7286. const char *qop,
  7287. const char *response)
  7288. {
  7289. char ha2[32 + 1], expected_response[32 + 1];
  7290. /* Some of the parameters may be NULL */
  7291. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7292. || (qop == NULL) || (response == NULL)) {
  7293. return 0;
  7294. }
  7295. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7296. if (strlen(response) != 32) {
  7297. return 0;
  7298. }
  7299. mg_md5(ha2, method, ":", uri, NULL);
  7300. mg_md5(expected_response,
  7301. ha1,
  7302. ":",
  7303. nonce,
  7304. ":",
  7305. nc,
  7306. ":",
  7307. cnonce,
  7308. ":",
  7309. qop,
  7310. ":",
  7311. ha2,
  7312. NULL);
  7313. return mg_strcasecmp(response, expected_response) == 0;
  7314. }
  7315. #if !defined(NO_FILESYSTEMS)
  7316. /* Use the global passwords file, if specified by auth_gpass option,
  7317. * or search for .htpasswd in the requested directory. */
  7318. static void
  7319. open_auth_file(struct mg_connection *conn,
  7320. const char *path,
  7321. struct mg_file *filep)
  7322. {
  7323. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7324. char name[PATH_MAX];
  7325. const char *p, *e,
  7326. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7327. int truncated;
  7328. if (gpass != NULL) {
  7329. /* Use global passwords file */
  7330. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7331. #if defined(DEBUG)
  7332. /* Use mg_cry_internal here, since gpass has been
  7333. * configured. */
  7334. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7335. #endif
  7336. }
  7337. /* Important: using local struct mg_file to test path for
  7338. * is_directory flag. If filep is used, mg_stat() makes it
  7339. * appear as if auth file was opened.
  7340. * TODO(mid): Check if this is still required after rewriting
  7341. * mg_stat */
  7342. } else if (mg_stat(conn, path, &filep->stat)
  7343. && filep->stat.is_directory) {
  7344. mg_snprintf(conn,
  7345. &truncated,
  7346. name,
  7347. sizeof(name),
  7348. "%s/%s",
  7349. path,
  7350. PASSWORDS_FILE_NAME);
  7351. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7352. #if defined(DEBUG)
  7353. /* Don't use mg_cry_internal here, but only a trace, since
  7354. * this is a typical case. It will occur for every directory
  7355. * without a password file. */
  7356. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7357. #endif
  7358. }
  7359. } else {
  7360. /* Try to find .htpasswd in requested directory. */
  7361. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7362. if (e[0] == '/') {
  7363. break;
  7364. }
  7365. }
  7366. mg_snprintf(conn,
  7367. &truncated,
  7368. name,
  7369. sizeof(name),
  7370. "%.*s/%s",
  7371. (int)(e - p),
  7372. p,
  7373. PASSWORDS_FILE_NAME);
  7374. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7375. #if defined(DEBUG)
  7376. /* Don't use mg_cry_internal here, but only a trace, since
  7377. * this is a typical case. It will occur for every directory
  7378. * without a password file. */
  7379. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7380. #endif
  7381. }
  7382. }
  7383. }
  7384. }
  7385. #endif /* NO_FILESYSTEMS */
  7386. /* Parsed Authorization header */
  7387. struct ah {
  7388. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7389. };
  7390. /* Return 1 on success. Always initializes the ah structure. */
  7391. static int
  7392. parse_auth_header(struct mg_connection *conn,
  7393. char *buf,
  7394. size_t buf_size,
  7395. struct ah *ah)
  7396. {
  7397. char *name, *value, *s;
  7398. const char *auth_header;
  7399. uint64_t nonce;
  7400. if (!ah || !conn) {
  7401. return 0;
  7402. }
  7403. (void)memset(ah, 0, sizeof(*ah));
  7404. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7405. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7406. return 0;
  7407. }
  7408. /* Make modifiable copy of the auth header */
  7409. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7410. s = buf;
  7411. /* Parse authorization header */
  7412. for (;;) {
  7413. /* Gobble initial spaces */
  7414. while (isspace((unsigned char)*s)) {
  7415. s++;
  7416. }
  7417. name = skip_quoted(&s, "=", " ", 0);
  7418. /* Value is either quote-delimited, or ends at first comma or space.
  7419. */
  7420. if (s[0] == '\"') {
  7421. s++;
  7422. value = skip_quoted(&s, "\"", " ", '\\');
  7423. if (s[0] == ',') {
  7424. s++;
  7425. }
  7426. } else {
  7427. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7428. * uses spaces */
  7429. }
  7430. if (*name == '\0') {
  7431. break;
  7432. }
  7433. if (!strcmp(name, "username")) {
  7434. ah->user = value;
  7435. } else if (!strcmp(name, "cnonce")) {
  7436. ah->cnonce = value;
  7437. } else if (!strcmp(name, "response")) {
  7438. ah->response = value;
  7439. } else if (!strcmp(name, "uri")) {
  7440. ah->uri = value;
  7441. } else if (!strcmp(name, "qop")) {
  7442. ah->qop = value;
  7443. } else if (!strcmp(name, "nc")) {
  7444. ah->nc = value;
  7445. } else if (!strcmp(name, "nonce")) {
  7446. ah->nonce = value;
  7447. }
  7448. }
  7449. #if !defined(NO_NONCE_CHECK)
  7450. /* Read the nonce from the response. */
  7451. if (ah->nonce == NULL) {
  7452. return 0;
  7453. }
  7454. s = NULL;
  7455. nonce = strtoull(ah->nonce, &s, 10);
  7456. if ((s == NULL) || (*s != 0)) {
  7457. return 0;
  7458. }
  7459. /* Convert the nonce from the client to a number. */
  7460. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7461. /* The converted number corresponds to the time the nounce has been
  7462. * created. This should not be earlier than the server start. */
  7463. /* Server side nonce check is valuable in all situations but one:
  7464. * if the server restarts frequently, but the client should not see
  7465. * that, so the server should accept nonces from previous starts. */
  7466. /* However, the reasonable default is to not accept a nonce from a
  7467. * previous start, so if anyone changed the access rights between
  7468. * two restarts, a new login is required. */
  7469. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7470. /* nonce is from a previous start of the server and no longer valid
  7471. * (replay attack?) */
  7472. return 0;
  7473. }
  7474. /* Check if the nonce is too high, so it has not (yet) been used by the
  7475. * server. */
  7476. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7477. + conn->dom_ctx->nonce_count)) {
  7478. return 0;
  7479. }
  7480. #else
  7481. (void)nonce;
  7482. #endif
  7483. /* CGI needs it as REMOTE_USER */
  7484. if (ah->user != NULL) {
  7485. conn->request_info.remote_user =
  7486. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7487. } else {
  7488. return 0;
  7489. }
  7490. return 1;
  7491. }
  7492. static const char *
  7493. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7494. {
  7495. #if defined(MG_USE_OPEN_FILE)
  7496. const char *eof;
  7497. size_t len;
  7498. const char *memend;
  7499. #else
  7500. (void)p; /* parameter is unused */
  7501. #endif
  7502. if (!filep) {
  7503. return NULL;
  7504. }
  7505. #if defined(MG_USE_OPEN_FILE)
  7506. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7507. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7508. /* Search for \n from p till the end of stream */
  7509. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7510. if (eof != NULL) {
  7511. eof += 1; /* Include \n */
  7512. } else {
  7513. eof = memend; /* Copy remaining data */
  7514. }
  7515. len =
  7516. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7517. memcpy(buf, *p, len);
  7518. buf[len] = '\0';
  7519. *p += len;
  7520. return len ? eof : NULL;
  7521. } else /* filep->access.fp block below */
  7522. #endif
  7523. if (filep->access.fp != NULL) {
  7524. return fgets(buf, (int)size, filep->access.fp);
  7525. } else {
  7526. return NULL;
  7527. }
  7528. }
  7529. /* Define the initial recursion depth for procesesing htpasswd files that
  7530. * include other htpasswd
  7531. * (or even the same) files. It is not difficult to provide a file or files
  7532. * s.t. they force civetweb
  7533. * to infinitely recurse and then crash.
  7534. */
  7535. #define INITIAL_DEPTH 9
  7536. #if INITIAL_DEPTH <= 0
  7537. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7538. #endif
  7539. #if !defined(NO_FILESYSTEMS)
  7540. struct read_auth_file_struct {
  7541. struct mg_connection *conn;
  7542. struct ah ah;
  7543. const char *domain;
  7544. char buf[256 + 256 + 40];
  7545. const char *f_user;
  7546. const char *f_domain;
  7547. const char *f_ha1;
  7548. };
  7549. static int
  7550. read_auth_file(struct mg_file *filep,
  7551. struct read_auth_file_struct *workdata,
  7552. int depth)
  7553. {
  7554. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7555. int is_authorized = 0;
  7556. struct mg_file fp;
  7557. size_t l;
  7558. if (!filep || !workdata || (0 == depth)) {
  7559. return 0;
  7560. }
  7561. /* Loop over passwords file */
  7562. #if defined(MG_USE_OPEN_FILE)
  7563. p = (char *)filep->access.membuf;
  7564. #endif
  7565. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7566. l = strlen(workdata->buf);
  7567. while (l > 0) {
  7568. if (isspace((unsigned char)workdata->buf[l - 1])
  7569. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7570. l--;
  7571. workdata->buf[l] = 0;
  7572. } else
  7573. break;
  7574. }
  7575. if (l < 1) {
  7576. continue;
  7577. }
  7578. workdata->f_user = workdata->buf;
  7579. if (workdata->f_user[0] == ':') {
  7580. /* user names may not contain a ':' and may not be empty,
  7581. * so lines starting with ':' may be used for a special purpose
  7582. */
  7583. if (workdata->f_user[1] == '#') {
  7584. /* :# is a comment */
  7585. continue;
  7586. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7587. if (mg_fopen(workdata->conn,
  7588. workdata->f_user + 9,
  7589. MG_FOPEN_MODE_READ,
  7590. &fp)) {
  7591. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7592. (void)mg_fclose(
  7593. &fp.access); /* ignore error on read only file */
  7594. /* No need to continue processing files once we have a
  7595. * match, since nothing will reset it back
  7596. * to 0.
  7597. */
  7598. if (is_authorized) {
  7599. return is_authorized;
  7600. }
  7601. } else {
  7602. mg_cry_internal(workdata->conn,
  7603. "%s: cannot open authorization file: %s",
  7604. __func__,
  7605. workdata->buf);
  7606. }
  7607. continue;
  7608. }
  7609. /* everything is invalid for the moment (might change in the
  7610. * future) */
  7611. mg_cry_internal(workdata->conn,
  7612. "%s: syntax error in authorization file: %s",
  7613. __func__,
  7614. workdata->buf);
  7615. continue;
  7616. }
  7617. workdata->f_domain = strchr(workdata->f_user, ':');
  7618. if (workdata->f_domain == NULL) {
  7619. mg_cry_internal(workdata->conn,
  7620. "%s: syntax error in authorization file: %s",
  7621. __func__,
  7622. workdata->buf);
  7623. continue;
  7624. }
  7625. *(char *)(workdata->f_domain) = 0;
  7626. (workdata->f_domain)++;
  7627. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7628. if (workdata->f_ha1 == NULL) {
  7629. mg_cry_internal(workdata->conn,
  7630. "%s: syntax error in authorization file: %s",
  7631. __func__,
  7632. workdata->buf);
  7633. continue;
  7634. }
  7635. *(char *)(workdata->f_ha1) = 0;
  7636. (workdata->f_ha1)++;
  7637. if (!strcmp(workdata->ah.user, workdata->f_user)
  7638. && !strcmp(workdata->domain, workdata->f_domain)) {
  7639. return check_password(workdata->conn->request_info.request_method,
  7640. workdata->f_ha1,
  7641. workdata->ah.uri,
  7642. workdata->ah.nonce,
  7643. workdata->ah.nc,
  7644. workdata->ah.cnonce,
  7645. workdata->ah.qop,
  7646. workdata->ah.response);
  7647. }
  7648. }
  7649. return is_authorized;
  7650. }
  7651. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7652. static int
  7653. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7654. {
  7655. struct read_auth_file_struct workdata;
  7656. char buf[MG_BUF_LEN];
  7657. if (!conn || !conn->dom_ctx) {
  7658. return 0;
  7659. }
  7660. memset(&workdata, 0, sizeof(workdata));
  7661. workdata.conn = conn;
  7662. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7663. return 0;
  7664. }
  7665. if (realm) {
  7666. workdata.domain = realm;
  7667. } else {
  7668. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7669. }
  7670. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7671. }
  7672. /* Public function to check http digest authentication header */
  7673. int
  7674. mg_check_digest_access_authentication(struct mg_connection *conn,
  7675. const char *realm,
  7676. const char *filename)
  7677. {
  7678. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7679. int auth;
  7680. if (!conn || !filename) {
  7681. return -1;
  7682. }
  7683. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7684. return -2;
  7685. }
  7686. auth = authorize(conn, &file, realm);
  7687. mg_fclose(&file.access);
  7688. return auth;
  7689. }
  7690. #endif /* NO_FILESYSTEMS */
  7691. /* Return 1 if request is authorised, 0 otherwise. */
  7692. static int
  7693. check_authorization(struct mg_connection *conn, const char *path)
  7694. {
  7695. #if !defined(NO_FILESYSTEMS)
  7696. char fname[PATH_MAX];
  7697. struct vec uri_vec, filename_vec;
  7698. const char *list;
  7699. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7700. int authorized = 1, truncated;
  7701. if (!conn || !conn->dom_ctx) {
  7702. return 0;
  7703. }
  7704. list = conn->dom_ctx->config[PROTECT_URI];
  7705. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7706. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7707. mg_snprintf(conn,
  7708. &truncated,
  7709. fname,
  7710. sizeof(fname),
  7711. "%.*s",
  7712. (int)filename_vec.len,
  7713. filename_vec.ptr);
  7714. if (truncated
  7715. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7716. mg_cry_internal(conn,
  7717. "%s: cannot open %s: %s",
  7718. __func__,
  7719. fname,
  7720. strerror(errno));
  7721. }
  7722. break;
  7723. }
  7724. }
  7725. if (!is_file_opened(&file.access)) {
  7726. open_auth_file(conn, path, &file);
  7727. }
  7728. if (is_file_opened(&file.access)) {
  7729. authorized = authorize(conn, &file, NULL);
  7730. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7731. }
  7732. return authorized;
  7733. #else
  7734. (void)conn;
  7735. (void)path;
  7736. return 1;
  7737. #endif /* NO_FILESYSTEMS */
  7738. }
  7739. /* Internal function. Assumes conn is valid */
  7740. static void
  7741. send_authorization_request(struct mg_connection *conn, const char *realm)
  7742. {
  7743. char date[64];
  7744. time_t curtime = time(NULL);
  7745. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7746. if (!realm) {
  7747. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7748. }
  7749. mg_lock_context(conn->phys_ctx);
  7750. nonce += conn->dom_ctx->nonce_count;
  7751. ++conn->dom_ctx->nonce_count;
  7752. mg_unlock_context(conn->phys_ctx);
  7753. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7754. conn->status_code = 401;
  7755. conn->must_close = 1;
  7756. gmt_time_string(date, sizeof(date), &curtime);
  7757. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7758. send_no_cache_header(conn);
  7759. send_additional_header(conn);
  7760. mg_printf(conn,
  7761. "Date: %s\r\n"
  7762. "Connection: %s\r\n"
  7763. "Content-Length: 0\r\n"
  7764. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7765. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7766. date,
  7767. suggest_connection_header(conn),
  7768. realm,
  7769. nonce);
  7770. }
  7771. /* Interface function. Parameters are provided by the user, so do
  7772. * at least some basic checks.
  7773. */
  7774. int
  7775. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7776. const char *realm)
  7777. {
  7778. if (conn && conn->dom_ctx) {
  7779. send_authorization_request(conn, realm);
  7780. return 0;
  7781. }
  7782. return -1;
  7783. }
  7784. #if !defined(NO_FILES)
  7785. static int
  7786. is_authorized_for_put(struct mg_connection *conn)
  7787. {
  7788. if (conn) {
  7789. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7790. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7791. int ret = 0;
  7792. if (passfile != NULL
  7793. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7794. ret = authorize(conn, &file, NULL);
  7795. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7796. }
  7797. return ret;
  7798. }
  7799. return 0;
  7800. }
  7801. #endif
  7802. int
  7803. mg_modify_passwords_file(const char *fname,
  7804. const char *domain,
  7805. const char *user,
  7806. const char *pass)
  7807. {
  7808. int found, i;
  7809. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7810. FILE *fp, *fp2;
  7811. found = 0;
  7812. fp = fp2 = NULL;
  7813. /* Regard empty password as no password - remove user record. */
  7814. if ((pass != NULL) && (pass[0] == '\0')) {
  7815. pass = NULL;
  7816. }
  7817. /* Other arguments must not be empty */
  7818. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7819. return 0;
  7820. }
  7821. /* Using the given file format, user name and domain must not contain
  7822. * ':'
  7823. */
  7824. if (strchr(user, ':') != NULL) {
  7825. return 0;
  7826. }
  7827. if (strchr(domain, ':') != NULL) {
  7828. return 0;
  7829. }
  7830. /* Do not allow control characters like newline in user name and domain.
  7831. * Do not allow excessively long names either. */
  7832. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7833. if (iscntrl((unsigned char)user[i])) {
  7834. return 0;
  7835. }
  7836. }
  7837. if (user[i]) {
  7838. return 0;
  7839. }
  7840. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7841. if (iscntrl((unsigned char)domain[i])) {
  7842. return 0;
  7843. }
  7844. }
  7845. if (domain[i]) {
  7846. return 0;
  7847. }
  7848. /* The maximum length of the path to the password file is limited */
  7849. if ((strlen(fname) + 4) >= PATH_MAX) {
  7850. return 0;
  7851. }
  7852. /* Create a temporary file name. Length has been checked before. */
  7853. strcpy(tmp, fname);
  7854. strcat(tmp, ".tmp");
  7855. /* Create the file if does not exist */
  7856. /* Use of fopen here is OK, since fname is only ASCII */
  7857. if ((fp = fopen(fname, "a+")) != NULL) {
  7858. (void)fclose(fp);
  7859. }
  7860. /* Open the given file and temporary file */
  7861. if ((fp = fopen(fname, "r")) == NULL) {
  7862. return 0;
  7863. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7864. fclose(fp);
  7865. return 0;
  7866. }
  7867. /* Copy the stuff to temporary file */
  7868. while (fgets(line, sizeof(line), fp) != NULL) {
  7869. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7870. continue;
  7871. }
  7872. u[255] = 0;
  7873. d[255] = 0;
  7874. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7875. found++;
  7876. if (pass != NULL) {
  7877. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7878. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7879. }
  7880. } else {
  7881. fprintf(fp2, "%s", line);
  7882. }
  7883. }
  7884. /* If new user, just add it */
  7885. if (!found && (pass != NULL)) {
  7886. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7887. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7888. }
  7889. /* Close files */
  7890. fclose(fp);
  7891. fclose(fp2);
  7892. /* Put the temp file in place of real file */
  7893. IGNORE_UNUSED_RESULT(remove(fname));
  7894. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7895. return 1;
  7896. }
  7897. static int
  7898. is_valid_port(unsigned long port)
  7899. {
  7900. return (port <= 0xffff);
  7901. }
  7902. static int
  7903. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7904. {
  7905. struct addrinfo hints, *res, *ressave;
  7906. int func_ret = 0;
  7907. int gai_ret;
  7908. memset(&hints, 0, sizeof(struct addrinfo));
  7909. hints.ai_family = af;
  7910. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7911. if (gai_ret != 0) {
  7912. /* gai_strerror could be used to convert gai_ret to a string */
  7913. /* POSIX return values: see
  7914. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7915. */
  7916. /* Windows return values: see
  7917. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7918. */
  7919. return 0;
  7920. }
  7921. ressave = res;
  7922. while (res) {
  7923. if (dstlen >= (size_t)res->ai_addrlen) {
  7924. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7925. func_ret = 1;
  7926. }
  7927. res = res->ai_next;
  7928. }
  7929. freeaddrinfo(ressave);
  7930. return func_ret;
  7931. }
  7932. static int
  7933. connect_socket(struct mg_context *ctx /* may be NULL */,
  7934. const char *host,
  7935. int port,
  7936. int use_ssl,
  7937. char *ebuf,
  7938. size_t ebuf_len,
  7939. SOCKET *sock /* output: socket, must not be NULL */,
  7940. union usa *sa /* output: socket address, must not be NULL */
  7941. )
  7942. {
  7943. int ip_ver = 0;
  7944. int conn_ret = -1;
  7945. int sockerr = 0;
  7946. *sock = INVALID_SOCKET;
  7947. memset(sa, 0, sizeof(*sa));
  7948. if (ebuf_len > 0) {
  7949. *ebuf = 0;
  7950. }
  7951. if (host == NULL) {
  7952. mg_snprintf(NULL,
  7953. NULL, /* No truncation check for ebuf */
  7954. ebuf,
  7955. ebuf_len,
  7956. "%s",
  7957. "NULL host");
  7958. return 0;
  7959. }
  7960. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7961. mg_snprintf(NULL,
  7962. NULL, /* No truncation check for ebuf */
  7963. ebuf,
  7964. ebuf_len,
  7965. "%s",
  7966. "invalid port");
  7967. return 0;
  7968. }
  7969. #if !defined(NO_SSL)
  7970. #if !defined(NO_SSL_DL)
  7971. #if defined(OPENSSL_API_1_1)
  7972. if (use_ssl && (TLS_client_method == NULL)) {
  7973. mg_snprintf(NULL,
  7974. NULL, /* No truncation check for ebuf */
  7975. ebuf,
  7976. ebuf_len,
  7977. "%s",
  7978. "SSL is not initialized");
  7979. return 0;
  7980. }
  7981. #else
  7982. if (use_ssl && (SSLv23_client_method == NULL)) {
  7983. mg_snprintf(NULL,
  7984. NULL, /* No truncation check for ebuf */
  7985. ebuf,
  7986. ebuf_len,
  7987. "%s",
  7988. "SSL is not initialized");
  7989. return 0;
  7990. }
  7991. #endif /* OPENSSL_API_1_1 */
  7992. #else
  7993. (void)use_ssl;
  7994. #endif /* NO_SSL_DL */
  7995. #else
  7996. (void)use_ssl;
  7997. #endif /* !defined(NO_SSL) */
  7998. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7999. sa->sin.sin_family = AF_INET;
  8000. sa->sin.sin_port = htons((uint16_t)port);
  8001. ip_ver = 4;
  8002. #if defined(USE_IPV6)
  8003. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  8004. sa->sin6.sin6_family = AF_INET6;
  8005. sa->sin6.sin6_port = htons((uint16_t)port);
  8006. ip_ver = 6;
  8007. } else if (host[0] == '[') {
  8008. /* While getaddrinfo on Windows will work with [::1],
  8009. * getaddrinfo on Linux only works with ::1 (without []). */
  8010. size_t l = strlen(host + 1);
  8011. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8012. if (h) {
  8013. h[l - 1] = 0;
  8014. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  8015. sa->sin6.sin6_family = AF_INET6;
  8016. sa->sin6.sin6_port = htons((uint16_t)port);
  8017. ip_ver = 6;
  8018. }
  8019. mg_free(h);
  8020. }
  8021. #endif
  8022. }
  8023. if (ip_ver == 0) {
  8024. mg_snprintf(NULL,
  8025. NULL, /* No truncation check for ebuf */
  8026. ebuf,
  8027. ebuf_len,
  8028. "%s",
  8029. "host not found");
  8030. return 0;
  8031. }
  8032. if (ip_ver == 4) {
  8033. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8034. }
  8035. #if defined(USE_IPV6)
  8036. else if (ip_ver == 6) {
  8037. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8038. }
  8039. #endif
  8040. if (*sock == INVALID_SOCKET) {
  8041. mg_snprintf(NULL,
  8042. NULL, /* No truncation check for ebuf */
  8043. ebuf,
  8044. ebuf_len,
  8045. "socket(): %s",
  8046. strerror(ERRNO));
  8047. return 0;
  8048. }
  8049. if (0 != set_non_blocking_mode(*sock)) {
  8050. mg_snprintf(NULL,
  8051. NULL, /* No truncation check for ebuf */
  8052. ebuf,
  8053. ebuf_len,
  8054. "Cannot set socket to non-blocking: %s",
  8055. strerror(ERRNO));
  8056. closesocket(*sock);
  8057. *sock = INVALID_SOCKET;
  8058. return 0;
  8059. }
  8060. set_close_on_exec(*sock, NULL, ctx);
  8061. if (ip_ver == 4) {
  8062. /* connected with IPv4 */
  8063. conn_ret = connect(*sock,
  8064. (struct sockaddr *)((void *)&sa->sin),
  8065. sizeof(sa->sin));
  8066. }
  8067. #if defined(USE_IPV6)
  8068. else if (ip_ver == 6) {
  8069. /* connected with IPv6 */
  8070. conn_ret = connect(*sock,
  8071. (struct sockaddr *)((void *)&sa->sin6),
  8072. sizeof(sa->sin6));
  8073. }
  8074. #endif
  8075. if (conn_ret != 0) {
  8076. sockerr = ERRNO;
  8077. }
  8078. #if defined(_WIN32)
  8079. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8080. #else
  8081. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8082. #endif
  8083. /* Data for getsockopt */
  8084. void *psockerr = &sockerr;
  8085. int ret;
  8086. #if defined(_WIN32)
  8087. int len = (int)sizeof(sockerr);
  8088. #else
  8089. socklen_t len = (socklen_t)sizeof(sockerr);
  8090. #endif
  8091. /* Data for poll */
  8092. struct mg_pollfd pfd[1];
  8093. int pollres;
  8094. int ms_wait = 10000; /* 10 second timeout */
  8095. stop_flag_t nonstop = 0;
  8096. /* For a non-blocking socket, the connect sequence is:
  8097. * 1) call connect (will not block)
  8098. * 2) wait until the socket is ready for writing (select or poll)
  8099. * 3) check connection state with getsockopt
  8100. */
  8101. pfd[0].fd = *sock;
  8102. pfd[0].events = POLLOUT;
  8103. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8104. if (pollres != 1) {
  8105. /* Not connected */
  8106. mg_snprintf(NULL,
  8107. NULL, /* No truncation check for ebuf */
  8108. ebuf,
  8109. ebuf_len,
  8110. "connect(%s:%d): timeout",
  8111. host,
  8112. port);
  8113. closesocket(*sock);
  8114. *sock = INVALID_SOCKET;
  8115. return 0;
  8116. }
  8117. #if defined(_WIN32)
  8118. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8119. #else
  8120. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8121. #endif
  8122. if ((ret == 0) && (sockerr == 0)) {
  8123. conn_ret = 0;
  8124. }
  8125. }
  8126. if (conn_ret != 0) {
  8127. /* Not connected */
  8128. mg_snprintf(NULL,
  8129. NULL, /* No truncation check for ebuf */
  8130. ebuf,
  8131. ebuf_len,
  8132. "connect(%s:%d): error %s",
  8133. host,
  8134. port,
  8135. strerror(sockerr));
  8136. closesocket(*sock);
  8137. *sock = INVALID_SOCKET;
  8138. return 0;
  8139. }
  8140. return 1;
  8141. }
  8142. int
  8143. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8144. {
  8145. static const char *dont_escape = "._-$,;~()";
  8146. static const char *hex = "0123456789abcdef";
  8147. char *pos = dst;
  8148. const char *end = dst + dst_len - 1;
  8149. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8150. if (isalnum((unsigned char)*src)
  8151. || (strchr(dont_escape, *src) != NULL)) {
  8152. *pos = *src;
  8153. } else if (pos + 2 < end) {
  8154. pos[0] = '%';
  8155. pos[1] = hex[(unsigned char)*src >> 4];
  8156. pos[2] = hex[(unsigned char)*src & 0xf];
  8157. pos += 2;
  8158. } else {
  8159. break;
  8160. }
  8161. }
  8162. *pos = '\0';
  8163. return (*src == '\0') ? (int)(pos - dst) : -1;
  8164. }
  8165. /* Return 0 on success, non-zero if an error occurs. */
  8166. static int
  8167. print_dir_entry(struct de *de)
  8168. {
  8169. size_t namesize, escsize, i;
  8170. char *href, *esc, *p;
  8171. char size[64], mod[64];
  8172. #if defined(REENTRANT_TIME)
  8173. struct tm _tm;
  8174. struct tm *tm = &_tm;
  8175. #else
  8176. struct tm *tm;
  8177. #endif
  8178. /* Estimate worst case size for encoding and escaping */
  8179. namesize = strlen(de->file_name) + 1;
  8180. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8181. href = (char *)mg_malloc(namesize * 3 + escsize);
  8182. if (href == NULL) {
  8183. return -1;
  8184. }
  8185. mg_url_encode(de->file_name, href, namesize * 3);
  8186. esc = NULL;
  8187. if (escsize > 0) {
  8188. /* HTML escaping needed */
  8189. esc = href + namesize * 3;
  8190. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8191. mg_strlcpy(p, de->file_name + i, 2);
  8192. if (*p == '&') {
  8193. strcpy(p, "&amp;");
  8194. } else if (*p == '<') {
  8195. strcpy(p, "&lt;");
  8196. } else if (*p == '>') {
  8197. strcpy(p, "&gt;");
  8198. }
  8199. }
  8200. }
  8201. if (de->file.is_directory) {
  8202. mg_snprintf(de->conn,
  8203. NULL, /* Buffer is big enough */
  8204. size,
  8205. sizeof(size),
  8206. "%s",
  8207. "[DIRECTORY]");
  8208. } else {
  8209. /* We use (signed) cast below because MSVC 6 compiler cannot
  8210. * convert unsigned __int64 to double. Sigh. */
  8211. if (de->file.size < 1024) {
  8212. mg_snprintf(de->conn,
  8213. NULL, /* Buffer is big enough */
  8214. size,
  8215. sizeof(size),
  8216. "%d",
  8217. (int)de->file.size);
  8218. } else if (de->file.size < 0x100000) {
  8219. mg_snprintf(de->conn,
  8220. NULL, /* Buffer is big enough */
  8221. size,
  8222. sizeof(size),
  8223. "%.1fk",
  8224. (double)de->file.size / 1024.0);
  8225. } else if (de->file.size < 0x40000000) {
  8226. mg_snprintf(de->conn,
  8227. NULL, /* Buffer is big enough */
  8228. size,
  8229. sizeof(size),
  8230. "%.1fM",
  8231. (double)de->file.size / 1048576);
  8232. } else {
  8233. mg_snprintf(de->conn,
  8234. NULL, /* Buffer is big enough */
  8235. size,
  8236. sizeof(size),
  8237. "%.1fG",
  8238. (double)de->file.size / 1073741824);
  8239. }
  8240. }
  8241. /* Note: mg_snprintf will not cause a buffer overflow above.
  8242. * So, string truncation checks are not required here. */
  8243. #if defined(REENTRANT_TIME)
  8244. localtime_r(&de->file.last_modified, tm);
  8245. #else
  8246. tm = localtime(&de->file.last_modified);
  8247. #endif
  8248. if (tm != NULL) {
  8249. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8250. } else {
  8251. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8252. mod[sizeof(mod) - 1] = '\0';
  8253. }
  8254. mg_printf(de->conn,
  8255. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8256. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8257. href,
  8258. de->file.is_directory ? "/" : "",
  8259. esc ? esc : de->file_name,
  8260. de->file.is_directory ? "/" : "",
  8261. mod,
  8262. size);
  8263. mg_free(href);
  8264. return 0;
  8265. }
  8266. /* This function is called from send_directory() and used for
  8267. * sorting directory entries by size, or name, or modification time.
  8268. * On windows, __cdecl specification is needed in case if project is built
  8269. * with __stdcall convention. qsort always requires __cdels callback. */
  8270. static int WINCDECL
  8271. compare_dir_entries(const void *p1, const void *p2)
  8272. {
  8273. if (p1 && p2) {
  8274. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8275. const char *query_string = a->conn->request_info.query_string;
  8276. int cmp_result = 0;
  8277. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8278. query_string = "n";
  8279. }
  8280. if (a->file.is_directory && !b->file.is_directory) {
  8281. return -1; /* Always put directories on top */
  8282. } else if (!a->file.is_directory && b->file.is_directory) {
  8283. return 1; /* Always put directories on top */
  8284. } else if (*query_string == 'n') {
  8285. cmp_result = strcmp(a->file_name, b->file_name);
  8286. } else if (*query_string == 's') {
  8287. cmp_result = (a->file.size == b->file.size)
  8288. ? 0
  8289. : ((a->file.size > b->file.size) ? 1 : -1);
  8290. } else if (*query_string == 'd') {
  8291. cmp_result =
  8292. (a->file.last_modified == b->file.last_modified)
  8293. ? 0
  8294. : ((a->file.last_modified > b->file.last_modified) ? 1
  8295. : -1);
  8296. }
  8297. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8298. }
  8299. return 0;
  8300. }
  8301. static int
  8302. must_hide_file(struct mg_connection *conn, const char *path)
  8303. {
  8304. if (conn && conn->dom_ctx) {
  8305. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8306. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8307. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8308. || ((pattern != NULL)
  8309. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8310. }
  8311. return 0;
  8312. }
  8313. #if !defined(NO_FILESYSTEMS)
  8314. static int
  8315. scan_directory(struct mg_connection *conn,
  8316. const char *dir,
  8317. void *data,
  8318. int (*cb)(struct de *, void *))
  8319. {
  8320. char path[PATH_MAX];
  8321. struct dirent *dp;
  8322. DIR *dirp;
  8323. struct de de;
  8324. int truncated;
  8325. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8326. return 0;
  8327. } else {
  8328. de.conn = conn;
  8329. while ((dp = mg_readdir(dirp)) != NULL) {
  8330. /* Do not show current dir and hidden files */
  8331. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8332. || must_hide_file(conn, dp->d_name)) {
  8333. continue;
  8334. }
  8335. mg_snprintf(
  8336. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8337. /* If we don't memset stat structure to zero, mtime will have
  8338. * garbage and strftime() will segfault later on in
  8339. * print_dir_entry(). memset is required only if mg_stat()
  8340. * fails. For more details, see
  8341. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8342. memset(&de.file, 0, sizeof(de.file));
  8343. if (truncated) {
  8344. /* If the path is not complete, skip processing. */
  8345. continue;
  8346. }
  8347. if (!mg_stat(conn, path, &de.file)) {
  8348. mg_cry_internal(conn,
  8349. "%s: mg_stat(%s) failed: %s",
  8350. __func__,
  8351. path,
  8352. strerror(ERRNO));
  8353. }
  8354. de.file_name = dp->d_name;
  8355. cb(&de, data);
  8356. }
  8357. (void)mg_closedir(dirp);
  8358. }
  8359. return 1;
  8360. }
  8361. #endif /* NO_FILESYSTEMS */
  8362. #if !defined(NO_FILES)
  8363. static int
  8364. remove_directory(struct mg_connection *conn, const char *dir)
  8365. {
  8366. char path[PATH_MAX];
  8367. struct dirent *dp;
  8368. DIR *dirp;
  8369. struct de de;
  8370. int truncated;
  8371. int ok = 1;
  8372. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8373. return 0;
  8374. } else {
  8375. de.conn = conn;
  8376. while ((dp = mg_readdir(dirp)) != NULL) {
  8377. /* Do not show current dir (but show hidden files as they will
  8378. * also be removed) */
  8379. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8380. continue;
  8381. }
  8382. mg_snprintf(
  8383. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8384. /* If we don't memset stat structure to zero, mtime will have
  8385. * garbage and strftime() will segfault later on in
  8386. * print_dir_entry(). memset is required only if mg_stat()
  8387. * fails. For more details, see
  8388. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8389. memset(&de.file, 0, sizeof(de.file));
  8390. if (truncated) {
  8391. /* Do not delete anything shorter */
  8392. ok = 0;
  8393. continue;
  8394. }
  8395. if (!mg_stat(conn, path, &de.file)) {
  8396. mg_cry_internal(conn,
  8397. "%s: mg_stat(%s) failed: %s",
  8398. __func__,
  8399. path,
  8400. strerror(ERRNO));
  8401. ok = 0;
  8402. }
  8403. if (de.file.is_directory) {
  8404. if (remove_directory(conn, path) == 0) {
  8405. ok = 0;
  8406. }
  8407. } else {
  8408. /* This will fail file is the file is in memory */
  8409. if (mg_remove(conn, path) == 0) {
  8410. ok = 0;
  8411. }
  8412. }
  8413. }
  8414. (void)mg_closedir(dirp);
  8415. IGNORE_UNUSED_RESULT(rmdir(dir));
  8416. }
  8417. return ok;
  8418. }
  8419. #endif
  8420. struct dir_scan_data {
  8421. struct de *entries;
  8422. unsigned int num_entries;
  8423. unsigned int arr_size;
  8424. };
  8425. /* Behaves like realloc(), but frees original pointer on failure */
  8426. static void *
  8427. realloc2(void *ptr, size_t size)
  8428. {
  8429. void *new_ptr = mg_realloc(ptr, size);
  8430. if ((new_ptr == NULL) && (size > 0)) {
  8431. mg_free(ptr);
  8432. }
  8433. return new_ptr;
  8434. }
  8435. #if !defined(NO_FILESYSTEMS)
  8436. static int
  8437. dir_scan_callback(struct de *de, void *data)
  8438. {
  8439. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8440. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8441. dsd->arr_size *= 2;
  8442. dsd->entries =
  8443. (struct de *)realloc2(dsd->entries,
  8444. dsd->arr_size * sizeof(dsd->entries[0]));
  8445. }
  8446. if (dsd->entries == NULL) {
  8447. /* TODO(lsm, low): propagate an error to the caller */
  8448. dsd->num_entries = 0;
  8449. } else {
  8450. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8451. dsd->entries[dsd->num_entries].file = de->file;
  8452. dsd->entries[dsd->num_entries].conn = de->conn;
  8453. dsd->num_entries++;
  8454. }
  8455. return 0;
  8456. }
  8457. static void
  8458. handle_directory_request(struct mg_connection *conn, const char *dir)
  8459. {
  8460. unsigned int i;
  8461. int sort_direction;
  8462. struct dir_scan_data data = {NULL, 0, 128};
  8463. char date[64], *esc, *p;
  8464. const char *title;
  8465. time_t curtime = time(NULL);
  8466. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8467. mg_send_http_error(conn,
  8468. 500,
  8469. "Error: Cannot open directory\nopendir(%s): %s",
  8470. dir,
  8471. strerror(ERRNO));
  8472. return;
  8473. }
  8474. gmt_time_string(date, sizeof(date), &curtime);
  8475. if (!conn) {
  8476. return;
  8477. }
  8478. esc = NULL;
  8479. title = conn->request_info.local_uri;
  8480. if (title[strcspn(title, "&<>")]) {
  8481. /* HTML escaping needed */
  8482. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8483. if (esc) {
  8484. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8485. mg_strlcpy(p, title + i, 2);
  8486. if (*p == '&') {
  8487. strcpy(p, "&amp;");
  8488. } else if (*p == '<') {
  8489. strcpy(p, "&lt;");
  8490. } else if (*p == '>') {
  8491. strcpy(p, "&gt;");
  8492. }
  8493. }
  8494. } else {
  8495. title = "";
  8496. }
  8497. }
  8498. sort_direction = ((conn->request_info.query_string != NULL)
  8499. && (conn->request_info.query_string[0] != '\0')
  8500. && (conn->request_info.query_string[1] == 'd'))
  8501. ? 'a'
  8502. : 'd';
  8503. conn->must_close = 1;
  8504. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8505. send_static_cache_header(conn);
  8506. send_additional_header(conn);
  8507. mg_printf(conn,
  8508. "Date: %s\r\n"
  8509. "Connection: close\r\n"
  8510. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8511. date);
  8512. mg_printf(conn,
  8513. "<html><head><title>Index of %s</title>"
  8514. "<style>th {text-align: left;}</style></head>"
  8515. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8516. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8517. "<th><a href=\"?d%c\">Modified</a></th>"
  8518. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8519. "<tr><td colspan=\"3\"><hr></td></tr>",
  8520. esc ? esc : title,
  8521. esc ? esc : title,
  8522. sort_direction,
  8523. sort_direction,
  8524. sort_direction);
  8525. mg_free(esc);
  8526. /* Print first entry - link to a parent directory */
  8527. mg_printf(conn,
  8528. "<tr><td><a href=\"%s\">%s</a></td>"
  8529. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8530. "..",
  8531. "Parent directory",
  8532. "-",
  8533. "-");
  8534. /* Sort and print directory entries */
  8535. if (data.entries != NULL) {
  8536. qsort(data.entries,
  8537. (size_t)data.num_entries,
  8538. sizeof(data.entries[0]),
  8539. compare_dir_entries);
  8540. for (i = 0; i < data.num_entries; i++) {
  8541. print_dir_entry(&data.entries[i]);
  8542. mg_free(data.entries[i].file_name);
  8543. }
  8544. mg_free(data.entries);
  8545. }
  8546. mg_printf(conn, "%s", "</table></pre></body></html>");
  8547. conn->status_code = 200;
  8548. }
  8549. #endif /* NO_FILESYSTEMS */
  8550. /* Send len bytes from the opened file to the client. */
  8551. static void
  8552. send_file_data(struct mg_connection *conn,
  8553. struct mg_file *filep,
  8554. int64_t offset,
  8555. int64_t len)
  8556. {
  8557. char buf[MG_BUF_LEN];
  8558. int to_read, num_read, num_written;
  8559. int64_t size;
  8560. if (!filep || !conn) {
  8561. return;
  8562. }
  8563. /* Sanity check the offset */
  8564. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8565. : (int64_t)(filep->stat.size);
  8566. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8567. #if defined(MG_USE_OPEN_FILE)
  8568. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8569. /* file stored in memory */
  8570. if (len > size - offset) {
  8571. len = size - offset;
  8572. }
  8573. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8574. } else /* else block below */
  8575. #endif
  8576. if (len > 0 && filep->access.fp != NULL) {
  8577. /* file stored on disk */
  8578. #if defined(__linux__)
  8579. /* sendfile is only available for Linux */
  8580. if ((conn->ssl == 0) && (conn->throttle == 0)
  8581. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8582. "yes"))) {
  8583. off_t sf_offs = (off_t)offset;
  8584. ssize_t sf_sent;
  8585. int sf_file = fileno(filep->access.fp);
  8586. int loop_cnt = 0;
  8587. do {
  8588. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8589. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8590. size_t sf_tosend =
  8591. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8592. sf_sent =
  8593. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8594. if (sf_sent > 0) {
  8595. len -= sf_sent;
  8596. offset += sf_sent;
  8597. } else if (loop_cnt == 0) {
  8598. /* This file can not be sent using sendfile.
  8599. * This might be the case for pseudo-files in the
  8600. * /sys/ and /proc/ file system.
  8601. * Use the regular user mode copy code instead. */
  8602. break;
  8603. } else if (sf_sent == 0) {
  8604. /* No error, but 0 bytes sent. May be EOF? */
  8605. return;
  8606. }
  8607. loop_cnt++;
  8608. } while ((len > 0) && (sf_sent >= 0));
  8609. if (sf_sent > 0) {
  8610. return; /* OK */
  8611. }
  8612. /* sf_sent<0 means error, thus fall back to the classic way */
  8613. /* This is always the case, if sf_file is not a "normal" file,
  8614. * e.g., for sending data from the output of a CGI process. */
  8615. offset = (int64_t)sf_offs;
  8616. }
  8617. #endif
  8618. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8619. mg_cry_internal(conn,
  8620. "%s: fseeko() failed: %s",
  8621. __func__,
  8622. strerror(ERRNO));
  8623. mg_send_http_error(
  8624. conn,
  8625. 500,
  8626. "%s",
  8627. "Error: Unable to access file at requested position.");
  8628. } else {
  8629. while (len > 0) {
  8630. /* Calculate how much to read from the file in the buffer */
  8631. to_read = sizeof(buf);
  8632. if ((int64_t)to_read > len) {
  8633. to_read = (int)len;
  8634. }
  8635. /* Read from file, exit the loop on error */
  8636. if ((num_read =
  8637. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8638. <= 0) {
  8639. break;
  8640. }
  8641. /* Send read bytes to the client, exit the loop on error */
  8642. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8643. != num_read) {
  8644. break;
  8645. }
  8646. /* Both read and were successful, adjust counters */
  8647. len -= num_written;
  8648. }
  8649. }
  8650. }
  8651. }
  8652. static int
  8653. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8654. {
  8655. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8656. }
  8657. static void
  8658. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8659. {
  8660. if ((filestat != NULL) && (buf != NULL)) {
  8661. mg_snprintf(NULL,
  8662. NULL, /* All calls to construct_etag use 64 byte buffer */
  8663. buf,
  8664. buf_len,
  8665. "\"%lx.%" INT64_FMT "\"",
  8666. (unsigned long)filestat->last_modified,
  8667. filestat->size);
  8668. }
  8669. }
  8670. static void
  8671. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8672. {
  8673. if (filep != NULL && filep->fp != NULL) {
  8674. #if defined(_WIN32)
  8675. (void)conn; /* Unused. */
  8676. #else
  8677. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8678. mg_cry_internal(conn,
  8679. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8680. __func__,
  8681. strerror(ERRNO));
  8682. }
  8683. #endif
  8684. }
  8685. }
  8686. #if defined(USE_ZLIB)
  8687. #include "mod_zlib.inl"
  8688. #endif
  8689. #if !defined(NO_FILESYSTEMS)
  8690. static void
  8691. handle_static_file_request(struct mg_connection *conn,
  8692. const char *path,
  8693. struct mg_file *filep,
  8694. const char *mime_type,
  8695. const char *additional_headers)
  8696. {
  8697. char date[64], lm[64], etag[64];
  8698. char range[128]; /* large enough, so there will be no overflow */
  8699. const char *msg = "OK";
  8700. const char *range_hdr;
  8701. time_t curtime = time(NULL);
  8702. int64_t cl, r1, r2;
  8703. struct vec mime_vec;
  8704. int n, truncated;
  8705. char gz_path[PATH_MAX];
  8706. const char *encoding = "";
  8707. const char *origin_hdr;
  8708. const char *cors_orig_cfg;
  8709. const char *cors1, *cors2, *cors3;
  8710. int is_head_request;
  8711. #if defined(USE_ZLIB)
  8712. /* Compression is allowed, unless there is a reason not to use
  8713. * compression. If the file is already compressed, too small or a
  8714. * "range" request was made, on the fly compression is not possible. */
  8715. int allow_on_the_fly_compression = 1;
  8716. #endif
  8717. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8718. return;
  8719. }
  8720. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8721. if (mime_type == NULL) {
  8722. get_mime_type(conn, path, &mime_vec);
  8723. } else {
  8724. mime_vec.ptr = mime_type;
  8725. mime_vec.len = strlen(mime_type);
  8726. }
  8727. if (filep->stat.size > INT64_MAX) {
  8728. mg_send_http_error(conn,
  8729. 500,
  8730. "Error: File size is too large to send\n%" INT64_FMT,
  8731. filep->stat.size);
  8732. return;
  8733. }
  8734. cl = (int64_t)filep->stat.size;
  8735. conn->status_code = 200;
  8736. range[0] = '\0';
  8737. #if defined(USE_ZLIB)
  8738. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8739. * it's important to rewrite the filename after resolving
  8740. * the mime type from it, to preserve the actual file's type */
  8741. if (!conn->accept_gzip) {
  8742. allow_on_the_fly_compression = 0;
  8743. }
  8744. #endif
  8745. /* Check if there is a range header */
  8746. range_hdr = mg_get_header(conn, "Range");
  8747. /* For gzipped files, add *.gz */
  8748. if (filep->stat.is_gzipped) {
  8749. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8750. if (truncated) {
  8751. mg_send_http_error(conn,
  8752. 500,
  8753. "Error: Path of zipped file too long (%s)",
  8754. path);
  8755. return;
  8756. }
  8757. path = gz_path;
  8758. encoding = "Content-Encoding: gzip\r\n";
  8759. #if defined(USE_ZLIB)
  8760. /* File is already compressed. No "on the fly" compression. */
  8761. allow_on_the_fly_compression = 0;
  8762. #endif
  8763. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8764. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8765. struct mg_file_stat file_stat;
  8766. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8767. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8768. && !file_stat.is_directory) {
  8769. file_stat.is_gzipped = 1;
  8770. filep->stat = file_stat;
  8771. cl = (int64_t)filep->stat.size;
  8772. path = gz_path;
  8773. encoding = "Content-Encoding: gzip\r\n";
  8774. #if defined(USE_ZLIB)
  8775. /* File is already compressed. No "on the fly" compression. */
  8776. allow_on_the_fly_compression = 0;
  8777. #endif
  8778. }
  8779. }
  8780. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8781. mg_send_http_error(conn,
  8782. 500,
  8783. "Error: Cannot open file\nfopen(%s): %s",
  8784. path,
  8785. strerror(ERRNO));
  8786. return;
  8787. }
  8788. fclose_on_exec(&filep->access, conn);
  8789. /* If "Range" request was made: parse header, send only selected part
  8790. * of the file. */
  8791. r1 = r2 = 0;
  8792. if ((range_hdr != NULL)
  8793. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8794. && (r2 >= 0)) {
  8795. /* actually, range requests don't play well with a pre-gzipped
  8796. * file (since the range is specified in the uncompressed space) */
  8797. if (filep->stat.is_gzipped) {
  8798. mg_send_http_error(
  8799. conn,
  8800. 416, /* 416 = Range Not Satisfiable */
  8801. "%s",
  8802. "Error: Range requests in gzipped files are not supported");
  8803. (void)mg_fclose(
  8804. &filep->access); /* ignore error on read only file */
  8805. return;
  8806. }
  8807. conn->status_code = 206;
  8808. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8809. mg_snprintf(conn,
  8810. NULL, /* range buffer is big enough */
  8811. range,
  8812. sizeof(range),
  8813. "Content-Range: bytes "
  8814. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8815. r1,
  8816. r1 + cl - 1,
  8817. filep->stat.size);
  8818. msg = "Partial Content";
  8819. #if defined(USE_ZLIB)
  8820. /* Do not compress ranges. */
  8821. allow_on_the_fly_compression = 0;
  8822. #endif
  8823. }
  8824. /* Do not compress small files. Small files do not benefit from file
  8825. * compression, but there is still some overhead. */
  8826. #if defined(USE_ZLIB)
  8827. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8828. /* File is below the size limit. */
  8829. allow_on_the_fly_compression = 0;
  8830. }
  8831. #endif
  8832. /* Standard CORS header */
  8833. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8834. origin_hdr = mg_get_header(conn, "Origin");
  8835. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8836. /* Cross-origin resource sharing (CORS), see
  8837. * http://www.html5rocks.com/en/tutorials/cors/,
  8838. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8839. * -
  8840. * preflight is not supported for files. */
  8841. cors1 = "Access-Control-Allow-Origin: ";
  8842. cors2 = cors_orig_cfg;
  8843. cors3 = "\r\n";
  8844. } else {
  8845. cors1 = cors2 = cors3 = "";
  8846. }
  8847. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8848. * according to
  8849. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8850. gmt_time_string(date, sizeof(date), &curtime);
  8851. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8852. construct_etag(etag, sizeof(etag), &filep->stat);
  8853. /* Send header */
  8854. (void)mg_printf(conn,
  8855. "HTTP/1.1 %d %s\r\n"
  8856. "%s%s%s" /* CORS */
  8857. "Date: %s\r\n"
  8858. "Last-Modified: %s\r\n"
  8859. "Etag: %s\r\n"
  8860. "Content-Type: %.*s\r\n"
  8861. "Connection: %s\r\n",
  8862. conn->status_code,
  8863. msg,
  8864. cors1,
  8865. cors2,
  8866. cors3,
  8867. date,
  8868. lm,
  8869. etag,
  8870. (int)mime_vec.len,
  8871. mime_vec.ptr,
  8872. suggest_connection_header(conn));
  8873. send_static_cache_header(conn);
  8874. send_additional_header(conn);
  8875. #if defined(USE_ZLIB)
  8876. /* On the fly compression allowed */
  8877. if (allow_on_the_fly_compression) {
  8878. /* For on the fly compression, we don't know the content size in
  8879. * advance, so we have to use chunked encoding */
  8880. (void)mg_printf(conn,
  8881. "Content-Encoding: gzip\r\n"
  8882. "Transfer-Encoding: chunked\r\n");
  8883. } else
  8884. #endif
  8885. {
  8886. /* Without on-the-fly compression, we know the content-length
  8887. * and we can use ranges (with on-the-fly compression we cannot).
  8888. * So we send these response headers only in this case. */
  8889. (void)mg_printf(conn,
  8890. "Content-Length: %" INT64_FMT "\r\n"
  8891. "Accept-Ranges: bytes\r\n"
  8892. "%s" /* range */
  8893. "%s" /* encoding */,
  8894. cl,
  8895. range,
  8896. encoding);
  8897. }
  8898. /* The previous code must not add any header starting with X- to make
  8899. * sure no one of the additional_headers is included twice */
  8900. if (additional_headers != NULL) {
  8901. (void)mg_printf(conn,
  8902. "%.*s\r\n\r\n",
  8903. (int)strlen(additional_headers),
  8904. additional_headers);
  8905. } else {
  8906. (void)mg_printf(conn, "\r\n");
  8907. }
  8908. if (!is_head_request) {
  8909. #if defined(USE_ZLIB)
  8910. if (allow_on_the_fly_compression) {
  8911. /* Compress and send */
  8912. send_compressed_data(conn, filep);
  8913. } else
  8914. #endif
  8915. {
  8916. /* Send file directly */
  8917. send_file_data(conn, filep, r1, cl);
  8918. }
  8919. }
  8920. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8921. }
  8922. int
  8923. mg_send_file_body(struct mg_connection *conn, const char *path)
  8924. {
  8925. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8926. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8927. return -1;
  8928. }
  8929. fclose_on_exec(&file.access, conn);
  8930. send_file_data(conn, &file, 0, INT64_MAX);
  8931. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8932. return 0; /* >= 0 for OK */
  8933. }
  8934. #endif /* NO_FILESYSTEMS */
  8935. #if !defined(NO_CACHING)
  8936. /* Return True if we should reply 304 Not Modified. */
  8937. static int
  8938. is_not_modified(const struct mg_connection *conn,
  8939. const struct mg_file_stat *filestat)
  8940. {
  8941. char etag[64];
  8942. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8943. const char *inm = mg_get_header(conn, "If-None-Match");
  8944. construct_etag(etag, sizeof(etag), filestat);
  8945. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8946. || ((ims != NULL)
  8947. && (filestat->last_modified <= parse_date_string(ims)));
  8948. }
  8949. static void
  8950. handle_not_modified_static_file_request(struct mg_connection *conn,
  8951. struct mg_file *filep)
  8952. {
  8953. char date[64], lm[64], etag[64];
  8954. time_t curtime = time(NULL);
  8955. if ((conn == NULL) || (filep == NULL)) {
  8956. return;
  8957. }
  8958. conn->status_code = 304;
  8959. gmt_time_string(date, sizeof(date), &curtime);
  8960. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8961. construct_etag(etag, sizeof(etag), &filep->stat);
  8962. (void)mg_printf(conn,
  8963. "HTTP/1.1 %d %s\r\n"
  8964. "Date: %s\r\n",
  8965. conn->status_code,
  8966. mg_get_response_code_text(conn, conn->status_code),
  8967. date);
  8968. send_static_cache_header(conn);
  8969. send_additional_header(conn);
  8970. (void)mg_printf(conn,
  8971. "Last-Modified: %s\r\n"
  8972. "Etag: %s\r\n"
  8973. "Connection: %s\r\n"
  8974. "\r\n",
  8975. lm,
  8976. etag,
  8977. suggest_connection_header(conn));
  8978. }
  8979. #endif
  8980. #if !defined(NO_FILESYSTEMS)
  8981. void
  8982. mg_send_file(struct mg_connection *conn, const char *path)
  8983. {
  8984. mg_send_mime_file2(conn, path, NULL, NULL);
  8985. }
  8986. void
  8987. mg_send_mime_file(struct mg_connection *conn,
  8988. const char *path,
  8989. const char *mime_type)
  8990. {
  8991. mg_send_mime_file2(conn, path, mime_type, NULL);
  8992. }
  8993. void
  8994. mg_send_mime_file2(struct mg_connection *conn,
  8995. const char *path,
  8996. const char *mime_type,
  8997. const char *additional_headers)
  8998. {
  8999. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9000. if (!conn) {
  9001. /* No conn */
  9002. return;
  9003. }
  9004. if (mg_stat(conn, path, &file.stat)) {
  9005. #if !defined(NO_CACHING)
  9006. if (is_not_modified(conn, &file.stat)) {
  9007. /* Send 304 "Not Modified" - this must not send any body data */
  9008. handle_not_modified_static_file_request(conn, &file);
  9009. } else
  9010. #endif /* NO_CACHING */
  9011. if (file.stat.is_directory) {
  9012. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9013. "yes")) {
  9014. handle_directory_request(conn, path);
  9015. } else {
  9016. mg_send_http_error(conn,
  9017. 403,
  9018. "%s",
  9019. "Error: Directory listing denied");
  9020. }
  9021. } else {
  9022. handle_static_file_request(
  9023. conn, path, &file, mime_type, additional_headers);
  9024. }
  9025. } else {
  9026. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9027. }
  9028. }
  9029. /* For a given PUT path, create all intermediate subdirectories.
  9030. * Return 0 if the path itself is a directory.
  9031. * Return 1 if the path leads to a file.
  9032. * Return -1 for if the path is too long.
  9033. * Return -2 if path can not be created.
  9034. */
  9035. static int
  9036. put_dir(struct mg_connection *conn, const char *path)
  9037. {
  9038. char buf[PATH_MAX];
  9039. const char *s, *p;
  9040. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9041. size_t len;
  9042. int res = 1;
  9043. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9044. len = (size_t)(p - path);
  9045. if (len >= sizeof(buf)) {
  9046. /* path too long */
  9047. res = -1;
  9048. break;
  9049. }
  9050. memcpy(buf, path, len);
  9051. buf[len] = '\0';
  9052. /* Try to create intermediate directory */
  9053. DEBUG_TRACE("mkdir(%s)", buf);
  9054. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9055. /* path does not exixt and can not be created */
  9056. res = -2;
  9057. break;
  9058. }
  9059. /* Is path itself a directory? */
  9060. if (p[1] == '\0') {
  9061. res = 0;
  9062. }
  9063. }
  9064. return res;
  9065. }
  9066. static void
  9067. remove_bad_file(const struct mg_connection *conn, const char *path)
  9068. {
  9069. int r = mg_remove(conn, path);
  9070. if (r != 0) {
  9071. mg_cry_internal(conn,
  9072. "%s: Cannot remove invalid file %s",
  9073. __func__,
  9074. path);
  9075. }
  9076. }
  9077. long long
  9078. mg_store_body(struct mg_connection *conn, const char *path)
  9079. {
  9080. char buf[MG_BUF_LEN];
  9081. long long len = 0;
  9082. int ret, n;
  9083. struct mg_file fi;
  9084. if (conn->consumed_content != 0) {
  9085. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9086. return -11;
  9087. }
  9088. ret = put_dir(conn, path);
  9089. if (ret < 0) {
  9090. /* -1 for path too long,
  9091. * -2 for path can not be created. */
  9092. return ret;
  9093. }
  9094. if (ret != 1) {
  9095. /* Return 0 means, path itself is a directory. */
  9096. return 0;
  9097. }
  9098. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9099. return -12;
  9100. }
  9101. ret = mg_read(conn, buf, sizeof(buf));
  9102. while (ret > 0) {
  9103. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9104. if (n != ret) {
  9105. (void)mg_fclose(
  9106. &fi.access); /* File is bad and will be removed anyway. */
  9107. remove_bad_file(conn, path);
  9108. return -13;
  9109. }
  9110. len += ret;
  9111. ret = mg_read(conn, buf, sizeof(buf));
  9112. }
  9113. /* File is open for writing. If fclose fails, there was probably an
  9114. * error flushing the buffer to disk, so the file on disk might be
  9115. * broken. Delete it and return an error to the caller. */
  9116. if (mg_fclose(&fi.access) != 0) {
  9117. remove_bad_file(conn, path);
  9118. return -14;
  9119. }
  9120. return len;
  9121. }
  9122. #endif /* NO_FILESYSTEMS */
  9123. /* Parse a buffer:
  9124. * Forward the string pointer till the end of a word, then
  9125. * terminate it and forward till the begin of the next word.
  9126. */
  9127. static int
  9128. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9129. {
  9130. /* Forward until a space is found - use isgraph here */
  9131. /* See http://www.cplusplus.com/reference/cctype/ */
  9132. while (isgraph((unsigned char)**ppw)) {
  9133. (*ppw)++;
  9134. }
  9135. /* Check end of word */
  9136. if (eol) {
  9137. /* must be a end of line */
  9138. if ((**ppw != '\r') && (**ppw != '\n')) {
  9139. return -1;
  9140. }
  9141. } else {
  9142. /* must be a end of a word, but not a line */
  9143. if (**ppw != ' ') {
  9144. return -1;
  9145. }
  9146. }
  9147. /* Terminate and forward to the next word */
  9148. do {
  9149. **ppw = 0;
  9150. (*ppw)++;
  9151. } while (isspace((unsigned char)**ppw));
  9152. /* Check after term */
  9153. if (!eol) {
  9154. /* if it's not the end of line, there must be a next word */
  9155. if (!isgraph((unsigned char)**ppw)) {
  9156. return -1;
  9157. }
  9158. }
  9159. /* ok */
  9160. return 1;
  9161. }
  9162. /* Parse HTTP headers from the given buffer, advance buf pointer
  9163. * to the point where parsing stopped.
  9164. * All parameters must be valid pointers (not NULL).
  9165. * Return <0 on error. */
  9166. static int
  9167. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9168. {
  9169. int i;
  9170. int num_headers = 0;
  9171. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9172. char *dp = *buf;
  9173. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9174. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9175. dp++;
  9176. }
  9177. if (dp == *buf) {
  9178. /* End of headers reached. */
  9179. break;
  9180. }
  9181. if (*dp != ':') {
  9182. /* This is not a valid field. */
  9183. return -1;
  9184. }
  9185. /* End of header key (*dp == ':') */
  9186. /* Truncate here and set the key name */
  9187. *dp = 0;
  9188. hdr[i].name = *buf;
  9189. /* Skip all spaces */
  9190. do {
  9191. dp++;
  9192. } while ((*dp == ' ') || (*dp == '\t'));
  9193. /* The rest of the line is the value */
  9194. hdr[i].value = dp;
  9195. /* Find end of line */
  9196. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9197. dp++;
  9198. };
  9199. /* eliminate \r */
  9200. if (*dp == '\r') {
  9201. *dp = 0;
  9202. dp++;
  9203. if (*dp != '\n') {
  9204. /* This is not a valid line. */
  9205. return -1;
  9206. }
  9207. }
  9208. /* here *dp is either 0 or '\n' */
  9209. /* in any case, we have a new header */
  9210. num_headers = i + 1;
  9211. if (*dp) {
  9212. *dp = 0;
  9213. dp++;
  9214. *buf = dp;
  9215. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9216. /* This is the end of the header */
  9217. break;
  9218. }
  9219. } else {
  9220. *buf = dp;
  9221. break;
  9222. }
  9223. }
  9224. return num_headers;
  9225. }
  9226. struct mg_http_method_info {
  9227. const char *name;
  9228. int request_has_body;
  9229. int response_has_body;
  9230. int is_safe;
  9231. int is_idempotent;
  9232. int is_cacheable;
  9233. };
  9234. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9235. static const struct mg_http_method_info http_methods[] = {
  9236. /* HTTP (RFC 2616) */
  9237. {"GET", 0, 1, 1, 1, 1},
  9238. {"POST", 1, 1, 0, 0, 0},
  9239. {"PUT", 1, 0, 0, 1, 0},
  9240. {"DELETE", 0, 0, 0, 1, 0},
  9241. {"HEAD", 0, 0, 1, 1, 1},
  9242. {"OPTIONS", 0, 0, 1, 1, 0},
  9243. {"CONNECT", 1, 1, 0, 0, 0},
  9244. /* TRACE method (RFC 2616) is not supported for security reasons */
  9245. /* PATCH method (RFC 5789) */
  9246. {"PATCH", 1, 0, 0, 0, 0},
  9247. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9248. /* WEBDAV (RFC 2518) */
  9249. {"PROPFIND", 0, 1, 1, 1, 0},
  9250. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9251. * Some PROPFIND results MAY be cached, with care,
  9252. * as there is no cache validation mechanism for
  9253. * most properties. This method is both safe and
  9254. * idempotent (see Section 9.1 of [RFC2616]). */
  9255. {"MKCOL", 0, 0, 0, 1, 0},
  9256. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9257. * When MKCOL is invoked without a request body,
  9258. * the newly created collection SHOULD have no
  9259. * members. A MKCOL request message may contain
  9260. * a message body. The precise behavior of a MKCOL
  9261. * request when the body is present is undefined,
  9262. * ... ==> We do not support MKCOL with body data.
  9263. * This method is idempotent, but not safe (see
  9264. * Section 9.1 of [RFC2616]). Responses to this
  9265. * method MUST NOT be cached. */
  9266. /* Unsupported WEBDAV Methods: */
  9267. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9268. /* + 11 methods from RFC 3253 */
  9269. /* ORDERPATCH (RFC 3648) */
  9270. /* ACL (RFC 3744) */
  9271. /* SEARCH (RFC 5323) */
  9272. /* + MicroSoft extensions
  9273. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9274. /* REPORT method (RFC 3253) */
  9275. {"REPORT", 1, 1, 1, 1, 1},
  9276. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9277. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9278. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9279. * to be useful for REST in case a "GET request with body" is
  9280. * required. */
  9281. {NULL, 0, 0, 0, 0, 0}
  9282. /* end of list */
  9283. };
  9284. static const struct mg_http_method_info *
  9285. get_http_method_info(const char *method)
  9286. {
  9287. /* Check if the method is known to the server. The list of all known
  9288. * HTTP methods can be found here at
  9289. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9290. */
  9291. const struct mg_http_method_info *m = http_methods;
  9292. while (m->name) {
  9293. if (!strcmp(m->name, method)) {
  9294. return m;
  9295. }
  9296. m++;
  9297. }
  9298. return NULL;
  9299. }
  9300. static int
  9301. is_valid_http_method(const char *method)
  9302. {
  9303. return (get_http_method_info(method) != NULL);
  9304. }
  9305. /* Parse HTTP request, fill in mg_request_info structure.
  9306. * This function modifies the buffer by NUL-terminating
  9307. * HTTP request components, header names and header values.
  9308. * Parameters:
  9309. * buf (in/out): pointer to the HTTP header to parse and split
  9310. * len (in): length of HTTP header buffer
  9311. * re (out): parsed header as mg_request_info
  9312. * buf and ri must be valid pointers (not NULL), len>0.
  9313. * Returns <0 on error. */
  9314. static int
  9315. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9316. {
  9317. int request_length;
  9318. int init_skip = 0;
  9319. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9320. * remote_port */
  9321. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9322. NULL;
  9323. ri->num_headers = 0;
  9324. /* RFC says that all initial whitespaces should be ingored */
  9325. /* This included all leading \r and \n (isspace) */
  9326. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9327. while ((len > 0) && isspace((unsigned char)*buf)) {
  9328. buf++;
  9329. len--;
  9330. init_skip++;
  9331. }
  9332. if (len == 0) {
  9333. /* Incomplete request */
  9334. return 0;
  9335. }
  9336. /* Control characters are not allowed, including zero */
  9337. if (iscntrl((unsigned char)*buf)) {
  9338. return -1;
  9339. }
  9340. /* Find end of HTTP header */
  9341. request_length = get_http_header_len(buf, len);
  9342. if (request_length <= 0) {
  9343. return request_length;
  9344. }
  9345. buf[request_length - 1] = '\0';
  9346. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9347. return -1;
  9348. }
  9349. /* The first word has to be the HTTP method */
  9350. ri->request_method = buf;
  9351. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9352. return -1;
  9353. }
  9354. /* The second word is the URI */
  9355. ri->request_uri = buf;
  9356. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9357. return -1;
  9358. }
  9359. /* Next would be the HTTP version */
  9360. ri->http_version = buf;
  9361. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9362. return -1;
  9363. }
  9364. /* Check for a valid HTTP version key */
  9365. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9366. /* Invalid request */
  9367. return -1;
  9368. }
  9369. ri->http_version += 5;
  9370. /* Parse all HTTP headers */
  9371. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9372. if (ri->num_headers < 0) {
  9373. /* Error while parsing headers */
  9374. return -1;
  9375. }
  9376. return request_length + init_skip;
  9377. }
  9378. static int
  9379. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9380. {
  9381. int response_length;
  9382. int init_skip = 0;
  9383. char *tmp, *tmp2;
  9384. long l;
  9385. /* Initialize elements. */
  9386. ri->http_version = ri->status_text = NULL;
  9387. ri->num_headers = ri->status_code = 0;
  9388. /* RFC says that all initial whitespaces should be ingored */
  9389. /* This included all leading \r and \n (isspace) */
  9390. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9391. while ((len > 0) && isspace((unsigned char)*buf)) {
  9392. buf++;
  9393. len--;
  9394. init_skip++;
  9395. }
  9396. if (len == 0) {
  9397. /* Incomplete request */
  9398. return 0;
  9399. }
  9400. /* Control characters are not allowed, including zero */
  9401. if (iscntrl((unsigned char)*buf)) {
  9402. return -1;
  9403. }
  9404. /* Find end of HTTP header */
  9405. response_length = get_http_header_len(buf, len);
  9406. if (response_length <= 0) {
  9407. return response_length;
  9408. }
  9409. buf[response_length - 1] = '\0';
  9410. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9411. return -1;
  9412. }
  9413. /* The first word is the HTTP version */
  9414. /* Check for a valid HTTP version key */
  9415. if (strncmp(buf, "HTTP/", 5) != 0) {
  9416. /* Invalid request */
  9417. return -1;
  9418. }
  9419. buf += 5;
  9420. if (!isgraph((unsigned char)buf[0])) {
  9421. /* Invalid request */
  9422. return -1;
  9423. }
  9424. ri->http_version = buf;
  9425. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9426. return -1;
  9427. }
  9428. /* The second word is the status as a number */
  9429. tmp = buf;
  9430. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9431. return -1;
  9432. }
  9433. l = strtol(tmp, &tmp2, 10);
  9434. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9435. /* Everything else but a 3 digit code is invalid */
  9436. return -1;
  9437. }
  9438. ri->status_code = (int)l;
  9439. /* The rest of the line is the status text */
  9440. ri->status_text = buf;
  9441. /* Find end of status text */
  9442. /* isgraph or isspace = isprint */
  9443. while (isprint((unsigned char)*buf)) {
  9444. buf++;
  9445. }
  9446. if ((*buf != '\r') && (*buf != '\n')) {
  9447. return -1;
  9448. }
  9449. /* Terminate string and forward buf to next line */
  9450. do {
  9451. *buf = 0;
  9452. buf++;
  9453. } while (isspace((unsigned char)*buf));
  9454. /* Parse all HTTP headers */
  9455. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9456. if (ri->num_headers < 0) {
  9457. /* Error while parsing headers */
  9458. return -1;
  9459. }
  9460. return response_length + init_skip;
  9461. }
  9462. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9463. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9464. * buffer (which marks the end of HTTP request). Buffer buf may already
  9465. * have some data. The length of the data is stored in nread.
  9466. * Upon every read operation, increase nread by the number of bytes read. */
  9467. static int
  9468. read_message(FILE *fp,
  9469. struct mg_connection *conn,
  9470. char *buf,
  9471. int bufsiz,
  9472. int *nread)
  9473. {
  9474. int request_len, n = 0;
  9475. struct timespec last_action_time;
  9476. double request_timeout;
  9477. if (!conn) {
  9478. return 0;
  9479. }
  9480. memset(&last_action_time, 0, sizeof(last_action_time));
  9481. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9482. /* value of request_timeout is in seconds, config in milliseconds */
  9483. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9484. } else {
  9485. request_timeout = -1.0;
  9486. }
  9487. if (conn->handled_requests > 0) {
  9488. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9489. request_timeout =
  9490. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9491. }
  9492. }
  9493. request_len = get_http_header_len(buf, *nread);
  9494. while (request_len == 0) {
  9495. /* Full request not yet received */
  9496. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9497. /* Server is to be stopped. */
  9498. return -1;
  9499. }
  9500. if (*nread >= bufsiz) {
  9501. /* Request too long */
  9502. return -2;
  9503. }
  9504. n = pull_inner(
  9505. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9506. if (n == -2) {
  9507. /* Receive error */
  9508. return -1;
  9509. }
  9510. /* update clock after every read request */
  9511. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9512. if (n > 0) {
  9513. *nread += n;
  9514. request_len = get_http_header_len(buf, *nread);
  9515. }
  9516. if ((request_len == 0) && (request_timeout >= 0)) {
  9517. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9518. > request_timeout) {
  9519. /* Timeout */
  9520. return -1;
  9521. }
  9522. }
  9523. }
  9524. return request_len;
  9525. }
  9526. #if !defined(NO_CGI) || !defined(NO_FILES)
  9527. static int
  9528. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9529. {
  9530. const char *expect;
  9531. char buf[MG_BUF_LEN];
  9532. int success = 0;
  9533. if (!conn) {
  9534. return 0;
  9535. }
  9536. expect = mg_get_header(conn, "Expect");
  9537. DEBUG_ASSERT(fp != NULL);
  9538. if (!fp) {
  9539. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9540. return 0;
  9541. }
  9542. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9543. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9544. */
  9545. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9546. } else {
  9547. if (expect != NULL) {
  9548. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9549. conn->status_code = 100;
  9550. } else {
  9551. conn->status_code = 200;
  9552. }
  9553. DEBUG_ASSERT(conn->consumed_content == 0);
  9554. if (conn->consumed_content != 0) {
  9555. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9556. return 0;
  9557. }
  9558. for (;;) {
  9559. int nread = mg_read(conn, buf, sizeof(buf));
  9560. if (nread <= 0) {
  9561. success = (nread == 0);
  9562. break;
  9563. }
  9564. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9565. break;
  9566. }
  9567. }
  9568. /* Each error code path in this function must send an error */
  9569. if (!success) {
  9570. /* NOTE: Maybe some data has already been sent. */
  9571. /* TODO (low): If some data has been sent, a correct error
  9572. * reply can no longer be sent, so just close the connection */
  9573. mg_send_http_error(conn, 500, "%s", "");
  9574. }
  9575. }
  9576. return success;
  9577. }
  9578. #endif
  9579. #if defined(USE_TIMERS)
  9580. #define TIMER_API static
  9581. #include "timer.inl"
  9582. #endif /* USE_TIMERS */
  9583. #if !defined(NO_CGI)
  9584. /* This structure helps to create an environment for the spawned CGI
  9585. * program.
  9586. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9587. * last element must be NULL.
  9588. * However, on Windows there is a requirement that all these
  9589. * VARIABLE=VALUE\0
  9590. * strings must reside in a contiguous buffer. The end of the buffer is
  9591. * marked by two '\0' characters.
  9592. * We satisfy both worlds: we create an envp array (which is vars), all
  9593. * entries are actually pointers inside buf. */
  9594. struct cgi_environment {
  9595. struct mg_connection *conn;
  9596. /* Data block */
  9597. char *buf; /* Environment buffer */
  9598. size_t buflen; /* Space available in buf */
  9599. size_t bufused; /* Space taken in buf */
  9600. /* Index block */
  9601. char **var; /* char **envp */
  9602. size_t varlen; /* Number of variables available in var */
  9603. size_t varused; /* Number of variables stored in var */
  9604. };
  9605. static void addenv(struct cgi_environment *env,
  9606. PRINTF_FORMAT_STRING(const char *fmt),
  9607. ...) PRINTF_ARGS(2, 3);
  9608. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9609. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9610. static void
  9611. addenv(struct cgi_environment *env, const char *fmt, ...)
  9612. {
  9613. size_t i, n, space;
  9614. int truncated = 0;
  9615. char *added;
  9616. va_list ap;
  9617. if ((env->varlen - env->varused) < 2) {
  9618. mg_cry_internal(env->conn,
  9619. "%s: Cannot register CGI variable [%s]",
  9620. __func__,
  9621. fmt);
  9622. return;
  9623. }
  9624. /* Calculate how much space is left in the buffer */
  9625. space = (env->buflen - env->bufused);
  9626. do {
  9627. /* Space for "\0\0" is always needed. */
  9628. if (space <= 2) {
  9629. /* Allocate new buffer */
  9630. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9631. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9632. if (!added) {
  9633. /* Out of memory */
  9634. mg_cry_internal(
  9635. env->conn,
  9636. "%s: Cannot allocate memory for CGI variable [%s]",
  9637. __func__,
  9638. fmt);
  9639. return;
  9640. }
  9641. /* Retarget pointers */
  9642. env->buf = added;
  9643. env->buflen = n;
  9644. for (i = 0, n = 0; i < env->varused; i++) {
  9645. env->var[i] = added + n;
  9646. n += strlen(added + n) + 1;
  9647. }
  9648. space = (env->buflen - env->bufused);
  9649. }
  9650. /* Make a pointer to the free space int the buffer */
  9651. added = env->buf + env->bufused;
  9652. /* Copy VARIABLE=VALUE\0 string into the free space */
  9653. va_start(ap, fmt);
  9654. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9655. va_end(ap);
  9656. /* Do not add truncated strings to the environment */
  9657. if (truncated) {
  9658. /* Reallocate the buffer */
  9659. space = 0;
  9660. }
  9661. } while (truncated);
  9662. /* Calculate number of bytes added to the environment */
  9663. n = strlen(added) + 1;
  9664. env->bufused += n;
  9665. /* Append a pointer to the added string into the envp array */
  9666. env->var[env->varused] = added;
  9667. env->varused++;
  9668. }
  9669. /* Return 0 on success, non-zero if an error occurs. */
  9670. static int
  9671. prepare_cgi_environment(struct mg_connection *conn,
  9672. const char *prog,
  9673. struct cgi_environment *env)
  9674. {
  9675. const char *s;
  9676. struct vec var_vec;
  9677. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9678. int i, truncated, uri_len;
  9679. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9680. return -1;
  9681. }
  9682. env->conn = conn;
  9683. env->buflen = CGI_ENVIRONMENT_SIZE;
  9684. env->bufused = 0;
  9685. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9686. if (env->buf == NULL) {
  9687. mg_cry_internal(conn,
  9688. "%s: Not enough memory for environmental buffer",
  9689. __func__);
  9690. return -1;
  9691. }
  9692. env->varlen = MAX_CGI_ENVIR_VARS;
  9693. env->varused = 0;
  9694. env->var =
  9695. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9696. if (env->var == NULL) {
  9697. mg_cry_internal(conn,
  9698. "%s: Not enough memory for environmental variables",
  9699. __func__);
  9700. mg_free(env->buf);
  9701. return -1;
  9702. }
  9703. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9704. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9705. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9706. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9707. /* Prepare the environment block */
  9708. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9709. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9710. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9711. #if defined(USE_IPV6)
  9712. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9713. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9714. } else
  9715. #endif
  9716. {
  9717. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9718. }
  9719. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9720. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9721. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9722. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9723. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9724. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9725. /* SCRIPT_NAME */
  9726. uri_len = (int)strlen(conn->request_info.local_uri);
  9727. if (conn->path_info == NULL) {
  9728. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9729. /* URI: /path_to_script/script.cgi */
  9730. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9731. } else {
  9732. /* URI: /path_to_script/ ... using index.cgi */
  9733. const char *index_file = strrchr(prog, '/');
  9734. if (index_file) {
  9735. addenv(env,
  9736. "SCRIPT_NAME=%s%s",
  9737. conn->request_info.local_uri,
  9738. index_file + 1);
  9739. }
  9740. }
  9741. } else {
  9742. /* URI: /path_to_script/script.cgi/path_info */
  9743. addenv(env,
  9744. "SCRIPT_NAME=%.*s",
  9745. uri_len - (int)strlen(conn->path_info),
  9746. conn->request_info.local_uri);
  9747. }
  9748. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9749. if (conn->path_info == NULL) {
  9750. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9751. } else {
  9752. addenv(env,
  9753. "PATH_TRANSLATED=%s%s",
  9754. conn->dom_ctx->config[DOCUMENT_ROOT],
  9755. conn->path_info);
  9756. }
  9757. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9758. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9759. addenv(env, "CONTENT_TYPE=%s", s);
  9760. }
  9761. if (conn->request_info.query_string != NULL) {
  9762. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9763. }
  9764. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9765. addenv(env, "CONTENT_LENGTH=%s", s);
  9766. }
  9767. if ((s = getenv("PATH")) != NULL) {
  9768. addenv(env, "PATH=%s", s);
  9769. }
  9770. if (conn->path_info != NULL) {
  9771. addenv(env, "PATH_INFO=%s", conn->path_info);
  9772. }
  9773. if (conn->status_code > 0) {
  9774. /* CGI error handler should show the status code */
  9775. addenv(env, "STATUS=%d", conn->status_code);
  9776. }
  9777. #if defined(_WIN32)
  9778. if ((s = getenv("COMSPEC")) != NULL) {
  9779. addenv(env, "COMSPEC=%s", s);
  9780. }
  9781. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9782. addenv(env, "SYSTEMROOT=%s", s);
  9783. }
  9784. if ((s = getenv("SystemDrive")) != NULL) {
  9785. addenv(env, "SystemDrive=%s", s);
  9786. }
  9787. if ((s = getenv("ProgramFiles")) != NULL) {
  9788. addenv(env, "ProgramFiles=%s", s);
  9789. }
  9790. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9791. addenv(env, "ProgramFiles(x86)=%s", s);
  9792. }
  9793. #else
  9794. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9795. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9796. }
  9797. #endif /* _WIN32 */
  9798. if ((s = getenv("PERLLIB")) != NULL) {
  9799. addenv(env, "PERLLIB=%s", s);
  9800. }
  9801. if (conn->request_info.remote_user != NULL) {
  9802. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9803. addenv(env, "%s", "AUTH_TYPE=Digest");
  9804. }
  9805. /* Add all headers as HTTP_* variables */
  9806. for (i = 0; i < conn->request_info.num_headers; i++) {
  9807. (void)mg_snprintf(conn,
  9808. &truncated,
  9809. http_var_name,
  9810. sizeof(http_var_name),
  9811. "HTTP_%s",
  9812. conn->request_info.http_headers[i].name);
  9813. if (truncated) {
  9814. mg_cry_internal(conn,
  9815. "%s: HTTP header variable too long [%s]",
  9816. __func__,
  9817. conn->request_info.http_headers[i].name);
  9818. continue;
  9819. }
  9820. /* Convert variable name into uppercase, and change - to _ */
  9821. for (p = http_var_name; *p != '\0'; p++) {
  9822. if (*p == '-') {
  9823. *p = '_';
  9824. }
  9825. *p = (char)toupper((unsigned char)*p);
  9826. }
  9827. addenv(env,
  9828. "%s=%s",
  9829. http_var_name,
  9830. conn->request_info.http_headers[i].value);
  9831. }
  9832. /* Add user-specified variables */
  9833. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9834. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9835. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9836. }
  9837. env->var[env->varused] = NULL;
  9838. env->buf[env->bufused] = '\0';
  9839. return 0;
  9840. }
  9841. /* Data for CGI process control: PID and number of references */
  9842. struct process_control_data {
  9843. pid_t pid;
  9844. int references;
  9845. };
  9846. static int
  9847. abort_process(void *data)
  9848. {
  9849. /* Waitpid checks for child status and won't work for a pid that does
  9850. * not identify a child of the current process. Thus, if the pid is
  9851. * reused, we will not affect a different process. */
  9852. struct process_control_data *proc = (struct process_control_data *)data;
  9853. int status = 0;
  9854. int refs;
  9855. pid_t ret_pid;
  9856. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9857. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9858. /* Stop child process */
  9859. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9860. kill(proc->pid, SIGABRT);
  9861. /* Wait until process is terminated (don't leave zombies) */
  9862. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9863. ;
  9864. } else {
  9865. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9866. }
  9867. /* Dec reference counter */
  9868. refs = mg_atomic_dec(&proc->references);
  9869. if (refs == 0) {
  9870. /* no more references - free data */
  9871. mg_free(data);
  9872. }
  9873. return 0;
  9874. }
  9875. /* Local (static) function assumes all arguments are valid. */
  9876. static void
  9877. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9878. {
  9879. char *buf;
  9880. size_t buflen;
  9881. int headers_len, data_len, i, truncated;
  9882. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9883. const char *status, *status_text, *connection_state;
  9884. char *pbuf, dir[PATH_MAX], *p;
  9885. struct mg_request_info ri;
  9886. struct cgi_environment blk;
  9887. FILE *in = NULL, *out = NULL, *err = NULL;
  9888. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9889. pid_t pid = (pid_t)-1;
  9890. struct process_control_data *proc = NULL;
  9891. #if defined(USE_TIMERS)
  9892. double cgi_timeout = -1.0;
  9893. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9894. /* Get timeout in seconds */
  9895. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9896. }
  9897. #endif
  9898. buf = NULL;
  9899. buflen = conn->phys_ctx->max_request_size;
  9900. i = prepare_cgi_environment(conn, prog, &blk);
  9901. if (i != 0) {
  9902. blk.buf = NULL;
  9903. blk.var = NULL;
  9904. goto done;
  9905. }
  9906. /* CGI must be executed in its own directory. 'dir' must point to the
  9907. * directory containing executable program, 'p' must point to the
  9908. * executable program name relative to 'dir'. */
  9909. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9910. if (truncated) {
  9911. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9912. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9913. goto done;
  9914. }
  9915. if ((p = strrchr(dir, '/')) != NULL) {
  9916. *p++ = '\0';
  9917. } else {
  9918. dir[0] = '.';
  9919. dir[1] = '\0';
  9920. p = (char *)prog;
  9921. }
  9922. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9923. status = strerror(ERRNO);
  9924. mg_cry_internal(
  9925. conn,
  9926. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9927. prog,
  9928. status);
  9929. mg_send_http_error(conn,
  9930. 500,
  9931. "Error: Cannot create CGI pipe: %s",
  9932. status);
  9933. goto done;
  9934. }
  9935. proc = (struct process_control_data *)
  9936. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9937. if (proc == NULL) {
  9938. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9939. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9940. goto done;
  9941. }
  9942. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9943. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9944. if (pid == (pid_t)-1) {
  9945. status = strerror(ERRNO);
  9946. mg_cry_internal(
  9947. conn,
  9948. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9949. prog,
  9950. status);
  9951. mg_send_http_error(conn,
  9952. 500,
  9953. "Error: Cannot spawn CGI process [%s]: %s",
  9954. prog,
  9955. status);
  9956. mg_free(proc);
  9957. proc = NULL;
  9958. goto done;
  9959. }
  9960. /* Store data in shared process_control_data */
  9961. proc->pid = pid;
  9962. proc->references = 1;
  9963. #if defined(USE_TIMERS)
  9964. if (cgi_timeout > 0.0) {
  9965. proc->references = 2;
  9966. // Start a timer for CGI
  9967. timer_add(conn->phys_ctx,
  9968. cgi_timeout /* in seconds */,
  9969. 0.0,
  9970. 1,
  9971. abort_process,
  9972. (void *)proc);
  9973. }
  9974. #endif
  9975. /* Parent closes only one side of the pipes.
  9976. * If we don't mark them as closed, close() attempt before
  9977. * return from this function throws an exception on Windows.
  9978. * Windows does not like when closed descriptor is closed again. */
  9979. (void)close(fdin[0]);
  9980. (void)close(fdout[1]);
  9981. (void)close(fderr[1]);
  9982. fdin[0] = fdout[1] = fderr[1] = -1;
  9983. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9984. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9985. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9986. status = strerror(ERRNO);
  9987. mg_cry_internal(conn,
  9988. "Error: CGI program \"%s\": Can not open fd: %s",
  9989. prog,
  9990. status);
  9991. mg_send_http_error(conn,
  9992. 500,
  9993. "Error: CGI can not open fd\nfdopen: %s",
  9994. status);
  9995. goto done;
  9996. }
  9997. setbuf(in, NULL);
  9998. setbuf(out, NULL);
  9999. setbuf(err, NULL);
  10000. fout.access.fp = out;
  10001. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10002. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10003. conn->content_len);
  10004. /* This is a POST/PUT request, or another request with body data. */
  10005. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10006. /* Error sending the body data */
  10007. mg_cry_internal(
  10008. conn,
  10009. "Error: CGI program \"%s\": Forward body data failed",
  10010. prog);
  10011. goto done;
  10012. }
  10013. }
  10014. /* Close so child gets an EOF. */
  10015. fclose(in);
  10016. in = NULL;
  10017. fdin[1] = -1;
  10018. /* Now read CGI reply into a buffer. We need to set correct
  10019. * status code, thus we need to see all HTTP headers first.
  10020. * Do not send anything back to client, until we buffer in all
  10021. * HTTP headers. */
  10022. data_len = 0;
  10023. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10024. if (buf == NULL) {
  10025. mg_send_http_error(conn,
  10026. 500,
  10027. "Error: Not enough memory for CGI buffer (%u bytes)",
  10028. (unsigned int)buflen);
  10029. mg_cry_internal(
  10030. conn,
  10031. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10032. "bytes)",
  10033. prog,
  10034. (unsigned int)buflen);
  10035. goto done;
  10036. }
  10037. DEBUG_TRACE("CGI: %s", "wait for response");
  10038. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10039. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10040. if (headers_len <= 0) {
  10041. /* Could not parse the CGI response. Check if some error message on
  10042. * stderr. */
  10043. i = pull_all(err, conn, buf, (int)buflen);
  10044. if (i > 0) {
  10045. /* CGI program explicitly sent an error */
  10046. /* Write the error message to the internal log */
  10047. mg_cry_internal(conn,
  10048. "Error: CGI program \"%s\" sent error "
  10049. "message: [%.*s]",
  10050. prog,
  10051. i,
  10052. buf);
  10053. /* Don't send the error message back to the client */
  10054. mg_send_http_error(conn,
  10055. 500,
  10056. "Error: CGI program \"%s\" failed.",
  10057. prog);
  10058. } else {
  10059. /* CGI program did not explicitly send an error, but a broken
  10060. * respon header */
  10061. mg_cry_internal(conn,
  10062. "Error: CGI program sent malformed or too big "
  10063. "(>%u bytes) HTTP headers: [%.*s]",
  10064. (unsigned)buflen,
  10065. data_len,
  10066. buf);
  10067. mg_send_http_error(conn,
  10068. 500,
  10069. "Error: CGI program sent malformed or too big "
  10070. "(>%u bytes) HTTP headers: [%.*s]",
  10071. (unsigned)buflen,
  10072. data_len,
  10073. buf);
  10074. }
  10075. /* in both cases, abort processing CGI */
  10076. goto done;
  10077. }
  10078. pbuf = buf;
  10079. buf[headers_len - 1] = '\0';
  10080. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10081. /* Make up and send the status line */
  10082. status_text = "OK";
  10083. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10084. != NULL) {
  10085. conn->status_code = atoi(status);
  10086. status_text = status;
  10087. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10088. status_text++;
  10089. }
  10090. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10091. != NULL) {
  10092. conn->status_code = 307;
  10093. } else {
  10094. conn->status_code = 200;
  10095. }
  10096. connection_state =
  10097. get_header(ri.http_headers, ri.num_headers, "Connection");
  10098. if (!header_has_option(connection_state, "keep-alive")) {
  10099. conn->must_close = 1;
  10100. }
  10101. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10102. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10103. /* Send headers */
  10104. for (i = 0; i < ri.num_headers; i++) {
  10105. DEBUG_TRACE("CGI header: %s: %s",
  10106. ri.http_headers[i].name,
  10107. ri.http_headers[i].value);
  10108. mg_printf(conn,
  10109. "%s: %s\r\n",
  10110. ri.http_headers[i].name,
  10111. ri.http_headers[i].value);
  10112. }
  10113. mg_write(conn, "\r\n", 2);
  10114. /* Send chunk of data that may have been read after the headers */
  10115. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10116. /* Read the rest of CGI output and send to the client */
  10117. DEBUG_TRACE("CGI: %s", "forward all data");
  10118. send_file_data(conn, &fout, 0, INT64_MAX);
  10119. DEBUG_TRACE("CGI: %s", "all data sent");
  10120. done:
  10121. mg_free(blk.var);
  10122. mg_free(blk.buf);
  10123. if (pid != (pid_t)-1) {
  10124. abort_process((void *)proc);
  10125. }
  10126. if (fdin[0] != -1) {
  10127. close(fdin[0]);
  10128. }
  10129. if (fdout[1] != -1) {
  10130. close(fdout[1]);
  10131. }
  10132. if (fderr[1] != -1) {
  10133. close(fderr[1]);
  10134. }
  10135. if (in != NULL) {
  10136. fclose(in);
  10137. } else if (fdin[1] != -1) {
  10138. close(fdin[1]);
  10139. }
  10140. if (out != NULL) {
  10141. fclose(out);
  10142. } else if (fdout[0] != -1) {
  10143. close(fdout[0]);
  10144. }
  10145. if (err != NULL) {
  10146. fclose(err);
  10147. } else if (fderr[0] != -1) {
  10148. close(fderr[0]);
  10149. }
  10150. mg_free(buf);
  10151. }
  10152. #endif /* !NO_CGI */
  10153. #if !defined(NO_FILES)
  10154. static void
  10155. mkcol(struct mg_connection *conn, const char *path)
  10156. {
  10157. int rc, body_len;
  10158. struct de de;
  10159. char date[64];
  10160. time_t curtime = time(NULL);
  10161. if (conn == NULL) {
  10162. return;
  10163. }
  10164. /* TODO (mid): Check the mg_send_http_error situations in this function
  10165. */
  10166. memset(&de.file, 0, sizeof(de.file));
  10167. if (!mg_stat(conn, path, &de.file)) {
  10168. mg_cry_internal(conn,
  10169. "%s: mg_stat(%s) failed: %s",
  10170. __func__,
  10171. path,
  10172. strerror(ERRNO));
  10173. }
  10174. if (de.file.last_modified) {
  10175. /* TODO (mid): This check does not seem to make any sense ! */
  10176. /* TODO (mid): Add a webdav unit test first, before changing
  10177. * anything here. */
  10178. mg_send_http_error(
  10179. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10180. return;
  10181. }
  10182. body_len = conn->data_len - conn->request_len;
  10183. if (body_len > 0) {
  10184. mg_send_http_error(
  10185. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10186. return;
  10187. }
  10188. rc = mg_mkdir(conn, path, 0755);
  10189. if (rc == 0) {
  10190. conn->status_code = 201;
  10191. gmt_time_string(date, sizeof(date), &curtime);
  10192. mg_printf(conn,
  10193. "HTTP/1.1 %d Created\r\n"
  10194. "Date: %s\r\n",
  10195. conn->status_code,
  10196. date);
  10197. send_static_cache_header(conn);
  10198. send_additional_header(conn);
  10199. mg_printf(conn,
  10200. "Content-Length: 0\r\n"
  10201. "Connection: %s\r\n\r\n",
  10202. suggest_connection_header(conn));
  10203. } else {
  10204. if (errno == EEXIST) {
  10205. mg_send_http_error(
  10206. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10207. } else if (errno == EACCES) {
  10208. mg_send_http_error(
  10209. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10210. } else if (errno == ENOENT) {
  10211. mg_send_http_error(
  10212. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10213. } else {
  10214. mg_send_http_error(
  10215. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10216. }
  10217. }
  10218. }
  10219. static void
  10220. put_file(struct mg_connection *conn, const char *path)
  10221. {
  10222. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10223. const char *range;
  10224. int64_t r1, r2;
  10225. int rc;
  10226. char date[64];
  10227. time_t curtime = time(NULL);
  10228. if (conn == NULL) {
  10229. return;
  10230. }
  10231. if (mg_stat(conn, path, &file.stat)) {
  10232. /* File already exists */
  10233. conn->status_code = 200;
  10234. if (file.stat.is_directory) {
  10235. /* This is an already existing directory,
  10236. * so there is nothing to do for the server. */
  10237. rc = 0;
  10238. } else {
  10239. /* File exists and is not a directory. */
  10240. /* Can it be replaced? */
  10241. #if defined(MG_USE_OPEN_FILE)
  10242. if (file.access.membuf != NULL) {
  10243. /* This is an "in-memory" file, that can not be replaced */
  10244. mg_send_http_error(conn,
  10245. 405,
  10246. "Error: Put not possible\nReplacing %s "
  10247. "is not supported",
  10248. path);
  10249. return;
  10250. }
  10251. #endif
  10252. /* Check if the server may write this file */
  10253. if (access(path, W_OK) == 0) {
  10254. /* Access granted */
  10255. rc = 1;
  10256. } else {
  10257. mg_send_http_error(
  10258. conn,
  10259. 403,
  10260. "Error: Put not possible\nReplacing %s is not allowed",
  10261. path);
  10262. return;
  10263. }
  10264. }
  10265. } else {
  10266. /* File should be created */
  10267. conn->status_code = 201;
  10268. rc = put_dir(conn, path);
  10269. }
  10270. if (rc == 0) {
  10271. /* put_dir returns 0 if path is a directory */
  10272. gmt_time_string(date, sizeof(date), &curtime);
  10273. mg_printf(conn,
  10274. "HTTP/1.1 %d %s\r\n",
  10275. conn->status_code,
  10276. mg_get_response_code_text(NULL, conn->status_code));
  10277. send_no_cache_header(conn);
  10278. send_additional_header(conn);
  10279. mg_printf(conn,
  10280. "Date: %s\r\n"
  10281. "Content-Length: 0\r\n"
  10282. "Connection: %s\r\n\r\n",
  10283. date,
  10284. suggest_connection_header(conn));
  10285. /* Request to create a directory has been fulfilled successfully.
  10286. * No need to put a file. */
  10287. return;
  10288. }
  10289. if (rc == -1) {
  10290. /* put_dir returns -1 if the path is too long */
  10291. mg_send_http_error(conn,
  10292. 414,
  10293. "Error: Path too long\nput_dir(%s): %s",
  10294. path,
  10295. strerror(ERRNO));
  10296. return;
  10297. }
  10298. if (rc == -2) {
  10299. /* put_dir returns -2 if the directory can not be created */
  10300. mg_send_http_error(conn,
  10301. 500,
  10302. "Error: Can not create directory\nput_dir(%s): %s",
  10303. path,
  10304. strerror(ERRNO));
  10305. return;
  10306. }
  10307. /* A file should be created or overwritten. */
  10308. /* Currently CivetWeb does not nead read+write access. */
  10309. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10310. || file.access.fp == NULL) {
  10311. (void)mg_fclose(&file.access);
  10312. mg_send_http_error(conn,
  10313. 500,
  10314. "Error: Can not create file\nfopen(%s): %s",
  10315. path,
  10316. strerror(ERRNO));
  10317. return;
  10318. }
  10319. fclose_on_exec(&file.access, conn);
  10320. range = mg_get_header(conn, "Content-Range");
  10321. r1 = r2 = 0;
  10322. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10323. conn->status_code = 206; /* Partial content */
  10324. fseeko(file.access.fp, r1, SEEK_SET);
  10325. }
  10326. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10327. /* forward_body_data failed.
  10328. * The error code has already been sent to the client,
  10329. * and conn->status_code is already set. */
  10330. (void)mg_fclose(&file.access);
  10331. return;
  10332. }
  10333. if (mg_fclose(&file.access) != 0) {
  10334. /* fclose failed. This might have different reasons, but a likely
  10335. * one is "no space on disk", http 507. */
  10336. conn->status_code = 507;
  10337. }
  10338. gmt_time_string(date, sizeof(date), &curtime);
  10339. mg_printf(conn,
  10340. "HTTP/1.1 %d %s\r\n",
  10341. conn->status_code,
  10342. mg_get_response_code_text(NULL, conn->status_code));
  10343. send_no_cache_header(conn);
  10344. send_additional_header(conn);
  10345. mg_printf(conn,
  10346. "Date: %s\r\n"
  10347. "Content-Length: 0\r\n"
  10348. "Connection: %s\r\n\r\n",
  10349. date,
  10350. suggest_connection_header(conn));
  10351. }
  10352. static void
  10353. delete_file(struct mg_connection *conn, const char *path)
  10354. {
  10355. struct de de;
  10356. memset(&de.file, 0, sizeof(de.file));
  10357. if (!mg_stat(conn, path, &de.file)) {
  10358. /* mg_stat returns 0 if the file does not exist */
  10359. mg_send_http_error(conn,
  10360. 404,
  10361. "Error: Cannot delete file\nFile %s not found",
  10362. path);
  10363. return;
  10364. }
  10365. #if 0 /* Ignore if a file in memory is inside a folder */
  10366. if (de.access.membuf != NULL) {
  10367. /* the file is cached in memory */
  10368. mg_send_http_error(
  10369. conn,
  10370. 405,
  10371. "Error: Delete not possible\nDeleting %s is not supported",
  10372. path);
  10373. return;
  10374. }
  10375. #endif
  10376. if (de.file.is_directory) {
  10377. if (remove_directory(conn, path)) {
  10378. /* Delete is successful: Return 204 without content. */
  10379. mg_send_http_error(conn, 204, "%s", "");
  10380. } else {
  10381. /* Delete is not successful: Return 500 (Server error). */
  10382. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10383. }
  10384. return;
  10385. }
  10386. /* This is an existing file (not a directory).
  10387. * Check if write permission is granted. */
  10388. if (access(path, W_OK) != 0) {
  10389. /* File is read only */
  10390. mg_send_http_error(
  10391. conn,
  10392. 403,
  10393. "Error: Delete not possible\nDeleting %s is not allowed",
  10394. path);
  10395. return;
  10396. }
  10397. /* Try to delete it. */
  10398. if (mg_remove(conn, path) == 0) {
  10399. /* Delete was successful: Return 204 without content. */
  10400. mg_send_http_error(conn, 204, "%s", "");
  10401. } else {
  10402. /* Delete not successful (file locked). */
  10403. mg_send_http_error(conn,
  10404. 423,
  10405. "Error: Cannot delete file\nremove(%s): %s",
  10406. path,
  10407. strerror(ERRNO));
  10408. }
  10409. }
  10410. #endif /* !NO_FILES */
  10411. #if !defined(NO_FILESYSTEMS)
  10412. static void
  10413. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10414. static void
  10415. do_ssi_include(struct mg_connection *conn,
  10416. const char *ssi,
  10417. char *tag,
  10418. int include_level)
  10419. {
  10420. char file_name[MG_BUF_LEN], path[512], *p;
  10421. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10422. size_t len;
  10423. int truncated = 0;
  10424. if (conn == NULL) {
  10425. return;
  10426. }
  10427. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10428. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10429. * always < MG_BUF_LEN. */
  10430. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10431. /* File name is relative to the webserver root */
  10432. file_name[511] = 0;
  10433. (void)mg_snprintf(conn,
  10434. &truncated,
  10435. path,
  10436. sizeof(path),
  10437. "%s/%s",
  10438. conn->dom_ctx->config[DOCUMENT_ROOT],
  10439. file_name);
  10440. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10441. /* File name is relative to the webserver working directory
  10442. * or it is absolute system path */
  10443. file_name[511] = 0;
  10444. (void)
  10445. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10446. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10447. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10448. /* File name is relative to the currect document */
  10449. file_name[511] = 0;
  10450. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10451. if (!truncated) {
  10452. if ((p = strrchr(path, '/')) != NULL) {
  10453. p[1] = '\0';
  10454. }
  10455. len = strlen(path);
  10456. (void)mg_snprintf(conn,
  10457. &truncated,
  10458. path + len,
  10459. sizeof(path) - len,
  10460. "%s",
  10461. file_name);
  10462. }
  10463. } else {
  10464. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10465. return;
  10466. }
  10467. if (truncated) {
  10468. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10469. return;
  10470. }
  10471. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10472. mg_cry_internal(conn,
  10473. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10474. tag,
  10475. path,
  10476. strerror(ERRNO));
  10477. } else {
  10478. fclose_on_exec(&file.access, conn);
  10479. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10480. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10481. path)
  10482. > 0) {
  10483. send_ssi_file(conn, path, &file, include_level + 1);
  10484. } else {
  10485. send_file_data(conn, &file, 0, INT64_MAX);
  10486. }
  10487. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10488. }
  10489. }
  10490. #if !defined(NO_POPEN)
  10491. static void
  10492. do_ssi_exec(struct mg_connection *conn, char *tag)
  10493. {
  10494. char cmd[1024] = "";
  10495. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10496. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10497. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10498. } else {
  10499. cmd[1023] = 0;
  10500. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10501. mg_cry_internal(conn,
  10502. "Cannot SSI #exec: [%s]: %s",
  10503. cmd,
  10504. strerror(ERRNO));
  10505. } else {
  10506. send_file_data(conn, &file, 0, INT64_MAX);
  10507. pclose(file.access.fp);
  10508. }
  10509. }
  10510. }
  10511. #endif /* !NO_POPEN */
  10512. static int
  10513. mg_fgetc(struct mg_file *filep, int offset)
  10514. {
  10515. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10516. if (filep == NULL) {
  10517. return EOF;
  10518. }
  10519. #if defined(MG_USE_OPEN_FILE)
  10520. if ((filep->access.membuf != NULL) && (offset >= 0)
  10521. && (((unsigned int)(offset)) < filep->stat.size)) {
  10522. return ((const unsigned char *)filep->access.membuf)[offset];
  10523. } else /* else block below */
  10524. #endif
  10525. if (filep->access.fp != NULL) {
  10526. return fgetc(filep->access.fp);
  10527. } else {
  10528. return EOF;
  10529. }
  10530. }
  10531. static void
  10532. send_ssi_file(struct mg_connection *conn,
  10533. const char *path,
  10534. struct mg_file *filep,
  10535. int include_level)
  10536. {
  10537. char buf[MG_BUF_LEN];
  10538. int ch, offset, len, in_tag, in_ssi_tag;
  10539. if (include_level > 10) {
  10540. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10541. return;
  10542. }
  10543. in_tag = in_ssi_tag = len = offset = 0;
  10544. /* Read file, byte by byte, and look for SSI include tags */
  10545. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10546. if (in_tag) {
  10547. /* We are in a tag, either SSI tag or html tag */
  10548. if (ch == '>') {
  10549. /* Tag is closing */
  10550. buf[len++] = '>';
  10551. if (in_ssi_tag) {
  10552. /* Handle SSI tag */
  10553. buf[len] = 0;
  10554. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10555. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10556. #if !defined(NO_POPEN)
  10557. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10558. do_ssi_exec(conn, buf + 9);
  10559. #endif /* !NO_POPEN */
  10560. } else {
  10561. mg_cry_internal(conn,
  10562. "%s: unknown SSI "
  10563. "command: \"%s\"",
  10564. path,
  10565. buf);
  10566. }
  10567. len = 0;
  10568. in_ssi_tag = in_tag = 0;
  10569. } else {
  10570. /* Not an SSI tag */
  10571. /* Flush buffer */
  10572. (void)mg_write(conn, buf, (size_t)len);
  10573. len = 0;
  10574. in_tag = 0;
  10575. }
  10576. } else {
  10577. /* Tag is still open */
  10578. buf[len++] = (char)(ch & 0xff);
  10579. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10580. /* All SSI tags start with <!--# */
  10581. in_ssi_tag = 1;
  10582. }
  10583. if ((len + 2) > (int)sizeof(buf)) {
  10584. /* Tag to long for buffer */
  10585. mg_cry_internal(conn, "%s: tag is too large", path);
  10586. return;
  10587. }
  10588. }
  10589. } else {
  10590. /* We are not in a tag yet. */
  10591. if (ch == '<') {
  10592. /* Tag is opening */
  10593. in_tag = 1;
  10594. if (len > 0) {
  10595. /* Flush current buffer.
  10596. * Buffer is filled with "len" bytes. */
  10597. (void)mg_write(conn, buf, (size_t)len);
  10598. }
  10599. /* Store the < */
  10600. len = 1;
  10601. buf[0] = '<';
  10602. } else {
  10603. /* No Tag */
  10604. /* Add data to buffer */
  10605. buf[len++] = (char)(ch & 0xff);
  10606. /* Flush if buffer is full */
  10607. if (len == (int)sizeof(buf)) {
  10608. mg_write(conn, buf, (size_t)len);
  10609. len = 0;
  10610. }
  10611. }
  10612. }
  10613. }
  10614. /* Send the rest of buffered data */
  10615. if (len > 0) {
  10616. mg_write(conn, buf, (size_t)len);
  10617. }
  10618. }
  10619. static void
  10620. handle_ssi_file_request(struct mg_connection *conn,
  10621. const char *path,
  10622. struct mg_file *filep)
  10623. {
  10624. char date[64];
  10625. time_t curtime = time(NULL);
  10626. const char *cors_orig_cfg;
  10627. const char *cors1, *cors2, *cors3;
  10628. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10629. return;
  10630. }
  10631. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10632. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10633. /* Cross-origin resource sharing (CORS). */
  10634. cors1 = "Access-Control-Allow-Origin: ";
  10635. cors2 = cors_orig_cfg;
  10636. cors3 = "\r\n";
  10637. } else {
  10638. cors1 = cors2 = cors3 = "";
  10639. }
  10640. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10641. /* File exists (precondition for calling this function),
  10642. * but can not be opened by the server. */
  10643. mg_send_http_error(conn,
  10644. 500,
  10645. "Error: Cannot read file\nfopen(%s): %s",
  10646. path,
  10647. strerror(ERRNO));
  10648. } else {
  10649. conn->must_close = 1;
  10650. gmt_time_string(date, sizeof(date), &curtime);
  10651. fclose_on_exec(&filep->access, conn);
  10652. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10653. send_no_cache_header(conn);
  10654. send_additional_header(conn);
  10655. mg_printf(conn,
  10656. "%s%s%s"
  10657. "Date: %s\r\n"
  10658. "Content-Type: text/html\r\n"
  10659. "Connection: %s\r\n\r\n",
  10660. cors1,
  10661. cors2,
  10662. cors3,
  10663. date,
  10664. suggest_connection_header(conn));
  10665. send_ssi_file(conn, path, filep, 0);
  10666. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10667. }
  10668. }
  10669. #endif /* NO_FILESYSTEMS */
  10670. #if !defined(NO_FILES)
  10671. static void
  10672. send_options(struct mg_connection *conn)
  10673. {
  10674. char date[64];
  10675. time_t curtime = time(NULL);
  10676. if (!conn) {
  10677. return;
  10678. }
  10679. conn->status_code = 200;
  10680. conn->must_close = 1;
  10681. gmt_time_string(date, sizeof(date), &curtime);
  10682. /* We do not set a "Cache-Control" header here, but leave the default.
  10683. * Since browsers do not send an OPTIONS request, we can not test the
  10684. * effect anyway. */
  10685. mg_printf(conn,
  10686. "HTTP/1.1 200 OK\r\n"
  10687. "Date: %s\r\n"
  10688. "Connection: %s\r\n"
  10689. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10690. "PROPFIND, MKCOL\r\n"
  10691. "DAV: 1\r\n",
  10692. date,
  10693. suggest_connection_header(conn));
  10694. send_additional_header(conn);
  10695. mg_printf(conn, "\r\n");
  10696. }
  10697. /* Writes PROPFIND properties for a collection element */
  10698. static int
  10699. print_props(struct mg_connection *conn,
  10700. const char *uri,
  10701. const char *name,
  10702. struct mg_file_stat *filep)
  10703. {
  10704. size_t href_size, i, j;
  10705. int len;
  10706. char *href, mtime[64];
  10707. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10708. return 0;
  10709. }
  10710. /* Estimate worst case size for encoding */
  10711. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10712. href = (char *)mg_malloc(href_size);
  10713. if (href == NULL) {
  10714. return 0;
  10715. }
  10716. len = mg_url_encode(uri, href, href_size);
  10717. if (len >= 0) {
  10718. /* Append an extra string */
  10719. mg_url_encode(name, href + len, href_size - (size_t)len);
  10720. }
  10721. /* Directory separator should be preserved. */
  10722. for (i = j = 0; href[i]; j++) {
  10723. if (!strncmp(href + i, "%2f", 3)) {
  10724. href[j] = '/';
  10725. i += 3;
  10726. } else {
  10727. href[j] = href[i++];
  10728. }
  10729. }
  10730. href[j] = '\0';
  10731. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10732. mg_printf(conn,
  10733. "<d:response>"
  10734. "<d:href>%s</d:href>"
  10735. "<d:propstat>"
  10736. "<d:prop>"
  10737. "<d:resourcetype>%s</d:resourcetype>"
  10738. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10739. "<d:getlastmodified>%s</d:getlastmodified>"
  10740. "</d:prop>"
  10741. "<d:status>HTTP/1.1 200 OK</d:status>"
  10742. "</d:propstat>"
  10743. "</d:response>\n",
  10744. href,
  10745. filep->is_directory ? "<d:collection/>" : "",
  10746. filep->size,
  10747. mtime);
  10748. mg_free(href);
  10749. return 1;
  10750. }
  10751. static int
  10752. print_dav_dir_entry(struct de *de, void *data)
  10753. {
  10754. struct mg_connection *conn = (struct mg_connection *)data;
  10755. if (!de || !conn
  10756. || !print_props(
  10757. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10758. return -1;
  10759. }
  10760. return 0;
  10761. }
  10762. static void
  10763. handle_propfind(struct mg_connection *conn,
  10764. const char *path,
  10765. struct mg_file_stat *filep)
  10766. {
  10767. const char *depth = mg_get_header(conn, "Depth");
  10768. char date[64];
  10769. time_t curtime = time(NULL);
  10770. gmt_time_string(date, sizeof(date), &curtime);
  10771. if (!conn || !path || !filep || !conn->dom_ctx) {
  10772. return;
  10773. }
  10774. conn->must_close = 1;
  10775. conn->status_code = 207;
  10776. mg_printf(conn,
  10777. "HTTP/1.1 207 Multi-Status\r\n"
  10778. "Date: %s\r\n",
  10779. date);
  10780. send_static_cache_header(conn);
  10781. send_additional_header(conn);
  10782. mg_printf(conn,
  10783. "Connection: %s\r\n"
  10784. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10785. suggest_connection_header(conn));
  10786. mg_printf(conn,
  10787. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10788. "<d:multistatus xmlns:d='DAV:'>\n");
  10789. /* Print properties for the requested resource itself */
  10790. print_props(conn, conn->request_info.local_uri, "", filep);
  10791. /* If it is a directory, print directory entries too if Depth is not 0
  10792. */
  10793. if (filep->is_directory
  10794. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10795. "yes")
  10796. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10797. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10798. }
  10799. mg_printf(conn, "%s\n", "</d:multistatus>");
  10800. }
  10801. #endif
  10802. void
  10803. mg_lock_connection(struct mg_connection *conn)
  10804. {
  10805. if (conn) {
  10806. (void)pthread_mutex_lock(&conn->mutex);
  10807. }
  10808. }
  10809. void
  10810. mg_unlock_connection(struct mg_connection *conn)
  10811. {
  10812. if (conn) {
  10813. (void)pthread_mutex_unlock(&conn->mutex);
  10814. }
  10815. }
  10816. void
  10817. mg_lock_context(struct mg_context *ctx)
  10818. {
  10819. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10820. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10821. }
  10822. }
  10823. void
  10824. mg_unlock_context(struct mg_context *ctx)
  10825. {
  10826. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10827. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10828. }
  10829. }
  10830. #if defined(USE_LUA)
  10831. #include "mod_lua.inl"
  10832. #endif /* USE_LUA */
  10833. #if defined(USE_DUKTAPE)
  10834. #include "mod_duktape.inl"
  10835. #endif /* USE_DUKTAPE */
  10836. #if defined(USE_WEBSOCKET)
  10837. #if !defined(NO_SSL_DL)
  10838. #define SHA_API static
  10839. #include "sha1.inl"
  10840. #endif
  10841. static int
  10842. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10843. {
  10844. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10845. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10846. SHA_CTX sha_ctx;
  10847. int truncated;
  10848. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10849. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10850. if (truncated) {
  10851. conn->must_close = 1;
  10852. return 0;
  10853. }
  10854. DEBUG_TRACE("%s", "Send websocket handshake");
  10855. SHA1_Init(&sha_ctx);
  10856. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10857. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10858. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10859. mg_printf(conn,
  10860. "HTTP/1.1 101 Switching Protocols\r\n"
  10861. "Upgrade: websocket\r\n"
  10862. "Connection: Upgrade\r\n"
  10863. "Sec-WebSocket-Accept: %s\r\n",
  10864. b64_sha);
  10865. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10866. mg_printf(conn,
  10867. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10868. conn->request_info.acceptedWebSocketSubprotocol);
  10869. } else {
  10870. mg_printf(conn, "%s", "\r\n");
  10871. }
  10872. return 1;
  10873. }
  10874. #if !defined(MG_MAX_UNANSWERED_PING)
  10875. /* Configuration of the maximum number of websocket PINGs that might
  10876. * stay unanswered before the connection is considered broken.
  10877. * Note: The name of this define may still change (until it is
  10878. * defined as a compile parameter in a documentation).
  10879. */
  10880. #define MG_MAX_UNANSWERED_PING (5)
  10881. #endif
  10882. static void
  10883. read_websocket(struct mg_connection *conn,
  10884. mg_websocket_data_handler ws_data_handler,
  10885. void *callback_data)
  10886. {
  10887. /* Pointer to the beginning of the portion of the incoming websocket
  10888. * message queue.
  10889. * The original websocket upgrade request is never removed, so the queue
  10890. * begins after it. */
  10891. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10892. int n, error, exit_by_callback;
  10893. int ret;
  10894. /* body_len is the length of the entire queue in bytes
  10895. * len is the length of the current message
  10896. * data_len is the length of the current message's data payload
  10897. * header_len is the length of the current message's header */
  10898. size_t i, len, mask_len = 0, header_len, body_len;
  10899. uint64_t data_len = 0;
  10900. /* "The masking key is a 32-bit value chosen at random by the client."
  10901. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10902. */
  10903. unsigned char mask[4];
  10904. /* data points to the place where the message is stored when passed to
  10905. * the websocket_data callback. This is either mem on the stack, or a
  10906. * dynamically allocated buffer if it is too large. */
  10907. unsigned char mem[4096];
  10908. unsigned char mop; /* mask flag and opcode */
  10909. /* Variables used for connection monitoring */
  10910. double timeout = -1.0;
  10911. int enable_ping_pong = 0;
  10912. int ping_count = 0;
  10913. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10914. enable_ping_pong =
  10915. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10916. "yes");
  10917. }
  10918. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10919. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10920. }
  10921. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10922. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10923. }
  10924. /* Enter data processing loop */
  10925. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10926. conn->request_info.remote_addr,
  10927. conn->request_info.remote_port);
  10928. conn->in_websocket_handling = 1;
  10929. mg_set_thread_name("wsock");
  10930. /* Loop continuously, reading messages from the socket, invoking the
  10931. * callback, and waiting repeatedly until an error occurs. */
  10932. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10933. && (!conn->must_close)) {
  10934. header_len = 0;
  10935. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10936. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10937. len = buf[1] & 127;
  10938. mask_len = (buf[1] & 128) ? 4 : 0;
  10939. if ((len < 126) && (body_len >= mask_len)) {
  10940. /* inline 7-bit length field */
  10941. data_len = len;
  10942. header_len = 2 + mask_len;
  10943. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10944. /* 16-bit length field */
  10945. header_len = 4 + mask_len;
  10946. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10947. } else if (body_len >= (10 + mask_len)) {
  10948. /* 64-bit length field */
  10949. uint32_t l1, l2;
  10950. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10951. memcpy(&l2, &buf[6], 4);
  10952. header_len = 10 + mask_len;
  10953. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10954. if (data_len > (uint64_t)0x7FFF0000ul) {
  10955. /* no can do */
  10956. mg_cry_internal(
  10957. conn,
  10958. "%s",
  10959. "websocket out of memory; closing connection");
  10960. break;
  10961. }
  10962. }
  10963. }
  10964. if ((header_len > 0) && (body_len >= header_len)) {
  10965. /* Allocate space to hold websocket payload */
  10966. unsigned char *data = mem;
  10967. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10968. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10969. conn->phys_ctx);
  10970. if (data == NULL) {
  10971. /* Allocation failed, exit the loop and then close the
  10972. * connection */
  10973. mg_cry_internal(
  10974. conn,
  10975. "%s",
  10976. "websocket out of memory; closing connection");
  10977. break;
  10978. }
  10979. }
  10980. /* Copy the mask before we shift the queue and destroy it */
  10981. if (mask_len > 0) {
  10982. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10983. } else {
  10984. memset(mask, 0, sizeof(mask));
  10985. }
  10986. /* Read frame payload from the first message in the queue into
  10987. * data and advance the queue by moving the memory in place. */
  10988. DEBUG_ASSERT(body_len >= header_len);
  10989. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10990. mop = buf[0]; /* current mask and opcode */
  10991. /* Overflow case */
  10992. len = body_len - header_len;
  10993. memcpy(data, buf + header_len, len);
  10994. error = 0;
  10995. while ((uint64_t)len < data_len) {
  10996. n = pull_inner(NULL,
  10997. conn,
  10998. (char *)(data + len),
  10999. (int)(data_len - len),
  11000. timeout);
  11001. if (n <= -2) {
  11002. error = 1;
  11003. break;
  11004. } else if (n > 0) {
  11005. len += (size_t)n;
  11006. } else {
  11007. /* Timeout: should retry */
  11008. /* TODO: retry condition */
  11009. }
  11010. }
  11011. if (error) {
  11012. mg_cry_internal(
  11013. conn,
  11014. "%s",
  11015. "Websocket pull failed; closing connection");
  11016. if (data != mem) {
  11017. mg_free(data);
  11018. }
  11019. break;
  11020. }
  11021. conn->data_len = conn->request_len;
  11022. } else {
  11023. mop = buf[0]; /* current mask and opcode, overwritten by
  11024. * memmove() */
  11025. /* Length of the message being read at the front of the
  11026. * queue. Cast to 31 bit is OK, since we limited
  11027. * data_len before. */
  11028. len = (size_t)data_len + header_len;
  11029. /* Copy the data payload into the data pointer for the
  11030. * callback. Cast to 31 bit is OK, since we
  11031. * limited data_len */
  11032. memcpy(data, buf + header_len, (size_t)data_len);
  11033. /* Move the queue forward len bytes */
  11034. memmove(buf, buf + len, body_len - len);
  11035. /* Mark the queue as advanced */
  11036. conn->data_len -= (int)len;
  11037. }
  11038. /* Apply mask if necessary */
  11039. if (mask_len > 0) {
  11040. for (i = 0; i < (size_t)data_len; i++) {
  11041. data[i] ^= mask[i & 3];
  11042. }
  11043. }
  11044. exit_by_callback = 0;
  11045. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11046. /* filter PONG messages */
  11047. DEBUG_TRACE("PONG from %s:%u",
  11048. conn->request_info.remote_addr,
  11049. conn->request_info.remote_port);
  11050. /* No unanwered PINGs left */
  11051. ping_count = 0;
  11052. } else if (enable_ping_pong
  11053. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11054. /* reply PING messages */
  11055. DEBUG_TRACE("Reply PING from %s:%u",
  11056. conn->request_info.remote_addr,
  11057. conn->request_info.remote_port);
  11058. ret = mg_websocket_write(conn,
  11059. MG_WEBSOCKET_OPCODE_PONG,
  11060. (char *)data,
  11061. (size_t)data_len);
  11062. if (ret <= 0) {
  11063. /* Error: send failed */
  11064. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11065. break;
  11066. }
  11067. } else {
  11068. /* Exit the loop if callback signals to exit (server side),
  11069. * or "connection close" opcode received (client side). */
  11070. if ((ws_data_handler != NULL)
  11071. && !ws_data_handler(conn,
  11072. mop,
  11073. (char *)data,
  11074. (size_t)data_len,
  11075. callback_data)) {
  11076. exit_by_callback = 1;
  11077. }
  11078. }
  11079. /* It a buffer has been allocated, free it again */
  11080. if (data != mem) {
  11081. mg_free(data);
  11082. }
  11083. if (exit_by_callback) {
  11084. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11085. conn->request_info.remote_addr,
  11086. conn->request_info.remote_port);
  11087. break;
  11088. }
  11089. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11090. /* Opcode == 8, connection close */
  11091. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11092. conn->request_info.remote_addr,
  11093. conn->request_info.remote_port);
  11094. break;
  11095. }
  11096. /* Not breaking the loop, process next websocket frame. */
  11097. } else {
  11098. /* Read from the socket into the next available location in the
  11099. * message queue. */
  11100. n = pull_inner(NULL,
  11101. conn,
  11102. conn->buf + conn->data_len,
  11103. conn->buf_size - conn->data_len,
  11104. timeout);
  11105. if (n <= -2) {
  11106. /* Error, no bytes read */
  11107. DEBUG_TRACE("PULL from %s:%u failed",
  11108. conn->request_info.remote_addr,
  11109. conn->request_info.remote_port);
  11110. break;
  11111. }
  11112. if (n > 0) {
  11113. conn->data_len += n;
  11114. /* Reset open PING count */
  11115. ping_count = 0;
  11116. } else {
  11117. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11118. && (!conn->must_close)) {
  11119. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11120. /* Stop sending PING */
  11121. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11122. "- closing connection",
  11123. ping_count,
  11124. conn->request_info.remote_addr,
  11125. conn->request_info.remote_port);
  11126. break;
  11127. }
  11128. if (enable_ping_pong) {
  11129. /* Send Websocket PING message */
  11130. DEBUG_TRACE("PING to %s:%u",
  11131. conn->request_info.remote_addr,
  11132. conn->request_info.remote_port);
  11133. ret = mg_websocket_write(conn,
  11134. MG_WEBSOCKET_OPCODE_PING,
  11135. NULL,
  11136. 0);
  11137. if (ret <= 0) {
  11138. /* Error: send failed */
  11139. DEBUG_TRACE("Send PING failed (%i)", ret);
  11140. break;
  11141. }
  11142. ping_count++;
  11143. }
  11144. }
  11145. /* Timeout: should retry */
  11146. /* TODO: get timeout def */
  11147. }
  11148. }
  11149. }
  11150. /* Leave data processing loop */
  11151. mg_set_thread_name("worker");
  11152. conn->in_websocket_handling = 0;
  11153. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11154. conn->request_info.remote_addr,
  11155. conn->request_info.remote_port);
  11156. }
  11157. static int
  11158. mg_websocket_write_exec(struct mg_connection *conn,
  11159. int opcode,
  11160. const char *data,
  11161. size_t dataLen,
  11162. uint32_t masking_key)
  11163. {
  11164. unsigned char header[14];
  11165. size_t headerLen;
  11166. int retval;
  11167. #if defined(GCC_DIAGNOSTIC)
  11168. /* Disable spurious conversion warning for GCC */
  11169. #pragma GCC diagnostic push
  11170. #pragma GCC diagnostic ignored "-Wconversion"
  11171. #endif
  11172. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11173. #if defined(GCC_DIAGNOSTIC)
  11174. #pragma GCC diagnostic pop
  11175. #endif
  11176. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11177. if (dataLen < 126) {
  11178. /* inline 7-bit length field */
  11179. header[1] = (unsigned char)dataLen;
  11180. headerLen = 2;
  11181. } else if (dataLen <= 0xFFFF) {
  11182. /* 16-bit length field */
  11183. uint16_t len = htons((uint16_t)dataLen);
  11184. header[1] = 126;
  11185. memcpy(header + 2, &len, 2);
  11186. headerLen = 4;
  11187. } else {
  11188. /* 64-bit length field */
  11189. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11190. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11191. header[1] = 127;
  11192. memcpy(header + 2, &len1, 4);
  11193. memcpy(header + 6, &len2, 4);
  11194. headerLen = 10;
  11195. }
  11196. if (masking_key) {
  11197. /* add mask */
  11198. header[1] |= 0x80;
  11199. memcpy(header + headerLen, &masking_key, 4);
  11200. headerLen += 4;
  11201. }
  11202. /* Note that POSIX/Winsock's send() is threadsafe
  11203. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11204. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11205. * push(), although that is only a problem if the packet is large or
  11206. * outgoing buffer is full). */
  11207. /* TODO: Check if this lock should be moved to user land.
  11208. * Currently the server sets this lock for websockets, but
  11209. * not for any other connection. It must be set for every
  11210. * conn read/written by more than one thread, no matter if
  11211. * it is a websocket or regular connection. */
  11212. (void)mg_lock_connection(conn);
  11213. retval = mg_write(conn, header, headerLen);
  11214. if (retval != (int)headerLen) {
  11215. /* Did not send complete header */
  11216. retval = -1;
  11217. } else {
  11218. if (dataLen > 0) {
  11219. retval = mg_write(conn, data, dataLen);
  11220. }
  11221. /* if dataLen == 0, the header length (2) is returned */
  11222. }
  11223. /* TODO: Remove this unlock as well, when lock is removed. */
  11224. mg_unlock_connection(conn);
  11225. return retval;
  11226. }
  11227. int
  11228. mg_websocket_write(struct mg_connection *conn,
  11229. int opcode,
  11230. const char *data,
  11231. size_t dataLen)
  11232. {
  11233. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11234. }
  11235. static void
  11236. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11237. {
  11238. size_t i = 0;
  11239. i = 0;
  11240. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11241. /* Convert in 32 bit words, if data is 4 byte aligned */
  11242. while (i < (in_len - 3)) {
  11243. *(uint32_t *)(void *)(out + i) =
  11244. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11245. i += 4;
  11246. }
  11247. }
  11248. if (i != in_len) {
  11249. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11250. while (i < in_len) {
  11251. *(uint8_t *)(void *)(out + i) =
  11252. *(uint8_t *)(void *)(in + i)
  11253. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11254. i++;
  11255. }
  11256. }
  11257. }
  11258. int
  11259. mg_websocket_client_write(struct mg_connection *conn,
  11260. int opcode,
  11261. const char *data,
  11262. size_t dataLen)
  11263. {
  11264. int retval = -1;
  11265. char *masked_data =
  11266. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11267. uint32_t masking_key = 0;
  11268. if (masked_data == NULL) {
  11269. /* Return -1 in an error case */
  11270. mg_cry_internal(conn,
  11271. "%s",
  11272. "Cannot allocate buffer for masked websocket response: "
  11273. "Out of memory");
  11274. return -1;
  11275. }
  11276. do {
  11277. /* Get a masking key - but not 0 */
  11278. masking_key = (uint32_t)get_random();
  11279. } while (masking_key == 0);
  11280. mask_data(data, dataLen, masking_key, masked_data);
  11281. retval = mg_websocket_write_exec(
  11282. conn, opcode, masked_data, dataLen, masking_key);
  11283. mg_free(masked_data);
  11284. return retval;
  11285. }
  11286. static void
  11287. handle_websocket_request(struct mg_connection *conn,
  11288. const char *path,
  11289. int is_callback_resource,
  11290. struct mg_websocket_subprotocols *subprotocols,
  11291. mg_websocket_connect_handler ws_connect_handler,
  11292. mg_websocket_ready_handler ws_ready_handler,
  11293. mg_websocket_data_handler ws_data_handler,
  11294. mg_websocket_close_handler ws_close_handler,
  11295. void *cbData)
  11296. {
  11297. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11298. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11299. ptrdiff_t lua_websock = 0;
  11300. #if !defined(USE_LUA)
  11301. (void)path;
  11302. #endif
  11303. /* Step 1: Check websocket protocol version. */
  11304. /* Step 1.1: Check Sec-WebSocket-Key. */
  11305. if (!websock_key) {
  11306. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11307. * requires a Sec-WebSocket-Key header.
  11308. */
  11309. /* It could be the hixie draft version
  11310. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11311. */
  11312. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11313. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11314. char key3[8];
  11315. if ((key1 != NULL) && (key2 != NULL)) {
  11316. /* This version uses 8 byte body data in a GET request */
  11317. conn->content_len = 8;
  11318. if (8 == mg_read(conn, key3, 8)) {
  11319. /* This is the hixie version */
  11320. mg_send_http_error(conn,
  11321. 426,
  11322. "%s",
  11323. "Protocol upgrade to RFC 6455 required");
  11324. return;
  11325. }
  11326. }
  11327. /* This is an unknown version */
  11328. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11329. return;
  11330. }
  11331. /* Step 1.2: Check websocket protocol version. */
  11332. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11333. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11334. /* Reject wrong versions */
  11335. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11336. return;
  11337. }
  11338. /* Step 1.3: Could check for "Host", but we do not really nead this
  11339. * value for anything, so just ignore it. */
  11340. /* Step 2: If a callback is responsible, call it. */
  11341. if (is_callback_resource) {
  11342. /* Step 2.1 check and select subprotocol */
  11343. const char *protocols[64]; // max 64 headers
  11344. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11345. "Sec-WebSocket-Protocol",
  11346. protocols,
  11347. 64);
  11348. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11349. int cnt = 0;
  11350. int idx;
  11351. unsigned long len;
  11352. const char *sep, *curSubProtocol,
  11353. *acceptedWebSocketSubprotocol = NULL;
  11354. /* look for matching subprotocol */
  11355. do {
  11356. const char *protocol = protocols[cnt];
  11357. do {
  11358. sep = strchr(protocol, ',');
  11359. curSubProtocol = protocol;
  11360. len = sep ? (unsigned long)(sep - protocol)
  11361. : (unsigned long)strlen(protocol);
  11362. while (sep && isspace((unsigned char)*++sep))
  11363. ; // ignore leading whitespaces
  11364. protocol = sep;
  11365. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11366. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11367. && (strncmp(curSubProtocol,
  11368. subprotocols->subprotocols[idx],
  11369. len)
  11370. == 0)) {
  11371. acceptedWebSocketSubprotocol =
  11372. subprotocols->subprotocols[idx];
  11373. break;
  11374. }
  11375. }
  11376. } while (sep && !acceptedWebSocketSubprotocol);
  11377. } while (++cnt < nbSubprotocolHeader
  11378. && !acceptedWebSocketSubprotocol);
  11379. conn->request_info.acceptedWebSocketSubprotocol =
  11380. acceptedWebSocketSubprotocol;
  11381. } else if (nbSubprotocolHeader > 0) {
  11382. /* keep legacy behavior */
  11383. const char *protocol = protocols[0];
  11384. /* The protocol is a comma separated list of names. */
  11385. /* The server must only return one value from this list. */
  11386. /* First check if it is a list or just a single value. */
  11387. const char *sep = strrchr(protocol, ',');
  11388. if (sep == NULL) {
  11389. /* Just a single protocol -> accept it. */
  11390. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11391. } else {
  11392. /* Multiple protocols -> accept the last one. */
  11393. /* This is just a quick fix if the client offers multiple
  11394. * protocols. The handler should have a list of accepted
  11395. * protocols on his own
  11396. * and use it to select one protocol among those the client
  11397. * has
  11398. * offered.
  11399. */
  11400. while (isspace((unsigned char)*++sep)) {
  11401. ; /* ignore leading whitespaces */
  11402. }
  11403. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11404. }
  11405. }
  11406. if ((ws_connect_handler != NULL)
  11407. && (ws_connect_handler(conn, cbData) != 0)) {
  11408. /* C callback has returned non-zero, do not proceed with
  11409. * handshake.
  11410. */
  11411. /* Note that C callbacks are no longer called when Lua is
  11412. * responsible, so C can no longer filter callbacks for Lua. */
  11413. return;
  11414. }
  11415. }
  11416. #if defined(USE_LUA)
  11417. /* Step 3: No callback. Check if Lua is responsible. */
  11418. else {
  11419. /* Step 3.1: Check if Lua is responsible. */
  11420. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11421. lua_websock = match_prefix(
  11422. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11423. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11424. path);
  11425. }
  11426. if (lua_websock) {
  11427. /* Step 3.2: Lua is responsible: call it. */
  11428. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11429. if (!conn->lua_websocket_state) {
  11430. /* Lua rejected the new client */
  11431. return;
  11432. }
  11433. }
  11434. }
  11435. #endif
  11436. /* Step 4: Check if there is a responsible websocket handler. */
  11437. if (!is_callback_resource && !lua_websock) {
  11438. /* There is no callback, and Lua is not responsible either. */
  11439. /* Reply with a 404 Not Found. We are still at a standard
  11440. * HTTP request here, before the websocket handshake, so
  11441. * we can still send standard HTTP error replies. */
  11442. mg_send_http_error(conn, 404, "%s", "Not found");
  11443. return;
  11444. }
  11445. /* Step 5: The websocket connection has been accepted */
  11446. if (!send_websocket_handshake(conn, websock_key)) {
  11447. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11448. return;
  11449. }
  11450. /* Step 6: Call the ready handler */
  11451. if (is_callback_resource) {
  11452. if (ws_ready_handler != NULL) {
  11453. ws_ready_handler(conn, cbData);
  11454. }
  11455. #if defined(USE_LUA)
  11456. } else if (lua_websock) {
  11457. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11458. /* the ready handler returned false */
  11459. return;
  11460. }
  11461. #endif
  11462. }
  11463. /* Step 7: Enter the read loop */
  11464. if (is_callback_resource) {
  11465. read_websocket(conn, ws_data_handler, cbData);
  11466. #if defined(USE_LUA)
  11467. } else if (lua_websock) {
  11468. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11469. #endif
  11470. }
  11471. /* Step 8: Call the close handler */
  11472. if (ws_close_handler) {
  11473. ws_close_handler(conn, cbData);
  11474. }
  11475. }
  11476. #endif /* !USE_WEBSOCKET */
  11477. /* Is upgrade request:
  11478. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11479. * 1 = upgrade to websocket
  11480. * 2 = upgrade to HTTP/2
  11481. * -1 = upgrade to unknown protocol
  11482. */
  11483. static int
  11484. should_switch_to_protocol(const struct mg_connection *conn)
  11485. {
  11486. const char *upgrade, *connection;
  11487. /* A websocket protocoll has the following HTTP headers:
  11488. *
  11489. * Connection: Upgrade
  11490. * Upgrade: Websocket
  11491. */
  11492. connection = mg_get_header(conn, "Connection");
  11493. if (connection == NULL) {
  11494. return PROTOCOL_TYPE_HTTP1;
  11495. }
  11496. if (!mg_strcasestr(connection, "upgrade")) {
  11497. return PROTOCOL_TYPE_HTTP1;
  11498. }
  11499. upgrade = mg_get_header(conn, "Upgrade");
  11500. if (upgrade == NULL) {
  11501. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11502. return -1;
  11503. }
  11504. /* Upgrade to ... */
  11505. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11506. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11507. * "Sec-WebSocket-Version" are also required.
  11508. * Don't check them here, since even an unsupported websocket protocol
  11509. * request still IS a websocket request (in contrast to a standard HTTP
  11510. * request). It will fail later in handle_websocket_request.
  11511. */
  11512. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11513. }
  11514. if (0 != mg_strcasestr(upgrade, "h2")) {
  11515. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11516. }
  11517. /* Upgrade to another protocol */
  11518. return -1;
  11519. }
  11520. static int
  11521. isbyte(int n)
  11522. {
  11523. return (n >= 0) && (n <= 255);
  11524. }
  11525. static int
  11526. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11527. {
  11528. int n, a, b, c, d, slash = 32, len = 0;
  11529. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11530. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11531. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11532. && (slash < 33)) {
  11533. len = n;
  11534. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11535. | (uint32_t)d;
  11536. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11537. }
  11538. return len;
  11539. }
  11540. static int
  11541. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11542. {
  11543. int throttle = 0;
  11544. struct vec vec, val;
  11545. uint32_t net, mask;
  11546. char mult;
  11547. double v;
  11548. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11549. mult = ',';
  11550. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11551. || (v < 0)
  11552. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11553. && (mult != ','))) {
  11554. continue;
  11555. }
  11556. v *= (lowercase(&mult) == 'k')
  11557. ? 1024
  11558. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11559. if (vec.len == 1 && vec.ptr[0] == '*') {
  11560. throttle = (int)v;
  11561. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11562. if ((remote_ip & mask) == net) {
  11563. throttle = (int)v;
  11564. }
  11565. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11566. throttle = (int)v;
  11567. }
  11568. }
  11569. return throttle;
  11570. }
  11571. static uint32_t
  11572. get_remote_ip(const struct mg_connection *conn)
  11573. {
  11574. if (!conn) {
  11575. return 0;
  11576. }
  11577. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11578. }
  11579. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11580. #include "handle_form.inl"
  11581. #if defined(MG_LEGACY_INTERFACE)
  11582. /* Implement the deprecated mg_upload function by calling the new
  11583. * mg_handle_form_request function. While mg_upload could only handle
  11584. * HTML forms sent as POST request in multipart/form-data format
  11585. * containing only file input elements, mg_handle_form_request can
  11586. * handle all form input elements and all standard request methods. */
  11587. struct mg_upload_user_data {
  11588. struct mg_connection *conn;
  11589. const char *destination_dir;
  11590. int num_uploaded_files;
  11591. };
  11592. /* Helper function for deprecated mg_upload. */
  11593. static int
  11594. mg_upload_field_found(const char *key,
  11595. const char *filename,
  11596. char *path,
  11597. size_t pathlen,
  11598. void *user_data)
  11599. {
  11600. int truncated = 0;
  11601. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11602. (void)key;
  11603. if (!filename) {
  11604. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11605. return FORM_FIELD_STORAGE_ABORT;
  11606. }
  11607. mg_snprintf(fud->conn,
  11608. &truncated,
  11609. path,
  11610. pathlen - 1,
  11611. "%s/%s",
  11612. fud->destination_dir,
  11613. filename);
  11614. if (truncated) {
  11615. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11616. return FORM_FIELD_STORAGE_ABORT;
  11617. }
  11618. return FORM_FIELD_STORAGE_STORE;
  11619. }
  11620. /* Helper function for deprecated mg_upload. */
  11621. static int
  11622. mg_upload_field_get(const char *key,
  11623. const char *value,
  11624. size_t value_size,
  11625. void *user_data)
  11626. {
  11627. /* Function should never be called */
  11628. (void)key;
  11629. (void)value;
  11630. (void)value_size;
  11631. (void)user_data;
  11632. return 0;
  11633. }
  11634. /* Helper function for deprecated mg_upload. */
  11635. static int
  11636. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11637. {
  11638. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11639. (void)file_size;
  11640. fud->num_uploaded_files++;
  11641. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11642. return 0;
  11643. }
  11644. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11645. int
  11646. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11647. {
  11648. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11649. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11650. mg_upload_field_get,
  11651. mg_upload_field_stored,
  11652. 0};
  11653. int ret;
  11654. fdh.user_data = (void *)&fud;
  11655. ret = mg_handle_form_request(conn, &fdh);
  11656. if (ret < 0) {
  11657. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11658. }
  11659. return fud.num_uploaded_files;
  11660. }
  11661. #endif
  11662. static int
  11663. get_first_ssl_listener_index(const struct mg_context *ctx)
  11664. {
  11665. unsigned int i;
  11666. int idx = -1;
  11667. if (ctx) {
  11668. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11669. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11670. }
  11671. }
  11672. return idx;
  11673. }
  11674. /* Return host (without port) */
  11675. /* Use mg_free to free the result */
  11676. static const char *
  11677. alloc_get_host(struct mg_connection *conn)
  11678. {
  11679. char buf[1025];
  11680. size_t buflen = sizeof(buf);
  11681. const char *host_header = get_header(conn->request_info.http_headers,
  11682. conn->request_info.num_headers,
  11683. "Host");
  11684. char *host;
  11685. if (host_header != NULL) {
  11686. char *pos;
  11687. /* Create a local copy of the "Host" header, since it might be
  11688. * modified here. */
  11689. mg_strlcpy(buf, host_header, buflen);
  11690. buf[buflen - 1] = '\0';
  11691. host = buf;
  11692. while (isspace((unsigned char)*host)) {
  11693. host++;
  11694. }
  11695. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11696. * is found. */
  11697. if (*host == '[') {
  11698. pos = strchr(host, ']');
  11699. if (!pos) {
  11700. /* Malformed hostname starts with '[', but no ']' found */
  11701. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11702. return NULL;
  11703. }
  11704. /* terminate after ']' */
  11705. pos[1] = 0;
  11706. } else {
  11707. /* Otherwise, a ':' separates hostname and port number */
  11708. pos = strchr(host, ':');
  11709. if (pos != NULL) {
  11710. *pos = '\0';
  11711. }
  11712. }
  11713. if (conn->ssl) {
  11714. /* This is a HTTPS connection, maybe we have a hostname
  11715. * from SNI (set in ssl_servername_callback). */
  11716. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11717. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11718. /* We are not using the default domain */
  11719. if (mg_strcasecmp(host, sslhost)) {
  11720. /* Mismatch between SNI domain and HTTP domain */
  11721. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11722. sslhost,
  11723. host);
  11724. return NULL;
  11725. }
  11726. }
  11727. DEBUG_TRACE("HTTPS Host: %s", host);
  11728. } else {
  11729. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11730. while (dom) {
  11731. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11732. /* Found matching domain */
  11733. DEBUG_TRACE("HTTP domain %s found",
  11734. dom->config[AUTHENTICATION_DOMAIN]);
  11735. /* TODO: Check if this is a HTTP or HTTPS domain */
  11736. conn->dom_ctx = dom;
  11737. break;
  11738. }
  11739. mg_lock_context(conn->phys_ctx);
  11740. dom = dom->next;
  11741. mg_unlock_context(conn->phys_ctx);
  11742. }
  11743. DEBUG_TRACE("HTTP Host: %s", host);
  11744. }
  11745. } else {
  11746. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11747. host = buf;
  11748. DEBUG_TRACE("IP: %s", host);
  11749. }
  11750. return mg_strdup_ctx(host, conn->phys_ctx);
  11751. }
  11752. static void
  11753. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11754. {
  11755. char target_url[MG_BUF_LEN];
  11756. int truncated = 0;
  11757. conn->must_close = 1;
  11758. /* Send host, port, uri and (if it exists) ?query_string */
  11759. if (conn->host) {
  11760. /* Use "308 Permanent Redirect" */
  11761. int redirect_code = 308;
  11762. /* Create target URL */
  11763. mg_snprintf(
  11764. conn,
  11765. &truncated,
  11766. target_url,
  11767. sizeof(target_url),
  11768. "https://%s:%d%s%s%s",
  11769. conn->host,
  11770. #if defined(USE_IPV6)
  11771. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11772. == AF_INET6)
  11773. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11774. .lsa.sin6.sin6_port)
  11775. :
  11776. #endif
  11777. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11778. .lsa.sin.sin_port),
  11779. conn->request_info.local_uri,
  11780. (conn->request_info.query_string == NULL) ? "" : "?",
  11781. (conn->request_info.query_string == NULL)
  11782. ? ""
  11783. : conn->request_info.query_string);
  11784. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11785. * is used as buffer size) */
  11786. if (truncated) {
  11787. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11788. return;
  11789. }
  11790. /* Use redirect helper function */
  11791. mg_send_http_redirect(conn, target_url, redirect_code);
  11792. }
  11793. }
  11794. static void
  11795. mg_set_handler_type(struct mg_context *phys_ctx,
  11796. struct mg_domain_context *dom_ctx,
  11797. const char *uri,
  11798. int handler_type,
  11799. int is_delete_request,
  11800. mg_request_handler handler,
  11801. struct mg_websocket_subprotocols *subprotocols,
  11802. mg_websocket_connect_handler connect_handler,
  11803. mg_websocket_ready_handler ready_handler,
  11804. mg_websocket_data_handler data_handler,
  11805. mg_websocket_close_handler close_handler,
  11806. mg_authorization_handler auth_handler,
  11807. void *cbdata)
  11808. {
  11809. struct mg_handler_info *tmp_rh, **lastref;
  11810. size_t urilen = strlen(uri);
  11811. if (handler_type == WEBSOCKET_HANDLER) {
  11812. DEBUG_ASSERT(handler == NULL);
  11813. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11814. || ready_handler != NULL || data_handler != NULL
  11815. || close_handler != NULL);
  11816. DEBUG_ASSERT(auth_handler == NULL);
  11817. if (handler != NULL) {
  11818. return;
  11819. }
  11820. if (!is_delete_request && (connect_handler == NULL)
  11821. && (ready_handler == NULL) && (data_handler == NULL)
  11822. && (close_handler == NULL)) {
  11823. return;
  11824. }
  11825. if (auth_handler != NULL) {
  11826. return;
  11827. }
  11828. } else if (handler_type == REQUEST_HANDLER) {
  11829. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11830. && data_handler == NULL && close_handler == NULL);
  11831. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11832. DEBUG_ASSERT(auth_handler == NULL);
  11833. if ((connect_handler != NULL) || (ready_handler != NULL)
  11834. || (data_handler != NULL) || (close_handler != NULL)) {
  11835. return;
  11836. }
  11837. if (!is_delete_request && (handler == NULL)) {
  11838. return;
  11839. }
  11840. if (auth_handler != NULL) {
  11841. return;
  11842. }
  11843. } else { /* AUTH_HANDLER */
  11844. DEBUG_ASSERT(handler == NULL);
  11845. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11846. && data_handler == NULL && close_handler == NULL);
  11847. DEBUG_ASSERT(auth_handler != NULL);
  11848. if (handler != NULL) {
  11849. return;
  11850. }
  11851. if ((connect_handler != NULL) || (ready_handler != NULL)
  11852. || (data_handler != NULL) || (close_handler != NULL)) {
  11853. return;
  11854. }
  11855. if (!is_delete_request && (auth_handler == NULL)) {
  11856. return;
  11857. }
  11858. }
  11859. if (!phys_ctx || !dom_ctx) {
  11860. return;
  11861. }
  11862. mg_lock_context(phys_ctx);
  11863. /* first try to find an existing handler */
  11864. do {
  11865. lastref = &(dom_ctx->handlers);
  11866. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11867. if (tmp_rh->handler_type == handler_type
  11868. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11869. if (!is_delete_request) {
  11870. /* update existing handler */
  11871. if (handler_type == REQUEST_HANDLER) {
  11872. /* Wait for end of use before updating */
  11873. if (tmp_rh->refcount) {
  11874. mg_unlock_context(phys_ctx);
  11875. mg_sleep(1);
  11876. mg_lock_context(phys_ctx);
  11877. /* tmp_rh might have been freed, search again. */
  11878. break;
  11879. }
  11880. /* Ok, the handler is no more use -> Update it */
  11881. tmp_rh->handler = handler;
  11882. } else if (handler_type == WEBSOCKET_HANDLER) {
  11883. tmp_rh->subprotocols = subprotocols;
  11884. tmp_rh->connect_handler = connect_handler;
  11885. tmp_rh->ready_handler = ready_handler;
  11886. tmp_rh->data_handler = data_handler;
  11887. tmp_rh->close_handler = close_handler;
  11888. } else { /* AUTH_HANDLER */
  11889. tmp_rh->auth_handler = auth_handler;
  11890. }
  11891. tmp_rh->cbdata = cbdata;
  11892. } else {
  11893. /* remove existing handler */
  11894. if (handler_type == REQUEST_HANDLER) {
  11895. /* Wait for end of use before removing */
  11896. if (tmp_rh->refcount) {
  11897. tmp_rh->removing = 1;
  11898. mg_unlock_context(phys_ctx);
  11899. mg_sleep(1);
  11900. mg_lock_context(phys_ctx);
  11901. /* tmp_rh might have been freed, search again. */
  11902. break;
  11903. }
  11904. /* Ok, the handler is no more used */
  11905. }
  11906. *lastref = tmp_rh->next;
  11907. mg_free(tmp_rh->uri);
  11908. mg_free(tmp_rh);
  11909. }
  11910. mg_unlock_context(phys_ctx);
  11911. return;
  11912. }
  11913. lastref = &(tmp_rh->next);
  11914. }
  11915. } while (tmp_rh != NULL);
  11916. if (is_delete_request) {
  11917. /* no handler to set, this was a remove request to a non-existing
  11918. * handler */
  11919. mg_unlock_context(phys_ctx);
  11920. return;
  11921. }
  11922. tmp_rh =
  11923. (struct mg_handler_info *)mg_calloc_ctx(1,
  11924. sizeof(struct mg_handler_info),
  11925. phys_ctx);
  11926. if (tmp_rh == NULL) {
  11927. mg_unlock_context(phys_ctx);
  11928. mg_cry_ctx_internal(phys_ctx,
  11929. "%s",
  11930. "Cannot create new request handler struct, OOM");
  11931. return;
  11932. }
  11933. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11934. if (!tmp_rh->uri) {
  11935. mg_unlock_context(phys_ctx);
  11936. mg_free(tmp_rh);
  11937. mg_cry_ctx_internal(phys_ctx,
  11938. "%s",
  11939. "Cannot create new request handler struct, OOM");
  11940. return;
  11941. }
  11942. tmp_rh->uri_len = urilen;
  11943. if (handler_type == REQUEST_HANDLER) {
  11944. tmp_rh->refcount = 0;
  11945. tmp_rh->removing = 0;
  11946. tmp_rh->handler = handler;
  11947. } else if (handler_type == WEBSOCKET_HANDLER) {
  11948. tmp_rh->subprotocols = subprotocols;
  11949. tmp_rh->connect_handler = connect_handler;
  11950. tmp_rh->ready_handler = ready_handler;
  11951. tmp_rh->data_handler = data_handler;
  11952. tmp_rh->close_handler = close_handler;
  11953. } else { /* AUTH_HANDLER */
  11954. tmp_rh->auth_handler = auth_handler;
  11955. }
  11956. tmp_rh->cbdata = cbdata;
  11957. tmp_rh->handler_type = handler_type;
  11958. tmp_rh->next = NULL;
  11959. *lastref = tmp_rh;
  11960. mg_unlock_context(phys_ctx);
  11961. }
  11962. void
  11963. mg_set_request_handler(struct mg_context *ctx,
  11964. const char *uri,
  11965. mg_request_handler handler,
  11966. void *cbdata)
  11967. {
  11968. mg_set_handler_type(ctx,
  11969. &(ctx->dd),
  11970. uri,
  11971. REQUEST_HANDLER,
  11972. handler == NULL,
  11973. handler,
  11974. NULL,
  11975. NULL,
  11976. NULL,
  11977. NULL,
  11978. NULL,
  11979. NULL,
  11980. cbdata);
  11981. }
  11982. void
  11983. mg_set_websocket_handler(struct mg_context *ctx,
  11984. const char *uri,
  11985. mg_websocket_connect_handler connect_handler,
  11986. mg_websocket_ready_handler ready_handler,
  11987. mg_websocket_data_handler data_handler,
  11988. mg_websocket_close_handler close_handler,
  11989. void *cbdata)
  11990. {
  11991. mg_set_websocket_handler_with_subprotocols(ctx,
  11992. uri,
  11993. NULL,
  11994. connect_handler,
  11995. ready_handler,
  11996. data_handler,
  11997. close_handler,
  11998. cbdata);
  11999. }
  12000. void
  12001. mg_set_websocket_handler_with_subprotocols(
  12002. struct mg_context *ctx,
  12003. const char *uri,
  12004. struct mg_websocket_subprotocols *subprotocols,
  12005. mg_websocket_connect_handler connect_handler,
  12006. mg_websocket_ready_handler ready_handler,
  12007. mg_websocket_data_handler data_handler,
  12008. mg_websocket_close_handler close_handler,
  12009. void *cbdata)
  12010. {
  12011. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12012. && (data_handler == NULL)
  12013. && (close_handler == NULL);
  12014. mg_set_handler_type(ctx,
  12015. &(ctx->dd),
  12016. uri,
  12017. WEBSOCKET_HANDLER,
  12018. is_delete_request,
  12019. NULL,
  12020. subprotocols,
  12021. connect_handler,
  12022. ready_handler,
  12023. data_handler,
  12024. close_handler,
  12025. NULL,
  12026. cbdata);
  12027. }
  12028. void
  12029. mg_set_auth_handler(struct mg_context *ctx,
  12030. const char *uri,
  12031. mg_authorization_handler handler,
  12032. void *cbdata)
  12033. {
  12034. mg_set_handler_type(ctx,
  12035. &(ctx->dd),
  12036. uri,
  12037. AUTH_HANDLER,
  12038. handler == NULL,
  12039. NULL,
  12040. NULL,
  12041. NULL,
  12042. NULL,
  12043. NULL,
  12044. NULL,
  12045. handler,
  12046. cbdata);
  12047. }
  12048. static int
  12049. get_request_handler(struct mg_connection *conn,
  12050. int handler_type,
  12051. mg_request_handler *handler,
  12052. struct mg_websocket_subprotocols **subprotocols,
  12053. mg_websocket_connect_handler *connect_handler,
  12054. mg_websocket_ready_handler *ready_handler,
  12055. mg_websocket_data_handler *data_handler,
  12056. mg_websocket_close_handler *close_handler,
  12057. mg_authorization_handler *auth_handler,
  12058. void **cbdata,
  12059. struct mg_handler_info **handler_info)
  12060. {
  12061. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12062. if (request_info) {
  12063. const char *uri = request_info->local_uri;
  12064. size_t urilen = strlen(uri);
  12065. struct mg_handler_info *tmp_rh;
  12066. int step, matched;
  12067. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12068. return 0;
  12069. }
  12070. mg_lock_context(conn->phys_ctx);
  12071. for (step = 0; step < 3; step++) {
  12072. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12073. tmp_rh = tmp_rh->next) {
  12074. if (tmp_rh->handler_type != handler_type) {
  12075. continue;
  12076. }
  12077. if (step == 0) {
  12078. /* first try for an exact match */
  12079. matched = (tmp_rh->uri_len == urilen)
  12080. && (strcmp(tmp_rh->uri, uri) == 0);
  12081. } else if (step == 1) {
  12082. /* next try for a partial match, we will accept
  12083. uri/something */
  12084. matched = (tmp_rh->uri_len < urilen)
  12085. && (uri[tmp_rh->uri_len] == '/')
  12086. && (memcmp(tmp_rh->uri, uri,
  12087. tmp_rh->uri_len) == 0);
  12088. } else {
  12089. /* finally try for pattern match */
  12090. matched = match_prefix(tmp_rh->uri,
  12091. tmp_rh->uri_len, uri) > 0;
  12092. }
  12093. if (matched) {
  12094. if (handler_type == WEBSOCKET_HANDLER) {
  12095. *subprotocols = tmp_rh->subprotocols;
  12096. *connect_handler = tmp_rh->connect_handler;
  12097. *ready_handler = tmp_rh->ready_handler;
  12098. *data_handler = tmp_rh->data_handler;
  12099. *close_handler = tmp_rh->close_handler;
  12100. } else if (handler_type == REQUEST_HANDLER) {
  12101. if (tmp_rh->removing) {
  12102. /* Treat as none found */
  12103. step = 2;
  12104. break;
  12105. }
  12106. *handler = tmp_rh->handler;
  12107. /* Acquire handler and give it back */
  12108. tmp_rh->refcount++;
  12109. *handler_info = tmp_rh;
  12110. } else { /* AUTH_HANDLER */
  12111. *auth_handler = tmp_rh->auth_handler;
  12112. }
  12113. *cbdata = tmp_rh->cbdata;
  12114. mg_unlock_context(conn->phys_ctx);
  12115. return 1;
  12116. }
  12117. }
  12118. }
  12119. mg_unlock_context(conn->phys_ctx);
  12120. }
  12121. return 0; /* none found */
  12122. }
  12123. /* Check if the script file is in a path, allowed for script files.
  12124. * This can be used if uploading files is possible not only for the server
  12125. * admin, and the upload mechanism does not check the file extension.
  12126. */
  12127. static int
  12128. is_in_script_path(const struct mg_connection *conn, const char *path)
  12129. {
  12130. /* TODO (Feature): Add config value for allowed script path.
  12131. * Default: All allowed. */
  12132. (void)conn;
  12133. (void)path;
  12134. return 1;
  12135. }
  12136. #if defined(USE_WEBSOCKET) \
  12137. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12138. static int
  12139. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12140. void *cbdata)
  12141. {
  12142. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12143. if (pcallbacks->websocket_connect) {
  12144. return pcallbacks->websocket_connect(conn);
  12145. }
  12146. /* No handler set - assume "OK" */
  12147. return 0;
  12148. }
  12149. static void
  12150. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12151. {
  12152. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12153. if (pcallbacks->websocket_ready) {
  12154. pcallbacks->websocket_ready(conn);
  12155. }
  12156. }
  12157. static int
  12158. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12159. int bits,
  12160. char *data,
  12161. size_t len,
  12162. void *cbdata)
  12163. {
  12164. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12165. if (pcallbacks->websocket_data) {
  12166. return pcallbacks->websocket_data(conn, bits, data, len);
  12167. }
  12168. /* No handler set - assume "OK" */
  12169. return 1;
  12170. }
  12171. static void
  12172. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12173. void *cbdata)
  12174. {
  12175. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12176. if (pcallbacks->connection_close) {
  12177. pcallbacks->connection_close(conn);
  12178. }
  12179. }
  12180. #endif
  12181. /* This is the heart of the Civetweb's logic.
  12182. * This function is called when the request is read, parsed and validated,
  12183. * and Civetweb must decide what action to take: serve a file, or
  12184. * a directory, or call embedded function, etcetera. */
  12185. static void
  12186. handle_request(struct mg_connection *conn)
  12187. {
  12188. struct mg_request_info *ri = &conn->request_info;
  12189. char path[PATH_MAX];
  12190. int uri_len, ssl_index;
  12191. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12192. is_put_or_delete_request = 0, is_callback_resource = 0;
  12193. int i;
  12194. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12195. mg_request_handler callback_handler = NULL;
  12196. struct mg_handler_info *handler_info = NULL;
  12197. struct mg_websocket_subprotocols *subprotocols;
  12198. mg_websocket_connect_handler ws_connect_handler = NULL;
  12199. mg_websocket_ready_handler ws_ready_handler = NULL;
  12200. mg_websocket_data_handler ws_data_handler = NULL;
  12201. mg_websocket_close_handler ws_close_handler = NULL;
  12202. void *callback_data = NULL;
  12203. mg_authorization_handler auth_handler = NULL;
  12204. void *auth_callback_data = NULL;
  12205. int handler_type;
  12206. time_t curtime = time(NULL);
  12207. char date[64];
  12208. path[0] = 0;
  12209. /* 1. get the request url */
  12210. /* 1.1. split into url and query string */
  12211. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12212. != NULL) {
  12213. *((char *)conn->request_info.query_string++) = '\0';
  12214. }
  12215. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12216. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12217. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12218. if (ssl_index >= 0) {
  12219. redirect_to_https_port(conn, ssl_index);
  12220. } else {
  12221. /* A http to https forward port has been specified,
  12222. * but no https port to forward to. */
  12223. mg_send_http_error(conn,
  12224. 503,
  12225. "%s",
  12226. "Error: SSL forward not configured properly");
  12227. mg_cry_internal(conn,
  12228. "%s",
  12229. "Can not redirect to SSL, no SSL port available");
  12230. }
  12231. return;
  12232. }
  12233. uri_len = (int)strlen(ri->local_uri);
  12234. /* 1.3. decode url (if config says so) */
  12235. if (should_decode_url(conn)) {
  12236. mg_url_decode(
  12237. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12238. }
  12239. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12240. * not possible */
  12241. remove_dot_segments((char *)ri->local_uri);
  12242. /* step 1. completed, the url is known now */
  12243. uri_len = (int)strlen(ri->local_uri);
  12244. DEBUG_TRACE("URL: %s", ri->local_uri);
  12245. /* 2. if this ip has limited speed, set it for this connection */
  12246. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12247. get_remote_ip(conn),
  12248. ri->local_uri);
  12249. /* 3. call a "handle everything" callback, if registered */
  12250. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12251. /* Note that since V1.7 the "begin_request" function is called
  12252. * before an authorization check. If an authorization check is
  12253. * required, use a request_handler instead. */
  12254. i = conn->phys_ctx->callbacks.begin_request(conn);
  12255. if (i > 0) {
  12256. /* callback already processed the request. Store the
  12257. return value as a status code for the access log. */
  12258. conn->status_code = i;
  12259. if (!conn->must_close) {
  12260. discard_unread_request_data(conn);
  12261. }
  12262. return;
  12263. } else if (i == 0) {
  12264. /* civetweb should process the request */
  12265. } else {
  12266. /* unspecified - may change with the next version */
  12267. return;
  12268. }
  12269. }
  12270. /* request not yet handled by a handler or redirect, so the request
  12271. * is processed here */
  12272. /* 4. Check for CORS preflight requests and handle them (if configured).
  12273. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12274. */
  12275. if (!strcmp(ri->request_method, "OPTIONS")) {
  12276. /* Send a response to CORS preflights only if
  12277. * access_control_allow_methods is not NULL and not an empty string.
  12278. * In this case, scripts can still handle CORS. */
  12279. const char *cors_meth_cfg =
  12280. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12281. const char *cors_orig_cfg =
  12282. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12283. const char *cors_origin =
  12284. get_header(ri->http_headers, ri->num_headers, "Origin");
  12285. const char *cors_acrm = get_header(ri->http_headers,
  12286. ri->num_headers,
  12287. "Access-Control-Request-Method");
  12288. /* Todo: check if cors_origin is in cors_orig_cfg.
  12289. * Or, let the client check this. */
  12290. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12291. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12292. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12293. /* This is a valid CORS preflight, and the server is configured
  12294. * to
  12295. * handle it automatically. */
  12296. const char *cors_acrh =
  12297. get_header(ri->http_headers,
  12298. ri->num_headers,
  12299. "Access-Control-Request-Headers");
  12300. gmt_time_string(date, sizeof(date), &curtime);
  12301. mg_printf(conn,
  12302. "HTTP/1.1 200 OK\r\n"
  12303. "Date: %s\r\n"
  12304. "Access-Control-Allow-Origin: %s\r\n"
  12305. "Access-Control-Allow-Methods: %s\r\n"
  12306. "Content-Length: 0\r\n"
  12307. "Connection: %s\r\n",
  12308. date,
  12309. cors_orig_cfg,
  12310. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12311. suggest_connection_header(conn));
  12312. if (cors_acrh != NULL) {
  12313. /* CORS request is asking for additional headers */
  12314. const char *cors_hdr_cfg =
  12315. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12316. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12317. /* Allow only if access_control_allow_headers is
  12318. * not NULL and not an empty string. If this
  12319. * configuration is set to *, allow everything.
  12320. * Otherwise this configuration must be a list
  12321. * of allowed HTTP header names. */
  12322. mg_printf(conn,
  12323. "Access-Control-Allow-Headers: %s\r\n",
  12324. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12325. : cors_hdr_cfg));
  12326. }
  12327. }
  12328. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12329. mg_printf(conn, "\r\n");
  12330. return;
  12331. }
  12332. }
  12333. /* 5. interpret the url to find out how the request must be handled
  12334. */
  12335. /* 5.1. first test, if the request targets the regular http(s)://
  12336. * protocol namespace or the websocket ws(s):// protocol namespace.
  12337. */
  12338. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12339. #if defined(USE_WEBSOCKET)
  12340. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12341. #else
  12342. handler_type = REQUEST_HANDLER;
  12343. #endif /* defined(USE_WEBSOCKET) */
  12344. /* 5.2. check if the request will be handled by a callback */
  12345. if (get_request_handler(conn,
  12346. handler_type,
  12347. &callback_handler,
  12348. &subprotocols,
  12349. &ws_connect_handler,
  12350. &ws_ready_handler,
  12351. &ws_data_handler,
  12352. &ws_close_handler,
  12353. NULL,
  12354. &callback_data,
  12355. &handler_info)) {
  12356. /* 5.2.1. A callback will handle this request. All requests
  12357. * handled
  12358. * by a callback have to be considered as requests to a script
  12359. * resource. */
  12360. is_callback_resource = 1;
  12361. is_script_resource = 1;
  12362. is_put_or_delete_request = is_put_or_delete_method(conn);
  12363. } else {
  12364. no_callback_resource:
  12365. /* 5.2.2. No callback is responsible for this request. The URI
  12366. * addresses a file based resource (static content or Lua/cgi
  12367. * scripts in the file system). */
  12368. is_callback_resource = 0;
  12369. interpret_uri(conn,
  12370. path,
  12371. sizeof(path),
  12372. &file.stat,
  12373. &is_found,
  12374. &is_script_resource,
  12375. &is_websocket_request,
  12376. &is_put_or_delete_request);
  12377. }
  12378. /* 6. authorization check */
  12379. /* 6.1. a custom authorization handler is installed */
  12380. if (get_request_handler(conn,
  12381. AUTH_HANDLER,
  12382. NULL,
  12383. NULL,
  12384. NULL,
  12385. NULL,
  12386. NULL,
  12387. NULL,
  12388. &auth_handler,
  12389. &auth_callback_data,
  12390. NULL)) {
  12391. if (!auth_handler(conn, auth_callback_data)) {
  12392. return;
  12393. }
  12394. } else if (is_put_or_delete_request && !is_script_resource
  12395. && !is_callback_resource) {
  12396. /* 6.2. this request is a PUT/DELETE to a real file */
  12397. /* 6.2.1. thus, the server must have real files */
  12398. #if defined(NO_FILES)
  12399. if (1) {
  12400. #else
  12401. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12402. #endif
  12403. /* This server does not have any real files, thus the
  12404. * PUT/DELETE methods are not valid. */
  12405. mg_send_http_error(conn,
  12406. 405,
  12407. "%s method not allowed",
  12408. conn->request_info.request_method);
  12409. return;
  12410. }
  12411. #if !defined(NO_FILES)
  12412. /* 6.2.2. Check if put authorization for static files is
  12413. * available.
  12414. */
  12415. if (!is_authorized_for_put(conn)) {
  12416. send_authorization_request(conn, NULL);
  12417. return;
  12418. }
  12419. #endif
  12420. } else {
  12421. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12422. * or it is a PUT or DELETE request to a resource that does not
  12423. * correspond to a file. Check authorization. */
  12424. if (!check_authorization(conn, path)) {
  12425. send_authorization_request(conn, NULL);
  12426. return;
  12427. }
  12428. }
  12429. /* request is authorized or does not need authorization */
  12430. /* 7. check if there are request handlers for this uri */
  12431. if (is_callback_resource) {
  12432. if (!is_websocket_request) {
  12433. i = callback_handler(conn, callback_data);
  12434. /* Callback handler will not be used anymore. Release it */
  12435. mg_lock_context(conn->phys_ctx);
  12436. handler_info->refcount--;
  12437. mg_unlock_context(conn->phys_ctx);
  12438. if (i > 0) {
  12439. /* Do nothing, callback has served the request. Store
  12440. * then return value as status code for the log and discard
  12441. * all data from the client not used by the callback. */
  12442. conn->status_code = i;
  12443. if (!conn->must_close) {
  12444. discard_unread_request_data(conn);
  12445. }
  12446. } else {
  12447. /* The handler did NOT handle the request. */
  12448. /* Some proper reactions would be:
  12449. * a) close the connections without sending anything
  12450. * b) send a 404 not found
  12451. * c) try if there is a file matching the URI
  12452. * It would be possible to do a, b or c in the callback
  12453. * implementation, and return 1 - we cannot do anything
  12454. * here, that is not possible in the callback.
  12455. *
  12456. * TODO: What would be the best reaction here?
  12457. * (Note: The reaction may change, if there is a better
  12458. *idea.)
  12459. */
  12460. /* For the moment, use option c: We look for a proper file,
  12461. * but since a file request is not always a script resource,
  12462. * the authorization check might be different. */
  12463. interpret_uri(conn,
  12464. path,
  12465. sizeof(path),
  12466. &file.stat,
  12467. &is_found,
  12468. &is_script_resource,
  12469. &is_websocket_request,
  12470. &is_put_or_delete_request);
  12471. callback_handler = NULL;
  12472. /* Here we are at a dead end:
  12473. * According to URI matching, a callback should be
  12474. * responsible for handling the request,
  12475. * we called it, but the callback declared itself
  12476. * not responsible.
  12477. * We use a goto here, to get out of this dead end,
  12478. * and continue with the default handling.
  12479. * A goto here is simpler and better to understand
  12480. * than some curious loop. */
  12481. goto no_callback_resource;
  12482. }
  12483. } else {
  12484. #if defined(USE_WEBSOCKET)
  12485. handle_websocket_request(conn,
  12486. path,
  12487. is_callback_resource,
  12488. subprotocols,
  12489. ws_connect_handler,
  12490. ws_ready_handler,
  12491. ws_data_handler,
  12492. ws_close_handler,
  12493. callback_data);
  12494. #endif
  12495. }
  12496. return;
  12497. }
  12498. /* 8. handle websocket requests */
  12499. #if defined(USE_WEBSOCKET)
  12500. if (is_websocket_request) {
  12501. if (is_script_resource) {
  12502. if (is_in_script_path(conn, path)) {
  12503. /* Websocket Lua script */
  12504. handle_websocket_request(conn,
  12505. path,
  12506. 0 /* Lua Script */,
  12507. NULL,
  12508. NULL,
  12509. NULL,
  12510. NULL,
  12511. NULL,
  12512. conn->phys_ctx->user_data);
  12513. } else {
  12514. /* Script was in an illegal path */
  12515. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12516. }
  12517. } else {
  12518. #if defined(MG_LEGACY_INTERFACE)
  12519. handle_websocket_request(
  12520. conn,
  12521. path,
  12522. !is_script_resource /* could be deprecated global callback
  12523. */
  12524. ,
  12525. NULL,
  12526. deprecated_websocket_connect_wrapper,
  12527. deprecated_websocket_ready_wrapper,
  12528. deprecated_websocket_data_wrapper,
  12529. NULL,
  12530. conn->phys_ctx->callbacks);
  12531. #else
  12532. mg_send_http_error(conn, 404, "%s", "Not found");
  12533. #endif
  12534. }
  12535. return;
  12536. } else
  12537. #endif
  12538. #if defined(NO_FILES)
  12539. /* 9a. In case the server uses only callbacks, this uri is
  12540. * unknown.
  12541. * Then, all request handling ends here. */
  12542. mg_send_http_error(conn, 404, "%s", "Not Found");
  12543. #else
  12544. /* 9b. This request is either for a static file or resource handled
  12545. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12546. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12547. mg_send_http_error(conn, 404, "%s", "Not Found");
  12548. return;
  12549. }
  12550. /* 10. Request is handled by a script */
  12551. if (is_script_resource) {
  12552. handle_file_based_request(conn, path, &file);
  12553. return;
  12554. }
  12555. /* 11. Handle put/delete/mkcol requests */
  12556. if (is_put_or_delete_request) {
  12557. /* 11.1. PUT method */
  12558. if (!strcmp(ri->request_method, "PUT")) {
  12559. put_file(conn, path);
  12560. return;
  12561. }
  12562. /* 11.2. DELETE method */
  12563. if (!strcmp(ri->request_method, "DELETE")) {
  12564. delete_file(conn, path);
  12565. return;
  12566. }
  12567. /* 11.3. MKCOL method */
  12568. if (!strcmp(ri->request_method, "MKCOL")) {
  12569. mkcol(conn, path);
  12570. return;
  12571. }
  12572. /* 11.4. PATCH method
  12573. * This method is not supported for static resources,
  12574. * only for scripts (Lua, CGI) and callbacks. */
  12575. mg_send_http_error(conn,
  12576. 405,
  12577. "%s method not allowed",
  12578. conn->request_info.request_method);
  12579. return;
  12580. }
  12581. /* 11. File does not exist, or it was configured that it should be
  12582. * hidden */
  12583. if (!is_found || (must_hide_file(conn, path))) {
  12584. mg_send_http_error(conn, 404, "%s", "Not found");
  12585. return;
  12586. }
  12587. /* 12. Directory uris should end with a slash */
  12588. if (file.stat.is_directory && (uri_len > 0)
  12589. && (ri->local_uri[uri_len - 1] != '/')) {
  12590. gmt_time_string(date, sizeof(date), &curtime);
  12591. mg_printf(conn,
  12592. "HTTP/1.1 301 Moved Permanently\r\n"
  12593. "Location: %s/\r\n"
  12594. "Date: %s\r\n"
  12595. /* "Cache-Control: private\r\n" (= default) */
  12596. "Content-Length: 0\r\n"
  12597. "Connection: %s\r\n",
  12598. ri->request_uri,
  12599. date,
  12600. suggest_connection_header(conn));
  12601. send_additional_header(conn);
  12602. mg_printf(conn, "\r\n");
  12603. return;
  12604. }
  12605. /* 13. Handle other methods than GET/HEAD */
  12606. /* 13.1. Handle PROPFIND */
  12607. if (!strcmp(ri->request_method, "PROPFIND")) {
  12608. handle_propfind(conn, path, &file.stat);
  12609. return;
  12610. }
  12611. /* 13.2. Handle OPTIONS for files */
  12612. if (!strcmp(ri->request_method, "OPTIONS")) {
  12613. /* This standard handler is only used for real files.
  12614. * Scripts should support the OPTIONS method themselves, to allow a
  12615. * maximum flexibility.
  12616. * Lua and CGI scripts may fully support CORS this way (including
  12617. * preflights). */
  12618. send_options(conn);
  12619. return;
  12620. }
  12621. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12622. if ((0 != strcmp(ri->request_method, "GET"))
  12623. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12624. mg_send_http_error(conn,
  12625. 405,
  12626. "%s method not allowed",
  12627. conn->request_info.request_method);
  12628. return;
  12629. }
  12630. /* 14. directories */
  12631. if (file.stat.is_directory) {
  12632. /* Substitute files have already been handled above. */
  12633. /* Here we can either generate and send a directory listing,
  12634. * or send an "access denied" error. */
  12635. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12636. "yes")) {
  12637. handle_directory_request(conn, path);
  12638. } else {
  12639. mg_send_http_error(conn,
  12640. 403,
  12641. "%s",
  12642. "Error: Directory listing denied");
  12643. }
  12644. return;
  12645. }
  12646. /* 15. read a normal file with GET or HEAD */
  12647. handle_file_based_request(conn, path, &file);
  12648. #endif /* !defined(NO_FILES) */
  12649. }
  12650. /* Include HTTP/2 modules */
  12651. #ifdef USE_HTTP2
  12652. #if defined(NO_SSL)
  12653. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12654. #endif
  12655. #include "mod_http2.inl"
  12656. #endif
  12657. #if !defined(NO_FILESYSTEMS)
  12658. static void
  12659. handle_file_based_request(struct mg_connection *conn,
  12660. const char *path,
  12661. struct mg_file *file)
  12662. {
  12663. if (!conn || !conn->dom_ctx) {
  12664. return;
  12665. }
  12666. if (0) {
  12667. #if defined(USE_LUA)
  12668. } else if (match_prefix(
  12669. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12670. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12671. path)
  12672. > 0) {
  12673. if (is_in_script_path(conn, path)) {
  12674. /* Lua server page: an SSI like page containing mostly plain
  12675. * html
  12676. * code
  12677. * plus some tags with server generated contents. */
  12678. handle_lsp_request(conn, path, file, NULL);
  12679. } else {
  12680. /* Script was in an illegal path */
  12681. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12682. }
  12683. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12684. strlen(
  12685. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12686. path)
  12687. > 0) {
  12688. if (is_in_script_path(conn, path)) {
  12689. /* Lua in-server module script: a CGI like script used to
  12690. * generate
  12691. * the
  12692. * entire reply. */
  12693. mg_exec_lua_script(conn, path, NULL);
  12694. } else {
  12695. /* Script was in an illegal path */
  12696. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12697. }
  12698. #endif
  12699. #if defined(USE_DUKTAPE)
  12700. } else if (match_prefix(
  12701. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12702. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12703. path)
  12704. > 0) {
  12705. if (is_in_script_path(conn, path)) {
  12706. /* Call duktape to generate the page */
  12707. mg_exec_duktape_script(conn, path);
  12708. } else {
  12709. /* Script was in an illegal path */
  12710. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12711. }
  12712. #endif
  12713. #if !defined(NO_CGI)
  12714. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12715. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12716. path)
  12717. > 0) {
  12718. if (is_in_script_path(conn, path)) {
  12719. /* CGI scripts may support all HTTP methods */
  12720. handle_cgi_request(conn, path);
  12721. } else {
  12722. /* Script was in an illegal path */
  12723. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12724. }
  12725. #endif /* !NO_CGI */
  12726. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12727. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12728. path)
  12729. > 0) {
  12730. if (is_in_script_path(conn, path)) {
  12731. handle_ssi_file_request(conn, path, file);
  12732. } else {
  12733. /* Script was in an illegal path */
  12734. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12735. }
  12736. #if !defined(NO_CACHING)
  12737. } else if ((!conn->in_error_handler)
  12738. && is_not_modified(conn, &file->stat)) {
  12739. /* Send 304 "Not Modified" - this must not send any body data */
  12740. handle_not_modified_static_file_request(conn, file);
  12741. #endif /* !NO_CACHING */
  12742. } else {
  12743. handle_static_file_request(conn, path, file, NULL, NULL);
  12744. }
  12745. }
  12746. #endif /* NO_FILESYSTEMS */
  12747. static void
  12748. close_all_listening_sockets(struct mg_context *ctx)
  12749. {
  12750. unsigned int i;
  12751. if (!ctx) {
  12752. return;
  12753. }
  12754. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12755. closesocket(ctx->listening_sockets[i].sock);
  12756. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12757. }
  12758. mg_free(ctx->listening_sockets);
  12759. ctx->listening_sockets = NULL;
  12760. mg_free(ctx->listening_socket_fds);
  12761. ctx->listening_socket_fds = NULL;
  12762. }
  12763. /* Valid listening port specification is: [ip_address:]port[s]
  12764. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12765. * Examples for IPv6: [::]:80, [::1]:80,
  12766. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12767. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12768. * In order to bind to both, IPv4 and IPv6, you can either add
  12769. * both ports using 8080,[::]:8080, or the short form +8080.
  12770. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12771. * one only accepting IPv4 the other only IPv6. +8080 creates
  12772. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12773. * environment, they might work differently, or might not work
  12774. * at all - it must be tested what options work best in the
  12775. * relevant network environment.
  12776. */
  12777. static int
  12778. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12779. {
  12780. unsigned int a, b, c, d;
  12781. unsigned port;
  12782. unsigned long portUL;
  12783. int ch, len;
  12784. const char *cb;
  12785. char *endptr;
  12786. #if defined(USE_IPV6)
  12787. char buf[100] = {0};
  12788. #endif
  12789. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12790. * Also, all-zeroes in the socket address means binding to all addresses
  12791. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12792. memset(so, 0, sizeof(*so));
  12793. so->lsa.sin.sin_family = AF_INET;
  12794. *ip_version = 0;
  12795. /* Initialize port and len as invalid. */
  12796. port = 0;
  12797. len = 0;
  12798. /* Test for different ways to format this string */
  12799. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12800. == 5) {
  12801. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12802. so->lsa.sin.sin_addr.s_addr =
  12803. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12804. so->lsa.sin.sin_port = htons((uint16_t)port);
  12805. *ip_version = 4;
  12806. #if defined(USE_IPV6)
  12807. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12808. && mg_inet_pton(
  12809. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12810. /* IPv6 address, examples: see above */
  12811. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12812. */
  12813. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12814. *ip_version = 6;
  12815. #endif
  12816. } else if ((vec->ptr[0] == '+')
  12817. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12818. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12819. /* Add 1 to len for the + character we skipped before */
  12820. len++;
  12821. #if defined(USE_IPV6)
  12822. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12823. so->lsa.sin6.sin6_family = AF_INET6;
  12824. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12825. *ip_version = 4 + 6;
  12826. #else
  12827. /* Bind to IPv4 only, since IPv6 is not built in. */
  12828. so->lsa.sin.sin_port = htons((uint16_t)port);
  12829. *ip_version = 4;
  12830. #endif
  12831. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12832. && (vec->ptr != endptr)) {
  12833. len = (int)(endptr - vec->ptr);
  12834. port = (uint16_t)portUL;
  12835. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12836. so->lsa.sin.sin_port = htons((uint16_t)port);
  12837. *ip_version = 4;
  12838. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12839. /* String could be a hostname. This check algotithm
  12840. * will only work for RFC 952 compliant hostnames,
  12841. * starting with a letter, containing only letters,
  12842. * digits and hyphen ('-'). Newer specs may allow
  12843. * more, but this is not guaranteed here, since it
  12844. * may interfere with rules for port option lists. */
  12845. /* According to RFC 1035, hostnames are restricted to 255 characters
  12846. * in total (63 between two dots). */
  12847. char hostname[256];
  12848. size_t hostnlen = (size_t)(cb - vec->ptr);
  12849. if (hostnlen >= sizeof(hostname)) {
  12850. /* This would be invalid in any case */
  12851. *ip_version = 0;
  12852. return 0;
  12853. }
  12854. memcpy(hostname, vec->ptr, hostnlen);
  12855. hostname[hostnlen] = 0;
  12856. if (mg_inet_pton(
  12857. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12858. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12859. *ip_version = 4;
  12860. so->lsa.sin.sin_family = AF_INET;
  12861. so->lsa.sin.sin_port = htons((uint16_t)port);
  12862. len += (int)(hostnlen + 1);
  12863. } else {
  12864. port = 0;
  12865. len = 0;
  12866. }
  12867. #if defined(USE_IPV6)
  12868. } else if (mg_inet_pton(AF_INET6,
  12869. hostname,
  12870. &so->lsa.sin6,
  12871. sizeof(so->lsa.sin6))) {
  12872. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12873. *ip_version = 6;
  12874. so->lsa.sin6.sin6_family = AF_INET6;
  12875. so->lsa.sin.sin_port = htons((uint16_t)port);
  12876. len += (int)(hostnlen + 1);
  12877. } else {
  12878. port = 0;
  12879. len = 0;
  12880. }
  12881. #endif
  12882. }
  12883. } else {
  12884. /* Parsing failure. */
  12885. }
  12886. /* sscanf and the option splitting code ensure the following condition
  12887. */
  12888. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12889. *ip_version = 0;
  12890. return 0;
  12891. }
  12892. ch = vec->ptr[len]; /* Next character after the port number */
  12893. so->is_ssl = (ch == 's');
  12894. so->ssl_redir = (ch == 'r');
  12895. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12896. if (is_valid_port(port)
  12897. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12898. return 1;
  12899. }
  12900. /* Reset ip_version to 0 if there is an error */
  12901. *ip_version = 0;
  12902. return 0;
  12903. }
  12904. /* Is there any SSL port in use? */
  12905. static int
  12906. is_ssl_port_used(const char *ports)
  12907. {
  12908. if (ports) {
  12909. /* There are several different allowed syntax variants:
  12910. * - "80" for a single port using every network interface
  12911. * - "localhost:80" for a single port using only localhost
  12912. * - "80,localhost:8080" for two ports, one bound to localhost
  12913. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12914. * to IPv4 localhost, one to IPv6 localhost
  12915. * - "+80" use port 80 for IPv4 and IPv6
  12916. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12917. * for both: IPv4 and IPv4
  12918. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12919. * additionally port 8080 bound to localhost connections
  12920. *
  12921. * If we just look for 's' anywhere in the string, "localhost:80"
  12922. * will be detected as SSL (false positive).
  12923. * Looking for 's' after a digit may cause false positives in
  12924. * "my24service:8080".
  12925. * Looking from 's' backward if there are only ':' and numbers
  12926. * before will not work for "24service:8080" (non SSL, port 8080)
  12927. * or "24s" (SSL, port 24).
  12928. *
  12929. * Remark: Initially hostnames were not allowed to start with a
  12930. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12931. * Section 2.1).
  12932. *
  12933. * To get this correct, the entire string must be parsed as a whole,
  12934. * reading it as a list element for element and parsing with an
  12935. * algorithm equivalent to parse_port_string.
  12936. *
  12937. * In fact, we use local interface names here, not arbitrary
  12938. * hostnames, so in most cases the only name will be "localhost".
  12939. *
  12940. * So, for now, we use this simple algorithm, that may still return
  12941. * a false positive in bizarre cases.
  12942. */
  12943. int i;
  12944. int portslen = (int)strlen(ports);
  12945. char prevIsNumber = 0;
  12946. for (i = 0; i < portslen; i++) {
  12947. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12948. return 1;
  12949. }
  12950. if (ports[i] >= '0' && ports[i] <= '9') {
  12951. prevIsNumber = 1;
  12952. } else {
  12953. prevIsNumber = 0;
  12954. }
  12955. }
  12956. }
  12957. return 0;
  12958. }
  12959. static int
  12960. set_ports_option(struct mg_context *phys_ctx)
  12961. {
  12962. const char *list;
  12963. int on = 1;
  12964. #if defined(USE_IPV6)
  12965. int off = 0;
  12966. #endif
  12967. struct vec vec;
  12968. struct socket so, *ptr;
  12969. struct mg_pollfd *pfd;
  12970. union usa usa;
  12971. socklen_t len;
  12972. int ip_version;
  12973. int portsTotal = 0;
  12974. int portsOk = 0;
  12975. const char *opt_txt;
  12976. long opt_listen_backlog;
  12977. if (!phys_ctx) {
  12978. return 0;
  12979. }
  12980. memset(&so, 0, sizeof(so));
  12981. memset(&usa, 0, sizeof(usa));
  12982. len = sizeof(usa);
  12983. list = phys_ctx->dd.config[LISTENING_PORTS];
  12984. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12985. portsTotal++;
  12986. if (!parse_port_string(&vec, &so, &ip_version)) {
  12987. mg_cry_ctx_internal(
  12988. phys_ctx,
  12989. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12990. (int)vec.len,
  12991. vec.ptr,
  12992. portsTotal,
  12993. "[IP_ADDRESS:]PORT[s|r]");
  12994. continue;
  12995. }
  12996. #if !defined(NO_SSL)
  12997. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12998. mg_cry_ctx_internal(phys_ctx,
  12999. "Cannot add SSL socket (entry %i)",
  13000. portsTotal);
  13001. continue;
  13002. }
  13003. #endif
  13004. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13005. == INVALID_SOCKET) {
  13006. mg_cry_ctx_internal(phys_ctx,
  13007. "cannot create socket (entry %i)",
  13008. portsTotal);
  13009. continue;
  13010. }
  13011. #if defined(_WIN32)
  13012. /* Windows SO_REUSEADDR lets many procs binds to a
  13013. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13014. * if someone already has the socket -- DTL */
  13015. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13016. * Windows might need a few seconds before
  13017. * the same port can be used again in the
  13018. * same process, so a short Sleep may be
  13019. * required between mg_stop and mg_start.
  13020. */
  13021. if (setsockopt(so.sock,
  13022. SOL_SOCKET,
  13023. SO_EXCLUSIVEADDRUSE,
  13024. (SOCK_OPT_TYPE)&on,
  13025. sizeof(on))
  13026. != 0) {
  13027. /* Set reuse option, but don't abort on errors. */
  13028. mg_cry_ctx_internal(
  13029. phys_ctx,
  13030. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13031. portsTotal);
  13032. }
  13033. #else
  13034. if (setsockopt(so.sock,
  13035. SOL_SOCKET,
  13036. SO_REUSEADDR,
  13037. (SOCK_OPT_TYPE)&on,
  13038. sizeof(on))
  13039. != 0) {
  13040. /* Set reuse option, but don't abort on errors. */
  13041. mg_cry_ctx_internal(
  13042. phys_ctx,
  13043. "cannot set socket option SO_REUSEADDR (entry %i)",
  13044. portsTotal);
  13045. }
  13046. #endif
  13047. if (ip_version > 4) {
  13048. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13049. #if defined(USE_IPV6)
  13050. if (ip_version > 6) {
  13051. if (so.lsa.sa.sa_family == AF_INET6
  13052. && setsockopt(so.sock,
  13053. IPPROTO_IPV6,
  13054. IPV6_V6ONLY,
  13055. (void *)&off,
  13056. sizeof(off))
  13057. != 0) {
  13058. /* Set IPv6 only option, but don't abort on errors. */
  13059. mg_cry_ctx_internal(phys_ctx,
  13060. "cannot set socket option "
  13061. "IPV6_V6ONLY=off (entry %i)",
  13062. portsTotal);
  13063. }
  13064. } else {
  13065. if (so.lsa.sa.sa_family == AF_INET6
  13066. && setsockopt(so.sock,
  13067. IPPROTO_IPV6,
  13068. IPV6_V6ONLY,
  13069. (void *)&on,
  13070. sizeof(on))
  13071. != 0) {
  13072. /* Set IPv6 only option, but don't abort on errors. */
  13073. mg_cry_ctx_internal(phys_ctx,
  13074. "cannot set socket option "
  13075. "IPV6_V6ONLY=on (entry %i)",
  13076. portsTotal);
  13077. }
  13078. }
  13079. #else
  13080. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13081. closesocket(so.sock);
  13082. so.sock = INVALID_SOCKET;
  13083. continue;
  13084. #endif
  13085. }
  13086. if (so.lsa.sa.sa_family == AF_INET) {
  13087. len = sizeof(so.lsa.sin);
  13088. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13089. mg_cry_ctx_internal(phys_ctx,
  13090. "cannot bind to %.*s: %d (%s)",
  13091. (int)vec.len,
  13092. vec.ptr,
  13093. (int)ERRNO,
  13094. strerror(errno));
  13095. closesocket(so.sock);
  13096. so.sock = INVALID_SOCKET;
  13097. continue;
  13098. }
  13099. }
  13100. #if defined(USE_IPV6)
  13101. else if (so.lsa.sa.sa_family == AF_INET6) {
  13102. len = sizeof(so.lsa.sin6);
  13103. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13104. mg_cry_ctx_internal(phys_ctx,
  13105. "cannot bind to IPv6 %.*s: %d (%s)",
  13106. (int)vec.len,
  13107. vec.ptr,
  13108. (int)ERRNO,
  13109. strerror(errno));
  13110. closesocket(so.sock);
  13111. so.sock = INVALID_SOCKET;
  13112. continue;
  13113. }
  13114. }
  13115. #endif
  13116. else {
  13117. mg_cry_ctx_internal(
  13118. phys_ctx,
  13119. "cannot bind: address family not supported (entry %i)",
  13120. portsTotal);
  13121. closesocket(so.sock);
  13122. so.sock = INVALID_SOCKET;
  13123. continue;
  13124. }
  13125. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13126. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13127. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13128. mg_cry_ctx_internal(phys_ctx,
  13129. "%s value \"%s\" is invalid",
  13130. config_options[LISTEN_BACKLOG_SIZE].name,
  13131. opt_txt);
  13132. closesocket(so.sock);
  13133. so.sock = INVALID_SOCKET;
  13134. continue;
  13135. }
  13136. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13137. mg_cry_ctx_internal(phys_ctx,
  13138. "cannot listen to %.*s: %d (%s)",
  13139. (int)vec.len,
  13140. vec.ptr,
  13141. (int)ERRNO,
  13142. strerror(errno));
  13143. closesocket(so.sock);
  13144. so.sock = INVALID_SOCKET;
  13145. continue;
  13146. }
  13147. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13148. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13149. int err = (int)ERRNO;
  13150. mg_cry_ctx_internal(phys_ctx,
  13151. "call to getsockname failed %.*s: %d (%s)",
  13152. (int)vec.len,
  13153. vec.ptr,
  13154. err,
  13155. strerror(errno));
  13156. closesocket(so.sock);
  13157. so.sock = INVALID_SOCKET;
  13158. continue;
  13159. }
  13160. /* Update lsa port in case of random free ports */
  13161. #if defined(USE_IPV6)
  13162. if (so.lsa.sa.sa_family == AF_INET6) {
  13163. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13164. } else
  13165. #endif
  13166. {
  13167. so.lsa.sin.sin_port = usa.sin.sin_port;
  13168. }
  13169. if ((ptr = (struct socket *)
  13170. mg_realloc_ctx(phys_ctx->listening_sockets,
  13171. (phys_ctx->num_listening_sockets + 1)
  13172. * sizeof(phys_ctx->listening_sockets[0]),
  13173. phys_ctx))
  13174. == NULL) {
  13175. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13176. closesocket(so.sock);
  13177. so.sock = INVALID_SOCKET;
  13178. continue;
  13179. }
  13180. if ((pfd = (struct mg_pollfd *)
  13181. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13182. (phys_ctx->num_listening_sockets + 1)
  13183. * sizeof(phys_ctx->listening_socket_fds[0]),
  13184. phys_ctx))
  13185. == NULL) {
  13186. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13187. closesocket(so.sock);
  13188. so.sock = INVALID_SOCKET;
  13189. mg_free(ptr);
  13190. continue;
  13191. }
  13192. set_close_on_exec(so.sock, NULL, phys_ctx);
  13193. phys_ctx->listening_sockets = ptr;
  13194. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13195. phys_ctx->listening_socket_fds = pfd;
  13196. phys_ctx->num_listening_sockets++;
  13197. portsOk++;
  13198. }
  13199. if (portsOk != portsTotal) {
  13200. close_all_listening_sockets(phys_ctx);
  13201. portsOk = 0;
  13202. }
  13203. return portsOk;
  13204. }
  13205. static const char *
  13206. header_val(const struct mg_connection *conn, const char *header)
  13207. {
  13208. const char *header_value;
  13209. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13210. return "-";
  13211. } else {
  13212. return header_value;
  13213. }
  13214. }
  13215. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13216. static void log_access(const struct mg_connection *conn);
  13217. #include "external_log_access.inl"
  13218. #elif !defined(NO_FILESYSTEMS)
  13219. static void
  13220. log_access(const struct mg_connection *conn)
  13221. {
  13222. const struct mg_request_info *ri;
  13223. struct mg_file fi;
  13224. char date[64], src_addr[IP_ADDR_STR_LEN];
  13225. struct tm *tm;
  13226. const char *referer;
  13227. const char *user_agent;
  13228. char buf[4096];
  13229. if (!conn || !conn->dom_ctx) {
  13230. return;
  13231. }
  13232. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13233. if (mg_fopen(conn,
  13234. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13235. MG_FOPEN_MODE_APPEND,
  13236. &fi)
  13237. == 0) {
  13238. fi.access.fp = NULL;
  13239. }
  13240. } else {
  13241. fi.access.fp = NULL;
  13242. }
  13243. /* Log is written to a file and/or a callback. If both are not set,
  13244. * executing the rest of the function is pointless. */
  13245. if ((fi.access.fp == NULL)
  13246. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13247. return;
  13248. }
  13249. tm = localtime(&conn->conn_birth_time);
  13250. if (tm != NULL) {
  13251. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13252. } else {
  13253. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13254. date[sizeof(date) - 1] = '\0';
  13255. }
  13256. ri = &conn->request_info;
  13257. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13258. referer = header_val(conn, "Referer");
  13259. user_agent = header_val(conn, "User-Agent");
  13260. mg_snprintf(conn,
  13261. NULL, /* Ignore truncation in access log */
  13262. buf,
  13263. sizeof(buf),
  13264. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13265. src_addr,
  13266. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13267. date,
  13268. ri->request_method ? ri->request_method : "-",
  13269. ri->request_uri ? ri->request_uri : "-",
  13270. ri->query_string ? "?" : "",
  13271. ri->query_string ? ri->query_string : "",
  13272. ri->http_version,
  13273. conn->status_code,
  13274. conn->num_bytes_sent,
  13275. referer,
  13276. user_agent);
  13277. if (conn->phys_ctx->callbacks.log_access) {
  13278. conn->phys_ctx->callbacks.log_access(conn, buf);
  13279. }
  13280. if (fi.access.fp) {
  13281. int ok = 1;
  13282. flockfile(fi.access.fp);
  13283. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13284. ok = 0;
  13285. }
  13286. if (fflush(fi.access.fp) != 0) {
  13287. ok = 0;
  13288. }
  13289. funlockfile(fi.access.fp);
  13290. if (mg_fclose(&fi.access) != 0) {
  13291. ok = 0;
  13292. }
  13293. if (!ok) {
  13294. mg_cry_internal(conn,
  13295. "Error writing log file %s",
  13296. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13297. }
  13298. }
  13299. }
  13300. #else
  13301. #error Must either enable filesystems or provide a custom log_access implementation
  13302. #endif /* Externally provided function */
  13303. /* Verify given socket address against the ACL.
  13304. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13305. */
  13306. static int
  13307. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13308. {
  13309. int allowed, flag;
  13310. uint32_t net, mask;
  13311. struct vec vec;
  13312. if (phys_ctx) {
  13313. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13314. /* If any ACL is set, deny by default */
  13315. allowed = (list == NULL) ? '+' : '-';
  13316. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13317. flag = vec.ptr[0];
  13318. if ((flag != '+' && flag != '-')
  13319. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13320. mg_cry_ctx_internal(phys_ctx,
  13321. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13322. __func__);
  13323. return -1;
  13324. }
  13325. if (net == (remote_ip & mask)) {
  13326. allowed = flag;
  13327. }
  13328. }
  13329. return allowed == '+';
  13330. }
  13331. return -1;
  13332. }
  13333. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13334. static int
  13335. set_uid_option(struct mg_context *phys_ctx)
  13336. {
  13337. int success = 0;
  13338. if (phys_ctx) {
  13339. /* We are currently running as curr_uid. */
  13340. const uid_t curr_uid = getuid();
  13341. /* If set, we want to run as run_as_user. */
  13342. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13343. const struct passwd *to_pw = NULL;
  13344. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13345. /* run_as_user does not exist on the system. We can't proceed
  13346. * further. */
  13347. mg_cry_ctx_internal(phys_ctx,
  13348. "%s: unknown user [%s]",
  13349. __func__,
  13350. run_as_user);
  13351. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13352. /* There was either no request to change user, or we're already
  13353. * running as run_as_user. Nothing else to do.
  13354. */
  13355. success = 1;
  13356. } else {
  13357. /* Valid change request. */
  13358. if (setgid(to_pw->pw_gid) == -1) {
  13359. mg_cry_ctx_internal(phys_ctx,
  13360. "%s: setgid(%s): %s",
  13361. __func__,
  13362. run_as_user,
  13363. strerror(errno));
  13364. } else if (setgroups(0, NULL) == -1) {
  13365. mg_cry_ctx_internal(phys_ctx,
  13366. "%s: setgroups(): %s",
  13367. __func__,
  13368. strerror(errno));
  13369. } else if (setuid(to_pw->pw_uid) == -1) {
  13370. mg_cry_ctx_internal(phys_ctx,
  13371. "%s: setuid(%s): %s",
  13372. __func__,
  13373. run_as_user,
  13374. strerror(errno));
  13375. } else {
  13376. success = 1;
  13377. }
  13378. }
  13379. }
  13380. return success;
  13381. }
  13382. #endif /* !_WIN32 */
  13383. static void
  13384. tls_dtor(void *key)
  13385. {
  13386. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13387. /* key == pthread_getspecific(sTlsKey); */
  13388. if (tls) {
  13389. if (tls->is_master == 2) {
  13390. tls->is_master = -3; /* Mark memory as dead */
  13391. mg_free(tls);
  13392. }
  13393. }
  13394. pthread_setspecific(sTlsKey, NULL);
  13395. }
  13396. #if !defined(NO_SSL)
  13397. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13398. struct mg_domain_context *dom_ctx,
  13399. const char *pem,
  13400. const char *chain);
  13401. static const char *ssl_error(void);
  13402. static int
  13403. refresh_trust(struct mg_connection *conn)
  13404. {
  13405. struct stat cert_buf;
  13406. int64_t t = 0;
  13407. const char *pem;
  13408. const char *chain;
  13409. int should_verify_peer;
  13410. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13411. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13412. * refresh_trust still can not work. */
  13413. return 0;
  13414. }
  13415. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13416. if (chain == NULL) {
  13417. /* pem is not NULL here */
  13418. chain = pem;
  13419. }
  13420. if (*chain == 0) {
  13421. chain = NULL;
  13422. }
  13423. if (stat(pem, &cert_buf) != -1) {
  13424. t = (int64_t)cert_buf.st_mtime;
  13425. }
  13426. mg_lock_context(conn->phys_ctx);
  13427. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13428. conn->dom_ctx->ssl_cert_last_mtime = t;
  13429. should_verify_peer = 0;
  13430. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13431. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13432. == 0) {
  13433. should_verify_peer = 1;
  13434. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13435. "optional")
  13436. == 0) {
  13437. should_verify_peer = 1;
  13438. }
  13439. }
  13440. if (should_verify_peer) {
  13441. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13442. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13443. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13444. ca_file,
  13445. ca_path)
  13446. != 1) {
  13447. mg_unlock_context(conn->phys_ctx);
  13448. mg_cry_ctx_internal(
  13449. conn->phys_ctx,
  13450. "SSL_CTX_load_verify_locations error: %s "
  13451. "ssl_verify_peer requires setting "
  13452. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13453. "present in "
  13454. "the .conf file?",
  13455. ssl_error());
  13456. return 0;
  13457. }
  13458. }
  13459. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13460. == 0) {
  13461. mg_unlock_context(conn->phys_ctx);
  13462. return 0;
  13463. }
  13464. }
  13465. mg_unlock_context(conn->phys_ctx);
  13466. return 1;
  13467. }
  13468. #if defined(OPENSSL_API_1_1)
  13469. #else
  13470. static pthread_mutex_t *ssl_mutexes;
  13471. #endif /* OPENSSL_API_1_1 */
  13472. static int
  13473. sslize(struct mg_connection *conn,
  13474. int (*func)(SSL *),
  13475. const struct mg_client_options *client_options)
  13476. {
  13477. int ret, err;
  13478. int short_trust;
  13479. unsigned timeout = 1024;
  13480. unsigned i;
  13481. if (!conn) {
  13482. return 0;
  13483. }
  13484. short_trust =
  13485. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13486. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13487. if (short_trust) {
  13488. int trust_ret = refresh_trust(conn);
  13489. if (!trust_ret) {
  13490. return trust_ret;
  13491. }
  13492. }
  13493. mg_lock_context(conn->phys_ctx);
  13494. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13495. mg_unlock_context(conn->phys_ctx);
  13496. if (conn->ssl == NULL) {
  13497. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13498. OPENSSL_REMOVE_THREAD_STATE();
  13499. return 0;
  13500. }
  13501. SSL_set_app_data(conn->ssl, (char *)conn);
  13502. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13503. if (ret != 1) {
  13504. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13505. SSL_free(conn->ssl);
  13506. conn->ssl = NULL;
  13507. OPENSSL_REMOVE_THREAD_STATE();
  13508. return 0;
  13509. }
  13510. if (client_options) {
  13511. if (client_options->host_name) {
  13512. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13513. }
  13514. }
  13515. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13516. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13517. /* NOTE: The loop below acts as a back-off, so we can end
  13518. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13519. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13520. if (to >= 0) {
  13521. timeout = (unsigned)to;
  13522. }
  13523. }
  13524. /* SSL functions may fail and require to be called again:
  13525. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13526. * Here "func" could be SSL_connect or SSL_accept. */
  13527. for (i = 0; i <= timeout; i += 50) {
  13528. ERR_clear_error();
  13529. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13530. ret = func(conn->ssl);
  13531. if (ret != 1) {
  13532. err = SSL_get_error(conn->ssl, ret);
  13533. if ((err == SSL_ERROR_WANT_CONNECT)
  13534. || (err == SSL_ERROR_WANT_ACCEPT)
  13535. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13536. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13537. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13538. /* Don't wait if the server is going to be stopped. */
  13539. break;
  13540. }
  13541. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13542. /* Simply retry the function call. */
  13543. mg_sleep(50);
  13544. } else {
  13545. /* Need to retry the function call "later".
  13546. * See https://linux.die.net/man/3/ssl_get_error
  13547. * This is typical for non-blocking sockets. */
  13548. struct mg_pollfd pfd;
  13549. int pollres;
  13550. pfd.fd = conn->client.sock;
  13551. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13552. || (err == SSL_ERROR_WANT_WRITE))
  13553. ? POLLOUT
  13554. : POLLIN;
  13555. pollres = mg_poll(&pfd, 1, 50,
  13556. &(conn->phys_ctx->stop_flag));
  13557. if (pollres < 0) {
  13558. /* Break if error occured (-1)
  13559. * or server shutdown (-2) */
  13560. break;
  13561. }
  13562. }
  13563. } else if (err == SSL_ERROR_SYSCALL) {
  13564. /* This is an IO error. Look at errno. */
  13565. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13566. break;
  13567. } else {
  13568. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13569. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13570. break;
  13571. }
  13572. } else {
  13573. /* success */
  13574. break;
  13575. }
  13576. }
  13577. ERR_clear_error();
  13578. if (ret != 1) {
  13579. SSL_free(conn->ssl);
  13580. conn->ssl = NULL;
  13581. OPENSSL_REMOVE_THREAD_STATE();
  13582. return 0;
  13583. }
  13584. return 1;
  13585. }
  13586. /* Return OpenSSL error message (from CRYPTO lib) */
  13587. static const char *
  13588. ssl_error(void)
  13589. {
  13590. unsigned long err;
  13591. err = ERR_get_error();
  13592. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13593. }
  13594. static int
  13595. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13596. {
  13597. int i;
  13598. const char hexdigit[] = "0123456789abcdef";
  13599. if ((memlen <= 0) || (buflen <= 0)) {
  13600. return 0;
  13601. }
  13602. if (buflen < (3 * memlen)) {
  13603. return 0;
  13604. }
  13605. for (i = 0; i < memlen; i++) {
  13606. if (i > 0) {
  13607. buf[3 * i - 1] = ' ';
  13608. }
  13609. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13610. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13611. }
  13612. buf[3 * memlen - 1] = 0;
  13613. return 1;
  13614. }
  13615. static int
  13616. ssl_get_client_cert_info(const struct mg_connection *conn,
  13617. struct mg_client_cert *client_cert)
  13618. {
  13619. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13620. if (cert) {
  13621. char str_buf[1024];
  13622. unsigned char buf[256];
  13623. char *str_serial = NULL;
  13624. unsigned int ulen;
  13625. int ilen;
  13626. unsigned char *tmp_buf;
  13627. unsigned char *tmp_p;
  13628. /* Handle to algorithm used for fingerprint */
  13629. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13630. /* Get Subject and issuer */
  13631. X509_NAME *subj = X509_get_subject_name(cert);
  13632. X509_NAME *iss = X509_get_issuer_name(cert);
  13633. /* Get serial number */
  13634. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13635. /* Translate serial number to a hex string */
  13636. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13637. if (serial_bn) {
  13638. str_serial = BN_bn2hex(serial_bn);
  13639. BN_free(serial_bn);
  13640. }
  13641. client_cert->serial =
  13642. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13643. /* Translate subject and issuer to a string */
  13644. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13645. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13646. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13647. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13648. /* Calculate SHA1 fingerprint and store as a hex string */
  13649. ulen = 0;
  13650. /* ASN1_digest is deprecated. Do the calculation manually,
  13651. * using EVP_Digest. */
  13652. ilen = i2d_X509(cert, NULL);
  13653. tmp_buf = (ilen > 0)
  13654. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13655. conn->phys_ctx)
  13656. : NULL;
  13657. if (tmp_buf) {
  13658. tmp_p = tmp_buf;
  13659. (void)i2d_X509(cert, &tmp_p);
  13660. if (!EVP_Digest(
  13661. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13662. ulen = 0;
  13663. }
  13664. mg_free(tmp_buf);
  13665. }
  13666. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13667. *str_buf = 0;
  13668. }
  13669. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13670. client_cert->peer_cert = (void *)cert;
  13671. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13672. * see https://linux.die.net/man/3/bn_bn2hex */
  13673. OPENSSL_free(str_serial);
  13674. return 1;
  13675. }
  13676. return 0;
  13677. }
  13678. #if defined(OPENSSL_API_1_1)
  13679. #else
  13680. static void
  13681. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13682. {
  13683. (void)line;
  13684. (void)file;
  13685. if (mode & 1) {
  13686. /* 1 is CRYPTO_LOCK */
  13687. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13688. } else {
  13689. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13690. }
  13691. }
  13692. #endif /* OPENSSL_API_1_1 */
  13693. #if !defined(NO_SSL_DL)
  13694. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13695. static void *
  13696. load_tls_dll(char *ebuf,
  13697. size_t ebuf_len,
  13698. const char *dll_name,
  13699. struct ssl_func *sw)
  13700. {
  13701. union {
  13702. void *p;
  13703. void (*fp)(void);
  13704. } u;
  13705. void *dll_handle;
  13706. struct ssl_func *fp;
  13707. int ok;
  13708. int truncated = 0;
  13709. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13710. mg_snprintf(NULL,
  13711. NULL, /* No truncation check for ebuf */
  13712. ebuf,
  13713. ebuf_len,
  13714. "%s: cannot load %s",
  13715. __func__,
  13716. dll_name);
  13717. return NULL;
  13718. }
  13719. ok = 1;
  13720. for (fp = sw; fp->name != NULL; fp++) {
  13721. enum ssl_func_category req = fp->required;
  13722. #if defined(_WIN32)
  13723. /* GetProcAddress() returns pointer to function */
  13724. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13725. #else
  13726. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13727. * pointers to function pointers. We need to use a union to make a
  13728. * cast. */
  13729. u.p = dlsym(dll_handle, fp->name);
  13730. #endif /* _WIN32 */
  13731. /* Set pointer (might be NULL) */
  13732. fp->ptr = u.fp;
  13733. if (u.fp == NULL) {
  13734. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13735. tls_feature_missing[req]++;
  13736. if (req == TLS_Mandatory) {
  13737. /* Mandatory function is missing */
  13738. if (ok) {
  13739. /* This is the first missing function.
  13740. * Create a new error message. */
  13741. mg_snprintf(NULL,
  13742. &truncated,
  13743. ebuf,
  13744. ebuf_len,
  13745. "%s: %s: cannot find %s",
  13746. __func__,
  13747. dll_name,
  13748. fp->name);
  13749. ok = 0;
  13750. } else {
  13751. /* This is yet anothermissing function.
  13752. * Append existing error message. */
  13753. size_t cur_len = strlen(ebuf);
  13754. if (!truncated) {
  13755. mg_snprintf(NULL,
  13756. &truncated,
  13757. ebuf + cur_len,
  13758. ebuf_len - cur_len - 3,
  13759. ", %s",
  13760. fp->name);
  13761. if (truncated) {
  13762. /* If truncated, add "..." */
  13763. strcat(ebuf, "...");
  13764. }
  13765. }
  13766. }
  13767. }
  13768. }
  13769. }
  13770. if (!ok) {
  13771. (void)dlclose(dll_handle);
  13772. return NULL;
  13773. }
  13774. return dll_handle;
  13775. }
  13776. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13777. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13778. #endif /* NO_SSL_DL */
  13779. #if defined(SSL_ALREADY_INITIALIZED)
  13780. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13781. #else
  13782. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13783. #endif
  13784. static int
  13785. initialize_ssl(char *ebuf, size_t ebuf_len)
  13786. {
  13787. #if defined(OPENSSL_API_1_1)
  13788. if (ebuf_len > 0) {
  13789. ebuf[0] = 0;
  13790. }
  13791. #if !defined(NO_SSL_DL)
  13792. if (!cryptolib_dll_handle) {
  13793. cryptolib_dll_handle =
  13794. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13795. if (!cryptolib_dll_handle) {
  13796. mg_snprintf(NULL,
  13797. NULL, /* No truncation check for ebuf */
  13798. ebuf,
  13799. ebuf_len,
  13800. "%s: error loading library %s",
  13801. __func__,
  13802. CRYPTO_LIB);
  13803. DEBUG_TRACE("%s", ebuf);
  13804. return 0;
  13805. }
  13806. }
  13807. #endif /* NO_SSL_DL */
  13808. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13809. return 1;
  13810. }
  13811. #else /* not OPENSSL_API_1_1 */
  13812. int i, num_locks;
  13813. size_t size;
  13814. if (ebuf_len > 0) {
  13815. ebuf[0] = 0;
  13816. }
  13817. #if !defined(NO_SSL_DL)
  13818. if (!cryptolib_dll_handle) {
  13819. cryptolib_dll_handle =
  13820. load_tls_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13821. if (!cryptolib_dll_handle) {
  13822. mg_snprintf(NULL,
  13823. NULL, /* No truncation check for ebuf */
  13824. ebuf,
  13825. ebuf_len,
  13826. "%s: error loading library %s",
  13827. __func__,
  13828. CRYPTO_LIB);
  13829. DEBUG_TRACE("%s", ebuf);
  13830. return 0;
  13831. }
  13832. }
  13833. #endif /* NO_SSL_DL */
  13834. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13835. return 1;
  13836. }
  13837. /* Initialize locking callbacks, needed for thread safety.
  13838. * http://www.openssl.org/support/faq.html#PROG1
  13839. */
  13840. num_locks = CRYPTO_num_locks();
  13841. if (num_locks < 0) {
  13842. num_locks = 0;
  13843. }
  13844. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13845. /* allocate mutex array, if required */
  13846. if (num_locks == 0) {
  13847. /* No mutex array required */
  13848. ssl_mutexes = NULL;
  13849. } else {
  13850. /* Mutex array required - allocate it */
  13851. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13852. /* Check OOM */
  13853. if (ssl_mutexes == NULL) {
  13854. mg_snprintf(NULL,
  13855. NULL, /* No truncation check for ebuf */
  13856. ebuf,
  13857. ebuf_len,
  13858. "%s: cannot allocate mutexes: %s",
  13859. __func__,
  13860. ssl_error());
  13861. DEBUG_TRACE("%s", ebuf);
  13862. return 0;
  13863. }
  13864. /* initialize mutex array */
  13865. for (i = 0; i < num_locks; i++) {
  13866. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13867. mg_snprintf(NULL,
  13868. NULL, /* No truncation check for ebuf */
  13869. ebuf,
  13870. ebuf_len,
  13871. "%s: error initializing mutex %i of %i",
  13872. __func__,
  13873. i,
  13874. num_locks);
  13875. DEBUG_TRACE("%s", ebuf);
  13876. mg_free(ssl_mutexes);
  13877. return 0;
  13878. }
  13879. }
  13880. }
  13881. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13882. CRYPTO_set_id_callback(&mg_current_thread_id);
  13883. #endif /* OPENSSL_API_1_1 */
  13884. #if !defined(NO_SSL_DL)
  13885. if (!ssllib_dll_handle) {
  13886. ssllib_dll_handle = load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13887. if (!ssllib_dll_handle) {
  13888. #if !defined(OPENSSL_API_1_1)
  13889. mg_free(ssl_mutexes);
  13890. #endif
  13891. DEBUG_TRACE("%s", ebuf);
  13892. return 0;
  13893. }
  13894. }
  13895. #endif /* NO_SSL_DL */
  13896. #if defined(OPENSSL_API_1_1)
  13897. /* Initialize SSL library */
  13898. OPENSSL_init_ssl(0, NULL);
  13899. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13900. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13901. NULL);
  13902. #else
  13903. /* Initialize SSL library */
  13904. SSL_library_init();
  13905. SSL_load_error_strings();
  13906. #endif
  13907. return 1;
  13908. }
  13909. static int
  13910. ssl_use_pem_file(struct mg_context *phys_ctx,
  13911. struct mg_domain_context *dom_ctx,
  13912. const char *pem,
  13913. const char *chain)
  13914. {
  13915. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13916. mg_cry_ctx_internal(phys_ctx,
  13917. "%s: cannot open certificate file %s: %s",
  13918. __func__,
  13919. pem,
  13920. ssl_error());
  13921. return 0;
  13922. }
  13923. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13924. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13925. mg_cry_ctx_internal(phys_ctx,
  13926. "%s: cannot open private key file %s: %s",
  13927. __func__,
  13928. pem,
  13929. ssl_error());
  13930. return 0;
  13931. }
  13932. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13933. mg_cry_ctx_internal(phys_ctx,
  13934. "%s: certificate and private key do not match: %s",
  13935. __func__,
  13936. pem);
  13937. return 0;
  13938. }
  13939. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13940. * chain files that contain private keys and certificates in
  13941. * SSL_CTX_use_certificate_chain_file.
  13942. * The CivetWeb-Server used pem-Files that contained both information.
  13943. * In order to make wolfSSL work, it is split in two files.
  13944. * One file that contains key and certificate used by the server and
  13945. * an optional chain file for the ssl stack.
  13946. */
  13947. if (chain) {
  13948. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13949. mg_cry_ctx_internal(phys_ctx,
  13950. "%s: cannot use certificate chain file %s: %s",
  13951. __func__,
  13952. chain,
  13953. ssl_error());
  13954. return 0;
  13955. }
  13956. }
  13957. return 1;
  13958. }
  13959. #if defined(OPENSSL_API_1_1)
  13960. static unsigned long
  13961. ssl_get_protocol(int version_id)
  13962. {
  13963. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13964. if (version_id > 0)
  13965. ret |= SSL_OP_NO_SSLv2;
  13966. if (version_id > 1)
  13967. ret |= SSL_OP_NO_SSLv3;
  13968. if (version_id > 2)
  13969. ret |= SSL_OP_NO_TLSv1;
  13970. if (version_id > 3)
  13971. ret |= SSL_OP_NO_TLSv1_1;
  13972. if (version_id > 4)
  13973. ret |= SSL_OP_NO_TLSv1_2;
  13974. #if defined(SSL_OP_NO_TLSv1_3)
  13975. if (version_id > 5)
  13976. ret |= SSL_OP_NO_TLSv1_3;
  13977. #endif
  13978. return ret;
  13979. }
  13980. #else
  13981. static long
  13982. ssl_get_protocol(int version_id)
  13983. {
  13984. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13985. if (version_id > 0)
  13986. ret |= SSL_OP_NO_SSLv2;
  13987. if (version_id > 1)
  13988. ret |= SSL_OP_NO_SSLv3;
  13989. if (version_id > 2)
  13990. ret |= SSL_OP_NO_TLSv1;
  13991. if (version_id > 3)
  13992. ret |= SSL_OP_NO_TLSv1_1;
  13993. if (version_id > 4)
  13994. ret |= SSL_OP_NO_TLSv1_2;
  13995. #if defined(SSL_OP_NO_TLSv1_3)
  13996. if (version_id > 5)
  13997. ret |= SSL_OP_NO_TLSv1_3;
  13998. #endif
  13999. return (long)ret;
  14000. }
  14001. #endif /* OPENSSL_API_1_1 */
  14002. /* SSL callback documentation:
  14003. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14004. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14005. * https://linux.die.net/man/3/ssl_set_info_callback */
  14006. /* Note: There is no "const" for the first argument in the documentation
  14007. * examples, however some (maybe most, but not all) headers of OpenSSL
  14008. * versions / OpenSSL compatibility layers have it. Having a different
  14009. * definition will cause a warning in C and an error in C++. Use "const SSL
  14010. * *", while automatical conversion from "SSL *" works for all compilers,
  14011. * but not other way around */
  14012. static void
  14013. ssl_info_callback(const SSL *ssl, int what, int ret)
  14014. {
  14015. (void)ret;
  14016. if (what & SSL_CB_HANDSHAKE_START) {
  14017. SSL_get_app_data(ssl);
  14018. }
  14019. if (what & SSL_CB_HANDSHAKE_DONE) {
  14020. /* TODO: check for openSSL 1.1 */
  14021. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14022. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14023. }
  14024. }
  14025. static int
  14026. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14027. {
  14028. #if defined(GCC_DIAGNOSTIC)
  14029. #pragma GCC diagnostic push
  14030. #pragma GCC diagnostic ignored "-Wcast-align"
  14031. #endif /* defined(GCC_DIAGNOSTIC) */
  14032. /* We used an aligned pointer in SSL_set_app_data */
  14033. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14034. #if defined(GCC_DIAGNOSTIC)
  14035. #pragma GCC diagnostic pop
  14036. #endif /* defined(GCC_DIAGNOSTIC) */
  14037. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14038. (void)ad;
  14039. (void)arg;
  14040. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14041. DEBUG_ASSERT(0);
  14042. return SSL_TLSEXT_ERR_NOACK;
  14043. }
  14044. conn->dom_ctx = &(conn->phys_ctx->dd);
  14045. /* Old clients (Win XP) will not support SNI. Then, there
  14046. * is no server name available in the request - we can
  14047. * only work with the default certificate.
  14048. * Multiple HTTPS hosts on one IP+port are only possible
  14049. * with a certificate containing all alternative names.
  14050. */
  14051. if ((servername == NULL) || (*servername == 0)) {
  14052. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14053. mg_lock_context(conn->phys_ctx);
  14054. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14055. mg_unlock_context(conn->phys_ctx);
  14056. return SSL_TLSEXT_ERR_NOACK;
  14057. }
  14058. DEBUG_TRACE("TLS connection to host %s", servername);
  14059. while (conn->dom_ctx) {
  14060. if (!mg_strcasecmp(servername,
  14061. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14062. /* Found matching domain */
  14063. DEBUG_TRACE("TLS domain %s found",
  14064. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14065. break;
  14066. }
  14067. mg_lock_context(conn->phys_ctx);
  14068. conn->dom_ctx = conn->dom_ctx->next;
  14069. mg_unlock_context(conn->phys_ctx);
  14070. }
  14071. if (conn->dom_ctx == NULL) {
  14072. /* Default domain */
  14073. DEBUG_TRACE("TLS default domain %s used",
  14074. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14075. conn->dom_ctx = &(conn->phys_ctx->dd);
  14076. }
  14077. mg_lock_context(conn->phys_ctx);
  14078. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14079. mg_unlock_context(conn->phys_ctx);
  14080. return SSL_TLSEXT_ERR_OK;
  14081. }
  14082. #if defined(USE_HTTP2)
  14083. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14084. static const char *alpn_proto_order[] = {alpn_proto_list,
  14085. alpn_proto_list + 3,
  14086. alpn_proto_list + 3 + 8,
  14087. NULL};
  14088. #else
  14089. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14090. static const char *alpn_proto_order[] = {alpn_proto_list,
  14091. alpn_proto_list + 8,
  14092. NULL};
  14093. #endif
  14094. static int
  14095. alpn_select_cb(SSL *ssl,
  14096. const unsigned char **out,
  14097. unsigned char *outlen,
  14098. const unsigned char *in,
  14099. unsigned int inlen,
  14100. void *arg)
  14101. {
  14102. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14103. unsigned int i, j;
  14104. struct mg_workerTLS *tls =
  14105. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14106. (void)ssl;
  14107. (void)dom_ctx;
  14108. if (tls == NULL) {
  14109. /* Need to store protocol in Thread Local Storage */
  14110. /* If there is no Thread Local Storage, don't use ALPN */
  14111. return SSL_TLSEXT_ERR_NOACK;
  14112. }
  14113. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14114. /* check all accepted protocols in this order */
  14115. const char *alpn_proto = alpn_proto_order[j];
  14116. /* search input for matching protocol */
  14117. for (i = 0; i < inlen; i++) {
  14118. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14119. *out = in + i + 1;
  14120. *outlen = in[i];
  14121. tls->alpn_proto = alpn_proto;
  14122. return SSL_TLSEXT_ERR_OK;
  14123. }
  14124. }
  14125. }
  14126. /* Nothing found */
  14127. return SSL_TLSEXT_ERR_NOACK;
  14128. }
  14129. static int
  14130. next_protos_advertised_cb(SSL *ssl,
  14131. const unsigned char **data,
  14132. unsigned int *len,
  14133. void *arg)
  14134. {
  14135. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14136. *data = (const unsigned char *)alpn_proto_list;
  14137. *len = (unsigned int)strlen((const char *)data);
  14138. (void)ssl;
  14139. (void)dom_ctx;
  14140. return SSL_TLSEXT_ERR_OK;
  14141. }
  14142. static int
  14143. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14144. {
  14145. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14146. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14147. (const unsigned char *)alpn_proto_list,
  14148. alpn_len);
  14149. if (ret != 0) {
  14150. mg_cry_ctx_internal(phys_ctx,
  14151. "SSL_CTX_set_alpn_protos error: %s",
  14152. ssl_error());
  14153. }
  14154. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14155. alpn_select_cb,
  14156. (void *)dom_ctx);
  14157. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14158. next_protos_advertised_cb,
  14159. (void *)dom_ctx);
  14160. return ret;
  14161. }
  14162. /* Setup SSL CTX as required by CivetWeb */
  14163. static int
  14164. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14165. struct mg_domain_context *dom_ctx,
  14166. const char *pem,
  14167. const char *chain)
  14168. {
  14169. int callback_ret;
  14170. int should_verify_peer;
  14171. int peer_certificate_optional;
  14172. const char *ca_path;
  14173. const char *ca_file;
  14174. int use_default_verify_paths;
  14175. int verify_depth;
  14176. struct timespec now_mt;
  14177. md5_byte_t ssl_context_id[16];
  14178. md5_state_t md5state;
  14179. int protocol_ver;
  14180. #if defined(OPENSSL_API_1_1)
  14181. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14182. mg_cry_ctx_internal(phys_ctx,
  14183. "SSL_CTX_new (server) error: %s",
  14184. ssl_error());
  14185. return 0;
  14186. }
  14187. #else
  14188. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14189. mg_cry_ctx_internal(phys_ctx,
  14190. "SSL_CTX_new (server) error: %s",
  14191. ssl_error());
  14192. return 0;
  14193. }
  14194. #endif /* OPENSSL_API_1_1 */
  14195. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14196. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14197. | SSL_OP_NO_TLSv1_1);
  14198. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14199. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14200. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14201. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14202. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14203. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14204. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14205. #if defined(SSL_OP_NO_RENEGOTIATION)
  14206. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14207. #endif
  14208. #if !defined(NO_SSL_DL)
  14209. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14210. #endif /* NO_SSL_DL */
  14211. /* In SSL documentation examples callback defined without const
  14212. * specifier 'void (*)(SSL *, int, int)' See:
  14213. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14214. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14215. * But in the source code const SSL is used:
  14216. * 'void (*)(const SSL *, int, int)' See:
  14217. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14218. * Problem about wrong documentation described, but not resolved:
  14219. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14220. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14221. * But when compiled with modern C++ compiler, correct const should be
  14222. * provided
  14223. */
  14224. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14225. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14226. ssl_servername_callback);
  14227. /* If a callback has been specified, call it. */
  14228. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14229. ? 0
  14230. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14231. phys_ctx->user_data));
  14232. /* If callback returns 0, civetweb sets up the SSL certificate.
  14233. * If it returns 1, civetweb assumes the calback already did this.
  14234. * If it returns -1, initializing ssl fails. */
  14235. if (callback_ret < 0) {
  14236. mg_cry_ctx_internal(phys_ctx,
  14237. "SSL callback returned error: %i",
  14238. callback_ret);
  14239. return 0;
  14240. }
  14241. if (callback_ret > 0) {
  14242. /* Callback did everything. */
  14243. return 1;
  14244. }
  14245. /* If a domain callback has been specified, call it. */
  14246. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14247. ? 0
  14248. : (phys_ctx->callbacks.init_ssl_domain(
  14249. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14250. dom_ctx->ssl_ctx,
  14251. phys_ctx->user_data));
  14252. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14253. * If it returns 1, civetweb assumes the calback already did this.
  14254. * If it returns -1, initializing ssl fails. */
  14255. if (callback_ret < 0) {
  14256. mg_cry_ctx_internal(phys_ctx,
  14257. "Domain SSL callback returned error: %i",
  14258. callback_ret);
  14259. return 0;
  14260. }
  14261. if (callback_ret > 0) {
  14262. /* Domain callback did everything. */
  14263. return 1;
  14264. }
  14265. /* Use some combination of start time, domain and port as a SSL
  14266. * context ID. This should be unique on the current machine. */
  14267. md5_init(&md5state);
  14268. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14269. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14270. md5_append(&md5state,
  14271. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14272. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14273. md5_append(&md5state,
  14274. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14275. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14276. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14277. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14278. md5_finish(&md5state, ssl_context_id);
  14279. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14280. (unsigned char *)ssl_context_id,
  14281. sizeof(ssl_context_id));
  14282. if (pem != NULL) {
  14283. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14284. return 0;
  14285. }
  14286. }
  14287. /* Should we support client certificates? */
  14288. /* Default is "no". */
  14289. should_verify_peer = 0;
  14290. peer_certificate_optional = 0;
  14291. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14292. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14293. /* Yes, they are mandatory */
  14294. should_verify_peer = 1;
  14295. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14296. "optional")
  14297. == 0) {
  14298. /* Yes, they are optional */
  14299. should_verify_peer = 1;
  14300. peer_certificate_optional = 1;
  14301. }
  14302. }
  14303. use_default_verify_paths =
  14304. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14305. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14306. == 0);
  14307. if (should_verify_peer) {
  14308. ca_path = dom_ctx->config[SSL_CA_PATH];
  14309. ca_file = dom_ctx->config[SSL_CA_FILE];
  14310. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14311. != 1) {
  14312. mg_cry_ctx_internal(phys_ctx,
  14313. "SSL_CTX_load_verify_locations error: %s "
  14314. "ssl_verify_peer requires setting "
  14315. "either ssl_ca_path or ssl_ca_file. "
  14316. "Is any of them present in the "
  14317. ".conf file?",
  14318. ssl_error());
  14319. return 0;
  14320. }
  14321. if (peer_certificate_optional) {
  14322. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14323. } else {
  14324. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14325. SSL_VERIFY_PEER
  14326. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14327. NULL);
  14328. }
  14329. if (use_default_verify_paths
  14330. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14331. mg_cry_ctx_internal(phys_ctx,
  14332. "SSL_CTX_set_default_verify_paths error: %s",
  14333. ssl_error());
  14334. return 0;
  14335. }
  14336. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14337. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14338. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14339. }
  14340. }
  14341. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14342. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14343. dom_ctx->config[SSL_CIPHER_LIST])
  14344. != 1) {
  14345. mg_cry_ctx_internal(phys_ctx,
  14346. "SSL_CTX_set_cipher_list error: %s",
  14347. ssl_error());
  14348. }
  14349. }
  14350. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14351. #if !defined(NO_SSL_DL)
  14352. if (!tls_feature_missing[TLS_ALPN])
  14353. #endif
  14354. {
  14355. init_alpn(phys_ctx, dom_ctx);
  14356. }
  14357. return 1;
  14358. }
  14359. /* Check if SSL is required.
  14360. * If so, dynamically load SSL library
  14361. * and set up ctx->ssl_ctx pointer. */
  14362. static int
  14363. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14364. {
  14365. void *ssl_ctx = 0;
  14366. int callback_ret;
  14367. const char *pem;
  14368. const char *chain;
  14369. char ebuf[128];
  14370. if (!phys_ctx) {
  14371. return 0;
  14372. }
  14373. if (!dom_ctx) {
  14374. dom_ctx = &(phys_ctx->dd);
  14375. }
  14376. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14377. /* No SSL port is set. No need to setup SSL. */
  14378. return 1;
  14379. }
  14380. /* Check for external SSL_CTX */
  14381. callback_ret =
  14382. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14383. ? 0
  14384. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14385. phys_ctx->user_data));
  14386. if (callback_ret < 0) {
  14387. mg_cry_ctx_internal(phys_ctx,
  14388. "external_ssl_ctx callback returned error: %i",
  14389. callback_ret);
  14390. return 0;
  14391. } else if (callback_ret > 0) {
  14392. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14393. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14394. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14395. return 0;
  14396. }
  14397. return 1;
  14398. }
  14399. /* Check for external domain SSL_CTX */
  14400. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14401. ? 0
  14402. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14403. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14404. &ssl_ctx,
  14405. phys_ctx->user_data));
  14406. if (callback_ret < 0) {
  14407. mg_cry_ctx_internal(
  14408. phys_ctx,
  14409. "external_ssl_ctx_domain callback returned error: %i",
  14410. callback_ret);
  14411. return 0;
  14412. } else if (callback_ret > 0) {
  14413. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14414. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14415. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14416. return 0;
  14417. }
  14418. return 1;
  14419. }
  14420. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14421. * 0, CivetWeb should continue initializing SSL */
  14422. /* If PEM file is not specified and the init_ssl callbacks
  14423. * are not specified, setup will fail. */
  14424. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14425. && (phys_ctx->callbacks.init_ssl == NULL)
  14426. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14427. /* No certificate and no init_ssl callbacks:
  14428. * Essential data to set up TLS is missing.
  14429. */
  14430. mg_cry_ctx_internal(phys_ctx,
  14431. "Initializing SSL failed: -%s is not set",
  14432. config_options[SSL_CERTIFICATE].name);
  14433. return 0;
  14434. }
  14435. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14436. if (chain == NULL) {
  14437. chain = pem;
  14438. }
  14439. if ((chain != NULL) && (*chain == 0)) {
  14440. chain = NULL;
  14441. }
  14442. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14443. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14444. return 0;
  14445. }
  14446. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14447. }
  14448. static void
  14449. uninitialize_ssl(void)
  14450. {
  14451. #if defined(OPENSSL_API_1_1)
  14452. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14453. /* Shutdown according to
  14454. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14455. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14456. */
  14457. CONF_modules_unload(1);
  14458. #else
  14459. int i;
  14460. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14461. /* Shutdown according to
  14462. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14463. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14464. */
  14465. CRYPTO_set_locking_callback(NULL);
  14466. CRYPTO_set_id_callback(NULL);
  14467. ENGINE_cleanup();
  14468. CONF_modules_unload(1);
  14469. ERR_free_strings();
  14470. EVP_cleanup();
  14471. CRYPTO_cleanup_all_ex_data();
  14472. OPENSSL_REMOVE_THREAD_STATE();
  14473. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14474. pthread_mutex_destroy(&ssl_mutexes[i]);
  14475. }
  14476. mg_free(ssl_mutexes);
  14477. ssl_mutexes = NULL;
  14478. #endif /* OPENSSL_API_1_1 */
  14479. }
  14480. }
  14481. #endif /* !NO_SSL */
  14482. #if !defined(NO_FILESYSTEMS)
  14483. static int
  14484. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14485. {
  14486. if (phys_ctx) {
  14487. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14488. const char *path;
  14489. struct mg_connection fc;
  14490. if (!dom_ctx) {
  14491. dom_ctx = &(phys_ctx->dd);
  14492. }
  14493. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14494. if ((path != NULL)
  14495. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14496. mg_cry_ctx_internal(phys_ctx,
  14497. "Cannot open %s: %s",
  14498. path,
  14499. strerror(ERRNO));
  14500. return 0;
  14501. }
  14502. return 1;
  14503. }
  14504. return 0;
  14505. }
  14506. #endif /* NO_FILESYSTEMS */
  14507. static int
  14508. set_acl_option(struct mg_context *phys_ctx)
  14509. {
  14510. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14511. }
  14512. static void
  14513. reset_per_request_attributes(struct mg_connection *conn)
  14514. {
  14515. if (!conn) {
  14516. return;
  14517. }
  14518. conn->connection_type =
  14519. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14520. conn->num_bytes_sent = conn->consumed_content = 0;
  14521. conn->path_info = NULL;
  14522. conn->status_code = -1;
  14523. conn->content_len = -1;
  14524. conn->is_chunked = 0;
  14525. conn->must_close = 0;
  14526. conn->request_len = 0;
  14527. conn->throttle = 0;
  14528. conn->accept_gzip = 0;
  14529. conn->response_info.content_length = conn->request_info.content_length = -1;
  14530. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14531. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14532. conn->response_info.status_text = NULL;
  14533. conn->response_info.status_code = 0;
  14534. conn->request_info.remote_user = NULL;
  14535. conn->request_info.request_method = NULL;
  14536. conn->request_info.request_uri = NULL;
  14537. conn->request_info.local_uri = NULL;
  14538. #if defined(MG_LEGACY_INTERFACE)
  14539. /* Legacy before split into local_uri and request_uri */
  14540. conn->request_info.uri = NULL;
  14541. #endif
  14542. }
  14543. static int
  14544. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14545. {
  14546. if (setsockopt(sock,
  14547. IPPROTO_TCP,
  14548. TCP_NODELAY,
  14549. (SOCK_OPT_TYPE)&nodelay_on,
  14550. sizeof(nodelay_on))
  14551. != 0) {
  14552. /* Error */
  14553. return 1;
  14554. }
  14555. /* OK */
  14556. return 0;
  14557. }
  14558. #if !defined(__ZEPHYR__)
  14559. static void
  14560. close_socket_gracefully(struct mg_connection *conn)
  14561. {
  14562. #if defined(_WIN32)
  14563. char buf[MG_BUF_LEN];
  14564. int n;
  14565. #endif
  14566. struct linger linger;
  14567. int error_code = 0;
  14568. int linger_timeout = -2;
  14569. socklen_t opt_len = sizeof(error_code);
  14570. if (!conn) {
  14571. return;
  14572. }
  14573. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14574. * "Note that enabling a nonzero timeout on a nonblocking socket
  14575. * is not recommended.", so set it to blocking now */
  14576. set_blocking_mode(conn->client.sock);
  14577. /* Send FIN to the client */
  14578. shutdown(conn->client.sock, SHUTDOWN_WR);
  14579. #if defined(_WIN32)
  14580. /* Read and discard pending incoming data. If we do not do that and
  14581. * close
  14582. * the socket, the data in the send buffer may be discarded. This
  14583. * behaviour is seen on Windows, when client keeps sending data
  14584. * when server decides to close the connection; then when client
  14585. * does recv() it gets no data back. */
  14586. do {
  14587. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14588. } while (n > 0);
  14589. #endif
  14590. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14591. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14592. }
  14593. /* Set linger option according to configuration */
  14594. if (linger_timeout >= 0) {
  14595. /* Set linger option to avoid socket hanging out after close. This
  14596. * prevent ephemeral port exhaust problem under high QPS. */
  14597. linger.l_onoff = 1;
  14598. #if defined(_MSC_VER)
  14599. #pragma warning(push)
  14600. #pragma warning(disable : 4244)
  14601. #endif
  14602. #if defined(GCC_DIAGNOSTIC)
  14603. #pragma GCC diagnostic push
  14604. #pragma GCC diagnostic ignored "-Wconversion"
  14605. #endif
  14606. /* Data type of linger structure elements may differ,
  14607. * so we don't know what cast we need here.
  14608. * Disable type conversion warnings. */
  14609. linger.l_linger = (linger_timeout + 999) / 1000;
  14610. #if defined(GCC_DIAGNOSTIC)
  14611. #pragma GCC diagnostic pop
  14612. #endif
  14613. #if defined(_MSC_VER)
  14614. #pragma warning(pop)
  14615. #endif
  14616. } else {
  14617. linger.l_onoff = 0;
  14618. linger.l_linger = 0;
  14619. }
  14620. if (linger_timeout < -1) {
  14621. /* Default: don't configure any linger */
  14622. } else if (getsockopt(conn->client.sock,
  14623. SOL_SOCKET,
  14624. SO_ERROR,
  14625. #if defined(_WIN32) /* WinSock uses different data type here */
  14626. (char *)&error_code,
  14627. #else
  14628. &error_code,
  14629. #endif
  14630. &opt_len)
  14631. != 0) {
  14632. /* Cannot determine if socket is already closed. This should
  14633. * not occur and never did in a test. Log an error message
  14634. * and continue. */
  14635. mg_cry_internal(conn,
  14636. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14637. __func__,
  14638. strerror(ERRNO));
  14639. #if defined(_WIN32)
  14640. } else if (error_code == WSAECONNRESET) {
  14641. #else
  14642. } else if (error_code == ECONNRESET) {
  14643. #endif
  14644. /* Socket already closed by client/peer, close socket without linger
  14645. */
  14646. } else {
  14647. /* Set linger timeout */
  14648. if (setsockopt(conn->client.sock,
  14649. SOL_SOCKET,
  14650. SO_LINGER,
  14651. (char *)&linger,
  14652. sizeof(linger))
  14653. != 0) {
  14654. mg_cry_internal(
  14655. conn,
  14656. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14657. __func__,
  14658. linger.l_onoff,
  14659. linger.l_linger,
  14660. strerror(ERRNO));
  14661. }
  14662. }
  14663. /* Now we know that our FIN is ACK-ed, safe to close */
  14664. closesocket(conn->client.sock);
  14665. conn->client.sock = INVALID_SOCKET;
  14666. }
  14667. #endif
  14668. static void
  14669. close_connection(struct mg_connection *conn)
  14670. {
  14671. #if defined(USE_SERVER_STATS)
  14672. conn->conn_state = 6; /* to close */
  14673. #endif
  14674. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14675. if (conn->lua_websocket_state) {
  14676. lua_websocket_close(conn, conn->lua_websocket_state);
  14677. conn->lua_websocket_state = NULL;
  14678. }
  14679. #endif
  14680. mg_lock_connection(conn);
  14681. /* Set close flag, so keep-alive loops will stop */
  14682. conn->must_close = 1;
  14683. /* call the connection_close callback if assigned */
  14684. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14685. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14686. conn->phys_ctx->callbacks.connection_close(conn);
  14687. }
  14688. }
  14689. /* Reset user data, after close callback is called.
  14690. * Do not reuse it. If the user needs a destructor,
  14691. * it must be done in the connection_close callback. */
  14692. mg_set_user_connection_data(conn, NULL);
  14693. #if defined(USE_SERVER_STATS)
  14694. conn->conn_state = 7; /* closing */
  14695. #endif
  14696. #if !defined(NO_SSL)
  14697. if (conn->ssl != NULL) {
  14698. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14699. */
  14700. SSL_shutdown(conn->ssl);
  14701. SSL_free(conn->ssl);
  14702. OPENSSL_REMOVE_THREAD_STATE();
  14703. conn->ssl = NULL;
  14704. }
  14705. #endif
  14706. if (conn->client.sock != INVALID_SOCKET) {
  14707. #if defined(__ZEPHYR__)
  14708. closesocket(conn->client.sock);
  14709. #else
  14710. close_socket_gracefully(conn);
  14711. #endif
  14712. conn->client.sock = INVALID_SOCKET;
  14713. }
  14714. if (conn->host) {
  14715. mg_free((void *)conn->host);
  14716. conn->host = NULL;
  14717. }
  14718. mg_unlock_connection(conn);
  14719. #if defined(USE_SERVER_STATS)
  14720. conn->conn_state = 8; /* closed */
  14721. #endif
  14722. }
  14723. void
  14724. mg_close_connection(struct mg_connection *conn)
  14725. {
  14726. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14727. return;
  14728. }
  14729. #if defined(USE_WEBSOCKET)
  14730. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14731. if (conn->in_websocket_handling) {
  14732. /* Set close flag, so the server thread can exit. */
  14733. conn->must_close = 1;
  14734. return;
  14735. }
  14736. }
  14737. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14738. unsigned int i;
  14739. /* client context: loops must end */
  14740. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14741. conn->must_close = 1;
  14742. /* We need to get the client thread out of the select/recv call
  14743. * here. */
  14744. /* Since we use a sleep quantum of some seconds to check for recv
  14745. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14746. /* join worker thread */
  14747. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14748. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14749. }
  14750. }
  14751. #endif /* defined(USE_WEBSOCKET) */
  14752. close_connection(conn);
  14753. #if !defined(NO_SSL)
  14754. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14755. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14756. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14757. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14758. }
  14759. #endif
  14760. #if defined(USE_WEBSOCKET)
  14761. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14762. mg_free(conn->phys_ctx->worker_threadids);
  14763. (void)pthread_mutex_destroy(&conn->mutex);
  14764. mg_free(conn);
  14765. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14766. (void)pthread_mutex_destroy(&conn->mutex);
  14767. mg_free(conn);
  14768. }
  14769. #else
  14770. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14771. (void)pthread_mutex_destroy(&conn->mutex);
  14772. mg_free(conn);
  14773. }
  14774. #endif /* defined(USE_WEBSOCKET) */
  14775. }
  14776. static struct mg_connection *
  14777. mg_connect_client_impl(const struct mg_client_options *client_options,
  14778. int use_ssl,
  14779. char *ebuf,
  14780. size_t ebuf_len)
  14781. {
  14782. struct mg_connection *conn = NULL;
  14783. SOCKET sock;
  14784. union usa sa;
  14785. struct sockaddr *psa;
  14786. socklen_t len;
  14787. unsigned max_req_size =
  14788. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14789. /* Size of structures, aligned to 8 bytes */
  14790. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14791. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14792. conn =
  14793. (struct mg_connection *)mg_calloc(1,
  14794. conn_size + ctx_size + max_req_size);
  14795. if (conn == NULL) {
  14796. mg_snprintf(NULL,
  14797. NULL, /* No truncation check for ebuf */
  14798. ebuf,
  14799. ebuf_len,
  14800. "calloc(): %s",
  14801. strerror(ERRNO));
  14802. return NULL;
  14803. }
  14804. #if defined(GCC_DIAGNOSTIC)
  14805. #pragma GCC diagnostic push
  14806. #pragma GCC diagnostic ignored "-Wcast-align"
  14807. #endif /* defined(GCC_DIAGNOSTIC) */
  14808. /* conn_size is aligned to 8 bytes */
  14809. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14810. #if defined(GCC_DIAGNOSTIC)
  14811. #pragma GCC diagnostic pop
  14812. #endif /* defined(GCC_DIAGNOSTIC) */
  14813. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14814. conn->buf_size = (int)max_req_size;
  14815. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14816. conn->dom_ctx = &(conn->phys_ctx->dd);
  14817. if (!connect_socket(conn->phys_ctx,
  14818. client_options->host,
  14819. client_options->port,
  14820. use_ssl,
  14821. ebuf,
  14822. ebuf_len,
  14823. &sock,
  14824. &sa)) {
  14825. /* ebuf is set by connect_socket,
  14826. * free all memory and return NULL; */
  14827. mg_free(conn);
  14828. return NULL;
  14829. }
  14830. #if !defined(NO_SSL)
  14831. #if defined(OPENSSL_API_1_1)
  14832. if (use_ssl
  14833. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14834. == NULL) {
  14835. mg_snprintf(NULL,
  14836. NULL, /* No truncation check for ebuf */
  14837. ebuf,
  14838. ebuf_len,
  14839. "SSL_CTX_new error: %s",
  14840. ssl_error());
  14841. closesocket(sock);
  14842. mg_free(conn);
  14843. return NULL;
  14844. }
  14845. #else
  14846. if (use_ssl
  14847. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14848. == NULL) {
  14849. mg_snprintf(NULL,
  14850. NULL, /* No truncation check for ebuf */
  14851. ebuf,
  14852. ebuf_len,
  14853. "SSL_CTX_new error: %s",
  14854. ssl_error());
  14855. closesocket(sock);
  14856. mg_free(conn);
  14857. return NULL;
  14858. }
  14859. #endif /* OPENSSL_API_1_1 */
  14860. #endif /* NO_SSL */
  14861. #if defined(USE_IPV6)
  14862. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14863. : sizeof(conn->client.rsa.sin6);
  14864. psa = (sa.sa.sa_family == AF_INET)
  14865. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14866. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14867. #else
  14868. len = sizeof(conn->client.rsa.sin);
  14869. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14870. #endif
  14871. conn->client.sock = sock;
  14872. conn->client.lsa = sa;
  14873. if (getsockname(sock, psa, &len) != 0) {
  14874. mg_cry_internal(conn,
  14875. "%s: getsockname() failed: %s",
  14876. __func__,
  14877. strerror(ERRNO));
  14878. }
  14879. conn->client.is_ssl = use_ssl ? 1 : 0;
  14880. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14881. mg_snprintf(NULL,
  14882. NULL, /* No truncation check for ebuf */
  14883. ebuf,
  14884. ebuf_len,
  14885. "Can not create mutex");
  14886. #if !defined(NO_SSL)
  14887. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14888. #endif
  14889. closesocket(sock);
  14890. mg_free(conn);
  14891. return NULL;
  14892. }
  14893. #if !defined(NO_SSL)
  14894. if (use_ssl) {
  14895. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14896. * SSL_CTX_set_verify call is needed to switch off server
  14897. * certificate checking, which is off by default in OpenSSL and
  14898. * on in yaSSL. */
  14899. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14900. * SSL_VERIFY_PEER, verify_ssl_server); */
  14901. if (client_options->client_cert) {
  14902. if (!ssl_use_pem_file(conn->phys_ctx,
  14903. conn->dom_ctx,
  14904. client_options->client_cert,
  14905. NULL)) {
  14906. mg_snprintf(NULL,
  14907. NULL, /* No truncation check for ebuf */
  14908. ebuf,
  14909. ebuf_len,
  14910. "Can not use SSL client certificate");
  14911. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14912. closesocket(sock);
  14913. mg_free(conn);
  14914. return NULL;
  14915. }
  14916. }
  14917. if (client_options->server_cert) {
  14918. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14919. client_options->server_cert,
  14920. NULL)
  14921. != 1) {
  14922. mg_cry_internal(conn,
  14923. "SSL_CTX_load_verify_locations error: %s ",
  14924. ssl_error());
  14925. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14926. closesocket(sock);
  14927. mg_free(conn);
  14928. return NULL;
  14929. }
  14930. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14931. } else {
  14932. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14933. }
  14934. if (!sslize(conn,
  14935. SSL_connect,
  14936. client_options)) {
  14937. mg_snprintf(NULL,
  14938. NULL, /* No truncation check for ebuf */
  14939. ebuf,
  14940. ebuf_len,
  14941. "SSL connection error");
  14942. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14943. closesocket(sock);
  14944. mg_free(conn);
  14945. return NULL;
  14946. }
  14947. }
  14948. #endif
  14949. return conn;
  14950. }
  14951. CIVETWEB_API struct mg_connection *
  14952. mg_connect_client_secure(const struct mg_client_options *client_options,
  14953. char *error_buffer,
  14954. size_t error_buffer_size)
  14955. {
  14956. return mg_connect_client_impl(client_options,
  14957. 1,
  14958. error_buffer,
  14959. error_buffer_size);
  14960. }
  14961. struct mg_connection *
  14962. mg_connect_client(const char *host,
  14963. int port,
  14964. int use_ssl,
  14965. char *error_buffer,
  14966. size_t error_buffer_size)
  14967. {
  14968. struct mg_client_options opts;
  14969. memset(&opts, 0, sizeof(opts));
  14970. opts.host = host;
  14971. opts.port = port;
  14972. return mg_connect_client_impl(&opts,
  14973. use_ssl,
  14974. error_buffer,
  14975. error_buffer_size);
  14976. }
  14977. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14978. struct mg_connection *
  14979. mg_connect_client2(const char *host,
  14980. const char *protocol,
  14981. int port,
  14982. const char *path,
  14983. struct mg_init_data *init,
  14984. struct mg_error_data *error)
  14985. {
  14986. int is_ssl, is_ws;
  14987. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14988. if (error != NULL) {
  14989. error->code = 0;
  14990. if (error->text_buffer_size > 0) {
  14991. *error->text = 0;
  14992. }
  14993. }
  14994. if ((host == NULL) || (protocol == NULL)) {
  14995. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14996. mg_snprintf(NULL,
  14997. NULL, /* No truncation check for error buffers */
  14998. error->text,
  14999. error->text_buffer_size,
  15000. "%s",
  15001. "Invalid parameters");
  15002. }
  15003. return NULL;
  15004. }
  15005. /* check all known protocolls */
  15006. if (!mg_strcasecmp(protocol, "http")) {
  15007. is_ssl = 0;
  15008. is_ws = 0;
  15009. } else if (!mg_strcasecmp(protocol, "https")) {
  15010. is_ssl = 1;
  15011. is_ws = 0;
  15012. #if defined(USE_WEBSOCKET)
  15013. } else if (!mg_strcasecmp(protocol, "ws")) {
  15014. is_ssl = 0;
  15015. is_ws = 1;
  15016. } else if (!mg_strcasecmp(protocol, "wss")) {
  15017. is_ssl = 1;
  15018. is_ws = 1;
  15019. #endif
  15020. } else {
  15021. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15022. mg_snprintf(NULL,
  15023. NULL, /* No truncation check for error buffers */
  15024. error->text,
  15025. error->text_buffer_size,
  15026. "Protocol %s not supported",
  15027. protocol);
  15028. }
  15029. return NULL;
  15030. }
  15031. /* TODO: The current implementation here just calls the old
  15032. * implementations, without using any new options. This is just a first
  15033. * step to test the new interfaces. */
  15034. #if defined(USE_WEBSOCKET)
  15035. if (is_ws) {
  15036. /* TODO: implement all options */
  15037. return mg_connect_websocket_client(
  15038. host,
  15039. port,
  15040. is_ssl,
  15041. ((error != NULL) ? error->text : NULL),
  15042. ((error != NULL) ? error->text_buffer_size : 0),
  15043. (path ? path : ""),
  15044. NULL /* TODO: origin */,
  15045. deprecated_websocket_data_wrapper,
  15046. deprecated_websocket_close_wrapper,
  15047. (void *)init->callbacks);
  15048. }
  15049. #endif
  15050. /* TODO: all additional options */
  15051. struct mg_client_options opts;
  15052. memset(&opts, 0, sizeof(opts));
  15053. opts.host = host;
  15054. opts.port = port;
  15055. return mg_connect_client_impl(&opts,
  15056. is_ssl,
  15057. ((error != NULL) ? error->text : NULL),
  15058. ((error != NULL) ? error->text_buffer_size
  15059. : 0));
  15060. }
  15061. #endif
  15062. static const struct {
  15063. const char *proto;
  15064. size_t proto_len;
  15065. unsigned default_port;
  15066. } abs_uri_protocols[] = {{"http://", 7, 80},
  15067. {"https://", 8, 443},
  15068. {"ws://", 5, 80},
  15069. {"wss://", 6, 443},
  15070. {NULL, 0, 0}};
  15071. /* Check if the uri is valid.
  15072. * return 0 for invalid uri,
  15073. * return 1 for *,
  15074. * return 2 for relative uri,
  15075. * return 3 for absolute uri without port,
  15076. * return 4 for absolute uri with port */
  15077. static int
  15078. get_uri_type(const char *uri)
  15079. {
  15080. int i;
  15081. const char *hostend, *portbegin;
  15082. char *portend;
  15083. unsigned long port;
  15084. /* According to the HTTP standard
  15085. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15086. * URI can be an asterisk (*) or should start with slash (relative uri),
  15087. * or it should start with the protocol (absolute uri). */
  15088. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15089. /* asterisk */
  15090. return 1;
  15091. }
  15092. /* Valid URIs according to RFC 3986
  15093. * (https://www.ietf.org/rfc/rfc3986.txt)
  15094. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15095. * and unreserved characters A-Z a-z 0-9 and -._~
  15096. * and % encoded symbols.
  15097. */
  15098. for (i = 0; uri[i] != 0; i++) {
  15099. if (uri[i] < 33) {
  15100. /* control characters and spaces are invalid */
  15101. return 0;
  15102. }
  15103. if (uri[i] > 126) {
  15104. /* non-ascii characters must be % encoded */
  15105. return 0;
  15106. } else {
  15107. switch (uri[i]) {
  15108. case '"': /* 34 */
  15109. case '<': /* 60 */
  15110. case '>': /* 62 */
  15111. case '\\': /* 92 */
  15112. case '^': /* 94 */
  15113. case '`': /* 96 */
  15114. case '{': /* 123 */
  15115. case '|': /* 124 */
  15116. case '}': /* 125 */
  15117. return 0;
  15118. default:
  15119. /* character is ok */
  15120. break;
  15121. }
  15122. }
  15123. }
  15124. /* A relative uri starts with a / character */
  15125. if (uri[0] == '/') {
  15126. /* relative uri */
  15127. return 2;
  15128. }
  15129. /* It could be an absolute uri: */
  15130. /* This function only checks if the uri is valid, not if it is
  15131. * addressing the current server. So civetweb can also be used
  15132. * as a proxy server. */
  15133. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15134. if (mg_strncasecmp(uri,
  15135. abs_uri_protocols[i].proto,
  15136. abs_uri_protocols[i].proto_len)
  15137. == 0) {
  15138. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15139. if (!hostend) {
  15140. return 0;
  15141. }
  15142. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15143. if (!portbegin) {
  15144. return 3;
  15145. }
  15146. port = strtoul(portbegin + 1, &portend, 10);
  15147. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15148. return 0;
  15149. }
  15150. return 4;
  15151. }
  15152. }
  15153. return 0;
  15154. }
  15155. /* Return NULL or the relative uri at the current server */
  15156. static const char *
  15157. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15158. {
  15159. const char *server_domain;
  15160. size_t server_domain_len;
  15161. size_t request_domain_len = 0;
  15162. unsigned long port = 0;
  15163. int i, auth_domain_check_enabled;
  15164. const char *hostbegin = NULL;
  15165. const char *hostend = NULL;
  15166. const char *portbegin;
  15167. char *portend;
  15168. auth_domain_check_enabled =
  15169. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15170. /* DNS is case insensitive, so use case insensitive string compare here
  15171. */
  15172. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15173. if (mg_strncasecmp(uri,
  15174. abs_uri_protocols[i].proto,
  15175. abs_uri_protocols[i].proto_len)
  15176. == 0) {
  15177. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15178. hostend = strchr(hostbegin, '/');
  15179. if (!hostend) {
  15180. return 0;
  15181. }
  15182. portbegin = strchr(hostbegin, ':');
  15183. if ((!portbegin) || (portbegin > hostend)) {
  15184. port = abs_uri_protocols[i].default_port;
  15185. request_domain_len = (size_t)(hostend - hostbegin);
  15186. } else {
  15187. port = strtoul(portbegin + 1, &portend, 10);
  15188. if ((portend != hostend) || (port <= 0)
  15189. || !is_valid_port(port)) {
  15190. return 0;
  15191. }
  15192. request_domain_len = (size_t)(portbegin - hostbegin);
  15193. }
  15194. /* protocol found, port set */
  15195. break;
  15196. }
  15197. }
  15198. if (!port) {
  15199. /* port remains 0 if the protocol is not found */
  15200. return 0;
  15201. }
  15202. /* Check if the request is directed to a different server. */
  15203. /* First check if the port is the same (IPv4 and IPv6). */
  15204. #if defined(USE_IPV6)
  15205. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15206. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15207. /* Request is directed to a different port */
  15208. return 0;
  15209. }
  15210. } else
  15211. #endif
  15212. {
  15213. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15214. /* Request is directed to a different port */
  15215. return 0;
  15216. }
  15217. }
  15218. /* Finally check if the server corresponds to the authentication
  15219. * domain of the server (the server domain).
  15220. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15221. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15222. * but do not allow substrings (like
  15223. * http://notmydomain.com/path/file.ext
  15224. * or http://mydomain.com.fake/path/file.ext).
  15225. */
  15226. if (auth_domain_check_enabled) {
  15227. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15228. server_domain_len = strlen(server_domain);
  15229. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15230. return 0;
  15231. }
  15232. if ((request_domain_len == server_domain_len)
  15233. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15234. /* Request is directed to this server - full name match. */
  15235. } else {
  15236. if (request_domain_len < (server_domain_len + 2)) {
  15237. /* Request is directed to another server: The server name
  15238. * is longer than the request name.
  15239. * Drop this case here to avoid overflows in the
  15240. * following checks. */
  15241. return 0;
  15242. }
  15243. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15244. /* Request is directed to another server: It could be a
  15245. * substring
  15246. * like notmyserver.com */
  15247. return 0;
  15248. }
  15249. if (0
  15250. != memcmp(server_domain,
  15251. hostbegin + request_domain_len - server_domain_len,
  15252. server_domain_len)) {
  15253. /* Request is directed to another server:
  15254. * The server name is different. */
  15255. return 0;
  15256. }
  15257. }
  15258. }
  15259. return hostend;
  15260. }
  15261. static int
  15262. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15263. {
  15264. if (ebuf_len > 0) {
  15265. ebuf[0] = '\0';
  15266. }
  15267. *err = 0;
  15268. reset_per_request_attributes(conn);
  15269. if (!conn) {
  15270. mg_snprintf(conn,
  15271. NULL, /* No truncation check for ebuf */
  15272. ebuf,
  15273. ebuf_len,
  15274. "%s",
  15275. "Internal error");
  15276. *err = 500;
  15277. return 0;
  15278. }
  15279. /* Set the time the request was received. This value should be used for
  15280. * timeouts. */
  15281. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15282. conn->request_len =
  15283. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15284. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15285. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15286. mg_snprintf(conn,
  15287. NULL, /* No truncation check for ebuf */
  15288. ebuf,
  15289. ebuf_len,
  15290. "%s",
  15291. "Invalid message size");
  15292. *err = 500;
  15293. return 0;
  15294. }
  15295. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15296. mg_snprintf(conn,
  15297. NULL, /* No truncation check for ebuf */
  15298. ebuf,
  15299. ebuf_len,
  15300. "%s",
  15301. "Message too large");
  15302. *err = 413;
  15303. return 0;
  15304. }
  15305. if (conn->request_len <= 0) {
  15306. if (conn->data_len > 0) {
  15307. mg_snprintf(conn,
  15308. NULL, /* No truncation check for ebuf */
  15309. ebuf,
  15310. ebuf_len,
  15311. "%s",
  15312. "Malformed message");
  15313. *err = 400;
  15314. } else {
  15315. /* Server did not recv anything -> just close the connection */
  15316. conn->must_close = 1;
  15317. mg_snprintf(conn,
  15318. NULL, /* No truncation check for ebuf */
  15319. ebuf,
  15320. ebuf_len,
  15321. "%s",
  15322. "No data received");
  15323. *err = 0;
  15324. }
  15325. return 0;
  15326. }
  15327. return 1;
  15328. }
  15329. static int
  15330. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15331. {
  15332. const char *cl;
  15333. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15334. return 0;
  15335. }
  15336. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15337. <= 0) {
  15338. mg_snprintf(conn,
  15339. NULL, /* No truncation check for ebuf */
  15340. ebuf,
  15341. ebuf_len,
  15342. "%s",
  15343. "Bad request");
  15344. *err = 400;
  15345. return 0;
  15346. }
  15347. /* Message is a valid request */
  15348. /* Is there a "host" ? */
  15349. if (conn->host != NULL) {
  15350. mg_free((void *)conn->host);
  15351. }
  15352. conn->host = alloc_get_host(conn);
  15353. if (!conn->host) {
  15354. mg_snprintf(conn,
  15355. NULL, /* No truncation check for ebuf */
  15356. ebuf,
  15357. ebuf_len,
  15358. "%s",
  15359. "Bad request: Host mismatch");
  15360. *err = 400;
  15361. return 0;
  15362. }
  15363. if (((cl = get_header(conn->request_info.http_headers,
  15364. conn->request_info.num_headers,
  15365. "Transfer-Encoding"))
  15366. != NULL)
  15367. && mg_strcasecmp(cl, "identity")) {
  15368. if (mg_strcasecmp(cl, "chunked")) {
  15369. mg_snprintf(conn,
  15370. NULL, /* No truncation check for ebuf */
  15371. ebuf,
  15372. ebuf_len,
  15373. "%s",
  15374. "Bad request");
  15375. *err = 400;
  15376. return 0;
  15377. }
  15378. conn->is_chunked = 1;
  15379. conn->content_len = 0; /* not yet read */
  15380. } else if ((cl = get_header(conn->request_info.http_headers,
  15381. conn->request_info.num_headers,
  15382. "Content-Length"))
  15383. != NULL) {
  15384. /* Request has content length set */
  15385. char *endptr = NULL;
  15386. conn->content_len = strtoll(cl, &endptr, 10);
  15387. if ((endptr == cl) || (conn->content_len < 0)) {
  15388. mg_snprintf(conn,
  15389. NULL, /* No truncation check for ebuf */
  15390. ebuf,
  15391. ebuf_len,
  15392. "%s",
  15393. "Bad request");
  15394. *err = 411;
  15395. return 0;
  15396. }
  15397. /* Publish the content length back to the request info. */
  15398. conn->request_info.content_length = conn->content_len;
  15399. } else {
  15400. /* There is no exception, see RFC7230. */
  15401. conn->content_len = 0;
  15402. }
  15403. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15404. return 1;
  15405. }
  15406. /* conn is assumed to be valid in this internal function */
  15407. static int
  15408. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15409. {
  15410. const char *cl;
  15411. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15412. return 0;
  15413. }
  15414. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15415. <= 0) {
  15416. mg_snprintf(conn,
  15417. NULL, /* No truncation check for ebuf */
  15418. ebuf,
  15419. ebuf_len,
  15420. "%s",
  15421. "Bad response");
  15422. *err = 400;
  15423. return 0;
  15424. }
  15425. /* Message is a valid response */
  15426. if (((cl = get_header(conn->response_info.http_headers,
  15427. conn->response_info.num_headers,
  15428. "Transfer-Encoding"))
  15429. != NULL)
  15430. && mg_strcasecmp(cl, "identity")) {
  15431. if (mg_strcasecmp(cl, "chunked")) {
  15432. mg_snprintf(conn,
  15433. NULL, /* No truncation check for ebuf */
  15434. ebuf,
  15435. ebuf_len,
  15436. "%s",
  15437. "Bad request");
  15438. *err = 400;
  15439. return 0;
  15440. }
  15441. conn->is_chunked = 1;
  15442. conn->content_len = 0; /* not yet read */
  15443. } else if ((cl = get_header(conn->response_info.http_headers,
  15444. conn->response_info.num_headers,
  15445. "Content-Length"))
  15446. != NULL) {
  15447. char *endptr = NULL;
  15448. conn->content_len = strtoll(cl, &endptr, 10);
  15449. if ((endptr == cl) || (conn->content_len < 0)) {
  15450. mg_snprintf(conn,
  15451. NULL, /* No truncation check for ebuf */
  15452. ebuf,
  15453. ebuf_len,
  15454. "%s",
  15455. "Bad request");
  15456. *err = 411;
  15457. return 0;
  15458. }
  15459. /* Publish the content length back to the response info. */
  15460. conn->response_info.content_length = conn->content_len;
  15461. /* TODO: check if it is still used in response_info */
  15462. conn->request_info.content_length = conn->content_len;
  15463. /* TODO: we should also consider HEAD method */
  15464. if (conn->response_info.status_code == 304) {
  15465. conn->content_len = 0;
  15466. }
  15467. } else {
  15468. /* TODO: we should also consider HEAD method */
  15469. if (((conn->response_info.status_code >= 100)
  15470. && (conn->response_info.status_code <= 199))
  15471. || (conn->response_info.status_code == 204)
  15472. || (conn->response_info.status_code == 304)) {
  15473. conn->content_len = 0;
  15474. } else {
  15475. conn->content_len = -1; /* unknown content length */
  15476. }
  15477. }
  15478. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15479. return 1;
  15480. }
  15481. int
  15482. mg_get_response(struct mg_connection *conn,
  15483. char *ebuf,
  15484. size_t ebuf_len,
  15485. int timeout)
  15486. {
  15487. int err, ret;
  15488. char txt[32]; /* will not overflow */
  15489. char *save_timeout;
  15490. char *new_timeout;
  15491. if (ebuf_len > 0) {
  15492. ebuf[0] = '\0';
  15493. }
  15494. if (!conn) {
  15495. mg_snprintf(conn,
  15496. NULL, /* No truncation check for ebuf */
  15497. ebuf,
  15498. ebuf_len,
  15499. "%s",
  15500. "Parameter error");
  15501. return -1;
  15502. }
  15503. /* Reset the previous responses */
  15504. conn->data_len = 0;
  15505. /* Implementation of API function for HTTP clients */
  15506. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15507. if (timeout >= 0) {
  15508. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15509. new_timeout = txt;
  15510. } else {
  15511. new_timeout = NULL;
  15512. }
  15513. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15514. ret = get_response(conn, ebuf, ebuf_len, &err);
  15515. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15516. #if defined(MG_LEGACY_INTERFACE)
  15517. /* TODO: 1) uri is deprecated;
  15518. * 2) here, ri.uri is the http response code */
  15519. conn->request_info.uri = conn->request_info.request_uri;
  15520. #endif
  15521. conn->request_info.local_uri = conn->request_info.request_uri;
  15522. /* TODO (mid): Define proper return values - maybe return length?
  15523. * For the first test use <0 for error and >0 for OK */
  15524. return (ret == 0) ? -1 : +1;
  15525. }
  15526. struct mg_connection *
  15527. mg_download(const char *host,
  15528. int port,
  15529. int use_ssl,
  15530. char *ebuf,
  15531. size_t ebuf_len,
  15532. const char *fmt,
  15533. ...)
  15534. {
  15535. struct mg_connection *conn;
  15536. va_list ap;
  15537. int i;
  15538. int reqerr;
  15539. if (ebuf_len > 0) {
  15540. ebuf[0] = '\0';
  15541. }
  15542. va_start(ap, fmt);
  15543. /* open a connection */
  15544. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15545. if (conn != NULL) {
  15546. i = mg_vprintf(conn, fmt, ap);
  15547. if (i <= 0) {
  15548. mg_snprintf(conn,
  15549. NULL, /* No truncation check for ebuf */
  15550. ebuf,
  15551. ebuf_len,
  15552. "%s",
  15553. "Error sending request");
  15554. } else {
  15555. /* make sure the buffer is clear */
  15556. conn->data_len = 0;
  15557. get_response(conn, ebuf, ebuf_len, &reqerr);
  15558. #if defined(MG_LEGACY_INTERFACE)
  15559. /* TODO: 1) uri is deprecated;
  15560. * 2) here, ri.uri is the http response code */
  15561. conn->request_info.uri = conn->request_info.request_uri;
  15562. #endif
  15563. conn->request_info.local_uri = conn->request_info.request_uri;
  15564. }
  15565. }
  15566. /* if an error occurred, close the connection */
  15567. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15568. mg_close_connection(conn);
  15569. conn = NULL;
  15570. }
  15571. va_end(ap);
  15572. return conn;
  15573. }
  15574. struct websocket_client_thread_data {
  15575. struct mg_connection *conn;
  15576. mg_websocket_data_handler data_handler;
  15577. mg_websocket_close_handler close_handler;
  15578. void *callback_data;
  15579. };
  15580. #if defined(USE_WEBSOCKET)
  15581. #if defined(_WIN32)
  15582. static unsigned __stdcall websocket_client_thread(void *data)
  15583. #else
  15584. static void *
  15585. websocket_client_thread(void *data)
  15586. #endif
  15587. {
  15588. struct websocket_client_thread_data *cdata =
  15589. (struct websocket_client_thread_data *)data;
  15590. void *user_thread_ptr = NULL;
  15591. #if !defined(_WIN32)
  15592. struct sigaction sa;
  15593. /* Ignore SIGPIPE */
  15594. memset(&sa, 0, sizeof(sa));
  15595. sa.sa_handler = SIG_IGN;
  15596. sigaction(SIGPIPE, &sa, NULL);
  15597. #endif
  15598. mg_set_thread_name("ws-clnt");
  15599. if (cdata->conn->phys_ctx) {
  15600. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15601. /* 3 indicates a websocket client thread */
  15602. /* TODO: check if conn->phys_ctx can be set */
  15603. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15604. cdata->conn->phys_ctx, 3);
  15605. }
  15606. }
  15607. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15608. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15609. if (cdata->close_handler != NULL) {
  15610. cdata->close_handler(cdata->conn, cdata->callback_data);
  15611. }
  15612. /* The websocket_client context has only this thread. If it runs out,
  15613. set the stop_flag to 2 (= "stopped"). */
  15614. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15615. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15616. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15617. 3,
  15618. user_thread_ptr);
  15619. }
  15620. mg_free((void *)cdata);
  15621. #if defined(_WIN32)
  15622. return 0;
  15623. #else
  15624. return NULL;
  15625. #endif
  15626. }
  15627. #endif
  15628. static struct mg_connection *
  15629. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15630. int use_ssl,
  15631. char *error_buffer,
  15632. size_t error_buffer_size,
  15633. const char *path,
  15634. const char *origin,
  15635. mg_websocket_data_handler data_func,
  15636. mg_websocket_close_handler close_func,
  15637. void *user_data)
  15638. {
  15639. struct mg_connection *conn = NULL;
  15640. #if defined(USE_WEBSOCKET)
  15641. struct websocket_client_thread_data *thread_data;
  15642. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15643. const char *handshake_req;
  15644. int port = client_options->port;
  15645. const char *host = client_options->host;
  15646. int i;
  15647. if (origin != NULL) {
  15648. handshake_req = "GET %s HTTP/1.1\r\n"
  15649. "Host: %s\r\n"
  15650. "Upgrade: websocket\r\n"
  15651. "Connection: Upgrade\r\n"
  15652. "Sec-WebSocket-Key: %s\r\n"
  15653. "Sec-WebSocket-Version: 13\r\n"
  15654. "Origin: %s\r\n"
  15655. "\r\n";
  15656. } else {
  15657. handshake_req = "GET %s HTTP/1.1\r\n"
  15658. "Host: %s\r\n"
  15659. "Upgrade: websocket\r\n"
  15660. "Connection: Upgrade\r\n"
  15661. "Sec-WebSocket-Key: %s\r\n"
  15662. "Sec-WebSocket-Version: 13\r\n"
  15663. "\r\n";
  15664. }
  15665. #if defined(__clang__)
  15666. #pragma clang diagnostic push
  15667. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15668. #endif
  15669. /* Establish the client connection and request upgrade */
  15670. conn =
  15671. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15672. if (conn == NULL) {
  15673. /* error_buffer already filled */
  15674. return NULL;
  15675. }
  15676. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15677. if (i <= 0) {
  15678. mg_snprintf(conn,
  15679. NULL, /* No truncation check for ebuf */
  15680. error_buffer,
  15681. error_buffer_size,
  15682. "%s",
  15683. "Error sending request");
  15684. mg_close_connection(conn);
  15685. return NULL;
  15686. }
  15687. conn->data_len = 0;
  15688. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15689. mg_close_connection(conn);
  15690. return NULL;
  15691. }
  15692. conn->request_info.local_uri = conn->request_info.request_uri;
  15693. #if defined(__clang__)
  15694. #pragma clang diagnostic pop
  15695. #endif
  15696. /* Connection object will be null if something goes wrong */
  15697. if (conn == NULL) {
  15698. if (!*error_buffer) {
  15699. /* There should be already an error message */
  15700. mg_snprintf(conn,
  15701. NULL, /* No truncation check for ebuf */
  15702. error_buffer,
  15703. error_buffer_size,
  15704. "Unexpected error");
  15705. }
  15706. return NULL;
  15707. }
  15708. if (conn->response_info.status_code != 101) {
  15709. /* We sent an "upgrade" request. For a correct websocket
  15710. * protocol handshake, we expect a "101 Continue" response.
  15711. * Otherwise it is a protocol violation. Maybe the HTTP
  15712. * Server does not know websockets. */
  15713. if (!*error_buffer) {
  15714. /* set an error, if not yet set */
  15715. mg_snprintf(conn,
  15716. NULL, /* No truncation check for ebuf */
  15717. error_buffer,
  15718. error_buffer_size,
  15719. "Unexpected server reply");
  15720. }
  15721. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15722. mg_close_connection(conn);
  15723. return NULL;
  15724. }
  15725. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15726. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15727. if (!thread_data) {
  15728. DEBUG_TRACE("%s\r\n", "Out of memory");
  15729. mg_close_connection(conn);
  15730. return NULL;
  15731. }
  15732. thread_data->conn = conn;
  15733. thread_data->data_handler = data_func;
  15734. thread_data->close_handler = close_func;
  15735. thread_data->callback_data = user_data;
  15736. conn->phys_ctx->worker_threadids =
  15737. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15738. if (!conn->phys_ctx->worker_threadids) {
  15739. DEBUG_TRACE("%s\r\n", "Out of memory");
  15740. mg_free(thread_data);
  15741. mg_close_connection(conn);
  15742. return NULL;
  15743. }
  15744. /* Now upgrade to ws/wss client context */
  15745. conn->phys_ctx->user_data = user_data;
  15746. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15747. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15748. /* Start a thread to read the websocket client connection
  15749. * This thread will automatically stop when mg_disconnect is
  15750. * called on the client connection */
  15751. if (mg_start_thread_with_id(websocket_client_thread,
  15752. thread_data,
  15753. conn->phys_ctx->worker_threadids)
  15754. != 0) {
  15755. conn->phys_ctx->cfg_worker_threads = 0;
  15756. mg_free(thread_data);
  15757. mg_close_connection(conn);
  15758. conn = NULL;
  15759. DEBUG_TRACE("%s",
  15760. "Websocket client connect thread could not be started\r\n");
  15761. }
  15762. #else
  15763. /* Appease "unused parameter" warnings */
  15764. (void)client_options;
  15765. (void)use_ssl;
  15766. (void)error_buffer;
  15767. (void)error_buffer_size;
  15768. (void)path;
  15769. (void)origin;
  15770. (void)user_data;
  15771. (void)data_func;
  15772. (void)close_func;
  15773. #endif
  15774. return conn;
  15775. }
  15776. struct mg_connection *
  15777. mg_connect_websocket_client(const char *host,
  15778. int port,
  15779. int use_ssl,
  15780. char *error_buffer,
  15781. size_t error_buffer_size,
  15782. const char *path,
  15783. const char *origin,
  15784. mg_websocket_data_handler data_func,
  15785. mg_websocket_close_handler close_func,
  15786. void *user_data)
  15787. {
  15788. struct mg_client_options client_options;
  15789. memset(&client_options, 0, sizeof(client_options));
  15790. client_options.host = host;
  15791. client_options.port = port;
  15792. return mg_connect_websocket_client_impl(&client_options,
  15793. use_ssl,
  15794. error_buffer,
  15795. error_buffer_size,
  15796. path,
  15797. origin,
  15798. data_func,
  15799. close_func,
  15800. user_data);
  15801. }
  15802. struct mg_connection *
  15803. mg_connect_websocket_client_secure(
  15804. const struct mg_client_options *client_options,
  15805. char *error_buffer,
  15806. size_t error_buffer_size,
  15807. const char *path,
  15808. const char *origin,
  15809. mg_websocket_data_handler data_func,
  15810. mg_websocket_close_handler close_func,
  15811. void *user_data)
  15812. {
  15813. if (!client_options) {
  15814. return NULL;
  15815. }
  15816. return mg_connect_websocket_client_impl(client_options,
  15817. 1,
  15818. error_buffer,
  15819. error_buffer_size,
  15820. path,
  15821. origin,
  15822. data_func,
  15823. close_func,
  15824. user_data);
  15825. }
  15826. /* Prepare connection data structure */
  15827. static void
  15828. init_connection(struct mg_connection *conn)
  15829. {
  15830. /* Is keep alive allowed by the server */
  15831. int keep_alive_enabled =
  15832. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15833. if (!keep_alive_enabled) {
  15834. conn->must_close = 1;
  15835. }
  15836. /* Important: on new connection, reset the receiving buffer. Credit
  15837. * goes to crule42. */
  15838. conn->data_len = 0;
  15839. conn->handled_requests = 0;
  15840. mg_set_user_connection_data(conn, NULL);
  15841. #if defined(USE_SERVER_STATS)
  15842. conn->conn_state = 2; /* init */
  15843. #endif
  15844. /* call the init_connection callback if assigned */
  15845. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15846. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15847. void *conn_data = NULL;
  15848. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15849. mg_set_user_connection_data(conn, conn_data);
  15850. }
  15851. }
  15852. }
  15853. /* Process a connection - may handle multiple requests
  15854. * using the same connection.
  15855. * Must be called with a valid connection (conn and
  15856. * conn->phys_ctx must be valid).
  15857. */
  15858. static void
  15859. process_new_connection(struct mg_connection *conn)
  15860. {
  15861. struct mg_request_info *ri = &conn->request_info;
  15862. int keep_alive, discard_len;
  15863. char ebuf[100];
  15864. const char *hostend;
  15865. int reqerr, uri_type;
  15866. #if defined(USE_SERVER_STATS)
  15867. (void)pthread_mutex_lock(&global_stats_mutex);
  15868. conn->phys_ctx->total_connections++;
  15869. if ((++conn->phys_ctx->active_connections)
  15870. > (conn->phys_ctx->max_active_connections)) {
  15871. conn->phys_ctx->max_active_connections =
  15872. conn->phys_ctx->active_connections;
  15873. }
  15874. (void)pthread_mutex_unlock(&global_stats_mutex);
  15875. #endif
  15876. init_connection(conn);
  15877. DEBUG_TRACE("Start processing connection from %s",
  15878. conn->request_info.remote_addr);
  15879. /* Loop over multiple requests sent using the same connection
  15880. * (while "keep alive"). */
  15881. do {
  15882. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15883. conn->handled_requests + 1);
  15884. #if defined(USE_SERVER_STATS)
  15885. conn->conn_state = 3; /* ready */
  15886. #endif
  15887. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15888. /* The request sent by the client could not be understood by
  15889. * the server, or it was incomplete or a timeout. Send an
  15890. * error message and close the connection. */
  15891. if (reqerr > 0) {
  15892. DEBUG_ASSERT(ebuf[0] != '\0');
  15893. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15894. }
  15895. } else if (strcmp(ri->http_version, "1.0")
  15896. && strcmp(ri->http_version, "1.1")) {
  15897. /* HTTP/2 is not allowed here */
  15898. mg_snprintf(conn,
  15899. NULL, /* No truncation check for ebuf */
  15900. ebuf,
  15901. sizeof(ebuf),
  15902. "Bad HTTP version: [%s]",
  15903. ri->http_version);
  15904. mg_send_http_error(conn, 505, "%s", ebuf);
  15905. }
  15906. if (ebuf[0] == '\0') {
  15907. uri_type = get_uri_type(conn->request_info.request_uri);
  15908. switch (uri_type) {
  15909. case 1:
  15910. /* Asterisk */
  15911. conn->request_info.local_uri = 0;
  15912. /* TODO: Deal with '*'. */
  15913. break;
  15914. case 2:
  15915. /* relative uri */
  15916. conn->request_info.local_uri = conn->request_info.request_uri;
  15917. break;
  15918. case 3:
  15919. case 4:
  15920. /* absolute uri (with/without port) */
  15921. hostend = get_rel_url_at_current_server(
  15922. conn->request_info.request_uri, conn);
  15923. if (hostend) {
  15924. conn->request_info.local_uri = hostend;
  15925. } else {
  15926. conn->request_info.local_uri = NULL;
  15927. }
  15928. break;
  15929. default:
  15930. mg_snprintf(conn,
  15931. NULL, /* No truncation check for ebuf */
  15932. ebuf,
  15933. sizeof(ebuf),
  15934. "Invalid URI");
  15935. mg_send_http_error(conn, 400, "%s", ebuf);
  15936. conn->request_info.local_uri = NULL;
  15937. break;
  15938. }
  15939. #if defined(MG_LEGACY_INTERFACE)
  15940. /* Legacy before split into local_uri and request_uri */
  15941. conn->request_info.uri = conn->request_info.local_uri;
  15942. #endif
  15943. }
  15944. if (ebuf[0] != '\0') {
  15945. conn->protocol_type = -1;
  15946. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15947. /* HTTP/1 allows protocol upgrade */
  15948. conn->protocol_type = should_switch_to_protocol(conn);
  15949. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15950. /* This will occur, if a HTTP/1.1 request should be upgraded
  15951. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15952. * Since most (all?) major browsers only support HTTP/2 using
  15953. * ALPN, this is hard to test and very low priority.
  15954. * Deactivate it (at least for now).
  15955. */
  15956. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15957. }
  15958. }
  15959. DEBUG_TRACE("http: %s, error: %s",
  15960. (ri->http_version ? ri->http_version : "none"),
  15961. (ebuf[0] ? ebuf : "none"));
  15962. if (ebuf[0] == '\0') {
  15963. if (conn->request_info.local_uri) {
  15964. /* handle request to local server */
  15965. #if defined(USE_SERVER_STATS)
  15966. conn->conn_state = 4; /* processing */
  15967. #endif
  15968. handle_request(conn);
  15969. #if defined(USE_SERVER_STATS)
  15970. conn->conn_state = 5; /* processed */
  15971. (void)pthread_mutex_lock(&global_stats_mutex);
  15972. conn->phys_ctx->total_data_read += conn->consumed_content;
  15973. conn->phys_ctx->total_data_written += conn->num_bytes_sent;
  15974. (void)pthread_mutex_unlock(&global_stats_mutex);
  15975. #endif
  15976. DEBUG_TRACE("%s", "handle_request done");
  15977. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15978. conn->phys_ctx->callbacks.end_request(conn,
  15979. conn->status_code);
  15980. DEBUG_TRACE("%s", "end_request callback done");
  15981. }
  15982. log_access(conn);
  15983. } else {
  15984. /* TODO: handle non-local request (PROXY) */
  15985. conn->must_close = 1;
  15986. }
  15987. } else {
  15988. conn->must_close = 1;
  15989. }
  15990. if (ri->remote_user != NULL) {
  15991. mg_free((void *)ri->remote_user);
  15992. /* Important! When having connections with and without auth
  15993. * would cause double free and then crash */
  15994. ri->remote_user = NULL;
  15995. }
  15996. /* NOTE(lsm): order is important here. should_keep_alive() call
  15997. * is using parsed request, which will be invalid after
  15998. * memmove's below.
  15999. * Therefore, memorize should_keep_alive() result now for later
  16000. * use in loop exit condition. */
  16001. /* Enable it only if this request is completely discardable. */
  16002. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16003. && should_keep_alive(conn) && (conn->content_len >= 0)
  16004. && (conn->request_len > 0)
  16005. && ((conn->is_chunked == 4)
  16006. || (!conn->is_chunked
  16007. && ((conn->consumed_content == conn->content_len)
  16008. || ((conn->request_len + conn->content_len)
  16009. <= conn->data_len))))
  16010. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16011. if (keep_alive) {
  16012. /* Discard all buffered data for this request */
  16013. discard_len =
  16014. ((conn->request_len + conn->content_len) < conn->data_len)
  16015. ? (int)(conn->request_len + conn->content_len)
  16016. : conn->data_len;
  16017. conn->data_len -= discard_len;
  16018. if (conn->data_len > 0) {
  16019. DEBUG_TRACE("discard_len = %d", discard_len);
  16020. memmove(conn->buf,
  16021. conn->buf + discard_len,
  16022. (size_t)conn->data_len);
  16023. }
  16024. }
  16025. DEBUG_ASSERT(conn->data_len >= 0);
  16026. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16027. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16028. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16029. (long int)conn->data_len,
  16030. (long int)conn->buf_size);
  16031. break;
  16032. }
  16033. conn->handled_requests++;
  16034. } while (keep_alive);
  16035. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16036. conn->request_info.remote_addr,
  16037. difftime(time(NULL), conn->conn_birth_time));
  16038. close_connection(conn);
  16039. #if defined(USE_SERVER_STATS)
  16040. (void)pthread_mutex_lock(&global_stats_mutex);
  16041. conn->phys_ctx->total_requests += conn->handled_requests;
  16042. conn->phys_ctx->active_connections--;
  16043. (void)pthread_mutex_unlock(&global_stats_mutex);
  16044. #endif
  16045. }
  16046. #if defined(ALTERNATIVE_QUEUE)
  16047. static void
  16048. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16049. {
  16050. unsigned int i;
  16051. while (!ctx->stop_flag) {
  16052. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16053. /* find a free worker slot and signal it */
  16054. if (ctx->client_socks[i].in_use == 2) {
  16055. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16056. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16057. ctx->client_socks[i] = *sp;
  16058. ctx->client_socks[i].in_use = 1;
  16059. /* socket has been moved to the consumer */
  16060. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16061. (void)event_signal(ctx->client_wait_events[i]);
  16062. return;
  16063. }
  16064. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16065. }
  16066. }
  16067. /* queue is full */
  16068. mg_sleep(1);
  16069. }
  16070. /* must consume */
  16071. set_blocking_mode(sp->sock);
  16072. closesocket(sp->sock);
  16073. }
  16074. static int
  16075. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16076. {
  16077. DEBUG_TRACE("%s", "going idle");
  16078. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16079. ctx->client_socks[thread_index].in_use = 2;
  16080. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16081. event_wait(ctx->client_wait_events[thread_index]);
  16082. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16083. *sp = ctx->client_socks[thread_index];
  16084. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16085. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16086. if (sp->in_use == 1) {
  16087. /* must consume */
  16088. set_blocking_mode(sp->sock);
  16089. closesocket(sp->sock);
  16090. }
  16091. return 0;
  16092. }
  16093. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16094. if (sp->in_use == 1) {
  16095. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16096. return 1;
  16097. }
  16098. /* must not reach here */
  16099. DEBUG_ASSERT(0);
  16100. return 0;
  16101. }
  16102. #else /* ALTERNATIVE_QUEUE */
  16103. /* Worker threads take accepted socket from the queue */
  16104. static int
  16105. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16106. {
  16107. (void)thread_index;
  16108. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16109. DEBUG_TRACE("%s", "going idle");
  16110. /* If the queue is empty, wait. We're idle at this point. */
  16111. while ((ctx->sq_head == ctx->sq_tail)
  16112. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16113. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16114. }
  16115. /* If we're stopping, sq_head may be equal to sq_tail. */
  16116. if (ctx->sq_head > ctx->sq_tail) {
  16117. /* Copy socket from the queue and increment tail */
  16118. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16119. ctx->sq_tail++;
  16120. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16121. /* Wrap pointers if needed */
  16122. while (ctx->sq_tail > ctx->sq_size) {
  16123. ctx->sq_tail -= ctx->sq_size;
  16124. ctx->sq_head -= ctx->sq_size;
  16125. }
  16126. #if defined(USE_SERVER_STATS)
  16127. (void)pthread_mutex_lock(&global_stats_mutex);
  16128. ctx->sq_filled = ctx->sq_head - ctx->sq_tail;
  16129. (void)pthread_mutex_unlock(&global_stats_mutex);
  16130. #endif
  16131. }
  16132. (void)pthread_cond_signal(&ctx->sq_empty);
  16133. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16134. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16135. }
  16136. /* Master thread adds accepted socket to a queue */
  16137. static void
  16138. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16139. {
  16140. int queue_filled;
  16141. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16142. queue_filled = ctx->sq_head - ctx->sq_tail;
  16143. /* If the queue is full, wait */
  16144. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16145. && (queue_filled >= ctx->sq_size)) {
  16146. #if defined(USE_SERVER_STATS)
  16147. (void)pthread_mutex_lock(&global_stats_mutex);
  16148. ctx->sq_blocked = 1; /* All threads busy */
  16149. (void)pthread_mutex_unlock(&global_stats_mutex);
  16150. #endif
  16151. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16152. #if defined(USE_SERVER_STATS)
  16153. (void)pthread_mutex_lock(&global_stats_mutex);
  16154. ctx->sq_blocked = 0; /* Not blocked now */
  16155. (void)pthread_mutex_unlock(&global_stats_mutex);
  16156. #endif
  16157. queue_filled = ctx->sq_head - ctx->sq_tail;
  16158. }
  16159. if (queue_filled < ctx->sq_size) {
  16160. /* Copy socket to the queue and increment head */
  16161. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16162. ctx->sq_head++;
  16163. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16164. }
  16165. queue_filled = ctx->sq_head - ctx->sq_tail;
  16166. #if defined(USE_SERVER_STATS)
  16167. (void)pthread_mutex_lock(&global_stats_mutex);
  16168. ctx->sq_filled = queue_filled;
  16169. if (queue_filled > ctx->sq_max_fill) {
  16170. ctx->sq_max_fill = queue_filled;
  16171. }
  16172. (void)pthread_mutex_unlock(&global_stats_mutex);
  16173. #endif
  16174. (void)pthread_cond_signal(&ctx->sq_full);
  16175. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16176. }
  16177. #endif /* ALTERNATIVE_QUEUE */
  16178. static void
  16179. worker_thread_run(struct mg_connection *conn)
  16180. {
  16181. struct mg_context *ctx = conn->phys_ctx;
  16182. int thread_index;
  16183. struct mg_workerTLS tls;
  16184. #if defined(MG_LEGACY_INTERFACE)
  16185. uint32_t addr;
  16186. #endif
  16187. mg_set_thread_name("worker");
  16188. tls.is_master = 0;
  16189. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16190. #if defined(_WIN32)
  16191. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16192. #endif
  16193. /* Initialize thread local storage before calling any callback */
  16194. pthread_setspecific(sTlsKey, &tls);
  16195. /* Check if there is a user callback */
  16196. if (ctx->callbacks.init_thread) {
  16197. /* call init_thread for a worker thread (type 1), and store the
  16198. * return value */
  16199. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16200. } else {
  16201. /* No callback: set user pointer to NULL */
  16202. tls.user_ptr = NULL;
  16203. }
  16204. /* Connection structure has been pre-allocated */
  16205. thread_index = (int)(conn - ctx->worker_connections);
  16206. if ((thread_index < 0)
  16207. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16208. mg_cry_ctx_internal(ctx,
  16209. "Internal error: Invalid worker index %i",
  16210. thread_index);
  16211. return;
  16212. }
  16213. /* Request buffers are not pre-allocated. They are private to the
  16214. * request and do not contain any state information that might be
  16215. * of interest to anyone observing a server status. */
  16216. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16217. if (conn->buf == NULL) {
  16218. mg_cry_ctx_internal(
  16219. ctx,
  16220. "Out of memory: Cannot allocate buffer for worker %i",
  16221. thread_index);
  16222. return;
  16223. }
  16224. conn->buf_size = (int)ctx->max_request_size;
  16225. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16226. conn->host = NULL; /* until we have more information. */
  16227. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16228. conn->request_info.user_data = ctx->user_data;
  16229. /* Allocate a mutex for this connection to allow communication both
  16230. * within the request handler and from elsewhere in the application
  16231. */
  16232. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16233. mg_free(conn->buf);
  16234. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16235. return;
  16236. }
  16237. #if defined(USE_SERVER_STATS)
  16238. conn->conn_state = 1; /* not consumed */
  16239. #endif
  16240. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16241. * signal sq_empty condvar to wake up the master waiting in
  16242. * produce_socket() */
  16243. while (consume_socket(ctx, &conn->client, thread_index)) {
  16244. /* New connections must start with new protocol negotiation */
  16245. tls.alpn_proto = NULL;
  16246. #if defined(USE_SERVER_STATS)
  16247. conn->conn_close_time = 0;
  16248. #endif
  16249. conn->conn_birth_time = time(NULL);
  16250. /* Fill in IP, port info early so even if SSL setup below fails,
  16251. * error handler would have the corresponding info.
  16252. * Thanks to Johannes Winkelmann for the patch.
  16253. */
  16254. #if defined(USE_IPV6)
  16255. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16256. conn->request_info.remote_port =
  16257. ntohs(conn->client.rsa.sin6.sin6_port);
  16258. } else
  16259. #endif
  16260. {
  16261. conn->request_info.remote_port =
  16262. ntohs(conn->client.rsa.sin.sin_port);
  16263. }
  16264. sockaddr_to_string(conn->request_info.remote_addr,
  16265. sizeof(conn->request_info.remote_addr),
  16266. &conn->client.rsa);
  16267. DEBUG_TRACE("Start processing connection from %s",
  16268. conn->request_info.remote_addr);
  16269. conn->request_info.is_ssl = conn->client.is_ssl;
  16270. if (conn->client.is_ssl) {
  16271. #if !defined(NO_SSL)
  16272. /* HTTPS connection */
  16273. if (sslize(conn,
  16274. SSL_accept,
  16275. NULL)) {
  16276. /* conn->dom_ctx is set in get_request */
  16277. /* Get SSL client certificate information (if set) */
  16278. struct mg_client_cert client_cert;
  16279. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16280. conn->request_info.client_cert = &client_cert;
  16281. }
  16282. /* process HTTPS connection */
  16283. #if defined(USE_HTTP2)
  16284. if ((tls.alpn_proto != NULL)
  16285. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16286. /* process HTTPS/2 connection */
  16287. init_connection(conn);
  16288. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16289. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16290. conn->content_len = -1;
  16291. conn->is_chunked = 0;
  16292. process_new_http2_connection(conn);
  16293. } else
  16294. #endif
  16295. {
  16296. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16297. process_new_connection(conn);
  16298. }
  16299. /* Free client certificate info */
  16300. if (conn->request_info.client_cert) {
  16301. mg_free((void *)(conn->request_info.client_cert->subject));
  16302. mg_free((void *)(conn->request_info.client_cert->issuer));
  16303. mg_free((void *)(conn->request_info.client_cert->serial));
  16304. mg_free((void *)(conn->request_info.client_cert->finger));
  16305. /* Free certificate memory */
  16306. X509_free(
  16307. (X509 *)conn->request_info.client_cert->peer_cert);
  16308. conn->request_info.client_cert->peer_cert = 0;
  16309. conn->request_info.client_cert->subject = 0;
  16310. conn->request_info.client_cert->issuer = 0;
  16311. conn->request_info.client_cert->serial = 0;
  16312. conn->request_info.client_cert->finger = 0;
  16313. conn->request_info.client_cert = 0;
  16314. }
  16315. } else {
  16316. /* make sure the connection is cleaned up on SSL failure */
  16317. close_connection(conn);
  16318. }
  16319. #endif
  16320. } else {
  16321. /* process HTTP connection */
  16322. process_new_connection(conn);
  16323. }
  16324. DEBUG_TRACE("%s", "Connection closed");
  16325. #if defined(USE_SERVER_STATS)
  16326. conn->conn_close_time = time(NULL);
  16327. #endif
  16328. }
  16329. /* Call exit thread user callback */
  16330. if (ctx->callbacks.exit_thread) {
  16331. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16332. }
  16333. /* delete thread local storage objects */
  16334. pthread_setspecific(sTlsKey, NULL);
  16335. #if defined(_WIN32)
  16336. CloseHandle(tls.pthread_cond_helper_mutex);
  16337. #endif
  16338. pthread_mutex_destroy(&conn->mutex);
  16339. /* Free the request buffer. */
  16340. conn->buf_size = 0;
  16341. mg_free(conn->buf);
  16342. conn->buf = NULL;
  16343. #if defined(USE_SERVER_STATS)
  16344. conn->conn_state = 9; /* done */
  16345. #endif
  16346. DEBUG_TRACE("%s", "exiting");
  16347. }
  16348. /* Threads have different return types on Windows and Unix. */
  16349. #if defined(_WIN32)
  16350. static unsigned __stdcall worker_thread(void *thread_func_param)
  16351. {
  16352. worker_thread_run((struct mg_connection *)thread_func_param);
  16353. return 0;
  16354. }
  16355. #else
  16356. static void *
  16357. worker_thread(void *thread_func_param)
  16358. {
  16359. #if !defined(__ZEPHYR__)
  16360. struct sigaction sa;
  16361. /* Ignore SIGPIPE */
  16362. memset(&sa, 0, sizeof(sa));
  16363. sa.sa_handler = SIG_IGN;
  16364. sigaction(SIGPIPE, &sa, NULL);
  16365. #endif
  16366. worker_thread_run((struct mg_connection *)thread_func_param);
  16367. return NULL;
  16368. }
  16369. #endif /* _WIN32 */
  16370. /* This is an internal function, thus all arguments are expected to be
  16371. * valid - a NULL check is not required. */
  16372. static void
  16373. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16374. {
  16375. struct socket so;
  16376. char src_addr[IP_ADDR_STR_LEN];
  16377. socklen_t len = sizeof(so.rsa);
  16378. #if !defined(__ZEPHYR__)
  16379. int on = 1;
  16380. #endif
  16381. memset(&so, 0, sizeof(so));
  16382. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16383. == INVALID_SOCKET) {
  16384. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16385. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16386. mg_cry_ctx_internal(ctx,
  16387. "%s: %s is not allowed to connect",
  16388. __func__,
  16389. src_addr);
  16390. closesocket(so.sock);
  16391. } else {
  16392. /* Put so socket structure into the queue */
  16393. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16394. set_close_on_exec(so.sock, NULL, ctx);
  16395. so.is_ssl = listener->is_ssl;
  16396. so.ssl_redir = listener->ssl_redir;
  16397. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16398. mg_cry_ctx_internal(ctx,
  16399. "%s: getsockname() failed: %s",
  16400. __func__,
  16401. strerror(ERRNO));
  16402. }
  16403. #if !defined(__ZEPHYR__)
  16404. /* Set TCP keep-alive. This is needed because if HTTP-level
  16405. * keep-alive
  16406. * is enabled, and client resets the connection, server won't get
  16407. * TCP FIN or RST and will keep the connection open forever. With
  16408. * TCP keep-alive, next keep-alive handshake will figure out that
  16409. * the client is down and will close the server end.
  16410. * Thanks to Igor Klopov who suggested the patch. */
  16411. if (setsockopt(so.sock,
  16412. SOL_SOCKET,
  16413. SO_KEEPALIVE,
  16414. (SOCK_OPT_TYPE)&on,
  16415. sizeof(on))
  16416. != 0) {
  16417. mg_cry_ctx_internal(
  16418. ctx,
  16419. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16420. __func__,
  16421. strerror(ERRNO));
  16422. }
  16423. #endif
  16424. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16425. * to effectively fill up the underlying IP packet payload and
  16426. * reduce the overhead of sending lots of small buffers. However
  16427. * this hurts the server's throughput (ie. operations per second)
  16428. * when HTTP 1.1 persistent connections are used and the responses
  16429. * are relatively small (eg. less than 1400 bytes).
  16430. */
  16431. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16432. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16433. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16434. mg_cry_ctx_internal(
  16435. ctx,
  16436. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16437. __func__,
  16438. strerror(ERRNO));
  16439. }
  16440. }
  16441. /* The "non blocking" property should already be
  16442. * inherited from the parent socket. Set it for
  16443. * non-compliant socket implementations. */
  16444. set_non_blocking_mode(so.sock);
  16445. so.in_use = 0;
  16446. produce_socket(ctx, &so);
  16447. }
  16448. }
  16449. static void
  16450. master_thread_run(struct mg_context *ctx)
  16451. {
  16452. struct mg_workerTLS tls;
  16453. struct mg_pollfd *pfd;
  16454. unsigned int i;
  16455. unsigned int workerthreadcount;
  16456. if (!ctx) {
  16457. return;
  16458. }
  16459. mg_set_thread_name("master");
  16460. /* Increase priority of the master thread */
  16461. #if defined(_WIN32)
  16462. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16463. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16464. int min_prio = sched_get_priority_min(SCHED_RR);
  16465. int max_prio = sched_get_priority_max(SCHED_RR);
  16466. if ((min_prio >= 0) && (max_prio >= 0)
  16467. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16468. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16469. struct sched_param sched_param = {0};
  16470. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16471. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16472. }
  16473. #endif
  16474. /* Initialize thread local storage */
  16475. #if defined(_WIN32)
  16476. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16477. #endif
  16478. tls.is_master = 1;
  16479. pthread_setspecific(sTlsKey, &tls);
  16480. if (ctx->callbacks.init_thread) {
  16481. /* Callback for the master thread (type 0) */
  16482. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16483. } else {
  16484. tls.user_ptr = NULL;
  16485. }
  16486. /* Server starts *now* */
  16487. ctx->start_time = time(NULL);
  16488. /* Start the server */
  16489. pfd = ctx->listening_socket_fds;
  16490. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16491. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16492. pfd[i].fd = ctx->listening_sockets[i].sock;
  16493. pfd[i].events = POLLIN;
  16494. }
  16495. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16496. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16497. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16498. * successful poll, and POLLIN is defined as
  16499. * (POLLRDNORM | POLLRDBAND)
  16500. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16501. * pfd[i].revents == POLLIN. */
  16502. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16503. && (pfd[i].revents & POLLIN)) {
  16504. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16505. }
  16506. }
  16507. }
  16508. }
  16509. /* Here stop_flag is 1 - Initiate shutdown. */
  16510. DEBUG_TRACE("%s", "stopping workers");
  16511. /* Stop signal received: somebody called mg_stop. Quit. */
  16512. close_all_listening_sockets(ctx);
  16513. /* Wakeup workers that are waiting for connections to handle. */
  16514. #if defined(ALTERNATIVE_QUEUE)
  16515. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16516. event_signal(ctx->client_wait_events[i]);
  16517. }
  16518. #else
  16519. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16520. pthread_cond_broadcast(&ctx->sq_full);
  16521. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16522. #endif
  16523. /* Join all worker threads to avoid leaking threads. */
  16524. workerthreadcount = ctx->cfg_worker_threads;
  16525. for (i = 0; i < workerthreadcount; i++) {
  16526. if (ctx->worker_threadids[i] != 0) {
  16527. mg_join_thread(ctx->worker_threadids[i]);
  16528. }
  16529. }
  16530. #if defined(USE_LUA)
  16531. /* Free Lua state of lua background task */
  16532. if (ctx->lua_background_state) {
  16533. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16534. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16535. if (lua_istable(lstate, -1)) {
  16536. reg_boolean(lstate, "shutdown", 1);
  16537. lua_pop(lstate, 1);
  16538. mg_sleep(2);
  16539. }
  16540. lua_close(lstate);
  16541. ctx->lua_background_state = 0;
  16542. }
  16543. #endif
  16544. DEBUG_TRACE("%s", "exiting");
  16545. /* call exit thread callback */
  16546. if (ctx->callbacks.exit_thread) {
  16547. /* Callback for the master thread (type 0) */
  16548. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16549. }
  16550. #if defined(_WIN32)
  16551. CloseHandle(tls.pthread_cond_helper_mutex);
  16552. #endif
  16553. pthread_setspecific(sTlsKey, NULL);
  16554. /* Signal mg_stop() that we're done.
  16555. * WARNING: This must be the very last thing this
  16556. * thread does, as ctx becomes invalid after this line. */
  16557. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16558. }
  16559. /* Threads have different return types on Windows and Unix. */
  16560. #if defined(_WIN32)
  16561. static unsigned __stdcall master_thread(void *thread_func_param)
  16562. {
  16563. master_thread_run((struct mg_context *)thread_func_param);
  16564. return 0;
  16565. }
  16566. #else
  16567. static void *
  16568. master_thread(void *thread_func_param)
  16569. {
  16570. #if !defined(__ZEPHYR__)
  16571. struct sigaction sa;
  16572. /* Ignore SIGPIPE */
  16573. memset(&sa, 0, sizeof(sa));
  16574. sa.sa_handler = SIG_IGN;
  16575. sigaction(SIGPIPE, &sa, NULL);
  16576. #endif
  16577. master_thread_run((struct mg_context *)thread_func_param);
  16578. return NULL;
  16579. }
  16580. #endif /* _WIN32 */
  16581. static void
  16582. free_context(struct mg_context *ctx)
  16583. {
  16584. int i;
  16585. struct mg_handler_info *tmp_rh;
  16586. if (ctx == NULL) {
  16587. return;
  16588. }
  16589. if (ctx->callbacks.exit_context) {
  16590. ctx->callbacks.exit_context(ctx);
  16591. }
  16592. /* All threads exited, no sync is needed. Destroy thread mutex and
  16593. * condvars
  16594. */
  16595. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16596. #if defined(ALTERNATIVE_QUEUE)
  16597. mg_free(ctx->client_socks);
  16598. if (ctx->client_wait_events != NULL) {
  16599. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16600. event_destroy(ctx->client_wait_events[i]);
  16601. }
  16602. mg_free(ctx->client_wait_events);
  16603. }
  16604. #else
  16605. (void)pthread_cond_destroy(&ctx->sq_empty);
  16606. (void)pthread_cond_destroy(&ctx->sq_full);
  16607. mg_free(ctx->squeue);
  16608. #endif
  16609. /* Destroy other context global data structures mutex */
  16610. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16611. #if defined(USE_TIMERS)
  16612. timers_exit(ctx);
  16613. #endif
  16614. /* Deallocate config parameters */
  16615. for (i = 0; i < NUM_OPTIONS; i++) {
  16616. if (ctx->dd.config[i] != NULL) {
  16617. #if defined(_MSC_VER)
  16618. #pragma warning(suppress : 6001)
  16619. #endif
  16620. mg_free(ctx->dd.config[i]);
  16621. }
  16622. }
  16623. /* Deallocate request handlers */
  16624. while (ctx->dd.handlers) {
  16625. tmp_rh = ctx->dd.handlers;
  16626. ctx->dd.handlers = tmp_rh->next;
  16627. mg_free(tmp_rh->uri);
  16628. mg_free(tmp_rh);
  16629. }
  16630. #if !defined(NO_SSL)
  16631. /* Deallocate SSL context */
  16632. if (ctx->dd.ssl_ctx != NULL) {
  16633. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16634. int callback_ret =
  16635. (ctx->callbacks.external_ssl_ctx == NULL)
  16636. ? 0
  16637. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16638. if (callback_ret == 0) {
  16639. SSL_CTX_free(ctx->dd.ssl_ctx);
  16640. }
  16641. /* else: ignore error and ommit SSL_CTX_free in case
  16642. * callback_ret is 1 */
  16643. }
  16644. #endif /* !NO_SSL */
  16645. /* Deallocate worker thread ID array */
  16646. mg_free(ctx->worker_threadids);
  16647. /* Deallocate worker thread ID array */
  16648. mg_free(ctx->worker_connections);
  16649. /* deallocate system name string */
  16650. mg_free(ctx->systemName);
  16651. /* Deallocate context itself */
  16652. mg_free(ctx);
  16653. }
  16654. void
  16655. mg_stop(struct mg_context *ctx)
  16656. {
  16657. pthread_t mt;
  16658. if (!ctx) {
  16659. return;
  16660. }
  16661. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16662. * two threads is not allowed. */
  16663. mt = ctx->masterthreadid;
  16664. if (mt == 0) {
  16665. return;
  16666. }
  16667. ctx->masterthreadid = 0;
  16668. /* Set stop flag, so all threads know they have to exit. */
  16669. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16670. /* Wait until everything has stopped. */
  16671. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16672. (void)mg_sleep(10);
  16673. }
  16674. mg_join_thread(mt);
  16675. free_context(ctx);
  16676. #if defined(_WIN32)
  16677. (void)WSACleanup();
  16678. #endif /* _WIN32 */
  16679. }
  16680. static void
  16681. get_system_name(char **sysName)
  16682. {
  16683. #if defined(_WIN32)
  16684. #if defined(_WIN32_WCE)
  16685. *sysName = mg_strdup("WinCE");
  16686. #else
  16687. char name[128];
  16688. DWORD dwVersion = 0;
  16689. DWORD dwMajorVersion = 0;
  16690. DWORD dwMinorVersion = 0;
  16691. DWORD dwBuild = 0;
  16692. BOOL wowRet, isWoW = FALSE;
  16693. #if defined(_MSC_VER)
  16694. #pragma warning(push)
  16695. /* GetVersion was declared deprecated */
  16696. #pragma warning(disable : 4996)
  16697. #endif
  16698. dwVersion = GetVersion();
  16699. #if defined(_MSC_VER)
  16700. #pragma warning(pop)
  16701. #endif
  16702. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16703. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16704. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16705. (void)dwBuild;
  16706. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16707. sprintf(name,
  16708. "Windows %u.%u%s",
  16709. (unsigned)dwMajorVersion,
  16710. (unsigned)dwMinorVersion,
  16711. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16712. *sysName = mg_strdup(name);
  16713. #endif
  16714. #elif defined(__ZEPHYR__)
  16715. *sysName = mg_strdup("Zephyr OS");
  16716. #else
  16717. struct utsname name;
  16718. memset(&name, 0, sizeof(name));
  16719. uname(&name);
  16720. *sysName = mg_strdup(name.sysname);
  16721. #endif
  16722. }
  16723. static void
  16724. legacy_init(const char **options)
  16725. {
  16726. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16727. if (options) {
  16728. const char **run_options = options;
  16729. const char *optname = config_options[LISTENING_PORTS].name;
  16730. /* Try to find the "listening_ports" option */
  16731. while (*run_options) {
  16732. if (!strcmp(*run_options, optname)) {
  16733. ports_option = run_options[1];
  16734. }
  16735. run_options += 2;
  16736. }
  16737. }
  16738. if (is_ssl_port_used(ports_option)) {
  16739. /* Initialize with SSL support */
  16740. mg_init_library(MG_FEATURES_TLS);
  16741. } else {
  16742. /* Initialize without SSL support */
  16743. mg_init_library(MG_FEATURES_DEFAULT);
  16744. }
  16745. }
  16746. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16747. static
  16748. #endif
  16749. struct mg_context *
  16750. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16751. {
  16752. struct mg_context *ctx;
  16753. const char *name, *value, *default_value;
  16754. int idx, ok, workerthreadcount;
  16755. unsigned int i;
  16756. int itmp;
  16757. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16758. const char **options =
  16759. ((init != NULL) ? (init->configuration_options) : (NULL));
  16760. struct mg_workerTLS tls;
  16761. #if defined(_WIN32)
  16762. WSADATA data;
  16763. WSAStartup(MAKEWORD(2, 2), &data);
  16764. #endif /* _WIN32 */
  16765. if (error != NULL) {
  16766. error->code = 0;
  16767. if (error->text_buffer_size > 0) {
  16768. *error->text = 0;
  16769. }
  16770. }
  16771. if (mg_init_library_called == 0) {
  16772. /* Legacy INIT, if mg_start is called without mg_init_library.
  16773. * Note: This will cause a memory leak when unloading the library.
  16774. */
  16775. legacy_init(options);
  16776. }
  16777. if (mg_init_library_called == 0) {
  16778. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16779. mg_snprintf(NULL,
  16780. NULL, /* No truncation check for error buffers */
  16781. error->text,
  16782. error->text_buffer_size,
  16783. "%s",
  16784. "Library uninitialized");
  16785. }
  16786. return NULL;
  16787. }
  16788. /* Allocate context and initialize reasonable general case defaults. */
  16789. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16790. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16791. mg_snprintf(NULL,
  16792. NULL, /* No truncation check for error buffers */
  16793. error->text,
  16794. error->text_buffer_size,
  16795. "%s",
  16796. "Out of memory");
  16797. }
  16798. return NULL;
  16799. }
  16800. /* Random number generator will initialize at the first call */
  16801. ctx->dd.auth_nonce_mask =
  16802. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16803. /* Save started thread index to reuse in other external API calls
  16804. * For the sake of thread synchronization all non-civetweb threads
  16805. * can be considered as single external thread */
  16806. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16807. tls.is_master = -1; /* Thread calling mg_start */
  16808. tls.thread_idx = ctx->starter_thread_idx;
  16809. #if defined(_WIN32)
  16810. tls.pthread_cond_helper_mutex = NULL;
  16811. #endif
  16812. pthread_setspecific(sTlsKey, &tls);
  16813. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16814. #if !defined(ALTERNATIVE_QUEUE)
  16815. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16816. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16817. #endif
  16818. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16819. if (!ok) {
  16820. const char *err_msg =
  16821. "Cannot initialize thread synchronization objects";
  16822. /* Fatal error - abort start. However, this situation should never
  16823. * occur in practice. */
  16824. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16825. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16826. mg_snprintf(NULL,
  16827. NULL, /* No truncation check for error buffers */
  16828. error->text,
  16829. error->text_buffer_size,
  16830. "%s",
  16831. err_msg);
  16832. }
  16833. mg_free(ctx);
  16834. pthread_setspecific(sTlsKey, NULL);
  16835. return NULL;
  16836. }
  16837. if ((init != NULL) && (init->callbacks != NULL)) {
  16838. /* Set all callbacks except exit_context. */
  16839. ctx->callbacks = *init->callbacks;
  16840. exit_callback = init->callbacks->exit_context;
  16841. /* The exit callback is activated once the context is successfully
  16842. * created. It should not be called, if an incomplete context object
  16843. * is deleted during a failed initialization. */
  16844. ctx->callbacks.exit_context = 0;
  16845. }
  16846. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16847. ctx->dd.handlers = NULL;
  16848. ctx->dd.next = NULL;
  16849. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16850. ctx->dd.shared_lua_websockets = NULL;
  16851. #endif
  16852. /* Store options */
  16853. while (options && (name = *options++) != NULL) {
  16854. if ((idx = get_option_index(name)) == -1) {
  16855. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16856. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16857. mg_snprintf(NULL,
  16858. NULL, /* No truncation check for error buffers */
  16859. error->text,
  16860. error->text_buffer_size,
  16861. "Invalid configuration option: %s",
  16862. name);
  16863. }
  16864. free_context(ctx);
  16865. pthread_setspecific(sTlsKey, NULL);
  16866. return NULL;
  16867. } else if ((value = *options++) == NULL) {
  16868. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16869. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16870. mg_snprintf(NULL,
  16871. NULL, /* No truncation check for error buffers */
  16872. error->text,
  16873. error->text_buffer_size,
  16874. "Invalid configuration option value: %s",
  16875. name);
  16876. }
  16877. free_context(ctx);
  16878. pthread_setspecific(sTlsKey, NULL);
  16879. return NULL;
  16880. }
  16881. if (ctx->dd.config[idx] != NULL) {
  16882. /* A duplicate configuration option is not an error - the last
  16883. * option value will be used. */
  16884. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16885. mg_free(ctx->dd.config[idx]);
  16886. }
  16887. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16888. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16889. }
  16890. /* Set default value if needed */
  16891. for (i = 0; config_options[i].name != NULL; i++) {
  16892. default_value = config_options[i].default_value;
  16893. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16894. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16895. }
  16896. }
  16897. /* Request size option */
  16898. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16899. if (itmp < 1024) {
  16900. mg_cry_ctx_internal(ctx,
  16901. "%s too small",
  16902. config_options[MAX_REQUEST_SIZE].name);
  16903. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16904. mg_snprintf(NULL,
  16905. NULL, /* No truncation check for error buffers */
  16906. error->text,
  16907. error->text_buffer_size,
  16908. "Invalid configuration option value: %s",
  16909. config_options[MAX_REQUEST_SIZE].name);
  16910. }
  16911. free_context(ctx);
  16912. pthread_setspecific(sTlsKey, NULL);
  16913. return NULL;
  16914. }
  16915. ctx->max_request_size = (unsigned)itmp;
  16916. /* Queue length */
  16917. #if !defined(ALTERNATIVE_QUEUE)
  16918. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16919. if (itmp < 1) {
  16920. mg_cry_ctx_internal(ctx,
  16921. "%s too small",
  16922. config_options[CONNECTION_QUEUE_SIZE].name);
  16923. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16924. mg_snprintf(NULL,
  16925. NULL, /* No truncation check for error buffers */
  16926. error->text,
  16927. error->text_buffer_size,
  16928. "Invalid configuration option value: %s",
  16929. config_options[CONNECTION_QUEUE_SIZE].name);
  16930. }
  16931. free_context(ctx);
  16932. pthread_setspecific(sTlsKey, NULL);
  16933. return NULL;
  16934. }
  16935. ctx->squeue =
  16936. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16937. if (ctx->squeue == NULL) {
  16938. mg_cry_ctx_internal(ctx,
  16939. "Out of memory: Cannot allocate %s",
  16940. config_options[CONNECTION_QUEUE_SIZE].name);
  16941. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16942. mg_snprintf(NULL,
  16943. NULL, /* No truncation check for error buffers */
  16944. error->text,
  16945. error->text_buffer_size,
  16946. "Out of memory: Cannot allocate %s",
  16947. config_options[CONNECTION_QUEUE_SIZE].name);
  16948. }
  16949. free_context(ctx);
  16950. pthread_setspecific(sTlsKey, NULL);
  16951. return NULL;
  16952. }
  16953. ctx->sq_size = itmp;
  16954. #endif
  16955. /* Worker thread count option */
  16956. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16957. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16958. if (workerthreadcount <= 0) {
  16959. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16960. } else {
  16961. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16962. }
  16963. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16964. mg_snprintf(NULL,
  16965. NULL, /* No truncation check for error buffers */
  16966. error->text,
  16967. error->text_buffer_size,
  16968. "Invalid configuration option value: %s",
  16969. config_options[NUM_THREADS].name);
  16970. }
  16971. free_context(ctx);
  16972. pthread_setspecific(sTlsKey, NULL);
  16973. return NULL;
  16974. }
  16975. /* Document root */
  16976. #if defined(NO_FILES)
  16977. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16978. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16979. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16980. mg_snprintf(NULL,
  16981. NULL, /* No truncation check for error buffers */
  16982. error->text,
  16983. error->text_buffer_size,
  16984. "Invalid configuration option value: %s",
  16985. config_options[DOCUMENT_ROOT].name);
  16986. }
  16987. free_context(ctx);
  16988. pthread_setspecific(sTlsKey, NULL);
  16989. return NULL;
  16990. }
  16991. #endif
  16992. get_system_name(&ctx->systemName);
  16993. #if defined(USE_LUA)
  16994. /* If a Lua background script has been configured, start it. */
  16995. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16996. char ebuf[256];
  16997. struct vec opt_vec;
  16998. struct vec eq_vec;
  16999. const char *sparams;
  17000. lua_State *state = mg_prepare_lua_context_script(
  17001. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17002. if (!state) {
  17003. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  17004. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17005. mg_snprintf(NULL,
  17006. NULL, /* No truncation check for error buffers */
  17007. error->text,
  17008. error->text_buffer_size,
  17009. "Error in script %s: %s",
  17010. config_options[DOCUMENT_ROOT].name,
  17011. ebuf);
  17012. }
  17013. free_context(ctx);
  17014. pthread_setspecific(sTlsKey, NULL);
  17015. return NULL;
  17016. }
  17017. ctx->lua_background_state = (void *)state;
  17018. lua_newtable(state);
  17019. reg_boolean(state, "shutdown", 0);
  17020. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17021. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17022. reg_llstring(
  17023. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17024. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17025. break;
  17026. }
  17027. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17028. } else {
  17029. ctx->lua_background_state = 0;
  17030. }
  17031. #endif
  17032. /* Step by step initialization of ctx - depending on build options */
  17033. #if !defined(NO_FILESYSTEMS)
  17034. if (!set_gpass_option(ctx, NULL)) {
  17035. const char *err_msg = "Invalid global password file";
  17036. /* Fatal error - abort start. */
  17037. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17038. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17039. mg_snprintf(NULL,
  17040. NULL, /* No truncation check for error buffers */
  17041. error->text,
  17042. error->text_buffer_size,
  17043. "%s",
  17044. err_msg);
  17045. }
  17046. free_context(ctx);
  17047. pthread_setspecific(sTlsKey, NULL);
  17048. return NULL;
  17049. }
  17050. #endif
  17051. #if !defined(NO_SSL)
  17052. if (!init_ssl_ctx(ctx, NULL)) {
  17053. const char *err_msg = "Error initializing SSL context";
  17054. /* Fatal error - abort start. */
  17055. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17056. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17057. mg_snprintf(NULL,
  17058. NULL, /* No truncation check for error buffers */
  17059. error->text,
  17060. error->text_buffer_size,
  17061. "%s",
  17062. err_msg);
  17063. }
  17064. free_context(ctx);
  17065. pthread_setspecific(sTlsKey, NULL);
  17066. return NULL;
  17067. }
  17068. #endif
  17069. if (!set_ports_option(ctx)) {
  17070. const char *err_msg = "Failed to setup server ports";
  17071. /* Fatal error - abort start. */
  17072. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17073. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17074. mg_snprintf(NULL,
  17075. NULL, /* No truncation check for error buffers */
  17076. error->text,
  17077. error->text_buffer_size,
  17078. "%s",
  17079. err_msg);
  17080. }
  17081. free_context(ctx);
  17082. pthread_setspecific(sTlsKey, NULL);
  17083. return NULL;
  17084. }
  17085. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17086. if (!set_uid_option(ctx)) {
  17087. const char *err_msg = "Failed to run as configured user";
  17088. /* Fatal error - abort start. */
  17089. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17090. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17091. mg_snprintf(NULL,
  17092. NULL, /* No truncation check for error buffers */
  17093. error->text,
  17094. error->text_buffer_size,
  17095. "%s",
  17096. err_msg);
  17097. }
  17098. free_context(ctx);
  17099. pthread_setspecific(sTlsKey, NULL);
  17100. return NULL;
  17101. }
  17102. #endif
  17103. if (!set_acl_option(ctx)) {
  17104. const char *err_msg = "Failed to setup access control list";
  17105. /* Fatal error - abort start. */
  17106. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17107. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17108. mg_snprintf(NULL,
  17109. NULL, /* No truncation check for error buffers */
  17110. error->text,
  17111. error->text_buffer_size,
  17112. "%s",
  17113. err_msg);
  17114. }
  17115. free_context(ctx);
  17116. pthread_setspecific(sTlsKey, NULL);
  17117. return NULL;
  17118. }
  17119. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17120. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17121. sizeof(pthread_t),
  17122. ctx);
  17123. if (ctx->worker_threadids == NULL) {
  17124. const char *err_msg = "Not enough memory for worker thread ID array";
  17125. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17126. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17127. mg_snprintf(NULL,
  17128. NULL, /* No truncation check for error buffers */
  17129. error->text,
  17130. error->text_buffer_size,
  17131. "%s",
  17132. err_msg);
  17133. }
  17134. free_context(ctx);
  17135. pthread_setspecific(sTlsKey, NULL);
  17136. return NULL;
  17137. }
  17138. ctx->worker_connections =
  17139. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17140. sizeof(struct mg_connection),
  17141. ctx);
  17142. if (ctx->worker_connections == NULL) {
  17143. const char *err_msg =
  17144. "Not enough memory for worker thread connection array";
  17145. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17146. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17147. mg_snprintf(NULL,
  17148. NULL, /* No truncation check for error buffers */
  17149. error->text,
  17150. error->text_buffer_size,
  17151. "%s",
  17152. err_msg);
  17153. }
  17154. free_context(ctx);
  17155. pthread_setspecific(sTlsKey, NULL);
  17156. return NULL;
  17157. }
  17158. #if defined(ALTERNATIVE_QUEUE)
  17159. ctx->client_wait_events =
  17160. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17161. sizeof(ctx->client_wait_events[0]),
  17162. ctx);
  17163. if (ctx->client_wait_events == NULL) {
  17164. const char *err_msg = "Not enough memory for worker event array";
  17165. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17166. mg_free(ctx->worker_threadids);
  17167. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17168. mg_snprintf(NULL,
  17169. NULL, /* No truncation check for error buffers */
  17170. error->text,
  17171. error->text_buffer_size,
  17172. "%s",
  17173. err_msg);
  17174. }
  17175. free_context(ctx);
  17176. pthread_setspecific(sTlsKey, NULL);
  17177. return NULL;
  17178. }
  17179. ctx->client_socks =
  17180. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17181. sizeof(ctx->client_socks[0]),
  17182. ctx);
  17183. if (ctx->client_socks == NULL) {
  17184. const char *err_msg = "Not enough memory for worker socket array";
  17185. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17186. mg_free(ctx->client_wait_events);
  17187. mg_free(ctx->worker_threadids);
  17188. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17189. mg_snprintf(NULL,
  17190. NULL, /* No truncation check for error buffers */
  17191. error->text,
  17192. error->text_buffer_size,
  17193. "%s",
  17194. err_msg);
  17195. }
  17196. free_context(ctx);
  17197. pthread_setspecific(sTlsKey, NULL);
  17198. return NULL;
  17199. }
  17200. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17201. ctx->client_wait_events[i] = event_create();
  17202. if (ctx->client_wait_events[i] == 0) {
  17203. const char *err_msg = "Error creating worker event %i";
  17204. mg_cry_ctx_internal(ctx, err_msg, i);
  17205. while (i > 0) {
  17206. i--;
  17207. event_destroy(ctx->client_wait_events[i]);
  17208. }
  17209. mg_free(ctx->client_socks);
  17210. mg_free(ctx->client_wait_events);
  17211. mg_free(ctx->worker_threadids);
  17212. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17213. mg_snprintf(NULL,
  17214. NULL, /* No truncation check for error buffers */
  17215. error->text,
  17216. error->text_buffer_size,
  17217. err_msg,
  17218. i);
  17219. }
  17220. free_context(ctx);
  17221. pthread_setspecific(sTlsKey, NULL);
  17222. return NULL;
  17223. }
  17224. }
  17225. #endif
  17226. #if defined(USE_TIMERS)
  17227. if (timers_init(ctx) != 0) {
  17228. const char *err_msg = "Error creating timers";
  17229. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17230. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17231. mg_snprintf(NULL,
  17232. NULL, /* No truncation check for error buffers */
  17233. error->text,
  17234. error->text_buffer_size,
  17235. "%s",
  17236. err_msg);
  17237. }
  17238. free_context(ctx);
  17239. pthread_setspecific(sTlsKey, NULL);
  17240. return NULL;
  17241. }
  17242. #endif
  17243. /* Context has been created - init user libraries */
  17244. if (ctx->callbacks.init_context) {
  17245. ctx->callbacks.init_context(ctx);
  17246. }
  17247. /* From now, the context is successfully created.
  17248. * When it is destroyed, the exit callback should be called. */
  17249. ctx->callbacks.exit_context = exit_callback;
  17250. ctx->context_type = CONTEXT_SERVER; /* server context */
  17251. /* Start worker threads */
  17252. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17253. /* worker_thread sets up the other fields */
  17254. ctx->worker_connections[i].phys_ctx = ctx;
  17255. if (mg_start_thread_with_id(worker_thread,
  17256. &ctx->worker_connections[i],
  17257. &ctx->worker_threadids[i])
  17258. != 0) {
  17259. long error_no = (long)ERRNO;
  17260. /* thread was not created */
  17261. if (i > 0) {
  17262. /* If the second, third, ... thread cannot be created, set a
  17263. * warning, but keep running. */
  17264. mg_cry_ctx_internal(ctx,
  17265. "Cannot start worker thread %i: error %ld",
  17266. i + 1,
  17267. error_no);
  17268. /* If the server initialization should stop here, all
  17269. * threads that have already been created must be stopped
  17270. * first, before any free_context(ctx) call.
  17271. */
  17272. } else {
  17273. /* If the first worker thread cannot be created, stop
  17274. * initialization and free the entire server context. */
  17275. mg_cry_ctx_internal(ctx,
  17276. "Cannot create threads: error %ld",
  17277. error_no);
  17278. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17279. mg_snprintf(
  17280. NULL,
  17281. NULL, /* No truncation check for error buffers */
  17282. error->text,
  17283. error->text_buffer_size,
  17284. "Cannot create first worker thread: error %ld",
  17285. error_no);
  17286. }
  17287. free_context(ctx);
  17288. pthread_setspecific(sTlsKey, NULL);
  17289. return NULL;
  17290. }
  17291. break;
  17292. }
  17293. }
  17294. /* Start master (listening) thread */
  17295. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17296. pthread_setspecific(sTlsKey, NULL);
  17297. return ctx;
  17298. }
  17299. struct mg_context *
  17300. mg_start(const struct mg_callbacks *callbacks,
  17301. void *user_data,
  17302. const char **options)
  17303. {
  17304. struct mg_init_data init = {0};
  17305. init.callbacks = callbacks;
  17306. init.user_data = user_data;
  17307. init.configuration_options = options;
  17308. return mg_start2(&init, NULL);
  17309. }
  17310. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17311. /* Add an additional domain to an already running web server. */
  17312. int
  17313. mg_start_domain2(struct mg_context *ctx,
  17314. const char **options,
  17315. struct mg_error_data *error)
  17316. {
  17317. const char *name;
  17318. const char *value;
  17319. const char *default_value;
  17320. struct mg_domain_context *new_dom;
  17321. struct mg_domain_context *dom;
  17322. int idx, i;
  17323. if (error != NULL) {
  17324. error->code = 0;
  17325. if (error->text_buffer_size > 0) {
  17326. *error->text = 0;
  17327. }
  17328. }
  17329. if ((ctx == NULL) || (options == NULL)) {
  17330. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17331. mg_snprintf(NULL,
  17332. NULL, /* No truncation check for error buffers */
  17333. error->text,
  17334. error->text_buffer_size,
  17335. "%s",
  17336. "Invalid parameters");
  17337. }
  17338. return -1;
  17339. }
  17340. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17341. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17342. mg_snprintf(NULL,
  17343. NULL, /* No truncation check for error buffers */
  17344. error->text,
  17345. error->text_buffer_size,
  17346. "%s",
  17347. "Server already stopped");
  17348. }
  17349. return -1;
  17350. }
  17351. new_dom = (struct mg_domain_context *)
  17352. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17353. if (!new_dom) {
  17354. /* Out of memory */
  17355. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17356. mg_snprintf(NULL,
  17357. NULL, /* No truncation check for error buffers */
  17358. error->text,
  17359. error->text_buffer_size,
  17360. "%s",
  17361. "Out or memory");
  17362. }
  17363. return -6;
  17364. }
  17365. /* Store options - TODO: unite duplicate code */
  17366. while (options && (name = *options++) != NULL) {
  17367. if ((idx = get_option_index(name)) == -1) {
  17368. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17369. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17370. mg_snprintf(NULL,
  17371. NULL, /* No truncation check for error buffers */
  17372. error->text,
  17373. error->text_buffer_size,
  17374. "Invalid option: %s",
  17375. name);
  17376. }
  17377. mg_free(new_dom);
  17378. return -2;
  17379. } else if ((value = *options++) == NULL) {
  17380. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17381. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17382. mg_snprintf(NULL,
  17383. NULL, /* No truncation check for error buffers */
  17384. error->text,
  17385. error->text_buffer_size,
  17386. "Invalid option value: %s",
  17387. name);
  17388. }
  17389. mg_free(new_dom);
  17390. return -2;
  17391. }
  17392. if (new_dom->config[idx] != NULL) {
  17393. /* Duplicate option: Later values overwrite earlier ones. */
  17394. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17395. mg_free(new_dom->config[idx]);
  17396. }
  17397. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17398. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17399. }
  17400. /* Authentication domain is mandatory */
  17401. /* TODO: Maybe use a new option hostname? */
  17402. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17403. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17404. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17405. mg_snprintf(NULL,
  17406. NULL, /* No truncation check for error buffers */
  17407. error->text,
  17408. error->text_buffer_size,
  17409. "Mandatory option %s missing",
  17410. config_options[AUTHENTICATION_DOMAIN].name);
  17411. }
  17412. mg_free(new_dom);
  17413. return -4;
  17414. }
  17415. /* Set default value if needed. Take the config value from
  17416. * ctx as a default value. */
  17417. for (i = 0; config_options[i].name != NULL; i++) {
  17418. default_value = ctx->dd.config[i];
  17419. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17420. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17421. }
  17422. }
  17423. new_dom->handlers = NULL;
  17424. new_dom->next = NULL;
  17425. new_dom->nonce_count = 0;
  17426. new_dom->auth_nonce_mask =
  17427. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17428. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17429. new_dom->shared_lua_websockets = NULL;
  17430. #endif
  17431. if (!init_ssl_ctx(ctx, new_dom)) {
  17432. /* Init SSL failed */
  17433. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17434. mg_snprintf(NULL,
  17435. NULL, /* No truncation check for error buffers */
  17436. error->text,
  17437. error->text_buffer_size,
  17438. "%s",
  17439. "Initializing SSL context failed");
  17440. }
  17441. mg_free(new_dom);
  17442. return -3;
  17443. }
  17444. /* Add element to linked list. */
  17445. mg_lock_context(ctx);
  17446. idx = 0;
  17447. dom = &(ctx->dd);
  17448. for (;;) {
  17449. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17450. dom->config[AUTHENTICATION_DOMAIN])) {
  17451. /* Domain collision */
  17452. mg_cry_ctx_internal(ctx,
  17453. "domain %s already in use",
  17454. new_dom->config[AUTHENTICATION_DOMAIN]);
  17455. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17456. mg_snprintf(NULL,
  17457. NULL, /* No truncation check for error buffers */
  17458. error->text,
  17459. error->text_buffer_size,
  17460. "Domain %s specified by %s is already in use",
  17461. new_dom->config[AUTHENTICATION_DOMAIN],
  17462. config_options[AUTHENTICATION_DOMAIN].name);
  17463. }
  17464. mg_free(new_dom);
  17465. mg_unlock_context(ctx);
  17466. return -5;
  17467. }
  17468. /* Count number of domains */
  17469. idx++;
  17470. if (dom->next == NULL) {
  17471. dom->next = new_dom;
  17472. break;
  17473. }
  17474. dom = dom->next;
  17475. }
  17476. mg_unlock_context(ctx);
  17477. /* Return domain number */
  17478. return idx;
  17479. }
  17480. int
  17481. mg_start_domain(struct mg_context *ctx, const char **options)
  17482. {
  17483. return mg_start_domain2(ctx, options, NULL);
  17484. }
  17485. #endif
  17486. /* Feature check API function */
  17487. unsigned
  17488. mg_check_feature(unsigned feature)
  17489. {
  17490. static const unsigned feature_set = 0
  17491. /* Set bits for available features according to API documentation.
  17492. * This bit mask is created at compile time, according to the active
  17493. * preprocessor defines. It is a single const value at runtime. */
  17494. #if !defined(NO_FILES)
  17495. | MG_FEATURES_FILES
  17496. #endif
  17497. #if !defined(NO_SSL)
  17498. | MG_FEATURES_SSL
  17499. #endif
  17500. #if !defined(NO_CGI)
  17501. | MG_FEATURES_CGI
  17502. #endif
  17503. #if defined(USE_IPV6)
  17504. | MG_FEATURES_IPV6
  17505. #endif
  17506. #if defined(USE_WEBSOCKET)
  17507. | MG_FEATURES_WEBSOCKET
  17508. #endif
  17509. #if defined(USE_LUA)
  17510. | MG_FEATURES_LUA
  17511. #endif
  17512. #if defined(USE_DUKTAPE)
  17513. | MG_FEATURES_SSJS
  17514. #endif
  17515. #if !defined(NO_CACHING)
  17516. | MG_FEATURES_CACHE
  17517. #endif
  17518. #if defined(USE_SERVER_STATS)
  17519. | MG_FEATURES_STATS
  17520. #endif
  17521. #if defined(USE_ZLIB)
  17522. | MG_FEATURES_COMPRESSION
  17523. #endif
  17524. /* Set some extra bits not defined in the API documentation.
  17525. * These bits may change without further notice. */
  17526. #if defined(MG_LEGACY_INTERFACE)
  17527. | 0x00008000u
  17528. #endif
  17529. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17530. | 0x00004000u
  17531. #endif
  17532. #if defined(MEMORY_DEBUGGING)
  17533. | 0x00001000u
  17534. #endif
  17535. #if defined(USE_TIMERS)
  17536. | 0x00020000u
  17537. #endif
  17538. #if !defined(NO_NONCE_CHECK)
  17539. | 0x00040000u
  17540. #endif
  17541. #if !defined(NO_POPEN)
  17542. | 0x00080000u
  17543. #endif
  17544. ;
  17545. return (feature & feature_set);
  17546. }
  17547. static size_t
  17548. mg_str_append(char **dst, char *end, const char *src)
  17549. {
  17550. size_t len = strlen(src);
  17551. if (*dst != end) {
  17552. /* Append src if enough space, or close dst. */
  17553. if ((size_t)(end - *dst) > len) {
  17554. strcpy(*dst, src);
  17555. *dst += len;
  17556. } else {
  17557. *dst = end;
  17558. }
  17559. }
  17560. return len;
  17561. }
  17562. /* Get system information. It can be printed or stored by the caller.
  17563. * Return the size of available information. */
  17564. int
  17565. mg_get_system_info(char *buffer, int buflen)
  17566. {
  17567. char *end, *append_eoobj = NULL, block[256];
  17568. size_t system_info_length = 0;
  17569. #if defined(_WIN32)
  17570. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17571. #else
  17572. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17573. #endif
  17574. if ((buffer == NULL) || (buflen < 1)) {
  17575. buflen = 0;
  17576. end = buffer;
  17577. } else {
  17578. *buffer = 0;
  17579. end = buffer + buflen;
  17580. }
  17581. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17582. /* has enough space to append eoobj */
  17583. append_eoobj = buffer;
  17584. if (end) {
  17585. end -= sizeof(eoobj) - 1;
  17586. }
  17587. }
  17588. system_info_length += mg_str_append(&buffer, end, "{");
  17589. /* Server version */
  17590. {
  17591. const char *version = mg_version();
  17592. mg_snprintf(NULL,
  17593. NULL,
  17594. block,
  17595. sizeof(block),
  17596. "%s\"version\" : \"%s\"",
  17597. eol,
  17598. version);
  17599. system_info_length += mg_str_append(&buffer, end, block);
  17600. }
  17601. /* System info */
  17602. {
  17603. #if defined(_WIN32)
  17604. DWORD dwVersion = 0;
  17605. DWORD dwMajorVersion = 0;
  17606. DWORD dwMinorVersion = 0;
  17607. SYSTEM_INFO si;
  17608. GetSystemInfo(&si);
  17609. #if defined(_MSC_VER)
  17610. #pragma warning(push)
  17611. /* GetVersion was declared deprecated */
  17612. #pragma warning(disable : 4996)
  17613. #endif
  17614. dwVersion = GetVersion();
  17615. #if defined(_MSC_VER)
  17616. #pragma warning(pop)
  17617. #endif
  17618. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17619. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17620. mg_snprintf(NULL,
  17621. NULL,
  17622. block,
  17623. sizeof(block),
  17624. ",%s\"os\" : \"Windows %u.%u\"",
  17625. eol,
  17626. (unsigned)dwMajorVersion,
  17627. (unsigned)dwMinorVersion);
  17628. system_info_length += mg_str_append(&buffer, end, block);
  17629. mg_snprintf(NULL,
  17630. NULL,
  17631. block,
  17632. sizeof(block),
  17633. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17634. eol,
  17635. (unsigned)si.wProcessorArchitecture,
  17636. (unsigned)si.dwNumberOfProcessors,
  17637. (unsigned)si.dwActiveProcessorMask);
  17638. system_info_length += mg_str_append(&buffer, end, block);
  17639. #elif defined(__ZEPHYR__)
  17640. mg_snprintf(NULL,
  17641. NULL,
  17642. block,
  17643. sizeof(block),
  17644. ",%s\"os\" : \"%s %s\"",
  17645. eol,
  17646. "Zephyr OS",
  17647. ZEPHYR_VERSION);
  17648. system_info_length += mg_str_append(&buffer, end, block);
  17649. #else
  17650. struct utsname name;
  17651. memset(&name, 0, sizeof(name));
  17652. uname(&name);
  17653. mg_snprintf(NULL,
  17654. NULL,
  17655. block,
  17656. sizeof(block),
  17657. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17658. eol,
  17659. name.sysname,
  17660. name.version,
  17661. name.release,
  17662. name.machine);
  17663. system_info_length += mg_str_append(&buffer, end, block);
  17664. #endif
  17665. }
  17666. /* Features */
  17667. {
  17668. mg_snprintf(NULL,
  17669. NULL,
  17670. block,
  17671. sizeof(block),
  17672. ",%s\"features\" : %lu"
  17673. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17674. eol,
  17675. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17676. eol,
  17677. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17678. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17679. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17680. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17681. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17682. : "",
  17683. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17684. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17685. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17686. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17687. system_info_length += mg_str_append(&buffer, end, block);
  17688. #if defined(USE_LUA)
  17689. mg_snprintf(NULL,
  17690. NULL,
  17691. block,
  17692. sizeof(block),
  17693. ",%s\"lua_version\" : \"%u (%s)\"",
  17694. eol,
  17695. (unsigned)LUA_VERSION_NUM,
  17696. LUA_RELEASE);
  17697. system_info_length += mg_str_append(&buffer, end, block);
  17698. #endif
  17699. #if defined(USE_DUKTAPE)
  17700. mg_snprintf(NULL,
  17701. NULL,
  17702. block,
  17703. sizeof(block),
  17704. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17705. eol,
  17706. (unsigned)DUK_VERSION / 10000,
  17707. ((unsigned)DUK_VERSION / 100) % 100,
  17708. (unsigned)DUK_VERSION % 100);
  17709. system_info_length += mg_str_append(&buffer, end, block);
  17710. #endif
  17711. }
  17712. /* Build date */
  17713. {
  17714. #if defined(GCC_DIAGNOSTIC)
  17715. #if GCC_VERSION >= 40900
  17716. #pragma GCC diagnostic push
  17717. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17718. #pragma GCC diagnostic ignored "-Wdate-time"
  17719. #endif
  17720. #endif
  17721. mg_snprintf(NULL,
  17722. NULL,
  17723. block,
  17724. sizeof(block),
  17725. ",%s\"build\" : \"%s\"",
  17726. eol,
  17727. __DATE__);
  17728. #if defined(GCC_DIAGNOSTIC)
  17729. #if GCC_VERSION >= 40900
  17730. #pragma GCC diagnostic pop
  17731. #endif
  17732. #endif
  17733. system_info_length += mg_str_append(&buffer, end, block);
  17734. }
  17735. /* Compiler information */
  17736. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17737. {
  17738. #if defined(_MSC_VER)
  17739. mg_snprintf(NULL,
  17740. NULL,
  17741. block,
  17742. sizeof(block),
  17743. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17744. eol,
  17745. (unsigned)_MSC_VER,
  17746. (unsigned)_MSC_FULL_VER);
  17747. system_info_length += mg_str_append(&buffer, end, block);
  17748. #elif defined(__MINGW64__)
  17749. mg_snprintf(NULL,
  17750. NULL,
  17751. block,
  17752. sizeof(block),
  17753. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17754. eol,
  17755. (unsigned)__MINGW64_VERSION_MAJOR,
  17756. (unsigned)__MINGW64_VERSION_MINOR);
  17757. system_info_length += mg_str_append(&buffer, end, block);
  17758. mg_snprintf(NULL,
  17759. NULL,
  17760. block,
  17761. sizeof(block),
  17762. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17763. eol,
  17764. (unsigned)__MINGW32_MAJOR_VERSION,
  17765. (unsigned)__MINGW32_MINOR_VERSION);
  17766. system_info_length += mg_str_append(&buffer, end, block);
  17767. #elif defined(__MINGW32__)
  17768. mg_snprintf(NULL,
  17769. NULL,
  17770. block,
  17771. sizeof(block),
  17772. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17773. eol,
  17774. (unsigned)__MINGW32_MAJOR_VERSION,
  17775. (unsigned)__MINGW32_MINOR_VERSION);
  17776. system_info_length += mg_str_append(&buffer, end, block);
  17777. #elif defined(__clang__)
  17778. mg_snprintf(NULL,
  17779. NULL,
  17780. block,
  17781. sizeof(block),
  17782. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17783. eol,
  17784. __clang_major__,
  17785. __clang_minor__,
  17786. __clang_patchlevel__,
  17787. __clang_version__);
  17788. system_info_length += mg_str_append(&buffer, end, block);
  17789. #elif defined(__GNUC__)
  17790. mg_snprintf(NULL,
  17791. NULL,
  17792. block,
  17793. sizeof(block),
  17794. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17795. eol,
  17796. (unsigned)__GNUC__,
  17797. (unsigned)__GNUC_MINOR__,
  17798. (unsigned)__GNUC_PATCHLEVEL__);
  17799. system_info_length += mg_str_append(&buffer, end, block);
  17800. #elif defined(__INTEL_COMPILER)
  17801. mg_snprintf(NULL,
  17802. NULL,
  17803. block,
  17804. sizeof(block),
  17805. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17806. eol,
  17807. (unsigned)__INTEL_COMPILER);
  17808. system_info_length += mg_str_append(&buffer, end, block);
  17809. #elif defined(__BORLANDC__)
  17810. mg_snprintf(NULL,
  17811. NULL,
  17812. block,
  17813. sizeof(block),
  17814. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17815. eol,
  17816. (unsigned)__BORLANDC__);
  17817. system_info_length += mg_str_append(&buffer, end, block);
  17818. #elif defined(__SUNPRO_C)
  17819. mg_snprintf(NULL,
  17820. NULL,
  17821. block,
  17822. sizeof(block),
  17823. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17824. eol,
  17825. (unsigned)__SUNPRO_C);
  17826. system_info_length += mg_str_append(&buffer, end, block);
  17827. #else
  17828. mg_snprintf(NULL,
  17829. NULL,
  17830. block,
  17831. sizeof(block),
  17832. ",%s\"compiler\" : \"other\"",
  17833. eol);
  17834. system_info_length += mg_str_append(&buffer, end, block);
  17835. #endif
  17836. }
  17837. /* Determine 32/64 bit data mode.
  17838. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17839. {
  17840. mg_snprintf(NULL,
  17841. NULL,
  17842. block,
  17843. sizeof(block),
  17844. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17845. "char:%u/%u, "
  17846. "ptr:%u, size:%u, time:%u\"",
  17847. eol,
  17848. (unsigned)sizeof(short),
  17849. (unsigned)sizeof(int),
  17850. (unsigned)sizeof(long),
  17851. (unsigned)sizeof(long long),
  17852. (unsigned)sizeof(float),
  17853. (unsigned)sizeof(double),
  17854. (unsigned)sizeof(long double),
  17855. (unsigned)sizeof(char),
  17856. (unsigned)sizeof(wchar_t),
  17857. (unsigned)sizeof(void *),
  17858. (unsigned)sizeof(size_t),
  17859. (unsigned)sizeof(time_t));
  17860. system_info_length += mg_str_append(&buffer, end, block);
  17861. }
  17862. /* Terminate string */
  17863. if (append_eoobj) {
  17864. strcat(append_eoobj, eoobj);
  17865. }
  17866. system_info_length += sizeof(eoobj) - 1;
  17867. return (int)system_info_length;
  17868. }
  17869. /* Get context information. It can be printed or stored by the caller.
  17870. * Return the size of available information. */
  17871. int
  17872. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17873. {
  17874. #if defined(USE_SERVER_STATS)
  17875. char *end, *append_eoobj = NULL, block[256];
  17876. size_t context_info_length = 0;
  17877. #if defined(_WIN32)
  17878. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17879. #else
  17880. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17881. #endif
  17882. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17883. if ((buffer == NULL) || (buflen < 1)) {
  17884. buflen = 0;
  17885. end = buffer;
  17886. } else {
  17887. *buffer = 0;
  17888. end = buffer + buflen;
  17889. }
  17890. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17891. /* has enough space to append eoobj */
  17892. append_eoobj = buffer;
  17893. end -= sizeof(eoobj) - 1;
  17894. }
  17895. context_info_length += mg_str_append(&buffer, end, "{");
  17896. if (ms) { /* <-- should be always true */
  17897. int blockCount;
  17898. int64_t totalMemUsed, maxMemUsed;
  17899. (void)pthread_mutex_lock(&global_stats_mutex);
  17900. blockCount = ms->blockCount;
  17901. totalMemUsed = ms->totalMemUsed;
  17902. maxMemUsed = ms->maxMemUsed;
  17903. (void)pthread_mutex_unlock(&global_stats_mutex);
  17904. /* Memory information */
  17905. mg_snprintf(NULL,
  17906. NULL,
  17907. block,
  17908. sizeof(block),
  17909. "%s\"memory\" : {%s"
  17910. "\"blocks\" : %i,%s"
  17911. "\"used\" : %" INT64_FMT ",%s"
  17912. "\"maxUsed\" : %" INT64_FMT "%s"
  17913. "}",
  17914. eol,
  17915. eol,
  17916. blockCount,
  17917. eol,
  17918. totalMemUsed,
  17919. eol,
  17920. maxMemUsed,
  17921. eol);
  17922. context_info_length += mg_str_append(&buffer, end, block);
  17923. }
  17924. if (ctx) {
  17925. /* Declare all variables at begin of the block, to comply
  17926. * with old C standards. */
  17927. char start_time_str[64] = {0};
  17928. char now_str[64] = {0};
  17929. time_t start_time = ctx->start_time;
  17930. time_t now = time(NULL);
  17931. int active_connections, max_active_connections;
  17932. int64_t total_connections;
  17933. int64_t total_requests;
  17934. int64_t total_data_read, total_data_written;
  17935. #if !defined(ALTERNATIVE_QUEUE)
  17936. int sq_filled, sq_max_fill, sq_blocked;
  17937. #endif
  17938. (void)pthread_mutex_lock(&global_stats_mutex);
  17939. active_connections = ctx->active_connections;
  17940. max_active_connections = ctx->max_active_connections;
  17941. total_connections = ctx->total_connections;
  17942. total_requests = ctx->total_requests;
  17943. total_data_read = ctx->total_data_read;
  17944. total_data_written = ctx->total_data_written;
  17945. #if !defined(ALTERNATIVE_QUEUE)
  17946. sq_filled = ctx->sq_filled;
  17947. sq_max_fill = ctx->sq_max_fill;
  17948. sq_blocked = ctx->sq_blocked;
  17949. #endif
  17950. (void)pthread_mutex_unlock(&global_stats_mutex);
  17951. /* Connections information */
  17952. mg_snprintf(NULL,
  17953. NULL,
  17954. block,
  17955. sizeof(block),
  17956. ",%s\"connections\" : {%s"
  17957. "\"active\" : %i,%s"
  17958. "\"maxActive\" : %i,%s"
  17959. "\"total\" : %" INT64_FMT "%s"
  17960. "}",
  17961. eol,
  17962. eol,
  17963. active_connections,
  17964. eol,
  17965. max_active_connections,
  17966. eol,
  17967. total_connections,
  17968. eol);
  17969. context_info_length += mg_str_append(&buffer, end, block);
  17970. /* Queue information */
  17971. #if !defined(ALTERNATIVE_QUEUE)
  17972. mg_snprintf(NULL,
  17973. NULL,
  17974. block,
  17975. sizeof(block),
  17976. ",%s\"queue\" : {%s"
  17977. "\"length\" : %i,%s"
  17978. "\"filled\" : %i,%s"
  17979. "\"maxFilled\" : %i,%s"
  17980. "\"full\" : %s%s"
  17981. "}",
  17982. eol,
  17983. eol,
  17984. ctx->sq_size,
  17985. eol,
  17986. sq_filled,
  17987. eol,
  17988. sq_max_fill,
  17989. eol,
  17990. (sq_blocked ? "true" : "false"),
  17991. eol);
  17992. context_info_length += mg_str_append(&buffer, end, block);
  17993. #endif
  17994. /* Requests information */
  17995. mg_snprintf(NULL,
  17996. NULL,
  17997. block,
  17998. sizeof(block),
  17999. ",%s\"requests\" : {%s"
  18000. "\"total\" : %" INT64_FMT "%s"
  18001. "}",
  18002. eol,
  18003. eol,
  18004. total_requests,
  18005. eol);
  18006. context_info_length += mg_str_append(&buffer, end, block);
  18007. /* Data information */
  18008. mg_snprintf(NULL,
  18009. NULL,
  18010. block,
  18011. sizeof(block),
  18012. ",%s\"data\" : {%s"
  18013. "\"read\" : %" INT64_FMT ",%s"
  18014. "\"written\" : %" INT64_FMT "%s"
  18015. "}",
  18016. eol,
  18017. eol,
  18018. total_data_read,
  18019. eol,
  18020. total_data_written,
  18021. eol);
  18022. context_info_length += mg_str_append(&buffer, end, block);
  18023. /* Execution time information */
  18024. gmt_time_string(start_time_str,
  18025. sizeof(start_time_str) - 1,
  18026. &start_time);
  18027. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18028. mg_snprintf(NULL,
  18029. NULL,
  18030. block,
  18031. sizeof(block),
  18032. ",%s\"time\" : {%s"
  18033. "\"uptime\" : %.0f,%s"
  18034. "\"start\" : \"%s\",%s"
  18035. "\"now\" : \"%s\"%s"
  18036. "}",
  18037. eol,
  18038. eol,
  18039. difftime(now, start_time),
  18040. eol,
  18041. start_time_str,
  18042. eol,
  18043. now_str,
  18044. eol);
  18045. context_info_length += mg_str_append(&buffer, end, block);
  18046. }
  18047. /* Terminate string */
  18048. if (append_eoobj) {
  18049. strcat(append_eoobj, eoobj);
  18050. }
  18051. context_info_length += sizeof(eoobj) - 1;
  18052. return (int)context_info_length;
  18053. #else
  18054. (void)ctx;
  18055. if ((buffer != NULL) && (buflen > 0)) {
  18056. *buffer = 0;
  18057. }
  18058. return 0;
  18059. #endif
  18060. }
  18061. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18062. /* Get connection information. It can be printed or stored by the caller.
  18063. * Return the size of available information. */
  18064. int
  18065. mg_get_connection_info(const struct mg_context *ctx,
  18066. int idx,
  18067. char *buffer,
  18068. int buflen)
  18069. {
  18070. const struct mg_connection *conn;
  18071. const struct mg_request_info *ri;
  18072. char *end, *append_eoobj = NULL, block[256];
  18073. size_t connection_info_length = 0;
  18074. int state = 0;
  18075. const char *state_str = "unknown";
  18076. #if defined(_WIN32)
  18077. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18078. #else
  18079. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18080. #endif
  18081. if ((buffer == NULL) || (buflen < 1)) {
  18082. buflen = 0;
  18083. end = buffer;
  18084. } else {
  18085. *buffer = 0;
  18086. end = buffer + buflen;
  18087. }
  18088. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18089. /* has enough space to append eoobj */
  18090. append_eoobj = buffer;
  18091. end -= sizeof(eoobj) - 1;
  18092. }
  18093. if ((ctx == NULL) || (idx < 0)) {
  18094. /* Parameter error */
  18095. return 0;
  18096. }
  18097. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18098. /* Out of range */
  18099. return 0;
  18100. }
  18101. /* Take connection [idx]. This connection is not locked in
  18102. * any way, so some other thread might use it. */
  18103. conn = (ctx->worker_connections) + idx;
  18104. /* Initialize output string */
  18105. connection_info_length += mg_str_append(&buffer, end, "{");
  18106. /* Init variables */
  18107. ri = &(conn->request_info);
  18108. #if defined(USE_SERVER_STATS)
  18109. state = conn->conn_state;
  18110. /* State as string */
  18111. switch (state) {
  18112. case 0:
  18113. state_str = "undefined";
  18114. break;
  18115. case 1:
  18116. state_str = "not used";
  18117. break;
  18118. case 2:
  18119. state_str = "init";
  18120. break;
  18121. case 3:
  18122. state_str = "ready";
  18123. break;
  18124. case 4:
  18125. state_str = "processing";
  18126. break;
  18127. case 5:
  18128. state_str = "processed";
  18129. break;
  18130. case 6:
  18131. state_str = "to close";
  18132. break;
  18133. case 7:
  18134. state_str = "closing";
  18135. break;
  18136. case 8:
  18137. state_str = "closed";
  18138. break;
  18139. case 9:
  18140. state_str = "done";
  18141. break;
  18142. }
  18143. #endif
  18144. /* Connection info */
  18145. if ((state >= 3) && (state < 9)) {
  18146. mg_snprintf(NULL,
  18147. NULL,
  18148. block,
  18149. sizeof(block),
  18150. "%s\"connection\" : {%s"
  18151. "\"remote\" : {%s"
  18152. "\"protocol\" : \"%s\",%s"
  18153. "\"addr\" : \"%s\",%s"
  18154. "\"port\" : %u%s"
  18155. "},%s"
  18156. "\"handled_requests\" : %u%s"
  18157. "}",
  18158. eol,
  18159. eol,
  18160. eol,
  18161. get_proto_name(conn),
  18162. eol,
  18163. ri->remote_addr,
  18164. eol,
  18165. ri->remote_port,
  18166. eol,
  18167. eol,
  18168. conn->handled_requests,
  18169. eol);
  18170. connection_info_length += mg_str_append(&buffer, end, block);
  18171. }
  18172. /* Request info */
  18173. if ((state >= 4) && (state < 6)) {
  18174. mg_snprintf(NULL,
  18175. NULL,
  18176. block,
  18177. sizeof(block),
  18178. "%s%s\"request_info\" : {%s"
  18179. "\"method\" : \"%s\",%s"
  18180. "\"uri\" : \"%s\",%s"
  18181. "\"query\" : %s%s%s%s"
  18182. "}",
  18183. (connection_info_length > 1 ? "," : ""),
  18184. eol,
  18185. eol,
  18186. ri->request_method,
  18187. eol,
  18188. ri->request_uri,
  18189. eol,
  18190. ri->query_string ? "\"" : "",
  18191. ri->query_string ? ri->query_string : "null",
  18192. ri->query_string ? "\"" : "",
  18193. eol);
  18194. connection_info_length += mg_str_append(&buffer, end, block);
  18195. }
  18196. /* Execution time information */
  18197. if ((state >= 2) && (state < 9)) {
  18198. char start_time_str[64] = {0};
  18199. char close_time_str[64] = {0};
  18200. time_t start_time = conn->conn_birth_time;
  18201. time_t close_time = conn->conn_close_time;
  18202. double time_diff;
  18203. gmt_time_string(start_time_str,
  18204. sizeof(start_time_str) - 1,
  18205. &start_time);
  18206. if (close_time != 0) {
  18207. time_diff = difftime(close_time, start_time);
  18208. gmt_time_string(close_time_str,
  18209. sizeof(close_time_str) - 1,
  18210. &close_time);
  18211. } else {
  18212. time_t now = time(NULL);
  18213. time_diff = difftime(now, start_time);
  18214. close_time_str[0] = 0; /* or use "now" ? */
  18215. }
  18216. mg_snprintf(NULL,
  18217. NULL,
  18218. block,
  18219. sizeof(block),
  18220. "%s%s\"time\" : {%s"
  18221. "\"uptime\" : %.0f,%s"
  18222. "\"start\" : \"%s\",%s"
  18223. "\"closed\" : \"%s\"%s"
  18224. "}",
  18225. (connection_info_length > 1 ? "," : ""),
  18226. eol,
  18227. eol,
  18228. time_diff,
  18229. eol,
  18230. start_time_str,
  18231. eol,
  18232. close_time_str,
  18233. eol);
  18234. connection_info_length += mg_str_append(&buffer, end, block);
  18235. }
  18236. /* Remote user name */
  18237. if ((ri->remote_user) && (state < 9)) {
  18238. mg_snprintf(NULL,
  18239. NULL,
  18240. block,
  18241. sizeof(block),
  18242. "%s%s\"user\" : {%s"
  18243. "\"name\" : \"%s\",%s"
  18244. "}",
  18245. (connection_info_length > 1 ? "," : ""),
  18246. eol,
  18247. eol,
  18248. ri->remote_user,
  18249. eol);
  18250. connection_info_length += mg_str_append(&buffer, end, block);
  18251. }
  18252. /* Data block */
  18253. if (state >= 3) {
  18254. mg_snprintf(NULL,
  18255. NULL,
  18256. block,
  18257. sizeof(block),
  18258. "%s%s\"data\" : {%s"
  18259. "\"read\" : %" INT64_FMT ",%s"
  18260. "\"written\" : %" INT64_FMT "%s"
  18261. "}",
  18262. (connection_info_length > 1 ? "," : ""),
  18263. eol,
  18264. eol,
  18265. conn->consumed_content,
  18266. eol,
  18267. conn->num_bytes_sent,
  18268. eol);
  18269. connection_info_length += mg_str_append(&buffer, end, block);
  18270. }
  18271. /* State */
  18272. mg_snprintf(NULL,
  18273. NULL,
  18274. block,
  18275. sizeof(block),
  18276. "%s%s\"state\" : \"%s\"",
  18277. (connection_info_length > 1 ? "," : ""),
  18278. eol,
  18279. state_str);
  18280. connection_info_length += mg_str_append(&buffer, end, block);
  18281. /* Terminate string */
  18282. if (append_eoobj) {
  18283. strcat(append_eoobj, eoobj);
  18284. }
  18285. connection_info_length += sizeof(eoobj) - 1;
  18286. return (int)connection_info_length;
  18287. }
  18288. #endif
  18289. /* Initialize this library. This function does not need to be thread safe.
  18290. */
  18291. unsigned
  18292. mg_init_library(unsigned features)
  18293. {
  18294. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18295. unsigned features_inited = features_to_init;
  18296. if (mg_init_library_called <= 0) {
  18297. /* Not initialized yet */
  18298. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18299. return 0;
  18300. }
  18301. }
  18302. mg_global_lock();
  18303. if (mg_init_library_called <= 0) {
  18304. #if defined(_WIN32)
  18305. int file_mutex_init = 1;
  18306. int wsa = 1;
  18307. #else
  18308. int mutexattr_init = 1;
  18309. #endif
  18310. int failed = 1;
  18311. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18312. if (key_create == 0) {
  18313. #if defined(_WIN32)
  18314. file_mutex_init = pthread_mutex_init(&global_log_file_lock,
  18315. &pthread_mutex_attr);
  18316. if (file_mutex_init == 0) {
  18317. /* Start WinSock */
  18318. WSADATA data;
  18319. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18320. }
  18321. #else
  18322. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18323. if (mutexattr_init == 0) {
  18324. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18325. PTHREAD_MUTEX_RECURSIVE);
  18326. }
  18327. #endif
  18328. }
  18329. #if defined(USE_SERVER_STATS)
  18330. if (failed == 0) {
  18331. failed = pthread_mutex_init(&global_stats_mutex,
  18332. &pthread_mutex_attr);
  18333. }
  18334. #endif
  18335. if (failed) {
  18336. #if defined(_WIN32)
  18337. if (wsa == 0) {
  18338. (void)WSACleanup();
  18339. }
  18340. if (file_mutex_init == 0) {
  18341. (void)pthread_mutex_destroy(&global_log_file_lock);
  18342. }
  18343. #else
  18344. if (mutexattr_init == 0) {
  18345. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18346. }
  18347. #endif
  18348. if (key_create == 0) {
  18349. (void)pthread_key_delete(sTlsKey);
  18350. }
  18351. mg_global_unlock();
  18352. (void)pthread_mutex_destroy(&global_lock_mutex);
  18353. return 0;
  18354. }
  18355. #if defined(USE_LUA)
  18356. lua_init_optional_libraries();
  18357. #endif
  18358. }
  18359. mg_global_unlock();
  18360. #if !defined(NO_SSL)
  18361. if (features_to_init & MG_FEATURES_SSL) {
  18362. if (!mg_ssl_initialized) {
  18363. char ebuf[128];
  18364. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18365. mg_ssl_initialized = 1;
  18366. } else {
  18367. (void)ebuf;
  18368. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18369. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18370. }
  18371. } else {
  18372. /* ssl already initialized */
  18373. }
  18374. }
  18375. #endif
  18376. mg_global_lock();
  18377. if (mg_init_library_called <= 0) {
  18378. mg_init_library_called = 1;
  18379. } else {
  18380. mg_init_library_called++;
  18381. }
  18382. mg_global_unlock();
  18383. return features_inited;
  18384. }
  18385. /* Un-initialize this library. */
  18386. unsigned
  18387. mg_exit_library(void)
  18388. {
  18389. if (mg_init_library_called <= 0) {
  18390. return 0;
  18391. }
  18392. mg_global_lock();
  18393. mg_init_library_called--;
  18394. if (mg_init_library_called == 0) {
  18395. #if !defined(NO_SSL)
  18396. if (mg_ssl_initialized) {
  18397. uninitialize_ssl();
  18398. mg_ssl_initialized = 0;
  18399. }
  18400. #endif
  18401. #if defined(USE_LUA)
  18402. lua_exit_optional_libraries();
  18403. #endif
  18404. #if defined(USE_SERVER_STATS)
  18405. (void)pthread_mutex_destroy(&global_stats_mutex);
  18406. #endif
  18407. #if defined(_WIN32)
  18408. (void)WSACleanup();
  18409. (void)pthread_mutex_destroy(&global_log_file_lock);
  18410. #else
  18411. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18412. #endif
  18413. (void)pthread_key_delete(sTlsKey);
  18414. mg_global_unlock();
  18415. (void)pthread_mutex_destroy(&global_lock_mutex);
  18416. return 1;
  18417. }
  18418. mg_global_unlock();
  18419. return 1;
  18420. }
  18421. /* End of civetweb.c */