civetweb.c 555 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677
  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__)
  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. #else
  209. #define DEBUG_TRACE(fmt, ...) \
  210. do { \
  211. } while (0)
  212. #endif /* DEBUG */
  213. #endif /* DEBUG_TRACE */
  214. #if !defined(DEBUG_ASSERT)
  215. #if defined(DEBUG)
  216. #define DEBUG_ASSERT(cond) \
  217. do { \
  218. if (!(cond)) { \
  219. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  220. exit(2); /* Exit with error */ \
  221. } \
  222. } while (0)
  223. #else
  224. #define DEBUG_ASSERT(cond)
  225. #endif /* DEBUG */
  226. #endif
  227. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  228. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  229. __attribute__((no_instrument_function));
  230. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  231. __attribute__((no_instrument_function));
  232. void
  233. __cyg_profile_func_enter(void *this_fn, void *call_site)
  234. {
  235. if ((void *)this_fn != (void *)printf) {
  236. printf("E %p %p\n", this_fn, call_site);
  237. }
  238. }
  239. void
  240. __cyg_profile_func_exit(void *this_fn, void *call_site)
  241. {
  242. if ((void *)this_fn != (void *)printf) {
  243. printf("X %p %p\n", this_fn, call_site);
  244. }
  245. }
  246. #endif
  247. #if !defined(IGNORE_UNUSED_RESULT)
  248. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  249. #endif
  250. #if defined(__GNUC__) || defined(__MINGW32__)
  251. /* GCC unused function attribute seems fundamentally broken.
  252. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  253. * OR UNUSED" for individual functions failed.
  254. * Either the compiler creates an "unused-function" warning if a
  255. * function is not marked with __attribute__((unused)).
  256. * On the other hand, if the function is marked with this attribute,
  257. * but is used, the compiler raises a completely idiotic
  258. * "used-but-marked-unused" warning - and
  259. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  260. * raises error: unknown option after "#pragma GCC diagnostic".
  261. * Disable this warning completely, until the GCC guys sober up
  262. * again.
  263. */
  264. #pragma GCC diagnostic ignored "-Wunused-function"
  265. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  266. #else
  267. #define FUNCTION_MAY_BE_UNUSED
  268. #endif
  269. /* Some ANSI #includes are not available on Windows CE */
  270. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  271. #include <errno.h>
  272. #include <fcntl.h>
  273. #include <signal.h>
  274. #include <stdlib.h>
  275. #include <sys/stat.h>
  276. #include <sys/types.h>
  277. #endif /* !_WIN32_WCE */
  278. #if defined(__clang__)
  279. /* When using -Weverything, clang does not accept it's own headers
  280. * in a release build configuration. Disable what is too much in
  281. * -Weverything. */
  282. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  283. #endif
  284. #if defined(__GNUC__) || defined(__MINGW32__)
  285. /* Who on earth came to the conclusion, using __DATE__ should rise
  286. * an "expansion of date or time macro is not reproducible"
  287. * warning. That's exactly what was intended by using this macro.
  288. * Just disable this nonsense warning. */
  289. /* And disabling them does not work either:
  290. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  291. * #pragma clang diagnostic ignored "-Wdate-time"
  292. * So we just have to disable ALL warnings for some lines
  293. * of code.
  294. * This seems to be a known GCC bug, not resolved since 2012:
  295. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  296. */
  297. #endif
  298. #if defined(__MACH__) /* Apple OSX section */
  299. #if defined(__clang__)
  300. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  301. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  302. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  303. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  304. #endif
  305. #endif
  306. #define CLOCK_MONOTONIC (1)
  307. #define CLOCK_REALTIME (2)
  308. #include <mach/clock.h>
  309. #include <mach/mach.h>
  310. #include <mach/mach_time.h>
  311. #include <sys/errno.h>
  312. #include <sys/time.h>
  313. /* clock_gettime is not implemented on OSX prior to 10.12 */
  314. static int
  315. _civet_clock_gettime(int clk_id, struct timespec *t)
  316. {
  317. memset(t, 0, sizeof(*t));
  318. if (clk_id == CLOCK_REALTIME) {
  319. struct timeval now;
  320. int rv = gettimeofday(&now, NULL);
  321. if (rv) {
  322. return rv;
  323. }
  324. t->tv_sec = now.tv_sec;
  325. t->tv_nsec = now.tv_usec * 1000;
  326. return 0;
  327. } else if (clk_id == CLOCK_MONOTONIC) {
  328. static uint64_t clock_start_time = 0;
  329. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  330. uint64_t now = mach_absolute_time();
  331. if (clock_start_time == 0) {
  332. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  333. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  334. /* appease "unused variable" warning for release builds */
  335. (void)mach_status;
  336. clock_start_time = now;
  337. }
  338. now = (uint64_t)((double)(now - clock_start_time)
  339. * (double)timebase_ifo.numer
  340. / (double)timebase_ifo.denom);
  341. t->tv_sec = now / 1000000000;
  342. t->tv_nsec = now % 1000000000;
  343. return 0;
  344. }
  345. return -1; /* EINVAL - Clock ID is unknown */
  346. }
  347. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  348. #if defined(__CLOCK_AVAILABILITY)
  349. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  350. * declared but it may be NULL at runtime. So we need to check before using
  351. * it. */
  352. static int
  353. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  354. {
  355. if (clock_gettime) {
  356. return clock_gettime(clk_id, t);
  357. }
  358. return _civet_clock_gettime(clk_id, t);
  359. }
  360. #define clock_gettime _civet_safe_clock_gettime
  361. #else
  362. #define clock_gettime _civet_clock_gettime
  363. #endif
  364. #endif
  365. /********************************************************************/
  366. /* CivetWeb configuration defines */
  367. /********************************************************************/
  368. /* Maximum number of threads that can be configured.
  369. * The number of threads actually created depends on the "num_threads"
  370. * configuration parameter, but this is the upper limit. */
  371. #if !defined(MAX_WORKER_THREADS)
  372. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  373. #endif
  374. /* Timeout interval for select/poll calls.
  375. * The timeouts depend on "*_timeout_ms" configuration values, but long
  376. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  377. * This reduces the time required to stop the server. */
  378. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  379. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  380. #endif
  381. /* Do not try to compress files smaller than this limit. */
  382. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  383. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  384. #endif
  385. #if !defined(PASSWORDS_FILE_NAME)
  386. #define PASSWORDS_FILE_NAME ".htpasswd"
  387. #endif
  388. /* Initial buffer size for all CGI environment variables. In case there is
  389. * not enough space, another block is allocated. */
  390. #if !defined(CGI_ENVIRONMENT_SIZE)
  391. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  392. #endif
  393. /* Maximum number of environment variables. */
  394. #if !defined(MAX_CGI_ENVIR_VARS)
  395. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  396. #endif
  397. /* General purpose buffer size. */
  398. #if !defined(MG_BUF_LEN) /* in bytes */
  399. #define MG_BUF_LEN (1024 * 8)
  400. #endif
  401. /********************************************************************/
  402. /* Helper makros */
  403. #if !defined(ARRAY_SIZE)
  404. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  405. #endif
  406. #include <stdint.h>
  407. /* Standard defines */
  408. #if !defined(INT64_MAX)
  409. #define INT64_MAX (9223372036854775807)
  410. #endif
  411. #define SHUTDOWN_RD (0)
  412. #define SHUTDOWN_WR (1)
  413. #define SHUTDOWN_BOTH (2)
  414. mg_static_assert(MAX_WORKER_THREADS >= 1,
  415. "worker threads must be a positive number");
  416. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  417. "size_t data type size check");
  418. #if defined(_WIN32) /* WINDOWS include block */
  419. #include <malloc.h> /* *alloc( */
  420. #include <stdlib.h> /* *alloc( */
  421. #include <time.h> /* struct timespec */
  422. #include <windows.h>
  423. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  424. #include <ws2tcpip.h>
  425. typedef const char *SOCK_OPT_TYPE;
  426. #if !defined(PATH_MAX)
  427. #define W_PATH_MAX (MAX_PATH)
  428. /* at most three UTF-8 chars per wchar_t */
  429. #define PATH_MAX (W_PATH_MAX * 3)
  430. #else
  431. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  432. #endif
  433. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  434. #if !defined(_IN_PORT_T)
  435. #if !defined(in_port_t)
  436. #define in_port_t u_short
  437. #endif
  438. #endif
  439. #if !defined(_WIN32_WCE)
  440. #include <direct.h>
  441. #include <io.h>
  442. #include <process.h>
  443. #else /* _WIN32_WCE */
  444. #define NO_CGI /* WinCE has no pipes */
  445. #define NO_POPEN /* WinCE has no popen */
  446. typedef long off_t;
  447. #define errno ((int)(GetLastError()))
  448. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  449. #endif /* _WIN32_WCE */
  450. #define MAKEUQUAD(lo, hi) \
  451. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  452. #define RATE_DIFF (10000000) /* 100 nsecs */
  453. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  454. #define SYS2UNIX_TIME(lo, hi) \
  455. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  456. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  457. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  458. * Also use _strtoui64 on modern M$ compilers */
  459. #if defined(_MSC_VER)
  460. #if (_MSC_VER < 1300)
  461. #define STRX(x) #x
  462. #define STR(x) STRX(x)
  463. #define __func__ __FILE__ ":" STR(__LINE__)
  464. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  465. #define strtoll(x, y, z) (_atoi64(x))
  466. #else
  467. #define __func__ __FUNCTION__
  468. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  469. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  470. #endif
  471. #endif /* _MSC_VER */
  472. #define ERRNO ((int)(GetLastError()))
  473. #define NO_SOCKLEN_T
  474. #if defined(_WIN64) || defined(__MINGW64__)
  475. #if !defined(SSL_LIB)
  476. #define SSL_LIB "ssleay64.dll"
  477. #endif
  478. #if !defined(CRYPTO_LIB)
  479. #define CRYPTO_LIB "libeay64.dll"
  480. #endif
  481. #else
  482. #if !defined(SSL_LIB)
  483. #define SSL_LIB "ssleay32.dll"
  484. #endif
  485. #if !defined(CRYPTO_LIB)
  486. #define CRYPTO_LIB "libeay32.dll"
  487. #endif
  488. #endif
  489. #define O_NONBLOCK (0)
  490. #if !defined(W_OK)
  491. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  492. #endif
  493. #define _POSIX_
  494. #define INT64_FMT "I64d"
  495. #define UINT64_FMT "I64u"
  496. #define WINCDECL __cdecl
  497. #define vsnprintf_impl _vsnprintf
  498. #define access _access
  499. #define mg_sleep(x) (Sleep(x))
  500. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  501. #if !defined(popen)
  502. #define popen(x, y) (_popen(x, y))
  503. #endif
  504. #if !defined(pclose)
  505. #define pclose(x) (_pclose(x))
  506. #endif
  507. #define close(x) (_close(x))
  508. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  509. #define RTLD_LAZY (0)
  510. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  511. #define fdopen(x, y) (_fdopen((x), (y)))
  512. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  513. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  514. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  515. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  516. #define sleep(x) (Sleep((x)*1000))
  517. #define rmdir(x) (_rmdir(x))
  518. #if defined(_WIN64) || !defined(__MINGW32__)
  519. /* Only MinGW 32 bit is missing this function */
  520. #define timegm(x) (_mkgmtime(x))
  521. #else
  522. time_t timegm(struct tm *tm);
  523. #define NEED_TIMEGM
  524. #endif
  525. #if !defined(fileno)
  526. #define fileno(x) (_fileno(x))
  527. #endif /* !fileno MINGW #defines fileno */
  528. typedef struct {
  529. CRITICAL_SECTION sec; /* Immovable */
  530. } pthread_mutex_t;
  531. typedef DWORD pthread_key_t;
  532. typedef HANDLE pthread_t;
  533. typedef struct {
  534. pthread_mutex_t threadIdSec;
  535. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  536. } pthread_cond_t;
  537. #if !defined(__clockid_t_defined)
  538. typedef DWORD clockid_t;
  539. #endif
  540. #if !defined(CLOCK_MONOTONIC)
  541. #define CLOCK_MONOTONIC (1)
  542. #endif
  543. #if !defined(CLOCK_REALTIME)
  544. #define CLOCK_REALTIME (2)
  545. #endif
  546. #if !defined(CLOCK_THREAD)
  547. #define CLOCK_THREAD (3)
  548. #endif
  549. #if !defined(CLOCK_PROCESS)
  550. #define CLOCK_PROCESS (4)
  551. #endif
  552. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  553. #define _TIMESPEC_DEFINED
  554. #endif
  555. #if !defined(_TIMESPEC_DEFINED)
  556. struct timespec {
  557. time_t tv_sec; /* seconds */
  558. long tv_nsec; /* nanoseconds */
  559. };
  560. #endif
  561. #if !defined(WIN_PTHREADS_TIME_H)
  562. #define MUST_IMPLEMENT_CLOCK_GETTIME
  563. #endif
  564. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  565. #define clock_gettime mg_clock_gettime
  566. static int
  567. clock_gettime(clockid_t clk_id, struct timespec *tp)
  568. {
  569. FILETIME ft;
  570. ULARGE_INTEGER li, li2;
  571. BOOL ok = FALSE;
  572. double d;
  573. static double perfcnt_per_sec = 0.0;
  574. static BOOL initialized = FALSE;
  575. if (!initialized) {
  576. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  577. perfcnt_per_sec = 1.0 / li.QuadPart;
  578. initialized = TRUE;
  579. }
  580. if (tp) {
  581. memset(tp, 0, sizeof(*tp));
  582. if (clk_id == CLOCK_REALTIME) {
  583. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  584. GetSystemTimeAsFileTime(&ft);
  585. li.LowPart = ft.dwLowDateTime;
  586. li.HighPart = ft.dwHighDateTime;
  587. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  588. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  589. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  590. ok = TRUE;
  591. /* END: CLOCK_REALTIME */
  592. } else if (clk_id == CLOCK_MONOTONIC) {
  593. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  594. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  595. d = li.QuadPart * perfcnt_per_sec;
  596. tp->tv_sec = (time_t)d;
  597. d -= (double)tp->tv_sec;
  598. tp->tv_nsec = (long)(d * 1.0E9);
  599. ok = TRUE;
  600. /* END: CLOCK_MONOTONIC */
  601. } else if (clk_id == CLOCK_THREAD) {
  602. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  603. FILETIME t_create, t_exit, t_kernel, t_user;
  604. if (GetThreadTimes(GetCurrentThread(),
  605. &t_create,
  606. &t_exit,
  607. &t_kernel,
  608. &t_user)) {
  609. li.LowPart = t_user.dwLowDateTime;
  610. li.HighPart = t_user.dwHighDateTime;
  611. li2.LowPart = t_kernel.dwLowDateTime;
  612. li2.HighPart = t_kernel.dwHighDateTime;
  613. li.QuadPart += li2.QuadPart;
  614. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  615. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  616. ok = TRUE;
  617. }
  618. /* END: CLOCK_THREAD */
  619. } else if (clk_id == CLOCK_PROCESS) {
  620. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  621. FILETIME t_create, t_exit, t_kernel, t_user;
  622. if (GetProcessTimes(GetCurrentProcess(),
  623. &t_create,
  624. &t_exit,
  625. &t_kernel,
  626. &t_user)) {
  627. li.LowPart = t_user.dwLowDateTime;
  628. li.HighPart = t_user.dwHighDateTime;
  629. li2.LowPart = t_kernel.dwLowDateTime;
  630. li2.HighPart = t_kernel.dwHighDateTime;
  631. li.QuadPart += li2.QuadPart;
  632. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  633. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  634. ok = TRUE;
  635. }
  636. /* END: CLOCK_PROCESS */
  637. } else {
  638. /* BEGIN: unknown clock */
  639. /* ok = FALSE; already set by init */
  640. /* END: unknown clock */
  641. }
  642. }
  643. return ok ? 0 : -1;
  644. }
  645. #endif
  646. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  647. static int pthread_mutex_lock(pthread_mutex_t *);
  648. static int pthread_mutex_unlock(pthread_mutex_t *);
  649. static void path_to_unicode(const struct mg_connection *conn,
  650. const char *path,
  651. wchar_t *wbuf,
  652. size_t wbuf_len);
  653. /* All file operations need to be rewritten to solve #246. */
  654. struct mg_file;
  655. static const char *
  656. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  657. /* POSIX dirent interface */
  658. struct dirent {
  659. char d_name[PATH_MAX];
  660. };
  661. typedef struct DIR {
  662. HANDLE handle;
  663. WIN32_FIND_DATAW info;
  664. struct dirent result;
  665. } DIR;
  666. #if defined(HAVE_POLL)
  667. #define mg_pollfd pollfd
  668. #else
  669. struct mg_pollfd {
  670. SOCKET fd;
  671. short events;
  672. short revents;
  673. };
  674. #endif
  675. /* Mark required libraries */
  676. #if defined(_MSC_VER)
  677. #pragma comment(lib, "Ws2_32.lib")
  678. #endif
  679. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  680. #include <inttypes.h>
  681. typedef const void *SOCK_OPT_TYPE;
  682. #if defined(ANDROID)
  683. typedef unsigned short int in_port_t;
  684. #endif
  685. #if !defined(__ZEPHYR__)
  686. #include <arpa/inet.h>
  687. #include <ctype.h>
  688. #include <dirent.h>
  689. #include <grp.h>
  690. #include <limits.h>
  691. #include <netdb.h>
  692. #include <netinet/in.h>
  693. #include <netinet/tcp.h>
  694. #include <pthread.h>
  695. #include <pwd.h>
  696. #include <stdarg.h>
  697. #include <stddef.h>
  698. #include <stdio.h>
  699. #include <stdlib.h>
  700. #include <string.h>
  701. #include <sys/poll.h>
  702. #include <sys/socket.h>
  703. #include <sys/time.h>
  704. #include <sys/utsname.h>
  705. #include <sys/wait.h>
  706. #include <time.h>
  707. #include <unistd.h>
  708. #endif
  709. #define vsnprintf_impl vsnprintf
  710. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  711. #include <dlfcn.h>
  712. #endif
  713. #if defined(__MACH__)
  714. #define SSL_LIB "libssl.dylib"
  715. #define CRYPTO_LIB "libcrypto.dylib"
  716. #else
  717. #if !defined(SSL_LIB)
  718. #define SSL_LIB "libssl.so"
  719. #endif
  720. #if !defined(CRYPTO_LIB)
  721. #define CRYPTO_LIB "libcrypto.so"
  722. #endif
  723. #endif
  724. #if !defined(O_BINARY)
  725. #define O_BINARY (0)
  726. #endif /* O_BINARY */
  727. #define closesocket(a) (close(a))
  728. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  729. #define mg_remove(conn, x) (remove(x))
  730. #define mg_sleep(x) (usleep((x)*1000))
  731. #define mg_opendir(conn, x) (opendir(x))
  732. #define mg_closedir(x) (closedir(x))
  733. #define mg_readdir(x) (readdir(x))
  734. #define ERRNO (errno)
  735. #define INVALID_SOCKET (-1)
  736. #define INT64_FMT PRId64
  737. #define UINT64_FMT PRIu64
  738. typedef int SOCKET;
  739. #define WINCDECL
  740. #if defined(__hpux)
  741. /* HPUX 11 does not have monotonic, fall back to realtime */
  742. #if !defined(CLOCK_MONOTONIC)
  743. #define CLOCK_MONOTONIC CLOCK_REALTIME
  744. #endif
  745. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  746. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  747. * the prototypes use int* rather than socklen_t* which matches the
  748. * actual library expectation. When called with the wrong size arg
  749. * accept() returns a zero client inet addr and check_acl() always
  750. * fails. Since socklen_t is widely used below, just force replace
  751. * their typedef with int. - DTL
  752. */
  753. #define socklen_t int
  754. #endif /* hpux */
  755. #define mg_pollfd pollfd
  756. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  757. /* In case our C library is missing "timegm", provide an implementation */
  758. #if defined(NEED_TIMEGM)
  759. static inline int
  760. is_leap(int y)
  761. {
  762. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  763. }
  764. static inline int
  765. count_leap(int y)
  766. {
  767. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  768. }
  769. time_t
  770. timegm(struct tm *tm)
  771. {
  772. static const unsigned short ydays[] = {
  773. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  774. int year = tm->tm_year + 1900;
  775. int mon = tm->tm_mon;
  776. int mday = tm->tm_mday - 1;
  777. int hour = tm->tm_hour;
  778. int min = tm->tm_min;
  779. int sec = tm->tm_sec;
  780. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  781. || (mday >= ydays[mon + 1] - ydays[mon]
  782. + (mon == 1 && is_leap(year) ? 1 : 0))
  783. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  784. return -1;
  785. time_t res = year - 1970;
  786. res *= 365;
  787. res += mday;
  788. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  789. res += count_leap(year);
  790. res *= 24;
  791. res += hour;
  792. res *= 60;
  793. res += min;
  794. res *= 60;
  795. res += sec;
  796. return res;
  797. }
  798. #endif /* NEED_TIMEGM */
  799. /* va_copy should always be a macro, C99 and C++11 - DTL */
  800. #if !defined(va_copy)
  801. #define va_copy(x, y) ((x) = (y))
  802. #endif
  803. #if defined(_WIN32)
  804. /* Create substitutes for POSIX functions in Win32. */
  805. #if defined(GCC_DIAGNOSTIC)
  806. /* Show no warning in case system functions are not used. */
  807. #pragma GCC diagnostic push
  808. #pragma GCC diagnostic ignored "-Wunused-function"
  809. #endif
  810. static pthread_mutex_t global_log_file_lock;
  811. FUNCTION_MAY_BE_UNUSED
  812. static DWORD
  813. pthread_self(void)
  814. {
  815. return GetCurrentThreadId();
  816. }
  817. FUNCTION_MAY_BE_UNUSED
  818. static int
  819. pthread_key_create(
  820. pthread_key_t *key,
  821. void (*_ignored)(void *) /* destructor not supported for Windows */
  822. )
  823. {
  824. (void)_ignored;
  825. if ((key != 0)) {
  826. *key = TlsAlloc();
  827. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  828. }
  829. return -2;
  830. }
  831. FUNCTION_MAY_BE_UNUSED
  832. static int
  833. pthread_key_delete(pthread_key_t key)
  834. {
  835. return TlsFree(key) ? 0 : 1;
  836. }
  837. FUNCTION_MAY_BE_UNUSED
  838. static int
  839. pthread_setspecific(pthread_key_t key, void *value)
  840. {
  841. return TlsSetValue(key, value) ? 0 : 1;
  842. }
  843. FUNCTION_MAY_BE_UNUSED
  844. static void *
  845. pthread_getspecific(pthread_key_t key)
  846. {
  847. return TlsGetValue(key);
  848. }
  849. #if defined(GCC_DIAGNOSTIC)
  850. /* Enable unused function warning again */
  851. #pragma GCC diagnostic pop
  852. #endif
  853. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  854. #else
  855. static pthread_mutexattr_t pthread_mutex_attr;
  856. #endif /* _WIN32 */
  857. #if defined(_WIN32_WCE)
  858. /* Create substitutes for POSIX functions in Win32. */
  859. #if defined(GCC_DIAGNOSTIC)
  860. /* Show no warning in case system functions are not used. */
  861. #pragma GCC diagnostic push
  862. #pragma GCC diagnostic ignored "-Wunused-function"
  863. #endif
  864. FUNCTION_MAY_BE_UNUSED
  865. static time_t
  866. time(time_t *ptime)
  867. {
  868. time_t t;
  869. SYSTEMTIME st;
  870. FILETIME ft;
  871. GetSystemTime(&st);
  872. SystemTimeToFileTime(&st, &ft);
  873. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  874. if (ptime != NULL) {
  875. *ptime = t;
  876. }
  877. return t;
  878. }
  879. FUNCTION_MAY_BE_UNUSED
  880. static struct tm *
  881. localtime_s(const time_t *ptime, struct tm *ptm)
  882. {
  883. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  884. FILETIME ft, lft;
  885. SYSTEMTIME st;
  886. TIME_ZONE_INFORMATION tzinfo;
  887. if (ptm == NULL) {
  888. return NULL;
  889. }
  890. *(int64_t *)&ft = t;
  891. FileTimeToLocalFileTime(&ft, &lft);
  892. FileTimeToSystemTime(&lft, &st);
  893. ptm->tm_year = st.wYear - 1900;
  894. ptm->tm_mon = st.wMonth - 1;
  895. ptm->tm_wday = st.wDayOfWeek;
  896. ptm->tm_mday = st.wDay;
  897. ptm->tm_hour = st.wHour;
  898. ptm->tm_min = st.wMinute;
  899. ptm->tm_sec = st.wSecond;
  900. ptm->tm_yday = 0; /* hope nobody uses this */
  901. ptm->tm_isdst =
  902. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  903. return ptm;
  904. }
  905. FUNCTION_MAY_BE_UNUSED
  906. static struct tm *
  907. gmtime_s(const time_t *ptime, struct tm *ptm)
  908. {
  909. /* FIXME(lsm): fix this. */
  910. return localtime_s(ptime, ptm);
  911. }
  912. static int mg_atomic_inc(volatile int *addr);
  913. static struct tm tm_array[MAX_WORKER_THREADS];
  914. static int tm_index = 0;
  915. FUNCTION_MAY_BE_UNUSED
  916. static struct tm *
  917. localtime(const time_t *ptime)
  918. {
  919. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  920. return localtime_s(ptime, tm_array + i);
  921. }
  922. FUNCTION_MAY_BE_UNUSED
  923. static struct tm *
  924. gmtime(const time_t *ptime)
  925. {
  926. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  927. return gmtime_s(ptime, tm_array + i);
  928. }
  929. FUNCTION_MAY_BE_UNUSED
  930. static size_t
  931. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  932. {
  933. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  934. * for WinCE"); */
  935. return 0;
  936. }
  937. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  938. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  939. #define remove(f) mg_remove(NULL, f)
  940. FUNCTION_MAY_BE_UNUSED
  941. static int
  942. rename(const char *a, const char *b)
  943. {
  944. wchar_t wa[W_PATH_MAX];
  945. wchar_t wb[W_PATH_MAX];
  946. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  947. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  948. return MoveFileW(wa, wb) ? 0 : -1;
  949. }
  950. struct stat {
  951. int64_t st_size;
  952. time_t st_mtime;
  953. };
  954. FUNCTION_MAY_BE_UNUSED
  955. static int
  956. stat(const char *name, struct stat *st)
  957. {
  958. wchar_t wbuf[W_PATH_MAX];
  959. WIN32_FILE_ATTRIBUTE_DATA attr;
  960. time_t creation_time, write_time;
  961. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  962. memset(&attr, 0, sizeof(attr));
  963. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  964. st->st_size =
  965. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  966. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  967. attr.ftLastWriteTime.dwHighDateTime);
  968. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  969. attr.ftCreationTime.dwHighDateTime);
  970. if (creation_time > write_time) {
  971. st->st_mtime = creation_time;
  972. } else {
  973. st->st_mtime = write_time;
  974. }
  975. return 0;
  976. }
  977. #define access(x, a) 1 /* not required anyway */
  978. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  979. /* Values from errno.h in Windows SDK (Visual Studio). */
  980. #define EEXIST 17
  981. #define EACCES 13
  982. #define ENOENT 2
  983. #if defined(GCC_DIAGNOSTIC)
  984. /* Enable unused function warning again */
  985. #pragma GCC diagnostic pop
  986. #endif
  987. #endif /* defined(_WIN32_WCE) */
  988. #if defined(GCC_DIAGNOSTIC)
  989. /* Show no warning in case system functions are not used. */
  990. #pragma GCC diagnostic push
  991. #pragma GCC diagnostic ignored "-Wunused-function"
  992. #endif /* defined(GCC_DIAGNOSTIC) */
  993. #if defined(__clang__)
  994. /* Show no warning in case system functions are not used. */
  995. #pragma clang diagnostic push
  996. #pragma clang diagnostic ignored "-Wunused-function"
  997. #endif
  998. static pthread_mutex_t global_lock_mutex;
  999. FUNCTION_MAY_BE_UNUSED
  1000. static void
  1001. mg_global_lock(void)
  1002. {
  1003. (void)pthread_mutex_lock(&global_lock_mutex);
  1004. }
  1005. FUNCTION_MAY_BE_UNUSED
  1006. static void
  1007. mg_global_unlock(void)
  1008. {
  1009. (void)pthread_mutex_unlock(&global_lock_mutex);
  1010. }
  1011. FUNCTION_MAY_BE_UNUSED
  1012. static int
  1013. mg_atomic_inc(volatile int *addr)
  1014. {
  1015. int ret;
  1016. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1017. /* Depending on the SDK, this function uses either
  1018. * (volatile unsigned int *) or (volatile LONG *),
  1019. * so whatever you use, the other SDK is likely to raise a warning. */
  1020. ret = InterlockedIncrement((volatile long *)addr);
  1021. #elif defined(__GNUC__) \
  1022. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1023. && !defined(NO_ATOMICS)
  1024. ret = __sync_add_and_fetch(addr, 1);
  1025. #else
  1026. mg_global_lock();
  1027. ret = (++(*addr));
  1028. mg_global_unlock();
  1029. #endif
  1030. return ret;
  1031. }
  1032. FUNCTION_MAY_BE_UNUSED
  1033. static int
  1034. mg_atomic_dec(volatile int *addr)
  1035. {
  1036. int ret;
  1037. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1038. /* Depending on the SDK, this function uses either
  1039. * (volatile unsigned int *) or (volatile LONG *),
  1040. * so whatever you use, the other SDK is likely to raise a warning. */
  1041. ret = InterlockedDecrement((volatile long *)addr);
  1042. #elif defined(__GNUC__) \
  1043. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1044. && !defined(NO_ATOMICS)
  1045. ret = __sync_sub_and_fetch(addr, 1);
  1046. #else
  1047. mg_global_lock();
  1048. ret = (--(*addr));
  1049. mg_global_unlock();
  1050. #endif
  1051. return ret;
  1052. }
  1053. #if defined(USE_SERVER_STATS)
  1054. static int64_t
  1055. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1056. {
  1057. int64_t ret;
  1058. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1059. ret = InterlockedAdd64(addr, value);
  1060. #elif defined(__GNUC__) \
  1061. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1062. && !defined(NO_ATOMICS)
  1063. ret = __sync_add_and_fetch(addr, value);
  1064. #else
  1065. mg_global_lock();
  1066. *addr += value;
  1067. ret = (*addr);
  1068. mg_global_unlock();
  1069. #endif
  1070. return ret;
  1071. }
  1072. #endif
  1073. #if defined(GCC_DIAGNOSTIC)
  1074. /* Show no warning in case system functions are not used. */
  1075. #pragma GCC diagnostic pop
  1076. #endif /* defined(GCC_DIAGNOSTIC) */
  1077. #if defined(__clang__)
  1078. /* Show no warning in case system functions are not used. */
  1079. #pragma clang diagnostic pop
  1080. #endif
  1081. #if defined(USE_SERVER_STATS)
  1082. struct mg_memory_stat {
  1083. volatile int64_t totalMemUsed;
  1084. volatile int64_t maxMemUsed;
  1085. volatile int blockCount;
  1086. };
  1087. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1088. static void *
  1089. mg_malloc_ex(size_t size,
  1090. struct mg_context *ctx,
  1091. const char *file,
  1092. unsigned line)
  1093. {
  1094. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1095. void *memory = 0;
  1096. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1097. #if defined(MEMORY_DEBUGGING)
  1098. char mallocStr[256];
  1099. #else
  1100. (void)file;
  1101. (void)line;
  1102. #endif
  1103. if (data) {
  1104. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1105. if (mmem > mstat->maxMemUsed) {
  1106. /* could use atomic compare exchange, but this
  1107. * seems overkill for statistics data */
  1108. mstat->maxMemUsed = mmem;
  1109. }
  1110. mg_atomic_inc(&mstat->blockCount);
  1111. ((uintptr_t *)data)[0] = size;
  1112. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1113. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1114. }
  1115. #if defined(MEMORY_DEBUGGING)
  1116. sprintf(mallocStr,
  1117. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1118. memory,
  1119. (unsigned long)size,
  1120. (unsigned long)mstat->totalMemUsed,
  1121. (unsigned long)mstat->blockCount,
  1122. file,
  1123. line);
  1124. #if defined(_WIN32)
  1125. OutputDebugStringA(mallocStr);
  1126. #else
  1127. DEBUG_TRACE("%s", mallocStr);
  1128. #endif
  1129. #endif
  1130. return memory;
  1131. }
  1132. static void *
  1133. mg_calloc_ex(size_t count,
  1134. size_t size,
  1135. struct mg_context *ctx,
  1136. const char *file,
  1137. unsigned line)
  1138. {
  1139. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1140. if (data) {
  1141. memset(data, 0, size * count);
  1142. }
  1143. return data;
  1144. }
  1145. static void
  1146. mg_free_ex(void *memory, const char *file, unsigned line)
  1147. {
  1148. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1149. #if defined(MEMORY_DEBUGGING)
  1150. char mallocStr[256];
  1151. #else
  1152. (void)file;
  1153. (void)line;
  1154. #endif
  1155. if (memory) {
  1156. uintptr_t size = ((uintptr_t *)data)[0];
  1157. struct mg_memory_stat *mstat =
  1158. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1159. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1160. mg_atomic_dec(&mstat->blockCount);
  1161. #if defined(MEMORY_DEBUGGING)
  1162. sprintf(mallocStr,
  1163. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1164. memory,
  1165. (unsigned long)size,
  1166. (unsigned long)mstat->totalMemUsed,
  1167. (unsigned long)mstat->blockCount,
  1168. file,
  1169. line);
  1170. #if defined(_WIN32)
  1171. OutputDebugStringA(mallocStr);
  1172. #else
  1173. DEBUG_TRACE("%s", mallocStr);
  1174. #endif
  1175. #endif
  1176. free(data);
  1177. }
  1178. }
  1179. static void *
  1180. mg_realloc_ex(void *memory,
  1181. size_t newsize,
  1182. struct mg_context *ctx,
  1183. const char *file,
  1184. unsigned line)
  1185. {
  1186. void *data;
  1187. void *_realloc;
  1188. uintptr_t oldsize;
  1189. #if defined(MEMORY_DEBUGGING)
  1190. char mallocStr[256];
  1191. #else
  1192. (void)file;
  1193. (void)line;
  1194. #endif
  1195. if (newsize) {
  1196. if (memory) {
  1197. /* Reallocate existing block */
  1198. struct mg_memory_stat *mstat;
  1199. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1200. oldsize = ((uintptr_t *)data)[0];
  1201. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1202. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1203. if (_realloc) {
  1204. data = _realloc;
  1205. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1206. #if defined(MEMORY_DEBUGGING)
  1207. sprintf(mallocStr,
  1208. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1209. memory,
  1210. (unsigned long)oldsize,
  1211. (unsigned long)mstat->totalMemUsed,
  1212. (unsigned long)mstat->blockCount,
  1213. file,
  1214. line);
  1215. #if defined(_WIN32)
  1216. OutputDebugStringA(mallocStr);
  1217. #else
  1218. DEBUG_TRACE("%s", mallocStr);
  1219. #endif
  1220. #endif
  1221. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1222. #if defined(MEMORY_DEBUGGING)
  1223. sprintf(mallocStr,
  1224. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1225. memory,
  1226. (unsigned long)newsize,
  1227. (unsigned long)mstat->totalMemUsed,
  1228. (unsigned long)mstat->blockCount,
  1229. file,
  1230. line);
  1231. #if defined(_WIN32)
  1232. OutputDebugStringA(mallocStr);
  1233. #else
  1234. DEBUG_TRACE("%s", mallocStr);
  1235. #endif
  1236. #endif
  1237. *(uintptr_t *)data = newsize;
  1238. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1239. } else {
  1240. #if defined(MEMORY_DEBUGGING)
  1241. #if defined(_WIN32)
  1242. OutputDebugStringA("MEM: realloc failed\n");
  1243. #else
  1244. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1245. #endif
  1246. #endif
  1247. return _realloc;
  1248. }
  1249. } else {
  1250. /* Allocate new block */
  1251. data = mg_malloc_ex(newsize, ctx, file, line);
  1252. }
  1253. } else {
  1254. /* Free existing block */
  1255. data = 0;
  1256. mg_free_ex(memory, file, line);
  1257. }
  1258. return data;
  1259. }
  1260. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1261. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1262. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1263. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1264. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1265. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1266. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1267. #else /* USE_SERVER_STATS */
  1268. static __inline void *
  1269. mg_malloc(size_t a)
  1270. {
  1271. return malloc(a);
  1272. }
  1273. static __inline void *
  1274. mg_calloc(size_t a, size_t b)
  1275. {
  1276. return calloc(a, b);
  1277. }
  1278. static __inline void *
  1279. mg_realloc(void *a, size_t b)
  1280. {
  1281. return realloc(a, b);
  1282. }
  1283. static __inline void
  1284. mg_free(void *a)
  1285. {
  1286. free(a);
  1287. }
  1288. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1289. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1290. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1291. #define mg_free_ctx(a, c) mg_free(a)
  1292. #endif /* USE_SERVER_STATS */
  1293. static void mg_vsnprintf(const struct mg_connection *conn,
  1294. int *truncated,
  1295. char *buf,
  1296. size_t buflen,
  1297. const char *fmt,
  1298. va_list ap);
  1299. static void mg_snprintf(const struct mg_connection *conn,
  1300. int *truncated,
  1301. char *buf,
  1302. size_t buflen,
  1303. PRINTF_FORMAT_STRING(const char *fmt),
  1304. ...) PRINTF_ARGS(5, 6);
  1305. /* This following lines are just meant as a reminder to use the mg-functions
  1306. * for memory management */
  1307. #if defined(malloc)
  1308. #undef malloc
  1309. #endif
  1310. #if defined(calloc)
  1311. #undef calloc
  1312. #endif
  1313. #if defined(realloc)
  1314. #undef realloc
  1315. #endif
  1316. #if defined(free)
  1317. #undef free
  1318. #endif
  1319. #if defined(snprintf)
  1320. #undef snprintf
  1321. #endif
  1322. #if defined(vsnprintf)
  1323. #undef vsnprintf
  1324. #endif
  1325. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1326. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1327. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1328. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1329. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1330. #if defined(_WIN32)
  1331. /* vsnprintf must not be used in any system,
  1332. * but this define only works well for Windows. */
  1333. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1334. #endif
  1335. /* mg_init_library counter */
  1336. static int mg_init_library_called = 0;
  1337. #if !defined(NO_SSL)
  1338. static int mg_ssl_initialized = 0;
  1339. #endif
  1340. static pthread_key_t sTlsKey; /* Thread local storage index */
  1341. static int thread_idx_max = 0;
  1342. #if defined(MG_LEGACY_INTERFACE)
  1343. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1344. #endif
  1345. struct mg_workerTLS {
  1346. int is_master;
  1347. unsigned long thread_idx;
  1348. void *user_ptr;
  1349. #if defined(_WIN32)
  1350. HANDLE pthread_cond_helper_mutex;
  1351. struct mg_workerTLS *next_waiting_thread;
  1352. #endif
  1353. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1354. char txtbuf[4];
  1355. #endif
  1356. };
  1357. #if defined(GCC_DIAGNOSTIC)
  1358. /* Show no warning in case system functions are not used. */
  1359. #pragma GCC diagnostic push
  1360. #pragma GCC diagnostic ignored "-Wunused-function"
  1361. #endif /* defined(GCC_DIAGNOSTIC) */
  1362. #if defined(__clang__)
  1363. /* Show no warning in case system functions are not used. */
  1364. #pragma clang diagnostic push
  1365. #pragma clang diagnostic ignored "-Wunused-function"
  1366. #endif
  1367. /* Get a unique thread ID as unsigned long, independent from the data type
  1368. * of thread IDs defined by the operating system API.
  1369. * If two calls to mg_current_thread_id return the same value, they calls
  1370. * are done from the same thread. If they return different values, they are
  1371. * done from different threads. (Provided this function is used in the same
  1372. * process context and threads are not repeatedly created and deleted, but
  1373. * CivetWeb does not do that).
  1374. * This function must match the signature required for SSL id callbacks:
  1375. * CRYPTO_set_id_callback
  1376. */
  1377. FUNCTION_MAY_BE_UNUSED
  1378. static unsigned long
  1379. mg_current_thread_id(void)
  1380. {
  1381. #if defined(_WIN32)
  1382. return GetCurrentThreadId();
  1383. #else
  1384. #if defined(__clang__)
  1385. #pragma clang diagnostic push
  1386. #pragma clang diagnostic ignored "-Wunreachable-code"
  1387. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1388. * or not, so one of the two conditions will be unreachable by construction.
  1389. * Unfortunately the C standard does not define a way to check this at
  1390. * compile time, since the #if preprocessor conditions can not use the sizeof
  1391. * operator as an argument. */
  1392. #endif
  1393. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1394. /* This is the problematic case for CRYPTO_set_id_callback:
  1395. * The OS pthread_t can not be cast to unsigned long. */
  1396. struct mg_workerTLS *tls =
  1397. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1398. if (tls == NULL) {
  1399. /* SSL called from an unknown thread: Create some thread index.
  1400. */
  1401. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1402. tls->is_master = -2; /* -2 means "3rd party thread" */
  1403. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1404. pthread_setspecific(sTlsKey, tls);
  1405. }
  1406. return tls->thread_idx;
  1407. } else {
  1408. /* pthread_t may be any data type, so a simple cast to unsigned long
  1409. * can rise a warning/error, depending on the platform.
  1410. * Here memcpy is used as an anything-to-anything cast. */
  1411. unsigned long ret = 0;
  1412. pthread_t t = pthread_self();
  1413. memcpy(&ret, &t, sizeof(pthread_t));
  1414. return ret;
  1415. }
  1416. #if defined(__clang__)
  1417. #pragma clang diagnostic pop
  1418. #endif
  1419. #endif
  1420. }
  1421. FUNCTION_MAY_BE_UNUSED
  1422. static uint64_t
  1423. mg_get_current_time_ns(void)
  1424. {
  1425. struct timespec tsnow;
  1426. clock_gettime(CLOCK_REALTIME, &tsnow);
  1427. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1428. }
  1429. #if defined(GCC_DIAGNOSTIC)
  1430. /* Show no warning in case system functions are not used. */
  1431. #pragma GCC diagnostic pop
  1432. #endif /* defined(GCC_DIAGNOSTIC) */
  1433. #if defined(__clang__)
  1434. /* Show no warning in case system functions are not used. */
  1435. #pragma clang diagnostic pop
  1436. #endif
  1437. #if defined(NEED_DEBUG_TRACE_FUNC)
  1438. static void
  1439. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1440. {
  1441. va_list args;
  1442. uint64_t nsnow;
  1443. static uint64_t nslast;
  1444. struct timespec tsnow;
  1445. /* Get some operating system independent thread id */
  1446. unsigned long thread_id = mg_current_thread_id();
  1447. clock_gettime(CLOCK_REALTIME, &tsnow);
  1448. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1449. + ((uint64_t)tsnow.tv_nsec);
  1450. if (!nslast) {
  1451. nslast = nsnow;
  1452. }
  1453. flockfile(stdout);
  1454. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1455. (unsigned long)tsnow.tv_sec,
  1456. (unsigned long)tsnow.tv_nsec,
  1457. nsnow - nslast,
  1458. thread_id,
  1459. func,
  1460. line);
  1461. va_start(args, fmt);
  1462. vprintf(fmt, args);
  1463. va_end(args);
  1464. putchar('\n');
  1465. fflush(stdout);
  1466. funlockfile(stdout);
  1467. nslast = nsnow;
  1468. }
  1469. #endif /* NEED_DEBUG_TRACE_FUNC */
  1470. #define MD5_STATIC static
  1471. #include "md5.inl"
  1472. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1473. #if defined(NO_SOCKLEN_T)
  1474. typedef int socklen_t;
  1475. #endif /* NO_SOCKLEN_T */
  1476. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1477. #if !defined(MSG_NOSIGNAL)
  1478. #define MSG_NOSIGNAL (0)
  1479. #endif
  1480. #if defined(NO_SSL)
  1481. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1482. typedef struct SSL_CTX SSL_CTX;
  1483. #else
  1484. #if defined(NO_SSL_DL)
  1485. #include <openssl/bn.h>
  1486. #include <openssl/conf.h>
  1487. #include <openssl/crypto.h>
  1488. #include <openssl/dh.h>
  1489. #include <openssl/engine.h>
  1490. #include <openssl/err.h>
  1491. #include <openssl/opensslv.h>
  1492. #include <openssl/pem.h>
  1493. #include <openssl/ssl.h>
  1494. #include <openssl/tls1.h>
  1495. #include <openssl/x509.h>
  1496. #if defined(WOLFSSL_VERSION)
  1497. /* Additional defines for WolfSSL, see
  1498. * https://github.com/civetweb/civetweb/issues/583 */
  1499. #include "wolfssl_extras.inl"
  1500. #endif
  1501. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1502. /* If OpenSSL headers are included, automatically select the API version */
  1503. #if !defined(OPENSSL_API_1_1)
  1504. #define OPENSSL_API_1_1
  1505. #endif
  1506. #define OPENSSL_REMOVE_THREAD_STATE()
  1507. #else
  1508. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1509. #endif
  1510. #else
  1511. /* SSL loaded dynamically from DLL.
  1512. * I put the prototypes here to be independent from OpenSSL source
  1513. * installation. */
  1514. typedef struct ssl_st SSL;
  1515. typedef struct ssl_method_st SSL_METHOD;
  1516. typedef struct ssl_ctx_st SSL_CTX;
  1517. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1518. typedef struct x509_name X509_NAME;
  1519. typedef struct asn1_integer ASN1_INTEGER;
  1520. typedef struct bignum BIGNUM;
  1521. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1522. typedef struct evp_md EVP_MD;
  1523. typedef struct x509 X509;
  1524. #define SSL_CTRL_OPTIONS (32)
  1525. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1526. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1527. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1528. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1529. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1530. #define SSL_VERIFY_NONE (0)
  1531. #define SSL_VERIFY_PEER (1)
  1532. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1533. #define SSL_VERIFY_CLIENT_ONCE (4)
  1534. #define SSL_OP_ALL (0x80000BFFul)
  1535. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1536. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1537. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1538. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1539. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1540. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1541. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1542. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1543. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1544. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1545. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1546. #define SSL_CB_HANDSHAKE_START (0x10)
  1547. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1548. #define SSL_ERROR_NONE (0)
  1549. #define SSL_ERROR_SSL (1)
  1550. #define SSL_ERROR_WANT_READ (2)
  1551. #define SSL_ERROR_WANT_WRITE (3)
  1552. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1553. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1554. #define SSL_ERROR_ZERO_RETURN (6)
  1555. #define SSL_ERROR_WANT_CONNECT (7)
  1556. #define SSL_ERROR_WANT_ACCEPT (8)
  1557. #define TLSEXT_TYPE_server_name (0)
  1558. #define TLSEXT_NAMETYPE_host_name (0)
  1559. #define SSL_TLSEXT_ERR_OK (0)
  1560. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1561. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1562. #define SSL_TLSEXT_ERR_NOACK (3)
  1563. struct ssl_func {
  1564. const char *name; /* SSL function name */
  1565. void (*ptr)(void); /* Function pointer */
  1566. };
  1567. #if defined(OPENSSL_API_1_1)
  1568. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1569. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1570. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1571. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1572. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1573. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1574. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1575. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1576. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1577. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1578. #define OPENSSL_init_ssl \
  1579. (*(int (*)(uint64_t opts, \
  1580. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1581. .ptr)
  1582. #define SSL_CTX_use_PrivateKey_file \
  1583. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1584. #define SSL_CTX_use_certificate_file \
  1585. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1586. #define SSL_CTX_set_default_passwd_cb \
  1587. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1588. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1589. #define SSL_CTX_use_certificate_chain_file \
  1590. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1591. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1592. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1593. #define SSL_CTX_set_verify \
  1594. (*(void (*)(SSL_CTX *, \
  1595. int, \
  1596. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1597. .ptr)
  1598. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1599. #define SSL_CTX_load_verify_locations \
  1600. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1601. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1602. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1603. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1604. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1605. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1606. #define SSL_CIPHER_get_name \
  1607. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1608. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1609. #define SSL_CTX_set_session_id_context \
  1610. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1611. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1612. #define SSL_CTX_set_cipher_list \
  1613. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1614. #define SSL_CTX_set_options \
  1615. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1616. #define SSL_CTX_set_info_callback \
  1617. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1618. ssl_sw[32] \
  1619. .ptr)
  1620. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1621. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1622. #define SSL_CTX_callback_ctrl \
  1623. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1624. #define SSL_get_servername \
  1625. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1626. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1627. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1628. #define SSL_CTX_clear_options(ctx, op) \
  1629. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1630. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1631. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1632. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1633. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1634. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1635. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1636. SSL_CTX_callback_ctrl(ctx, \
  1637. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1638. (void (*)(void))cb)
  1639. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1640. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1641. #define SSL_set_tlsext_host_name(ctx, arg) \
  1642. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1643. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1644. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1645. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1646. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1647. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1648. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1649. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1650. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1651. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1652. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1653. #define X509_NAME_oneline \
  1654. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1655. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1656. #define EVP_get_digestbyname \
  1657. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1658. #define EVP_Digest \
  1659. (*(int (*)( \
  1660. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1661. crypto_sw[9] \
  1662. .ptr)
  1663. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1664. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1665. #define ASN1_INTEGER_to_BN \
  1666. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1667. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1668. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1669. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1670. #define OPENSSL_free(a) CRYPTO_free(a)
  1671. #define OPENSSL_REMOVE_THREAD_STATE()
  1672. /* init_ssl_ctx() function updates this array.
  1673. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1674. * of respective functions. The macros above (like SSL_connect()) are really
  1675. * just calling these functions indirectly via the pointer. */
  1676. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1677. {"SSL_accept", NULL},
  1678. {"SSL_connect", NULL},
  1679. {"SSL_read", NULL},
  1680. {"SSL_write", NULL},
  1681. {"SSL_get_error", NULL},
  1682. {"SSL_set_fd", NULL},
  1683. {"SSL_new", NULL},
  1684. {"SSL_CTX_new", NULL},
  1685. {"TLS_server_method", NULL},
  1686. {"OPENSSL_init_ssl", NULL},
  1687. {"SSL_CTX_use_PrivateKey_file", NULL},
  1688. {"SSL_CTX_use_certificate_file", NULL},
  1689. {"SSL_CTX_set_default_passwd_cb", NULL},
  1690. {"SSL_CTX_free", NULL},
  1691. {"SSL_CTX_use_certificate_chain_file", NULL},
  1692. {"TLS_client_method", NULL},
  1693. {"SSL_pending", NULL},
  1694. {"SSL_CTX_set_verify", NULL},
  1695. {"SSL_shutdown", NULL},
  1696. {"SSL_CTX_load_verify_locations", NULL},
  1697. {"SSL_CTX_set_default_verify_paths", NULL},
  1698. {"SSL_CTX_set_verify_depth", NULL},
  1699. {"SSL_get_peer_certificate", NULL},
  1700. {"SSL_get_version", NULL},
  1701. {"SSL_get_current_cipher", NULL},
  1702. {"SSL_CIPHER_get_name", NULL},
  1703. {"SSL_CTX_check_private_key", NULL},
  1704. {"SSL_CTX_set_session_id_context", NULL},
  1705. {"SSL_CTX_ctrl", NULL},
  1706. {"SSL_CTX_set_cipher_list", NULL},
  1707. {"SSL_CTX_set_options", NULL},
  1708. {"SSL_CTX_set_info_callback", NULL},
  1709. {"SSL_get_ex_data", NULL},
  1710. {"SSL_set_ex_data", NULL},
  1711. {"SSL_CTX_callback_ctrl", NULL},
  1712. {"SSL_get_servername", NULL},
  1713. {"SSL_set_SSL_CTX", NULL},
  1714. {"SSL_ctrl", NULL},
  1715. {NULL, NULL}};
  1716. /* Similar array as ssl_sw. These functions could be located in different
  1717. * lib. */
  1718. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1719. {"ERR_error_string", NULL},
  1720. {"CONF_modules_unload", NULL},
  1721. {"X509_free", NULL},
  1722. {"X509_get_subject_name", NULL},
  1723. {"X509_get_issuer_name", NULL},
  1724. {"X509_NAME_oneline", NULL},
  1725. {"X509_get_serialNumber", NULL},
  1726. {"EVP_get_digestbyname", NULL},
  1727. {"EVP_Digest", NULL},
  1728. {"i2d_X509", NULL},
  1729. {"BN_bn2hex", NULL},
  1730. {"ASN1_INTEGER_to_BN", NULL},
  1731. {"BN_free", NULL},
  1732. {"CRYPTO_free", NULL},
  1733. {"ERR_clear_error", NULL},
  1734. {NULL, NULL}};
  1735. #else
  1736. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1737. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1738. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1739. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1740. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1741. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1742. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1743. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1744. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1745. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1746. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1747. #define SSL_CTX_use_PrivateKey_file \
  1748. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1749. #define SSL_CTX_use_certificate_file \
  1750. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1751. #define SSL_CTX_set_default_passwd_cb \
  1752. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1753. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1754. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1755. #define SSL_CTX_use_certificate_chain_file \
  1756. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1757. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1758. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1759. #define SSL_CTX_set_verify \
  1760. (*(void (*)(SSL_CTX *, \
  1761. int, \
  1762. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1763. .ptr)
  1764. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1765. #define SSL_CTX_load_verify_locations \
  1766. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1767. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1768. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1769. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1770. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1771. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1772. #define SSL_CIPHER_get_name \
  1773. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1774. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1775. #define SSL_CTX_set_session_id_context \
  1776. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1777. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1778. #define SSL_CTX_set_cipher_list \
  1779. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1780. #define SSL_CTX_set_info_callback \
  1781. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1782. .ptr)
  1783. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1784. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1785. #define SSL_CTX_callback_ctrl \
  1786. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1787. #define SSL_get_servername \
  1788. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1789. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1790. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1791. #define SSL_CTX_set_options(ctx, op) \
  1792. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1793. #define SSL_CTX_clear_options(ctx, op) \
  1794. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1795. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1796. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1797. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1798. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1799. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1800. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1801. SSL_CTX_callback_ctrl(ctx, \
  1802. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1803. (void (*)(void))cb)
  1804. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1805. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1806. #define SSL_set_tlsext_host_name(ctx, arg) \
  1807. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1808. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1809. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1810. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1811. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1812. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1813. #define CRYPTO_set_locking_callback \
  1814. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1815. #define CRYPTO_set_id_callback \
  1816. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1817. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1818. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1819. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1820. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1821. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1822. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1823. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1824. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1825. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1826. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1827. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1828. #define X509_NAME_oneline \
  1829. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1830. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1831. #define i2c_ASN1_INTEGER \
  1832. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1833. #define EVP_get_digestbyname \
  1834. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1835. #define EVP_Digest \
  1836. (*(int (*)( \
  1837. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1838. crypto_sw[18] \
  1839. .ptr)
  1840. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1841. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1842. #define ASN1_INTEGER_to_BN \
  1843. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1844. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1845. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1846. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1847. #define OPENSSL_free(a) CRYPTO_free(a)
  1848. /* use here ERR_remove_state,
  1849. * while on some platforms function is not included into library due to
  1850. * deprication */
  1851. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1852. /* init_ssl_ctx() function updates this array.
  1853. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1854. * of respective functions. The macros above (like SSL_connect()) are really
  1855. * just calling these functions indirectly via the pointer. */
  1856. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1857. {"SSL_accept", NULL},
  1858. {"SSL_connect", NULL},
  1859. {"SSL_read", NULL},
  1860. {"SSL_write", NULL},
  1861. {"SSL_get_error", NULL},
  1862. {"SSL_set_fd", NULL},
  1863. {"SSL_new", NULL},
  1864. {"SSL_CTX_new", NULL},
  1865. {"SSLv23_server_method", NULL},
  1866. {"SSL_library_init", NULL},
  1867. {"SSL_CTX_use_PrivateKey_file", NULL},
  1868. {"SSL_CTX_use_certificate_file", NULL},
  1869. {"SSL_CTX_set_default_passwd_cb", NULL},
  1870. {"SSL_CTX_free", NULL},
  1871. {"SSL_load_error_strings", NULL},
  1872. {"SSL_CTX_use_certificate_chain_file", NULL},
  1873. {"SSLv23_client_method", NULL},
  1874. {"SSL_pending", NULL},
  1875. {"SSL_CTX_set_verify", NULL},
  1876. {"SSL_shutdown", NULL},
  1877. {"SSL_CTX_load_verify_locations", NULL},
  1878. {"SSL_CTX_set_default_verify_paths", NULL},
  1879. {"SSL_CTX_set_verify_depth", NULL},
  1880. {"SSL_get_peer_certificate", NULL},
  1881. {"SSL_get_version", NULL},
  1882. {"SSL_get_current_cipher", NULL},
  1883. {"SSL_CIPHER_get_name", NULL},
  1884. {"SSL_CTX_check_private_key", NULL},
  1885. {"SSL_CTX_set_session_id_context", NULL},
  1886. {"SSL_CTX_ctrl", NULL},
  1887. {"SSL_CTX_set_cipher_list", NULL},
  1888. {"SSL_CTX_set_info_callback", NULL},
  1889. {"SSL_get_ex_data", NULL},
  1890. {"SSL_set_ex_data", NULL},
  1891. {"SSL_CTX_callback_ctrl", NULL},
  1892. {"SSL_get_servername", NULL},
  1893. {"SSL_set_SSL_CTX", NULL},
  1894. {"SSL_ctrl", NULL},
  1895. {NULL, NULL}};
  1896. /* Similar array as ssl_sw. These functions could be located in different
  1897. * lib. */
  1898. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1899. {"CRYPTO_set_locking_callback", NULL},
  1900. {"CRYPTO_set_id_callback", NULL},
  1901. {"ERR_get_error", NULL},
  1902. {"ERR_error_string", NULL},
  1903. {"ERR_remove_state", NULL},
  1904. {"ERR_free_strings", NULL},
  1905. {"ENGINE_cleanup", NULL},
  1906. {"CONF_modules_unload", NULL},
  1907. {"CRYPTO_cleanup_all_ex_data", NULL},
  1908. {"EVP_cleanup", NULL},
  1909. {"X509_free", NULL},
  1910. {"X509_get_subject_name", NULL},
  1911. {"X509_get_issuer_name", NULL},
  1912. {"X509_NAME_oneline", NULL},
  1913. {"X509_get_serialNumber", NULL},
  1914. {"i2c_ASN1_INTEGER", NULL},
  1915. {"EVP_get_digestbyname", NULL},
  1916. {"EVP_Digest", NULL},
  1917. {"i2d_X509", NULL},
  1918. {"BN_bn2hex", NULL},
  1919. {"ASN1_INTEGER_to_BN", NULL},
  1920. {"BN_free", NULL},
  1921. {"CRYPTO_free", NULL},
  1922. {"ERR_clear_error", NULL},
  1923. {NULL, NULL}};
  1924. #endif /* OPENSSL_API_1_1 */
  1925. #endif /* NO_SSL_DL */
  1926. #endif /* NO_SSL */
  1927. #if !defined(NO_CACHING)
  1928. static const char month_names[][4] = {"Jan",
  1929. "Feb",
  1930. "Mar",
  1931. "Apr",
  1932. "May",
  1933. "Jun",
  1934. "Jul",
  1935. "Aug",
  1936. "Sep",
  1937. "Oct",
  1938. "Nov",
  1939. "Dec"};
  1940. #endif /* !NO_CACHING */
  1941. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1942. * the
  1943. * union u. */
  1944. union usa {
  1945. struct sockaddr sa;
  1946. struct sockaddr_in sin;
  1947. #if defined(USE_IPV6)
  1948. struct sockaddr_in6 sin6;
  1949. #endif
  1950. };
  1951. /* Describes a string (chunk of memory). */
  1952. struct vec {
  1953. const char *ptr;
  1954. size_t len;
  1955. };
  1956. struct mg_file_stat {
  1957. /* File properties filled by mg_stat: */
  1958. uint64_t size;
  1959. time_t last_modified;
  1960. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1961. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1962. * case we need a "Content-Eencoding: gzip" header */
  1963. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1964. };
  1965. struct mg_file_in_memory {
  1966. char *p;
  1967. uint32_t pos;
  1968. char mode;
  1969. };
  1970. struct mg_file_access {
  1971. /* File properties filled by mg_fopen: */
  1972. FILE *fp;
  1973. #if defined(MG_USE_OPEN_FILE)
  1974. /* TODO (low): Remove obsolete "file in memory" implementation.
  1975. * In an "early 2017" discussion at Google groups
  1976. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1977. * we decided to get rid of this feature (after some fade-out
  1978. * phase). */
  1979. const char *membuf;
  1980. #endif
  1981. };
  1982. struct mg_file {
  1983. struct mg_file_stat stat;
  1984. struct mg_file_access access;
  1985. };
  1986. #if defined(MG_USE_OPEN_FILE)
  1987. #define STRUCT_FILE_INITIALIZER \
  1988. { \
  1989. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1990. { \
  1991. (FILE *)NULL, (const char *)NULL \
  1992. } \
  1993. }
  1994. #else
  1995. #define STRUCT_FILE_INITIALIZER \
  1996. { \
  1997. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1998. { \
  1999. (FILE *)NULL \
  2000. } \
  2001. }
  2002. #endif
  2003. /* Describes listening socket, or socket which was accept()-ed by the master
  2004. * thread and queued for future handling by the worker thread. */
  2005. struct socket {
  2006. SOCKET sock; /* Listening socket */
  2007. union usa lsa; /* Local socket address */
  2008. union usa rsa; /* Remote socket address */
  2009. unsigned char is_ssl; /* Is port SSL-ed */
  2010. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2011. * port */
  2012. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2013. };
  2014. /* Enum const for all options must be in sync with
  2015. * static struct mg_option config_options[]
  2016. * This is tested in the unit test (test/private.c)
  2017. * "Private Config Options"
  2018. */
  2019. enum {
  2020. /* Once for each server */
  2021. LISTENING_PORTS,
  2022. NUM_THREADS,
  2023. RUN_AS_USER,
  2024. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2025. * socket option typedef TCP_NODELAY. */
  2026. MAX_REQUEST_SIZE,
  2027. LINGER_TIMEOUT,
  2028. CONNECTION_QUEUE_SIZE,
  2029. MAX_CONNECTIONS,
  2030. #if defined(__linux__)
  2031. ALLOW_SENDFILE_CALL,
  2032. #endif
  2033. #if defined(_WIN32)
  2034. CASE_SENSITIVE_FILES,
  2035. #endif
  2036. THROTTLE,
  2037. ACCESS_LOG_FILE,
  2038. ERROR_LOG_FILE,
  2039. ENABLE_KEEP_ALIVE,
  2040. REQUEST_TIMEOUT,
  2041. KEEP_ALIVE_TIMEOUT,
  2042. #if defined(USE_WEBSOCKET)
  2043. WEBSOCKET_TIMEOUT,
  2044. ENABLE_WEBSOCKET_PING_PONG,
  2045. #endif
  2046. DECODE_URL,
  2047. #if defined(USE_LUA)
  2048. LUA_BACKGROUND_SCRIPT,
  2049. LUA_BACKGROUND_SCRIPT_PARAMS,
  2050. #endif
  2051. #if defined(USE_TIMERS)
  2052. CGI_TIMEOUT,
  2053. #endif
  2054. /* Once for each domain */
  2055. DOCUMENT_ROOT,
  2056. CGI_EXTENSIONS,
  2057. CGI_ENVIRONMENT,
  2058. PUT_DELETE_PASSWORDS_FILE,
  2059. CGI_INTERPRETER,
  2060. PROTECT_URI,
  2061. AUTHENTICATION_DOMAIN,
  2062. ENABLE_AUTH_DOMAIN_CHECK,
  2063. SSI_EXTENSIONS,
  2064. ENABLE_DIRECTORY_LISTING,
  2065. GLOBAL_PASSWORDS_FILE,
  2066. INDEX_FILES,
  2067. ACCESS_CONTROL_LIST,
  2068. EXTRA_MIME_TYPES,
  2069. SSL_CERTIFICATE,
  2070. SSL_CERTIFICATE_CHAIN,
  2071. URL_REWRITE_PATTERN,
  2072. HIDE_FILES,
  2073. SSL_DO_VERIFY_PEER,
  2074. SSL_CA_PATH,
  2075. SSL_CA_FILE,
  2076. SSL_VERIFY_DEPTH,
  2077. SSL_DEFAULT_VERIFY_PATHS,
  2078. SSL_CIPHER_LIST,
  2079. SSL_PROTOCOL_VERSION,
  2080. SSL_SHORT_TRUST,
  2081. #if defined(USE_LUA)
  2082. LUA_PRELOAD_FILE,
  2083. LUA_SCRIPT_EXTENSIONS,
  2084. LUA_SERVER_PAGE_EXTENSIONS,
  2085. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2086. LUA_DEBUG_PARAMS,
  2087. #endif
  2088. #endif
  2089. #if defined(USE_DUKTAPE)
  2090. DUKTAPE_SCRIPT_EXTENSIONS,
  2091. #endif
  2092. #if defined(USE_WEBSOCKET)
  2093. WEBSOCKET_ROOT,
  2094. #endif
  2095. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2096. LUA_WEBSOCKET_EXTENSIONS,
  2097. #endif
  2098. ACCESS_CONTROL_ALLOW_ORIGIN,
  2099. ACCESS_CONTROL_ALLOW_METHODS,
  2100. ACCESS_CONTROL_ALLOW_HEADERS,
  2101. ERROR_PAGES,
  2102. #if !defined(NO_CACHING)
  2103. STATIC_FILE_MAX_AGE,
  2104. STATIC_FILE_CACHE_CONTROL,
  2105. #endif
  2106. #if !defined(NO_SSL)
  2107. STRICT_HTTPS_MAX_AGE,
  2108. #endif
  2109. ADDITIONAL_HEADER,
  2110. ALLOW_INDEX_SCRIPT_SUB_RES,
  2111. #if defined(DAEMONIZE)
  2112. ENABLE_DAEMONIZE,
  2113. #endif
  2114. NUM_OPTIONS
  2115. };
  2116. /* Config option name, config types, default value.
  2117. * Must be in the same order as the enum const above.
  2118. */
  2119. static const struct mg_option config_options[] = {
  2120. /* Once for each server */
  2121. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2122. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2123. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2124. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2125. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2126. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2127. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2128. {"max_connections", MG_CONFIG_TYPE_NUMBER, "100"},
  2129. #if defined(__linux__)
  2130. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2131. #endif
  2132. #if defined(_WIN32)
  2133. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2134. #endif
  2135. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2136. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2137. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2138. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2139. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2140. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2141. #if defined(USE_WEBSOCKET)
  2142. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2143. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2144. #endif
  2145. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2146. #if defined(USE_LUA)
  2147. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2148. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2149. #endif
  2150. #if defined(USE_TIMERS)
  2151. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2152. #endif
  2153. /* Once for each domain */
  2154. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2155. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2156. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2157. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2158. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2159. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2160. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2161. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2162. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2163. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2164. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2165. {"index_files",
  2166. MG_CONFIG_TYPE_STRING_LIST,
  2167. #if defined(USE_LUA)
  2168. "index.xhtml,index.html,index.htm,"
  2169. "index.lp,index.lsp,index.lua,index.cgi,"
  2170. "index.shtml,index.php"},
  2171. #else
  2172. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2173. #endif
  2174. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2175. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2176. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2177. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2178. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2179. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2180. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2181. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2182. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2183. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2184. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2185. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2186. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2187. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2188. #if defined(USE_LUA)
  2189. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2190. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2191. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2192. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2193. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2194. #endif
  2195. #endif
  2196. #if defined(USE_DUKTAPE)
  2197. /* The support for duktape is still in alpha version state.
  2198. * The name of this config option might change. */
  2199. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2200. #endif
  2201. #if defined(USE_WEBSOCKET)
  2202. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2203. #endif
  2204. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2205. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2206. #endif
  2207. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2208. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2209. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2210. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2211. #if !defined(NO_CACHING)
  2212. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2213. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2214. #endif
  2215. #if !defined(NO_SSL)
  2216. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2217. #endif
  2218. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2219. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2220. #if defined(DAEMONIZE)
  2221. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2222. #endif
  2223. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2224. /* Check if the config_options and the corresponding enum have compatible
  2225. * sizes. */
  2226. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2227. == (NUM_OPTIONS + 1),
  2228. "config_options and enum not sync");
  2229. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2230. struct mg_handler_info {
  2231. /* Name/Pattern of the URI. */
  2232. char *uri;
  2233. size_t uri_len;
  2234. /* handler type */
  2235. int handler_type;
  2236. /* Handler for http/https or authorization requests. */
  2237. mg_request_handler handler;
  2238. unsigned int refcount;
  2239. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2240. pthread_cond_t
  2241. refcount_cond; /* Signaled when handler refcount is decremented */
  2242. /* Handler for ws/wss (websocket) requests. */
  2243. mg_websocket_connect_handler connect_handler;
  2244. mg_websocket_ready_handler ready_handler;
  2245. mg_websocket_data_handler data_handler;
  2246. mg_websocket_close_handler close_handler;
  2247. /* accepted subprotocols for ws/wss requests. */
  2248. struct mg_websocket_subprotocols *subprotocols;
  2249. /* Handler for authorization requests */
  2250. mg_authorization_handler auth_handler;
  2251. /* User supplied argument for the handler function. */
  2252. void *cbdata;
  2253. /* next handler in a linked list */
  2254. struct mg_handler_info *next;
  2255. };
  2256. enum {
  2257. CONTEXT_INVALID,
  2258. CONTEXT_SERVER,
  2259. CONTEXT_HTTP_CLIENT,
  2260. CONTEXT_WS_CLIENT
  2261. };
  2262. struct mg_domain_context {
  2263. SSL_CTX *ssl_ctx; /* SSL context */
  2264. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2265. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2266. /* Server nonce */
  2267. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2268. unsigned long nonce_count; /* Used nonces, used for authentication */
  2269. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2270. /* linked list of shared lua websockets */
  2271. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2272. #endif
  2273. /* Linked list of domains */
  2274. struct mg_domain_context *next;
  2275. };
  2276. struct mg_context {
  2277. /* Part 1 - Physical context:
  2278. * This holds threads, ports, timeouts, ...
  2279. * set for the entire server, independent from the
  2280. * addressed hostname.
  2281. */
  2282. /* Connection related */
  2283. int context_type; /* See CONTEXT_* above */
  2284. struct socket *listening_sockets;
  2285. struct mg_pollfd *listening_socket_fds;
  2286. unsigned int num_listening_sockets;
  2287. struct mg_connection *worker_connections; /* The connection struct, pre-
  2288. * allocated for each worker */
  2289. #if defined(USE_SERVER_STATS)
  2290. int active_connections;
  2291. int max_active_connections;
  2292. int64_t total_connections;
  2293. int64_t total_requests;
  2294. int64_t total_data_read;
  2295. int64_t total_data_written;
  2296. #endif
  2297. /* Thread related */
  2298. volatile int stop_flag; /* Should we stop event loop */
  2299. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2300. pthread_t masterthreadid; /* The master thread ID */
  2301. unsigned int
  2302. cfg_worker_threads; /* The number of configured worker threads. */
  2303. pthread_t *worker_threadids; /* The worker thread IDs */
  2304. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2305. /* Connection to thread dispatching */
  2306. #if defined(ALTERNATIVE_QUEUE)
  2307. struct socket *client_socks;
  2308. void **client_wait_events;
  2309. #else
  2310. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2311. worker thread */
  2312. volatile int sq_head; /* Head of the socket queue */
  2313. volatile int sq_tail; /* Tail of the socket queue */
  2314. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2315. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2316. volatile int sq_blocked; /* Status information: sq is full */
  2317. int sq_size; /* No of elements in socket queue */
  2318. #if defined(USE_SERVER_STATS)
  2319. int sq_max_fill;
  2320. #endif /* USE_SERVER_STATS */
  2321. #endif /* ALTERNATIVE_QUEUE */
  2322. /* Memory related */
  2323. unsigned int max_request_size; /* The max request size */
  2324. #if defined(USE_SERVER_STATS)
  2325. struct mg_memory_stat ctx_memory;
  2326. #endif
  2327. /* Operating system related */
  2328. char *systemName; /* What operating system is running */
  2329. time_t start_time; /* Server start time, used for authentication
  2330. * and for diagnstics. */
  2331. #if defined(USE_TIMERS)
  2332. struct ttimers *timers;
  2333. #endif
  2334. /* Lua specific: Background operations and shared websockets */
  2335. #if defined(USE_LUA)
  2336. void *lua_background_state;
  2337. #endif
  2338. /* Server nonce */
  2339. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2340. /* Server callbacks */
  2341. struct mg_callbacks callbacks; /* User-defined callback function */
  2342. void *user_data; /* User-defined data */
  2343. /* Part 2 - Logical domain:
  2344. * This holds hostname, TLS certificate, document root, ...
  2345. * set for a domain hosted at the server.
  2346. * There may be multiple domains hosted at one physical server.
  2347. * The default domain "dd" is the first element of a list of
  2348. * domains.
  2349. */
  2350. struct mg_domain_context dd; /* default domain */
  2351. };
  2352. #if defined(USE_SERVER_STATS)
  2353. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2354. static struct mg_memory_stat *
  2355. get_memory_stat(struct mg_context *ctx)
  2356. {
  2357. if (ctx) {
  2358. return &(ctx->ctx_memory);
  2359. }
  2360. return &mg_common_memory;
  2361. }
  2362. #endif
  2363. enum {
  2364. CONNECTION_TYPE_INVALID,
  2365. CONNECTION_TYPE_REQUEST,
  2366. CONNECTION_TYPE_RESPONSE
  2367. };
  2368. struct mg_connection {
  2369. int connection_type; /* see CONNECTION_TYPE_* above */
  2370. struct mg_request_info request_info;
  2371. struct mg_response_info response_info;
  2372. struct mg_context *phys_ctx;
  2373. struct mg_domain_context *dom_ctx;
  2374. #if defined(USE_SERVER_STATS)
  2375. int conn_state; /* 0 = undef, numerical value may change in different
  2376. * versions. For the current definition, see
  2377. * mg_get_connection_info_impl */
  2378. #endif
  2379. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2380. SSL *ssl; /* SSL descriptor */
  2381. struct socket client; /* Connected client */
  2382. time_t conn_birth_time; /* Time (wall clock) when connection was
  2383. * established */
  2384. #if defined(USE_SERVER_STATS)
  2385. time_t conn_close_time; /* Time (wall clock) when connection was
  2386. * closed (or 0 if still open) */
  2387. #endif
  2388. struct timespec req_time; /* Time (since system start) when the request
  2389. * was received */
  2390. int64_t num_bytes_sent; /* Total bytes sent to client */
  2391. int64_t content_len; /* How many bytes of content can be read
  2392. * !is_chunked: Content-Length header value
  2393. * or -1 (until connection closed,
  2394. * not allowed for a request)
  2395. * is_chunked: >= 0, appended gradually
  2396. */
  2397. int64_t consumed_content; /* How many bytes of content have been read */
  2398. int is_chunked; /* Transfer-Encoding is chunked:
  2399. * 0 = not chunked,
  2400. * 1 = chunked, not yet, or some data read,
  2401. * 2 = chunked, has error,
  2402. * 3 = chunked, all data read except trailer,
  2403. * 4 = chunked, all data read
  2404. */
  2405. char *buf; /* Buffer for received data */
  2406. char *path_info; /* PATH_INFO part of the URL */
  2407. int must_close; /* 1 if connection must be closed */
  2408. int accept_gzip; /* 1 if gzip encoding is accepted */
  2409. int in_error_handler; /* 1 if in handler for user defined error
  2410. * pages */
  2411. #if defined(USE_WEBSOCKET)
  2412. int in_websocket_handling; /* 1 if in read_websocket */
  2413. #endif
  2414. int handled_requests; /* Number of requests handled by this connection
  2415. */
  2416. int buf_size; /* Buffer size */
  2417. int request_len; /* Size of the request + headers in a buffer */
  2418. int data_len; /* Total size of data in a buffer */
  2419. int status_code; /* HTTP reply status code, e.g. 200 */
  2420. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2421. * throttle */
  2422. time_t last_throttle_time; /* Last time throttled data was sent */
  2423. int last_throttle_bytes; /* Bytes sent this second */
  2424. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2425. * atomic transmissions for websockets */
  2426. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2427. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2428. #endif
  2429. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2430. * for quick access */
  2431. };
  2432. /* Directory entry */
  2433. struct de {
  2434. struct mg_connection *conn;
  2435. char *file_name;
  2436. struct mg_file_stat file;
  2437. };
  2438. #if defined(USE_WEBSOCKET)
  2439. static int is_websocket_protocol(const struct mg_connection *conn);
  2440. #else
  2441. #define is_websocket_protocol(conn) (0)
  2442. #endif
  2443. #define mg_cry_internal(conn, fmt, ...) \
  2444. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2445. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2446. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2447. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2448. struct mg_context *ctx,
  2449. const char *func,
  2450. unsigned line,
  2451. const char *fmt,
  2452. ...) PRINTF_ARGS(5, 6);
  2453. #if !defined(NO_THREAD_NAME)
  2454. #if defined(_WIN32) && defined(_MSC_VER)
  2455. /* Set the thread name for debugging purposes in Visual Studio
  2456. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2457. */
  2458. #pragma pack(push, 8)
  2459. typedef struct tagTHREADNAME_INFO {
  2460. DWORD dwType; /* Must be 0x1000. */
  2461. LPCSTR szName; /* Pointer to name (in user addr space). */
  2462. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2463. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2464. } THREADNAME_INFO;
  2465. #pragma pack(pop)
  2466. #elif defined(__linux__)
  2467. #include <sys/prctl.h>
  2468. #include <sys/sendfile.h>
  2469. #if defined(ALTERNATIVE_QUEUE)
  2470. #include <sys/eventfd.h>
  2471. #endif /* ALTERNATIVE_QUEUE */
  2472. #if defined(ALTERNATIVE_QUEUE)
  2473. static void *
  2474. event_create(void)
  2475. {
  2476. int evhdl = eventfd(0, EFD_CLOEXEC);
  2477. int *ret;
  2478. if (evhdl == -1) {
  2479. /* Linux uses -1 on error, Windows NULL. */
  2480. /* However, Linux does not return 0 on success either. */
  2481. return 0;
  2482. }
  2483. ret = (int *)mg_malloc(sizeof(int));
  2484. if (ret) {
  2485. *ret = evhdl;
  2486. } else {
  2487. (void)close(evhdl);
  2488. }
  2489. return (void *)ret;
  2490. }
  2491. static int
  2492. event_wait(void *eventhdl)
  2493. {
  2494. uint64_t u;
  2495. int evhdl, s;
  2496. if (!eventhdl) {
  2497. /* error */
  2498. return 0;
  2499. }
  2500. evhdl = *(int *)eventhdl;
  2501. s = (int)read(evhdl, &u, sizeof(u));
  2502. if (s != sizeof(u)) {
  2503. /* error */
  2504. return 0;
  2505. }
  2506. (void)u; /* the value is not required */
  2507. return 1;
  2508. }
  2509. static int
  2510. event_signal(void *eventhdl)
  2511. {
  2512. uint64_t u = 1;
  2513. int evhdl, s;
  2514. if (!eventhdl) {
  2515. /* error */
  2516. return 0;
  2517. }
  2518. evhdl = *(int *)eventhdl;
  2519. s = (int)write(evhdl, &u, sizeof(u));
  2520. if (s != sizeof(u)) {
  2521. /* error */
  2522. return 0;
  2523. }
  2524. return 1;
  2525. }
  2526. static void
  2527. event_destroy(void *eventhdl)
  2528. {
  2529. int evhdl;
  2530. if (!eventhdl) {
  2531. /* error */
  2532. return;
  2533. }
  2534. evhdl = *(int *)eventhdl;
  2535. close(evhdl);
  2536. mg_free(eventhdl);
  2537. }
  2538. #endif
  2539. #endif
  2540. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2541. struct posix_event {
  2542. pthread_mutex_t mutex;
  2543. pthread_cond_t cond;
  2544. int signaled;
  2545. };
  2546. static void *
  2547. event_create(void)
  2548. {
  2549. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2550. if (ret == 0) {
  2551. /* out of memory */
  2552. return 0;
  2553. }
  2554. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2555. /* pthread mutex not available */
  2556. mg_free(ret);
  2557. return 0;
  2558. }
  2559. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2560. /* pthread cond not available */
  2561. pthread_mutex_destroy(&(ret->mutex));
  2562. mg_free(ret);
  2563. return 0;
  2564. }
  2565. ret->signaled = 0;
  2566. return (void *)ret;
  2567. }
  2568. static int
  2569. event_wait(void *eventhdl)
  2570. {
  2571. struct posix_event *ev = (struct posix_event *)eventhdl;
  2572. pthread_mutex_lock(&(ev->mutex));
  2573. while (!ev->signaled) {
  2574. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2575. }
  2576. ev->signaled = 0;
  2577. pthread_mutex_unlock(&(ev->mutex));
  2578. return 1;
  2579. }
  2580. static int
  2581. event_signal(void *eventhdl)
  2582. {
  2583. struct posix_event *ev = (struct posix_event *)eventhdl;
  2584. pthread_mutex_lock(&(ev->mutex));
  2585. pthread_cond_signal(&(ev->cond));
  2586. ev->signaled = 1;
  2587. pthread_mutex_unlock(&(ev->mutex));
  2588. return 1;
  2589. }
  2590. static void
  2591. event_destroy(void *eventhdl)
  2592. {
  2593. struct posix_event *ev = (struct posix_event *)eventhdl;
  2594. pthread_cond_destroy(&(ev->cond));
  2595. pthread_mutex_destroy(&(ev->mutex));
  2596. mg_free(ev);
  2597. }
  2598. #endif
  2599. static void
  2600. mg_set_thread_name(const char *name)
  2601. {
  2602. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2603. mg_snprintf(
  2604. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2605. #if defined(_WIN32)
  2606. #if defined(_MSC_VER)
  2607. /* Windows and Visual Studio Compiler */
  2608. __try {
  2609. THREADNAME_INFO info;
  2610. info.dwType = 0x1000;
  2611. info.szName = threadName;
  2612. info.dwThreadID = ~0U;
  2613. info.dwFlags = 0;
  2614. RaiseException(0x406D1388,
  2615. 0,
  2616. sizeof(info) / sizeof(ULONG_PTR),
  2617. (ULONG_PTR *)&info);
  2618. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2619. }
  2620. #elif defined(__MINGW32__)
  2621. /* No option known to set thread name for MinGW known */
  2622. #endif
  2623. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2624. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2625. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2626. #if defined(__MACH__)
  2627. /* OS X only current thread name can be changed */
  2628. (void)pthread_setname_np(threadName);
  2629. #else
  2630. (void)pthread_setname_np(pthread_self(), threadName);
  2631. #endif
  2632. #elif defined(__linux__)
  2633. /* On Linux we can use the prctl function.
  2634. * When building for Linux Standard Base (LSB) use
  2635. * NO_THREAD_NAME. However, thread names are a big
  2636. * help for debugging, so the stadard is to set them.
  2637. */
  2638. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2639. #endif
  2640. }
  2641. #else /* !defined(NO_THREAD_NAME) */
  2642. void
  2643. mg_set_thread_name(const char *threadName)
  2644. {
  2645. }
  2646. #endif
  2647. #if defined(MG_LEGACY_INTERFACE)
  2648. const char **
  2649. mg_get_valid_option_names(void)
  2650. {
  2651. /* This function is deprecated. Use mg_get_valid_options instead. */
  2652. static const char
  2653. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2654. int i;
  2655. for (i = 0; config_options[i].name != NULL; i++) {
  2656. data[i * 2] = config_options[i].name;
  2657. data[i * 2 + 1] = config_options[i].default_value;
  2658. }
  2659. return data;
  2660. }
  2661. #endif
  2662. const struct mg_option *
  2663. mg_get_valid_options(void)
  2664. {
  2665. return config_options;
  2666. }
  2667. /* Do not open file (used in is_file_in_memory) */
  2668. #define MG_FOPEN_MODE_NONE (0)
  2669. /* Open file for read only access */
  2670. #define MG_FOPEN_MODE_READ (1)
  2671. /* Open file for writing, create and overwrite */
  2672. #define MG_FOPEN_MODE_WRITE (2)
  2673. /* Open file for writing, create and append */
  2674. #define MG_FOPEN_MODE_APPEND (4)
  2675. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2676. * output filep and return 1, otherwise return 0 and don't modify anything.
  2677. */
  2678. static int
  2679. open_file_in_memory(const struct mg_connection *conn,
  2680. const char *path,
  2681. struct mg_file *filep,
  2682. int mode)
  2683. {
  2684. #if defined(MG_USE_OPEN_FILE)
  2685. size_t size = 0;
  2686. const char *buf = NULL;
  2687. if (!conn) {
  2688. return 0;
  2689. }
  2690. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2691. return 0;
  2692. }
  2693. if (conn->phys_ctx->callbacks.open_file) {
  2694. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2695. if (buf != NULL) {
  2696. if (filep == NULL) {
  2697. /* This is a file in memory, but we cannot store the
  2698. * properties
  2699. * now.
  2700. * Called from "is_file_in_memory" function. */
  2701. return 1;
  2702. }
  2703. /* NOTE: override filep->size only on success. Otherwise, it
  2704. * might
  2705. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2706. filep->access.membuf = buf;
  2707. filep->access.fp = NULL;
  2708. /* Size was set by the callback */
  2709. filep->stat.size = size;
  2710. /* Assume the data may change during runtime by setting
  2711. * last_modified = now */
  2712. filep->stat.last_modified = time(NULL);
  2713. filep->stat.is_directory = 0;
  2714. filep->stat.is_gzipped = 0;
  2715. }
  2716. }
  2717. return (buf != NULL);
  2718. #else
  2719. (void)conn;
  2720. (void)path;
  2721. (void)filep;
  2722. (void)mode;
  2723. return 0;
  2724. #endif
  2725. }
  2726. static int
  2727. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2728. {
  2729. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2730. }
  2731. static int
  2732. is_file_opened(const struct mg_file_access *fileacc)
  2733. {
  2734. if (!fileacc) {
  2735. return 0;
  2736. }
  2737. #if defined(MG_USE_OPEN_FILE)
  2738. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2739. #else
  2740. return (fileacc->fp != NULL);
  2741. #endif
  2742. }
  2743. #if !defined(NO_FILESYSTEMS)
  2744. static int mg_stat(const struct mg_connection *conn,
  2745. const char *path,
  2746. struct mg_file_stat *filep);
  2747. /* mg_fopen will open a file either in memory or on the disk.
  2748. * The input parameter path is a string in UTF-8 encoding.
  2749. * The input parameter mode is MG_FOPEN_MODE_*
  2750. * On success, either fp or membuf will be set in the output
  2751. * struct file. All status members will also be set.
  2752. * The function returns 1 on success, 0 on error. */
  2753. static int
  2754. mg_fopen(const struct mg_connection *conn,
  2755. const char *path,
  2756. int mode,
  2757. struct mg_file *filep)
  2758. {
  2759. int found;
  2760. if (!filep) {
  2761. return 0;
  2762. }
  2763. filep->access.fp = NULL;
  2764. #if defined(MG_USE_OPEN_FILE)
  2765. filep->access.membuf = NULL;
  2766. #endif
  2767. if (!is_file_in_memory(conn, path)) {
  2768. /* filep is initialized in mg_stat: all fields with memset to,
  2769. * some fields like size and modification date with values */
  2770. found = mg_stat(conn, path, &(filep->stat));
  2771. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2772. /* file does not exist and will not be created */
  2773. return 0;
  2774. }
  2775. #if defined(_WIN32)
  2776. {
  2777. wchar_t wbuf[W_PATH_MAX];
  2778. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2779. switch (mode) {
  2780. case MG_FOPEN_MODE_READ:
  2781. filep->access.fp = _wfopen(wbuf, L"rb");
  2782. break;
  2783. case MG_FOPEN_MODE_WRITE:
  2784. filep->access.fp = _wfopen(wbuf, L"wb");
  2785. break;
  2786. case MG_FOPEN_MODE_APPEND:
  2787. filep->access.fp = _wfopen(wbuf, L"ab");
  2788. break;
  2789. }
  2790. }
  2791. #else
  2792. /* Linux et al already use unicode. No need to convert. */
  2793. switch (mode) {
  2794. case MG_FOPEN_MODE_READ:
  2795. filep->access.fp = fopen(path, "r");
  2796. break;
  2797. case MG_FOPEN_MODE_WRITE:
  2798. filep->access.fp = fopen(path, "w");
  2799. break;
  2800. case MG_FOPEN_MODE_APPEND:
  2801. filep->access.fp = fopen(path, "a");
  2802. break;
  2803. }
  2804. #endif
  2805. if (!found) {
  2806. /* File did not exist before fopen was called.
  2807. * Maybe it has been created now. Get stat info
  2808. * like creation time now. */
  2809. found = mg_stat(conn, path, &(filep->stat));
  2810. (void)found;
  2811. }
  2812. /* file is on disk */
  2813. return (filep->access.fp != NULL);
  2814. } else {
  2815. #if defined(MG_USE_OPEN_FILE)
  2816. /* is_file_in_memory returned true */
  2817. if (open_file_in_memory(conn, path, filep, mode)) {
  2818. /* file is in memory */
  2819. return (filep->access.membuf != NULL);
  2820. }
  2821. #endif
  2822. }
  2823. /* Open failed */
  2824. return 0;
  2825. }
  2826. /* return 0 on success, just like fclose */
  2827. static int
  2828. mg_fclose(struct mg_file_access *fileacc)
  2829. {
  2830. int ret = -1;
  2831. if (fileacc != NULL) {
  2832. if (fileacc->fp != NULL) {
  2833. ret = fclose(fileacc->fp);
  2834. #if defined(MG_USE_OPEN_FILE)
  2835. } else if (fileacc->membuf != NULL) {
  2836. ret = 0;
  2837. #endif
  2838. }
  2839. /* reset all members of fileacc */
  2840. memset(fileacc, 0, sizeof(*fileacc));
  2841. }
  2842. return ret;
  2843. }
  2844. #endif /* NO_FILESYSTEMS */
  2845. static void
  2846. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2847. {
  2848. for (; *src != '\0' && n > 1; n--) {
  2849. *dst++ = *src++;
  2850. }
  2851. *dst = '\0';
  2852. }
  2853. static int
  2854. lowercase(const char *s)
  2855. {
  2856. return tolower((unsigned char)*s);
  2857. }
  2858. int
  2859. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2860. {
  2861. int diff = 0;
  2862. if (len > 0) {
  2863. do {
  2864. diff = lowercase(s1++) - lowercase(s2++);
  2865. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2866. }
  2867. return diff;
  2868. }
  2869. int
  2870. mg_strcasecmp(const char *s1, const char *s2)
  2871. {
  2872. int diff;
  2873. do {
  2874. diff = lowercase(s1++) - lowercase(s2++);
  2875. } while (diff == 0 && s1[-1] != '\0');
  2876. return diff;
  2877. }
  2878. static char *
  2879. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2880. {
  2881. char *p;
  2882. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2883. * defined */
  2884. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2885. mg_strlcpy(p, ptr, len + 1);
  2886. }
  2887. return p;
  2888. }
  2889. static char *
  2890. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2891. {
  2892. return mg_strndup_ctx(str, strlen(str), ctx);
  2893. }
  2894. static char *
  2895. mg_strdup(const char *str)
  2896. {
  2897. return mg_strndup_ctx(str, strlen(str), NULL);
  2898. }
  2899. static const char *
  2900. mg_strcasestr(const char *big_str, const char *small_str)
  2901. {
  2902. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2903. if (big_len >= small_len) {
  2904. for (i = 0; i <= (big_len - small_len); i++) {
  2905. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2906. return big_str + i;
  2907. }
  2908. }
  2909. }
  2910. return NULL;
  2911. }
  2912. /* Return null terminated string of given maximum length.
  2913. * Report errors if length is exceeded. */
  2914. static void
  2915. mg_vsnprintf(const struct mg_connection *conn,
  2916. int *truncated,
  2917. char *buf,
  2918. size_t buflen,
  2919. const char *fmt,
  2920. va_list ap)
  2921. {
  2922. int n, ok;
  2923. if (buflen == 0) {
  2924. if (truncated) {
  2925. *truncated = 1;
  2926. }
  2927. return;
  2928. }
  2929. #if defined(__clang__)
  2930. #pragma clang diagnostic push
  2931. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2932. /* Using fmt as a non-literal is intended here, since it is mostly called
  2933. * indirectly by mg_snprintf */
  2934. #endif
  2935. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2936. ok = (n >= 0) && ((size_t)n < buflen);
  2937. #if defined(__clang__)
  2938. #pragma clang diagnostic pop
  2939. #endif
  2940. if (ok) {
  2941. if (truncated) {
  2942. *truncated = 0;
  2943. }
  2944. } else {
  2945. if (truncated) {
  2946. *truncated = 1;
  2947. }
  2948. mg_cry_internal(conn,
  2949. "truncating vsnprintf buffer: [%.*s]",
  2950. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2951. buf);
  2952. n = (int)buflen - 1;
  2953. }
  2954. buf[n] = '\0';
  2955. }
  2956. static void
  2957. mg_snprintf(const struct mg_connection *conn,
  2958. int *truncated,
  2959. char *buf,
  2960. size_t buflen,
  2961. const char *fmt,
  2962. ...)
  2963. {
  2964. va_list ap;
  2965. va_start(ap, fmt);
  2966. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2967. va_end(ap);
  2968. }
  2969. static int
  2970. get_option_index(const char *name)
  2971. {
  2972. int i;
  2973. for (i = 0; config_options[i].name != NULL; i++) {
  2974. if (strcmp(config_options[i].name, name) == 0) {
  2975. return i;
  2976. }
  2977. }
  2978. return -1;
  2979. }
  2980. const char *
  2981. mg_get_option(const struct mg_context *ctx, const char *name)
  2982. {
  2983. int i;
  2984. if ((i = get_option_index(name)) == -1) {
  2985. return NULL;
  2986. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2987. return "";
  2988. } else {
  2989. return ctx->dd.config[i];
  2990. }
  2991. }
  2992. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2993. struct mg_context *
  2994. mg_get_context(const struct mg_connection *conn)
  2995. {
  2996. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2997. }
  2998. void *
  2999. mg_get_user_data(const struct mg_context *ctx)
  3000. {
  3001. return (ctx == NULL) ? NULL : ctx->user_data;
  3002. }
  3003. void *
  3004. mg_get_user_context_data(const struct mg_connection *conn)
  3005. {
  3006. return mg_get_user_data(mg_get_context(conn));
  3007. }
  3008. void *
  3009. mg_get_thread_pointer(const struct mg_connection *conn)
  3010. {
  3011. /* both methods should return the same pointer */
  3012. if (conn) {
  3013. /* quick access, in case conn is known */
  3014. return conn->tls_user_ptr;
  3015. } else {
  3016. /* otherwise get pointer from thread local storage (TLS) */
  3017. struct mg_workerTLS *tls =
  3018. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3019. return tls->user_ptr;
  3020. }
  3021. }
  3022. void
  3023. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3024. {
  3025. if (conn != NULL) {
  3026. conn->request_info.conn_data = data;
  3027. }
  3028. }
  3029. void *
  3030. mg_get_user_connection_data(const struct mg_connection *conn)
  3031. {
  3032. if (conn != NULL) {
  3033. return conn->request_info.conn_data;
  3034. }
  3035. return NULL;
  3036. }
  3037. #if defined(MG_LEGACY_INTERFACE)
  3038. /* Deprecated: Use mg_get_server_ports instead. */
  3039. size_t
  3040. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3041. {
  3042. size_t i;
  3043. if (!ctx) {
  3044. return 0;
  3045. }
  3046. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3047. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3048. ports[i] =
  3049. #if defined(USE_IPV6)
  3050. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3051. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3052. :
  3053. #endif
  3054. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3055. }
  3056. return i;
  3057. }
  3058. #endif
  3059. int
  3060. mg_get_server_ports(const struct mg_context *ctx,
  3061. int size,
  3062. struct mg_server_port *ports)
  3063. {
  3064. int i, cnt = 0;
  3065. if (size <= 0) {
  3066. return -1;
  3067. }
  3068. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3069. if (!ctx) {
  3070. return -1;
  3071. }
  3072. if (!ctx->listening_sockets) {
  3073. return -1;
  3074. }
  3075. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3076. ports[cnt].port =
  3077. #if defined(USE_IPV6)
  3078. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3079. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3080. :
  3081. #endif
  3082. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3083. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3084. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3085. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3086. /* IPv4 */
  3087. ports[cnt].protocol = 1;
  3088. cnt++;
  3089. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3090. /* IPv6 */
  3091. ports[cnt].protocol = 3;
  3092. cnt++;
  3093. }
  3094. }
  3095. return cnt;
  3096. }
  3097. static void
  3098. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3099. {
  3100. buf[0] = '\0';
  3101. if (!usa) {
  3102. return;
  3103. }
  3104. if (usa->sa.sa_family == AF_INET) {
  3105. getnameinfo(&usa->sa,
  3106. sizeof(usa->sin),
  3107. buf,
  3108. (unsigned)len,
  3109. NULL,
  3110. 0,
  3111. NI_NUMERICHOST);
  3112. }
  3113. #if defined(USE_IPV6)
  3114. else if (usa->sa.sa_family == AF_INET6) {
  3115. getnameinfo(&usa->sa,
  3116. sizeof(usa->sin6),
  3117. buf,
  3118. (unsigned)len,
  3119. NULL,
  3120. 0,
  3121. NI_NUMERICHOST);
  3122. }
  3123. #endif
  3124. }
  3125. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3126. * included in all responses other than 100, 101, 5xx. */
  3127. static void
  3128. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3129. {
  3130. #if !defined(REENTRANT_TIME)
  3131. struct tm *tm;
  3132. tm = ((t != NULL) ? gmtime(t) : NULL);
  3133. if (tm != NULL) {
  3134. #else
  3135. struct tm _tm;
  3136. struct tm *tm = &_tm;
  3137. if (t != NULL) {
  3138. gmtime_r(t, tm);
  3139. #endif
  3140. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3141. } else {
  3142. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3143. buf[buf_len - 1] = '\0';
  3144. }
  3145. }
  3146. /* difftime for struct timespec. Return value is in seconds. */
  3147. static double
  3148. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3149. {
  3150. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3151. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3152. }
  3153. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3154. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3155. const char *func,
  3156. unsigned line,
  3157. const char *fmt,
  3158. va_list ap);
  3159. #include "external_mg_cry_internal_impl.inl"
  3160. #elif !defined(NO_FILESYSTEMS)
  3161. /* Print error message to the opened error log stream. */
  3162. static void
  3163. mg_cry_internal_impl(const struct mg_connection *conn,
  3164. const char *func,
  3165. unsigned line,
  3166. const char *fmt,
  3167. va_list ap)
  3168. {
  3169. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3170. struct mg_file fi;
  3171. time_t timestamp;
  3172. /* Unused, in the RELEASE build */
  3173. (void)func;
  3174. (void)line;
  3175. #if defined(GCC_DIAGNOSTIC)
  3176. #pragma GCC diagnostic push
  3177. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3178. #endif
  3179. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3180. #if defined(GCC_DIAGNOSTIC)
  3181. #pragma GCC diagnostic pop
  3182. #endif
  3183. buf[sizeof(buf) - 1] = 0;
  3184. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3185. if (!conn) {
  3186. puts(buf);
  3187. return;
  3188. }
  3189. /* Do not lock when getting the callback value, here and below.
  3190. * I suppose this is fine, since function cannot disappear in the
  3191. * same way string option can. */
  3192. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3193. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3194. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3195. if (mg_fopen(conn,
  3196. conn->dom_ctx->config[ERROR_LOG_FILE],
  3197. MG_FOPEN_MODE_APPEND,
  3198. &fi)
  3199. == 0) {
  3200. fi.access.fp = NULL;
  3201. }
  3202. } else {
  3203. fi.access.fp = NULL;
  3204. }
  3205. if (fi.access.fp != NULL) {
  3206. flockfile(fi.access.fp);
  3207. timestamp = time(NULL);
  3208. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3209. fprintf(fi.access.fp,
  3210. "[%010lu] [error] [client %s] ",
  3211. (unsigned long)timestamp,
  3212. src_addr);
  3213. if (conn->request_info.request_method != NULL) {
  3214. fprintf(fi.access.fp,
  3215. "%s %s: ",
  3216. conn->request_info.request_method,
  3217. conn->request_info.request_uri
  3218. ? conn->request_info.request_uri
  3219. : "");
  3220. }
  3221. fprintf(fi.access.fp, "%s", buf);
  3222. fputc('\n', fi.access.fp);
  3223. fflush(fi.access.fp);
  3224. funlockfile(fi.access.fp);
  3225. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3226. * mg_cry here anyway ;-) */
  3227. }
  3228. }
  3229. }
  3230. #else
  3231. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3232. #endif /* Externally provided function */
  3233. /* Construct fake connection structure. Used for logging, if connection
  3234. * is not applicable at the moment of logging. */
  3235. static struct mg_connection *
  3236. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3237. {
  3238. static const struct mg_connection conn_zero = {0};
  3239. *fc = conn_zero;
  3240. fc->phys_ctx = ctx;
  3241. fc->dom_ctx = &(ctx->dd);
  3242. return fc;
  3243. }
  3244. static void
  3245. mg_cry_internal_wrap(const struct mg_connection *conn,
  3246. struct mg_context *ctx,
  3247. const char *func,
  3248. unsigned line,
  3249. const char *fmt,
  3250. ...)
  3251. {
  3252. va_list ap;
  3253. va_start(ap, fmt);
  3254. if (!conn && ctx) {
  3255. struct mg_connection fc;
  3256. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3257. } else {
  3258. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3259. }
  3260. va_end(ap);
  3261. }
  3262. void
  3263. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3264. {
  3265. va_list ap;
  3266. va_start(ap, fmt);
  3267. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3268. va_end(ap);
  3269. }
  3270. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3271. const char *
  3272. mg_version(void)
  3273. {
  3274. return CIVETWEB_VERSION;
  3275. }
  3276. const struct mg_request_info *
  3277. mg_get_request_info(const struct mg_connection *conn)
  3278. {
  3279. if (!conn) {
  3280. return NULL;
  3281. }
  3282. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3283. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3284. char txt[16];
  3285. struct mg_workerTLS *tls =
  3286. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3287. sprintf(txt, "%03i", conn->response_info.status_code);
  3288. if (strlen(txt) == 3) {
  3289. memcpy(tls->txtbuf, txt, 4);
  3290. } else {
  3291. strcpy(tls->txtbuf, "ERR");
  3292. }
  3293. ((struct mg_connection *)conn)->request_info.local_uri =
  3294. ((struct mg_connection *)conn)->request_info.request_uri =
  3295. tls->txtbuf; /* use thread safe buffer */
  3296. ((struct mg_connection *)conn)->request_info.num_headers =
  3297. conn->response_info.num_headers;
  3298. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3299. conn->response_info.http_headers,
  3300. sizeof(conn->response_info.http_headers));
  3301. } else
  3302. #endif
  3303. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3304. return NULL;
  3305. }
  3306. return &conn->request_info;
  3307. }
  3308. const struct mg_response_info *
  3309. mg_get_response_info(const struct mg_connection *conn)
  3310. {
  3311. if (!conn) {
  3312. return NULL;
  3313. }
  3314. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3315. return NULL;
  3316. }
  3317. return &conn->response_info;
  3318. }
  3319. static const char *
  3320. get_proto_name(const struct mg_connection *conn)
  3321. {
  3322. #if defined(__clang__)
  3323. #pragma clang diagnostic push
  3324. #pragma clang diagnostic ignored "-Wunreachable-code"
  3325. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3326. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3327. * unreachable, but splitting into four different #ifdef clauses here is more
  3328. * complicated.
  3329. */
  3330. #endif
  3331. const struct mg_request_info *ri = &conn->request_info;
  3332. const char *proto =
  3333. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3334. : (ri->is_ssl ? "https" : "http"));
  3335. return proto;
  3336. #if defined(__clang__)
  3337. #pragma clang diagnostic pop
  3338. #endif
  3339. }
  3340. int
  3341. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3342. {
  3343. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3344. return -1;
  3345. } else {
  3346. int truncated = 0;
  3347. const struct mg_request_info *ri = &conn->request_info;
  3348. const char *proto = get_proto_name(conn);
  3349. if (ri->local_uri == NULL) {
  3350. return -1;
  3351. }
  3352. if ((ri->request_uri != NULL)
  3353. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3354. /* The request uri is different from the local uri.
  3355. * This is usually if an absolute URI, including server
  3356. * name has been provided. */
  3357. mg_snprintf(conn,
  3358. &truncated,
  3359. buf,
  3360. buflen,
  3361. "%s://%s",
  3362. proto,
  3363. ri->request_uri);
  3364. if (truncated) {
  3365. return -1;
  3366. }
  3367. return 0;
  3368. } else {
  3369. /* The common case is a relative URI, so we have to
  3370. * construct an absolute URI from server name and port */
  3371. #if defined(USE_IPV6)
  3372. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3373. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3374. : htons(conn->client.lsa.sin.sin_port);
  3375. #else
  3376. int port = htons(conn->client.lsa.sin.sin_port);
  3377. #endif
  3378. int def_port = ri->is_ssl ? 443 : 80;
  3379. int auth_domain_check_enabled =
  3380. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3381. && (!mg_strcasecmp(
  3382. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3383. const char *server_domain =
  3384. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3385. char portstr[16];
  3386. char server_ip[48];
  3387. if (port != def_port) {
  3388. sprintf(portstr, ":%u", (unsigned)port);
  3389. } else {
  3390. portstr[0] = 0;
  3391. }
  3392. if (!auth_domain_check_enabled || !server_domain) {
  3393. sockaddr_to_string(server_ip,
  3394. sizeof(server_ip),
  3395. &conn->client.lsa);
  3396. server_domain = server_ip;
  3397. }
  3398. mg_snprintf(conn,
  3399. &truncated,
  3400. buf,
  3401. buflen,
  3402. "%s://%s%s%s",
  3403. proto,
  3404. server_domain,
  3405. portstr,
  3406. ri->local_uri);
  3407. if (truncated) {
  3408. return -1;
  3409. }
  3410. return 0;
  3411. }
  3412. }
  3413. }
  3414. /* Skip the characters until one of the delimiters characters found.
  3415. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3416. * Advance pointer to buffer to the next word. Return found 0-terminated
  3417. * word.
  3418. * Delimiters can be quoted with quotechar. */
  3419. static char *
  3420. skip_quoted(char **buf,
  3421. const char *delimiters,
  3422. const char *whitespace,
  3423. char quotechar)
  3424. {
  3425. char *p, *begin_word, *end_word, *end_whitespace;
  3426. begin_word = *buf;
  3427. end_word = begin_word + strcspn(begin_word, delimiters);
  3428. /* Check for quotechar */
  3429. if (end_word > begin_word) {
  3430. p = end_word - 1;
  3431. while (*p == quotechar) {
  3432. /* While the delimiter is quoted, look for the next delimiter.
  3433. */
  3434. /* This happens, e.g., in calls from parse_auth_header,
  3435. * if the user name contains a " character. */
  3436. /* If there is anything beyond end_word, copy it. */
  3437. if (*end_word != '\0') {
  3438. size_t end_off = strcspn(end_word + 1, delimiters);
  3439. memmove(p, end_word, end_off + 1);
  3440. p += end_off; /* p must correspond to end_word - 1 */
  3441. end_word += end_off + 1;
  3442. } else {
  3443. *p = '\0';
  3444. break;
  3445. }
  3446. }
  3447. for (p++; p < end_word; p++) {
  3448. *p = '\0';
  3449. }
  3450. }
  3451. if (*end_word == '\0') {
  3452. *buf = end_word;
  3453. } else {
  3454. #if defined(GCC_DIAGNOSTIC)
  3455. /* Disable spurious conversion warning for GCC */
  3456. #pragma GCC diagnostic push
  3457. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3458. #endif /* defined(GCC_DIAGNOSTIC) */
  3459. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3460. #if defined(GCC_DIAGNOSTIC)
  3461. #pragma GCC diagnostic pop
  3462. #endif /* defined(GCC_DIAGNOSTIC) */
  3463. for (p = end_word; p < end_whitespace; p++) {
  3464. *p = '\0';
  3465. }
  3466. *buf = end_whitespace;
  3467. }
  3468. return begin_word;
  3469. }
  3470. /* Return HTTP header value, or NULL if not found. */
  3471. static const char *
  3472. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3473. {
  3474. int i;
  3475. for (i = 0; i < num_hdr; i++) {
  3476. if (!mg_strcasecmp(name, hdr[i].name)) {
  3477. return hdr[i].value;
  3478. }
  3479. }
  3480. return NULL;
  3481. }
  3482. #if defined(USE_WEBSOCKET)
  3483. /* Retrieve requested HTTP header multiple values, and return the number of
  3484. * found occurrences */
  3485. static int
  3486. get_req_headers(const struct mg_request_info *ri,
  3487. const char *name,
  3488. const char **output,
  3489. int output_max_size)
  3490. {
  3491. int i;
  3492. int cnt = 0;
  3493. if (ri) {
  3494. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3495. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3496. output[cnt++] = ri->http_headers[i].value;
  3497. }
  3498. }
  3499. }
  3500. return cnt;
  3501. }
  3502. #endif
  3503. const char *
  3504. mg_get_header(const struct mg_connection *conn, const char *name)
  3505. {
  3506. if (!conn) {
  3507. return NULL;
  3508. }
  3509. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3510. return get_header(conn->request_info.http_headers,
  3511. conn->request_info.num_headers,
  3512. name);
  3513. }
  3514. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3515. return get_header(conn->response_info.http_headers,
  3516. conn->response_info.num_headers,
  3517. name);
  3518. }
  3519. return NULL;
  3520. }
  3521. static const char *
  3522. get_http_version(const struct mg_connection *conn)
  3523. {
  3524. if (!conn) {
  3525. return NULL;
  3526. }
  3527. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3528. return conn->request_info.http_version;
  3529. }
  3530. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3531. return conn->response_info.http_version;
  3532. }
  3533. return NULL;
  3534. }
  3535. /* A helper function for traversing a comma separated list of values.
  3536. * It returns a list pointer shifted to the next value, or NULL if the end
  3537. * of the list found.
  3538. * Value is stored in val vector. If value has form "x=y", then eq_val
  3539. * vector is initialized to point to the "y" part, and val vector length
  3540. * is adjusted to point only to "x". */
  3541. static const char *
  3542. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3543. {
  3544. int end;
  3545. reparse:
  3546. if (val == NULL || list == NULL || *list == '\0') {
  3547. /* End of the list */
  3548. return NULL;
  3549. }
  3550. /* Skip over leading LWS */
  3551. while (*list == ' ' || *list == '\t')
  3552. list++;
  3553. val->ptr = list;
  3554. if ((list = strchr(val->ptr, ',')) != NULL) {
  3555. /* Comma found. Store length and shift the list ptr */
  3556. val->len = ((size_t)(list - val->ptr));
  3557. list++;
  3558. } else {
  3559. /* This value is the last one */
  3560. list = val->ptr + strlen(val->ptr);
  3561. val->len = ((size_t)(list - val->ptr));
  3562. }
  3563. /* Adjust length for trailing LWS */
  3564. end = (int)val->len - 1;
  3565. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3566. end--;
  3567. val->len = (size_t)(end) + (size_t)(1);
  3568. if (val->len == 0) {
  3569. /* Ignore any empty entries. */
  3570. goto reparse;
  3571. }
  3572. if (eq_val != NULL) {
  3573. /* Value has form "x=y", adjust pointers and lengths
  3574. * so that val points to "x", and eq_val points to "y". */
  3575. eq_val->len = 0;
  3576. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3577. if (eq_val->ptr != NULL) {
  3578. eq_val->ptr++; /* Skip over '=' character */
  3579. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3580. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3581. }
  3582. }
  3583. return list;
  3584. }
  3585. /* A helper function for checking if a comma separated list of values
  3586. * contains
  3587. * the given option (case insensitvely).
  3588. * 'header' can be NULL, in which case false is returned. */
  3589. static int
  3590. header_has_option(const char *header, const char *option)
  3591. {
  3592. struct vec opt_vec;
  3593. struct vec eq_vec;
  3594. DEBUG_ASSERT(option != NULL);
  3595. DEBUG_ASSERT(option[0] != '\0');
  3596. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3597. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3598. return 1;
  3599. }
  3600. return 0;
  3601. }
  3602. /* Perform case-insensitive match of string against pattern */
  3603. static ptrdiff_t
  3604. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3605. {
  3606. const char *or_str;
  3607. ptrdiff_t i, j, len, res;
  3608. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3609. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3610. return (res > 0) ? res
  3611. : match_prefix(or_str + 1,
  3612. (size_t)((pattern + pattern_len)
  3613. - (or_str + 1)),
  3614. str);
  3615. }
  3616. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3617. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3618. continue;
  3619. } else if (pattern[i] == '$') {
  3620. return (str[j] == '\0') ? j : -1;
  3621. } else if (pattern[i] == '*') {
  3622. i++;
  3623. if (pattern[i] == '*') {
  3624. i++;
  3625. len = strlen(str + j);
  3626. } else {
  3627. len = strcspn(str + j, "/");
  3628. }
  3629. if (i == (ptrdiff_t)pattern_len) {
  3630. return j + len;
  3631. }
  3632. do {
  3633. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3634. } while (res == -1 && len-- > 0);
  3635. return (res == -1) ? -1 : j + res + len;
  3636. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3637. return -1;
  3638. }
  3639. }
  3640. return (ptrdiff_t)j;
  3641. }
  3642. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3643. * This function must tolerate situations when connection info is not
  3644. * set up, for example if request parsing failed. */
  3645. static int
  3646. should_keep_alive(const struct mg_connection *conn)
  3647. {
  3648. const char *http_version;
  3649. const char *header;
  3650. /* First satisfy needs of the server */
  3651. if ((conn == NULL) || conn->must_close) {
  3652. /* Close, if civetweb framework needs to close */
  3653. return 0;
  3654. }
  3655. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3656. /* Close, if keep alive is not enabled */
  3657. return 0;
  3658. }
  3659. /* Check explicit wish of the client */
  3660. header = mg_get_header(conn, "Connection");
  3661. if (header) {
  3662. /* If there is a connection header from the client, obey */
  3663. if (header_has_option(header, "keep-alive")) {
  3664. return 1;
  3665. }
  3666. return 0;
  3667. }
  3668. /* Use default of the standard */
  3669. http_version = get_http_version(conn);
  3670. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3671. /* HTTP 1.1 default is keep alive */
  3672. return 1;
  3673. }
  3674. /* HTTP 1.0 (and earlier) default is to close the connection */
  3675. return 0;
  3676. }
  3677. static int
  3678. should_decode_url(const struct mg_connection *conn)
  3679. {
  3680. if (!conn || !conn->dom_ctx) {
  3681. return 0;
  3682. }
  3683. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3684. }
  3685. static const char *
  3686. suggest_connection_header(const struct mg_connection *conn)
  3687. {
  3688. return should_keep_alive(conn) ? "keep-alive" : "close";
  3689. }
  3690. static int
  3691. send_no_cache_header(struct mg_connection *conn)
  3692. {
  3693. /* Send all current and obsolete cache opt-out directives. */
  3694. return mg_printf(conn,
  3695. "Cache-Control: no-cache, no-store, "
  3696. "must-revalidate, private, max-age=0\r\n"
  3697. "Pragma: no-cache\r\n"
  3698. "Expires: 0\r\n");
  3699. }
  3700. static int
  3701. send_static_cache_header(struct mg_connection *conn)
  3702. {
  3703. #if !defined(NO_CACHING)
  3704. int max_age;
  3705. const char *cache_control =
  3706. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3707. if (cache_control != NULL) {
  3708. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3709. }
  3710. /* Read the server config to check how long a file may be cached.
  3711. * The configuration is in seconds. */
  3712. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3713. if (max_age <= 0) {
  3714. /* 0 means "do not cache". All values <0 are reserved
  3715. * and may be used differently in the future. */
  3716. /* If a file should not be cached, do not only send
  3717. * max-age=0, but also pragmas and Expires headers. */
  3718. return send_no_cache_header(conn);
  3719. }
  3720. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3721. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3722. /* See also https://www.mnot.net/cache_docs/ */
  3723. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3724. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3725. * leap
  3726. * year to 31622400 seconds. For the moment, we just send whatever has
  3727. * been configured, still the behavior for >1 year should be considered
  3728. * as undefined. */
  3729. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3730. #else /* NO_CACHING */
  3731. return send_no_cache_header(conn);
  3732. #endif /* !NO_CACHING */
  3733. }
  3734. static int
  3735. send_additional_header(struct mg_connection *conn)
  3736. {
  3737. int i = 0;
  3738. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3739. #if !defined(NO_SSL)
  3740. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3741. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3742. if (max_age >= 0) {
  3743. i += mg_printf(conn,
  3744. "Strict-Transport-Security: max-age=%u\r\n",
  3745. (unsigned)max_age);
  3746. }
  3747. }
  3748. #endif
  3749. if (header && header[0]) {
  3750. i += mg_printf(conn, "%s\r\n", header);
  3751. }
  3752. return i;
  3753. }
  3754. #if !defined(NO_FILESYSTEMS)
  3755. static void handle_file_based_request(struct mg_connection *conn,
  3756. const char *path,
  3757. struct mg_file *filep);
  3758. #endif /* NO_FILESYSTEMS */
  3759. const char *
  3760. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3761. {
  3762. /* See IANA HTTP status code assignment:
  3763. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3764. */
  3765. switch (response_code) {
  3766. /* RFC2616 Section 10.1 - Informational 1xx */
  3767. case 100:
  3768. return "Continue"; /* RFC2616 Section 10.1.1 */
  3769. case 101:
  3770. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3771. case 102:
  3772. return "Processing"; /* RFC2518 Section 10.1 */
  3773. /* RFC2616 Section 10.2 - Successful 2xx */
  3774. case 200:
  3775. return "OK"; /* RFC2616 Section 10.2.1 */
  3776. case 201:
  3777. return "Created"; /* RFC2616 Section 10.2.2 */
  3778. case 202:
  3779. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3780. case 203:
  3781. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3782. case 204:
  3783. return "No Content"; /* RFC2616 Section 10.2.5 */
  3784. case 205:
  3785. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3786. case 206:
  3787. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3788. case 207:
  3789. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3790. */
  3791. case 208:
  3792. return "Already Reported"; /* RFC5842 Section 7.1 */
  3793. case 226:
  3794. return "IM used"; /* RFC3229 Section 10.4.1 */
  3795. /* RFC2616 Section 10.3 - Redirection 3xx */
  3796. case 300:
  3797. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3798. case 301:
  3799. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3800. case 302:
  3801. return "Found"; /* RFC2616 Section 10.3.3 */
  3802. case 303:
  3803. return "See Other"; /* RFC2616 Section 10.3.4 */
  3804. case 304:
  3805. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3806. case 305:
  3807. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3808. case 307:
  3809. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3810. case 308:
  3811. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3812. /* RFC2616 Section 10.4 - Client Error 4xx */
  3813. case 400:
  3814. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3815. case 401:
  3816. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3817. case 402:
  3818. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3819. case 403:
  3820. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3821. case 404:
  3822. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3823. case 405:
  3824. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3825. case 406:
  3826. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3827. case 407:
  3828. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3829. case 408:
  3830. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3831. case 409:
  3832. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3833. case 410:
  3834. return "Gone"; /* RFC2616 Section 10.4.11 */
  3835. case 411:
  3836. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3837. case 412:
  3838. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3839. case 413:
  3840. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3841. case 414:
  3842. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3843. case 415:
  3844. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3845. case 416:
  3846. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3847. */
  3848. case 417:
  3849. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3850. case 421:
  3851. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3852. case 422:
  3853. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3854. * Section 11.2 */
  3855. case 423:
  3856. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3857. case 424:
  3858. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3859. * Section 11.4 */
  3860. case 426:
  3861. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3862. case 428:
  3863. return "Precondition Required"; /* RFC 6585, Section 3 */
  3864. case 429:
  3865. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3866. case 431:
  3867. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3868. case 451:
  3869. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3870. * Section 3 */
  3871. /* RFC2616 Section 10.5 - Server Error 5xx */
  3872. case 500:
  3873. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3874. case 501:
  3875. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3876. case 502:
  3877. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3878. case 503:
  3879. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3880. case 504:
  3881. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3882. case 505:
  3883. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3884. case 506:
  3885. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3886. case 507:
  3887. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3888. * Section 11.5 */
  3889. case 508:
  3890. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3891. case 510:
  3892. return "Not Extended"; /* RFC 2774, Section 7 */
  3893. case 511:
  3894. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3895. /* Other status codes, not shown in the IANA HTTP status code
  3896. * assignment.
  3897. * E.g., "de facto" standards due to common use, ... */
  3898. case 418:
  3899. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3900. case 419:
  3901. return "Authentication Timeout"; /* common use */
  3902. case 420:
  3903. return "Enhance Your Calm"; /* common use */
  3904. case 440:
  3905. return "Login Timeout"; /* common use */
  3906. case 509:
  3907. return "Bandwidth Limit Exceeded"; /* common use */
  3908. default:
  3909. /* This error code is unknown. This should not happen. */
  3910. if (conn) {
  3911. mg_cry_internal(conn,
  3912. "Unknown HTTP response code: %u",
  3913. response_code);
  3914. }
  3915. /* Return at least a category according to RFC 2616 Section 10. */
  3916. if (response_code >= 100 && response_code < 200) {
  3917. /* Unknown informational status code */
  3918. return "Information";
  3919. }
  3920. if (response_code >= 200 && response_code < 300) {
  3921. /* Unknown success code */
  3922. return "Success";
  3923. }
  3924. if (response_code >= 300 && response_code < 400) {
  3925. /* Unknown redirection code */
  3926. return "Redirection";
  3927. }
  3928. if (response_code >= 400 && response_code < 500) {
  3929. /* Unknown request error code */
  3930. return "Client Error";
  3931. }
  3932. if (response_code >= 500 && response_code < 600) {
  3933. /* Unknown server error code */
  3934. return "Server Error";
  3935. }
  3936. /* Response code not even within reasonable range */
  3937. return "";
  3938. }
  3939. }
  3940. static int
  3941. mg_send_http_error_impl(struct mg_connection *conn,
  3942. int status,
  3943. const char *fmt,
  3944. va_list args)
  3945. {
  3946. char errmsg_buf[MG_BUF_LEN];
  3947. va_list ap;
  3948. int has_body;
  3949. char date[64];
  3950. time_t curtime = time(NULL);
  3951. #if !defined(NO_FILESYSTEMS)
  3952. char path_buf[PATH_MAX];
  3953. int len, i, page_handler_found, scope, truncated;
  3954. const char *error_handler = NULL;
  3955. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3956. const char *error_page_file_ext, *tstr;
  3957. #endif /* NO_FILESYSTEMS */
  3958. int handled_by_callback = 0;
  3959. const char *status_text = mg_get_response_code_text(conn, status);
  3960. if ((conn == NULL) || (fmt == NULL)) {
  3961. return -2;
  3962. }
  3963. /* Set status (for log) */
  3964. conn->status_code = status;
  3965. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3966. has_body = ((status > 199) && (status != 204) && (status != 304));
  3967. /* Prepare message in buf, if required */
  3968. if (has_body
  3969. || (!conn->in_error_handler
  3970. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3971. /* Store error message in errmsg_buf */
  3972. va_copy(ap, args);
  3973. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3974. va_end(ap);
  3975. /* In a debug build, print all html errors */
  3976. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3977. }
  3978. /* If there is a http_error callback, call it.
  3979. * But don't do it recursively, if callback calls mg_send_http_error again.
  3980. */
  3981. if (!conn->in_error_handler
  3982. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3983. /* Mark in_error_handler to avoid recursion and call user callback. */
  3984. conn->in_error_handler = 1;
  3985. handled_by_callback =
  3986. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3987. == 0);
  3988. conn->in_error_handler = 0;
  3989. }
  3990. if (!handled_by_callback) {
  3991. /* Check for recursion */
  3992. if (conn->in_error_handler) {
  3993. DEBUG_TRACE(
  3994. "Recursion when handling error %u - fall back to default",
  3995. status);
  3996. #if !defined(NO_FILESYSTEMS)
  3997. } else {
  3998. /* Send user defined error pages, if defined */
  3999. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4000. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4001. page_handler_found = 0;
  4002. if (error_handler != NULL) {
  4003. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4004. switch (scope) {
  4005. case 1: /* Handler for specific error, e.g. 404 error */
  4006. mg_snprintf(conn,
  4007. &truncated,
  4008. path_buf,
  4009. sizeof(path_buf) - 32,
  4010. "%serror%03u.",
  4011. error_handler,
  4012. status);
  4013. break;
  4014. case 2: /* Handler for error group, e.g., 5xx error
  4015. * handler
  4016. * for all server errors (500-599) */
  4017. mg_snprintf(conn,
  4018. &truncated,
  4019. path_buf,
  4020. sizeof(path_buf) - 32,
  4021. "%serror%01uxx.",
  4022. error_handler,
  4023. status / 100);
  4024. break;
  4025. default: /* Handler for all errors */
  4026. mg_snprintf(conn,
  4027. &truncated,
  4028. path_buf,
  4029. sizeof(path_buf) - 32,
  4030. "%serror.",
  4031. error_handler);
  4032. break;
  4033. }
  4034. /* String truncation in buf may only occur if
  4035. * error_handler is too long. This string is
  4036. * from the config, not from a client. */
  4037. (void)truncated;
  4038. len = (int)strlen(path_buf);
  4039. tstr = strchr(error_page_file_ext, '.');
  4040. while (tstr) {
  4041. for (i = 1;
  4042. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4043. i++) {
  4044. /* buffer overrun is not possible here, since
  4045. * (i < 32) && (len < sizeof(path_buf) - 32)
  4046. * ==> (i + len) < sizeof(path_buf) */
  4047. path_buf[len + i - 1] = tstr[i];
  4048. }
  4049. /* buffer overrun is not possible here, since
  4050. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4051. * ==> (i + len) <= sizeof(path_buf) */
  4052. path_buf[len + i - 1] = 0;
  4053. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4054. DEBUG_TRACE("Check error page %s - found",
  4055. path_buf);
  4056. page_handler_found = 1;
  4057. break;
  4058. }
  4059. DEBUG_TRACE("Check error page %s - not found",
  4060. path_buf);
  4061. tstr = strchr(tstr + i, '.');
  4062. }
  4063. }
  4064. }
  4065. if (page_handler_found) {
  4066. conn->in_error_handler = 1;
  4067. handle_file_based_request(conn, path_buf, &error_page_file);
  4068. conn->in_error_handler = 0;
  4069. return 0;
  4070. }
  4071. #endif /* NO_FILESYSTEMS */
  4072. }
  4073. /* No custom error page. Send default error page. */
  4074. gmt_time_string(date, sizeof(date), &curtime);
  4075. conn->must_close = 1;
  4076. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4077. send_no_cache_header(conn);
  4078. send_additional_header(conn);
  4079. if (has_body) {
  4080. mg_printf(conn,
  4081. "%s",
  4082. "Content-Type: text/plain; charset=utf-8\r\n");
  4083. }
  4084. mg_printf(conn,
  4085. "Date: %s\r\n"
  4086. "Connection: close\r\n\r\n",
  4087. date);
  4088. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4089. if (has_body) {
  4090. /* For other errors, send a generic error message. */
  4091. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4092. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4093. } else {
  4094. /* No body allowed. Close the connection. */
  4095. DEBUG_TRACE("Error %i", status);
  4096. }
  4097. }
  4098. return 0;
  4099. }
  4100. int
  4101. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4102. {
  4103. va_list ap;
  4104. int ret;
  4105. va_start(ap, fmt);
  4106. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4107. va_end(ap);
  4108. return ret;
  4109. }
  4110. int
  4111. mg_send_http_ok(struct mg_connection *conn,
  4112. const char *mime_type,
  4113. long long content_length)
  4114. {
  4115. char date[64];
  4116. time_t curtime = time(NULL);
  4117. if ((mime_type == NULL) || (*mime_type == 0)) {
  4118. /* Parameter error */
  4119. return -2;
  4120. }
  4121. gmt_time_string(date, sizeof(date), &curtime);
  4122. mg_printf(conn,
  4123. "HTTP/1.1 200 OK\r\n"
  4124. "Content-Type: %s\r\n"
  4125. "Date: %s\r\n"
  4126. "Connection: %s\r\n",
  4127. mime_type,
  4128. date,
  4129. suggest_connection_header(conn));
  4130. send_no_cache_header(conn);
  4131. send_additional_header(conn);
  4132. if (content_length < 0) {
  4133. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4134. } else {
  4135. mg_printf(conn,
  4136. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4137. (uint64_t)content_length);
  4138. }
  4139. return 0;
  4140. }
  4141. int
  4142. mg_send_http_redirect(struct mg_connection *conn,
  4143. const char *target_url,
  4144. int redirect_code)
  4145. {
  4146. /* Send a 30x redirect response.
  4147. *
  4148. * Redirect types (status codes):
  4149. *
  4150. * Status | Perm/Temp | Method | Version
  4151. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4152. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4153. * 303 | temporary | always use GET | HTTP/1.1
  4154. * 307 | temporary | always keep method | HTTP/1.1
  4155. * 308 | permanent | always keep method | HTTP/1.1
  4156. */
  4157. const char *redirect_text;
  4158. int ret;
  4159. size_t content_len = 0;
  4160. char reply[MG_BUF_LEN];
  4161. /* In case redirect_code=0, use 307. */
  4162. if (redirect_code == 0) {
  4163. redirect_code = 307;
  4164. }
  4165. /* In case redirect_code is none of the above, return error. */
  4166. if ((redirect_code != 301) && (redirect_code != 302)
  4167. && (redirect_code != 303) && (redirect_code != 307)
  4168. && (redirect_code != 308)) {
  4169. /* Parameter error */
  4170. return -2;
  4171. }
  4172. /* Get proper text for response code */
  4173. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4174. /* If target_url is not defined, redirect to "/". */
  4175. if ((target_url == NULL) || (*target_url == 0)) {
  4176. target_url = "/";
  4177. }
  4178. #if defined(MG_SEND_REDIRECT_BODY)
  4179. /* TODO: condition name? */
  4180. /* Prepare a response body with a hyperlink.
  4181. *
  4182. * According to RFC2616 (and RFC1945 before):
  4183. * Unless the request method was HEAD, the entity of the
  4184. * response SHOULD contain a short hypertext note with a hyperlink to
  4185. * the new URI(s).
  4186. *
  4187. * However, this response body is not useful in M2M communication.
  4188. * Probably the original reason in the RFC was, clients not supporting
  4189. * a 30x HTTP redirect could still show the HTML page and let the user
  4190. * press the link. Since current browsers support 30x HTTP, the additional
  4191. * HTML body does not seem to make sense anymore.
  4192. *
  4193. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4194. * but it only notes:
  4195. * The server's response payload usually contains a short
  4196. * hypertext note with a hyperlink to the new URI(s).
  4197. *
  4198. * Deactivated by default. If you need the 30x body, set the define.
  4199. */
  4200. mg_snprintf(
  4201. conn,
  4202. NULL /* ignore truncation */,
  4203. reply,
  4204. sizeof(reply),
  4205. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4206. redirect_text,
  4207. target_url,
  4208. target_url);
  4209. content_len = strlen(reply);
  4210. #else
  4211. reply[0] = 0;
  4212. #endif
  4213. /* Do not send any additional header. For all other options,
  4214. * including caching, there are suitable defaults. */
  4215. ret = mg_printf(conn,
  4216. "HTTP/1.1 %i %s\r\n"
  4217. "Location: %s\r\n"
  4218. "Content-Length: %u\r\n"
  4219. "Connection: %s\r\n\r\n",
  4220. redirect_code,
  4221. redirect_text,
  4222. target_url,
  4223. (unsigned int)content_len,
  4224. suggest_connection_header(conn));
  4225. /* Send response body */
  4226. if (ret > 0) {
  4227. /* ... unless it is a HEAD request */
  4228. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4229. ret = mg_write(conn, reply, content_len);
  4230. }
  4231. }
  4232. return (ret > 0) ? ret : -1;
  4233. }
  4234. #if defined(_WIN32)
  4235. /* Create substitutes for POSIX functions in Win32. */
  4236. #if defined(GCC_DIAGNOSTIC)
  4237. /* Show no warning in case system functions are not used. */
  4238. #pragma GCC diagnostic push
  4239. #pragma GCC diagnostic ignored "-Wunused-function"
  4240. #endif
  4241. static int
  4242. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4243. {
  4244. (void)unused;
  4245. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4246. InitializeCriticalSection(&mutex->sec);
  4247. return 0;
  4248. }
  4249. static int
  4250. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4251. {
  4252. DeleteCriticalSection(&mutex->sec);
  4253. return 0;
  4254. }
  4255. static int
  4256. pthread_mutex_lock(pthread_mutex_t *mutex)
  4257. {
  4258. EnterCriticalSection(&mutex->sec);
  4259. return 0;
  4260. }
  4261. static int
  4262. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4263. {
  4264. LeaveCriticalSection(&mutex->sec);
  4265. return 0;
  4266. }
  4267. FUNCTION_MAY_BE_UNUSED
  4268. static int
  4269. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4270. {
  4271. (void)unused;
  4272. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4273. cv->waiting_thread = NULL;
  4274. return 0;
  4275. }
  4276. FUNCTION_MAY_BE_UNUSED
  4277. static int
  4278. pthread_cond_timedwait(pthread_cond_t *cv,
  4279. pthread_mutex_t *mutex,
  4280. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4281. {
  4282. struct mg_workerTLS **ptls,
  4283. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4284. int ok;
  4285. int64_t nsnow, nswaitabs, nswaitrel;
  4286. DWORD mswaitrel;
  4287. pthread_mutex_lock(&cv->threadIdSec);
  4288. /* Add this thread to cv's waiting list */
  4289. ptls = &cv->waiting_thread;
  4290. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4291. ;
  4292. tls->next_waiting_thread = NULL;
  4293. *ptls = tls;
  4294. pthread_mutex_unlock(&cv->threadIdSec);
  4295. if (abstime) {
  4296. nsnow = mg_get_current_time_ns();
  4297. nswaitabs =
  4298. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4299. nswaitrel = nswaitabs - nsnow;
  4300. if (nswaitrel < 0) {
  4301. nswaitrel = 0;
  4302. }
  4303. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4304. } else {
  4305. mswaitrel = (DWORD)INFINITE;
  4306. }
  4307. pthread_mutex_unlock(mutex);
  4308. ok = (WAIT_OBJECT_0
  4309. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4310. if (!ok) {
  4311. ok = 1;
  4312. pthread_mutex_lock(&cv->threadIdSec);
  4313. ptls = &cv->waiting_thread;
  4314. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4315. if (*ptls == tls) {
  4316. *ptls = tls->next_waiting_thread;
  4317. ok = 0;
  4318. break;
  4319. }
  4320. }
  4321. pthread_mutex_unlock(&cv->threadIdSec);
  4322. if (ok) {
  4323. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4324. (DWORD)INFINITE);
  4325. }
  4326. }
  4327. /* This thread has been removed from cv's waiting list */
  4328. pthread_mutex_lock(mutex);
  4329. return ok ? 0 : -1;
  4330. }
  4331. FUNCTION_MAY_BE_UNUSED
  4332. static int
  4333. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4334. {
  4335. return pthread_cond_timedwait(cv, mutex, NULL);
  4336. }
  4337. FUNCTION_MAY_BE_UNUSED
  4338. static int
  4339. pthread_cond_signal(pthread_cond_t *cv)
  4340. {
  4341. HANDLE wkup = NULL;
  4342. BOOL ok = FALSE;
  4343. pthread_mutex_lock(&cv->threadIdSec);
  4344. if (cv->waiting_thread) {
  4345. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4346. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4347. ok = SetEvent(wkup);
  4348. DEBUG_ASSERT(ok);
  4349. }
  4350. pthread_mutex_unlock(&cv->threadIdSec);
  4351. return ok ? 0 : 1;
  4352. }
  4353. FUNCTION_MAY_BE_UNUSED
  4354. static int
  4355. pthread_cond_broadcast(pthread_cond_t *cv)
  4356. {
  4357. pthread_mutex_lock(&cv->threadIdSec);
  4358. while (cv->waiting_thread) {
  4359. pthread_cond_signal(cv);
  4360. }
  4361. pthread_mutex_unlock(&cv->threadIdSec);
  4362. return 0;
  4363. }
  4364. FUNCTION_MAY_BE_UNUSED
  4365. static int
  4366. pthread_cond_destroy(pthread_cond_t *cv)
  4367. {
  4368. pthread_mutex_lock(&cv->threadIdSec);
  4369. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4370. pthread_mutex_unlock(&cv->threadIdSec);
  4371. pthread_mutex_destroy(&cv->threadIdSec);
  4372. return 0;
  4373. }
  4374. #if defined(ALTERNATIVE_QUEUE)
  4375. FUNCTION_MAY_BE_UNUSED
  4376. static void *
  4377. event_create(void)
  4378. {
  4379. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4380. }
  4381. FUNCTION_MAY_BE_UNUSED
  4382. static int
  4383. event_wait(void *eventhdl)
  4384. {
  4385. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4386. return (res == WAIT_OBJECT_0);
  4387. }
  4388. FUNCTION_MAY_BE_UNUSED
  4389. static int
  4390. event_signal(void *eventhdl)
  4391. {
  4392. return (int)SetEvent((HANDLE)eventhdl);
  4393. }
  4394. FUNCTION_MAY_BE_UNUSED
  4395. static void
  4396. event_destroy(void *eventhdl)
  4397. {
  4398. CloseHandle((HANDLE)eventhdl);
  4399. }
  4400. #endif
  4401. #if defined(GCC_DIAGNOSTIC)
  4402. /* Enable unused function warning again */
  4403. #pragma GCC diagnostic pop
  4404. #endif
  4405. /* For Windows, change all slashes to backslashes in path names. */
  4406. static void
  4407. change_slashes_to_backslashes(char *path)
  4408. {
  4409. int i;
  4410. for (i = 0; path[i] != '\0'; i++) {
  4411. if (path[i] == '/') {
  4412. path[i] = '\\';
  4413. }
  4414. /* remove double backslash (check i > 0 to preserve UNC paths,
  4415. * like \\server\file.txt) */
  4416. if ((path[i] == '\\') && (i > 0)) {
  4417. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4418. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4419. }
  4420. }
  4421. }
  4422. }
  4423. static int
  4424. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4425. {
  4426. int diff;
  4427. do {
  4428. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4429. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4430. s1++;
  4431. s2++;
  4432. } while ((diff == 0) && (s1[-1] != L'\0'));
  4433. return diff;
  4434. }
  4435. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4436. * wbuf and wbuf_len is a target buffer and its length. */
  4437. static void
  4438. path_to_unicode(const struct mg_connection *conn,
  4439. const char *path,
  4440. wchar_t *wbuf,
  4441. size_t wbuf_len)
  4442. {
  4443. char buf[PATH_MAX], buf2[PATH_MAX];
  4444. wchar_t wbuf2[W_PATH_MAX + 1];
  4445. DWORD long_len, err;
  4446. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4447. mg_strlcpy(buf, path, sizeof(buf));
  4448. change_slashes_to_backslashes(buf);
  4449. /* Convert to Unicode and back. If doubly-converted string does not
  4450. * match the original, something is fishy, reject. */
  4451. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4452. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4453. WideCharToMultiByte(
  4454. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4455. if (strcmp(buf, buf2) != 0) {
  4456. wbuf[0] = L'\0';
  4457. }
  4458. /* Windows file systems are not case sensitive, but you can still use
  4459. * uppercase and lowercase letters (on all modern file systems).
  4460. * The server can check if the URI uses the same upper/lowercase
  4461. * letters an the file system, effectively making Windows servers
  4462. * case sensitive (like Linux servers are). It is still not possible
  4463. * to use two files with the same name in different cases on Windows
  4464. * (like /a and /A) - this would be possible in Linux.
  4465. * As a default, Windows is not case sensitive, but the case sensitive
  4466. * file name check can be activated by an additional configuration. */
  4467. if (conn) {
  4468. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4469. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4470. "yes")) {
  4471. /* Use case sensitive compare function */
  4472. fcompare = wcscmp;
  4473. }
  4474. }
  4475. (void)conn; /* conn is currently unused */
  4476. #if !defined(_WIN32_WCE)
  4477. /* Only accept a full file path, not a Windows short (8.3) path. */
  4478. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4479. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4480. if (long_len == 0) {
  4481. err = GetLastError();
  4482. if (err == ERROR_FILE_NOT_FOUND) {
  4483. /* File does not exist. This is not always a problem here. */
  4484. return;
  4485. }
  4486. }
  4487. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4488. /* Short name is used. */
  4489. wbuf[0] = L'\0';
  4490. }
  4491. #else
  4492. (void)long_len;
  4493. (void)wbuf2;
  4494. (void)err;
  4495. if (strchr(path, '~')) {
  4496. wbuf[0] = L'\0';
  4497. }
  4498. #endif
  4499. }
  4500. #if !defined(NO_FILESYSTEMS)
  4501. static int
  4502. mg_stat(const struct mg_connection *conn,
  4503. const char *path,
  4504. struct mg_file_stat *filep)
  4505. {
  4506. wchar_t wbuf[W_PATH_MAX];
  4507. WIN32_FILE_ATTRIBUTE_DATA info;
  4508. time_t creation_time;
  4509. size_t len;
  4510. if (!filep) {
  4511. return 0;
  4512. }
  4513. memset(filep, 0, sizeof(*filep));
  4514. if (conn && is_file_in_memory(conn, path)) {
  4515. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4516. * memset */
  4517. /* Quick fix (for 1.9.x): */
  4518. /* mg_stat must fill all fields, also for files in memory */
  4519. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4520. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4521. filep->size = tmp_file.stat.size;
  4522. filep->location = 2;
  4523. /* TODO: for 1.10: restructure how files in memory are handled */
  4524. /* The "file in memory" feature is a candidate for deletion.
  4525. * Please join the discussion at
  4526. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4527. */
  4528. filep->last_modified = time(NULL); /* TODO */
  4529. /* last_modified = now ... assumes the file may change during
  4530. * runtime,
  4531. * so every mg_fopen call may return different data */
  4532. /* last_modified = conn->phys_ctx.start_time;
  4533. * May be used it the data does not change during runtime. This
  4534. * allows
  4535. * browser caching. Since we do not know, we have to assume the file
  4536. * in memory may change. */
  4537. return 1;
  4538. }
  4539. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4540. /* Windows happily opens files with some garbage at the end of file name.
  4541. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4542. * "a.cgi", despite one would expect an error back. */
  4543. len = strlen(path);
  4544. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4545. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4546. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4547. filep->last_modified =
  4548. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4549. info.ftLastWriteTime.dwHighDateTime);
  4550. /* On Windows, the file creation time can be higher than the
  4551. * modification time, e.g. when a file is copied.
  4552. * Since the Last-Modified timestamp is used for caching
  4553. * it should be based on the most recent timestamp. */
  4554. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4555. info.ftCreationTime.dwHighDateTime);
  4556. if (creation_time > filep->last_modified) {
  4557. filep->last_modified = creation_time;
  4558. }
  4559. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4560. return 1;
  4561. }
  4562. return 0;
  4563. }
  4564. #endif
  4565. static int
  4566. mg_remove(const struct mg_connection *conn, const char *path)
  4567. {
  4568. wchar_t wbuf[W_PATH_MAX];
  4569. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4570. return DeleteFileW(wbuf) ? 0 : -1;
  4571. }
  4572. static int
  4573. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4574. {
  4575. wchar_t wbuf[W_PATH_MAX];
  4576. (void)mode;
  4577. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4578. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4579. }
  4580. /* Create substitutes for POSIX functions in Win32. */
  4581. #if defined(GCC_DIAGNOSTIC)
  4582. /* Show no warning in case system functions are not used. */
  4583. #pragma GCC diagnostic push
  4584. #pragma GCC diagnostic ignored "-Wunused-function"
  4585. #endif
  4586. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4587. FUNCTION_MAY_BE_UNUSED
  4588. static DIR *
  4589. mg_opendir(const struct mg_connection *conn, const char *name)
  4590. {
  4591. DIR *dir = NULL;
  4592. wchar_t wpath[W_PATH_MAX];
  4593. DWORD attrs;
  4594. if (name == NULL) {
  4595. SetLastError(ERROR_BAD_ARGUMENTS);
  4596. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4597. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4598. } else {
  4599. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4600. attrs = GetFileAttributesW(wpath);
  4601. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4602. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4603. (void)wcscat(wpath, L"\\*");
  4604. dir->handle = FindFirstFileW(wpath, &dir->info);
  4605. dir->result.d_name[0] = '\0';
  4606. } else {
  4607. mg_free(dir);
  4608. dir = NULL;
  4609. }
  4610. }
  4611. return dir;
  4612. }
  4613. FUNCTION_MAY_BE_UNUSED
  4614. static int
  4615. mg_closedir(DIR *dir)
  4616. {
  4617. int result = 0;
  4618. if (dir != NULL) {
  4619. if (dir->handle != INVALID_HANDLE_VALUE)
  4620. result = FindClose(dir->handle) ? 0 : -1;
  4621. mg_free(dir);
  4622. } else {
  4623. result = -1;
  4624. SetLastError(ERROR_BAD_ARGUMENTS);
  4625. }
  4626. return result;
  4627. }
  4628. FUNCTION_MAY_BE_UNUSED
  4629. static struct dirent *
  4630. mg_readdir(DIR *dir)
  4631. {
  4632. struct dirent *result = 0;
  4633. if (dir) {
  4634. if (dir->handle != INVALID_HANDLE_VALUE) {
  4635. result = &dir->result;
  4636. (void)WideCharToMultiByte(CP_UTF8,
  4637. 0,
  4638. dir->info.cFileName,
  4639. -1,
  4640. result->d_name,
  4641. sizeof(result->d_name),
  4642. NULL,
  4643. NULL);
  4644. if (!FindNextFileW(dir->handle, &dir->info)) {
  4645. (void)FindClose(dir->handle);
  4646. dir->handle = INVALID_HANDLE_VALUE;
  4647. }
  4648. } else {
  4649. SetLastError(ERROR_FILE_NOT_FOUND);
  4650. }
  4651. } else {
  4652. SetLastError(ERROR_BAD_ARGUMENTS);
  4653. }
  4654. return result;
  4655. }
  4656. #if !defined(HAVE_POLL)
  4657. #undef POLLIN
  4658. #undef POLLPRI
  4659. #undef POLLOUT
  4660. #define POLLIN (1) /* Data ready - read will not block. */
  4661. #define POLLPRI (2) /* Priority data ready. */
  4662. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4663. FUNCTION_MAY_BE_UNUSED
  4664. static int
  4665. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4666. {
  4667. struct timeval tv;
  4668. fd_set rset;
  4669. fd_set wset;
  4670. unsigned int i;
  4671. int result;
  4672. SOCKET maxfd = 0;
  4673. memset(&tv, 0, sizeof(tv));
  4674. tv.tv_sec = milliseconds / 1000;
  4675. tv.tv_usec = (milliseconds % 1000) * 1000;
  4676. FD_ZERO(&rset);
  4677. FD_ZERO(&wset);
  4678. for (i = 0; i < n; i++) {
  4679. if (pfd[i].events & POLLIN) {
  4680. FD_SET(pfd[i].fd, &rset);
  4681. }
  4682. if (pfd[i].events & POLLOUT) {
  4683. FD_SET(pfd[i].fd, &wset);
  4684. }
  4685. pfd[i].revents = 0;
  4686. if (pfd[i].fd > maxfd) {
  4687. maxfd = pfd[i].fd;
  4688. }
  4689. }
  4690. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4691. for (i = 0; i < n; i++) {
  4692. if (FD_ISSET(pfd[i].fd, &rset)) {
  4693. pfd[i].revents |= POLLIN;
  4694. }
  4695. if (FD_ISSET(pfd[i].fd, &wset)) {
  4696. pfd[i].revents |= POLLOUT;
  4697. }
  4698. }
  4699. }
  4700. /* We should subtract the time used in select from remaining
  4701. * "milliseconds", in particular if called from mg_poll with a
  4702. * timeout quantum.
  4703. * Unfortunately, the remaining time is not stored in "tv" in all
  4704. * implementations, so the result in "tv" must be considered undefined.
  4705. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4706. return result;
  4707. }
  4708. #endif /* HAVE_POLL */
  4709. #if defined(GCC_DIAGNOSTIC)
  4710. /* Enable unused function warning again */
  4711. #pragma GCC diagnostic pop
  4712. #endif
  4713. static void
  4714. set_close_on_exec(SOCKET sock,
  4715. const struct mg_connection *conn /* may be null */,
  4716. struct mg_context *ctx /* may be null */)
  4717. {
  4718. (void)conn; /* Unused. */
  4719. (void)ctx;
  4720. #if defined(_WIN32_WCE)
  4721. (void)sock;
  4722. #else
  4723. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4724. #endif
  4725. }
  4726. int
  4727. mg_start_thread(mg_thread_func_t f, void *p)
  4728. {
  4729. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4730. /* Compile-time option to control stack size, e.g.
  4731. * -DUSE_STACK_SIZE=16384
  4732. */
  4733. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4734. == ((uintptr_t)(-1L)))
  4735. ? -1
  4736. : 0);
  4737. #else
  4738. return (
  4739. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4740. ? -1
  4741. : 0);
  4742. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4743. }
  4744. /* Start a thread storing the thread context. */
  4745. static int
  4746. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4747. void *p,
  4748. pthread_t *threadidptr)
  4749. {
  4750. uintptr_t uip;
  4751. HANDLE threadhandle;
  4752. int result = -1;
  4753. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4754. threadhandle = (HANDLE)uip;
  4755. if ((uip != 0) && (threadidptr != NULL)) {
  4756. *threadidptr = threadhandle;
  4757. result = 0;
  4758. }
  4759. return result;
  4760. }
  4761. /* Wait for a thread to finish. */
  4762. static int
  4763. mg_join_thread(pthread_t threadid)
  4764. {
  4765. int result;
  4766. DWORD dwevent;
  4767. result = -1;
  4768. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4769. if (dwevent == WAIT_FAILED) {
  4770. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4771. } else {
  4772. if (dwevent == WAIT_OBJECT_0) {
  4773. CloseHandle(threadid);
  4774. result = 0;
  4775. }
  4776. }
  4777. return result;
  4778. }
  4779. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4780. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4781. /* Create substitutes for POSIX functions in Win32. */
  4782. #if defined(GCC_DIAGNOSTIC)
  4783. /* Show no warning in case system functions are not used. */
  4784. #pragma GCC diagnostic push
  4785. #pragma GCC diagnostic ignored "-Wunused-function"
  4786. #endif
  4787. FUNCTION_MAY_BE_UNUSED
  4788. static HANDLE
  4789. dlopen(const char *dll_name, int flags)
  4790. {
  4791. wchar_t wbuf[W_PATH_MAX];
  4792. (void)flags;
  4793. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4794. return LoadLibraryW(wbuf);
  4795. }
  4796. FUNCTION_MAY_BE_UNUSED
  4797. static int
  4798. dlclose(void *handle)
  4799. {
  4800. int result;
  4801. if (FreeLibrary((HMODULE)handle) != 0) {
  4802. result = 0;
  4803. } else {
  4804. result = -1;
  4805. }
  4806. return result;
  4807. }
  4808. #if defined(GCC_DIAGNOSTIC)
  4809. /* Enable unused function warning again */
  4810. #pragma GCC diagnostic pop
  4811. #endif
  4812. #endif
  4813. #if !defined(NO_CGI)
  4814. #define SIGKILL (0)
  4815. static int
  4816. kill(pid_t pid, int sig_num)
  4817. {
  4818. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4819. (void)CloseHandle((HANDLE)pid);
  4820. return 0;
  4821. }
  4822. #if !defined(WNOHANG)
  4823. #define WNOHANG (1)
  4824. #endif
  4825. static pid_t
  4826. waitpid(pid_t pid, int *status, int flags)
  4827. {
  4828. DWORD timeout = INFINITE;
  4829. DWORD waitres;
  4830. (void)status; /* Currently not used by any client here */
  4831. if ((flags | WNOHANG) == WNOHANG) {
  4832. timeout = 0;
  4833. }
  4834. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4835. if (waitres == WAIT_OBJECT_0) {
  4836. return pid;
  4837. }
  4838. if (waitres == WAIT_TIMEOUT) {
  4839. return 0;
  4840. }
  4841. return (pid_t)-1;
  4842. }
  4843. static void
  4844. trim_trailing_whitespaces(char *s)
  4845. {
  4846. char *e = s + strlen(s);
  4847. while ((e > s) && isspace((unsigned char)e[-1])) {
  4848. *(--e) = '\0';
  4849. }
  4850. }
  4851. static pid_t
  4852. spawn_process(struct mg_connection *conn,
  4853. const char *prog,
  4854. char *envblk,
  4855. char *envp[],
  4856. int fdin[2],
  4857. int fdout[2],
  4858. int fderr[2],
  4859. const char *dir)
  4860. {
  4861. HANDLE me;
  4862. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4863. cmdline[PATH_MAX], buf[PATH_MAX];
  4864. int truncated;
  4865. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4866. STARTUPINFOA si;
  4867. PROCESS_INFORMATION pi = {0};
  4868. (void)envp;
  4869. memset(&si, 0, sizeof(si));
  4870. si.cb = sizeof(si);
  4871. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4872. si.wShowWindow = SW_HIDE;
  4873. me = GetCurrentProcess();
  4874. DuplicateHandle(me,
  4875. (HANDLE)_get_osfhandle(fdin[0]),
  4876. me,
  4877. &si.hStdInput,
  4878. 0,
  4879. TRUE,
  4880. DUPLICATE_SAME_ACCESS);
  4881. DuplicateHandle(me,
  4882. (HANDLE)_get_osfhandle(fdout[1]),
  4883. me,
  4884. &si.hStdOutput,
  4885. 0,
  4886. TRUE,
  4887. DUPLICATE_SAME_ACCESS);
  4888. DuplicateHandle(me,
  4889. (HANDLE)_get_osfhandle(fderr[1]),
  4890. me,
  4891. &si.hStdError,
  4892. 0,
  4893. TRUE,
  4894. DUPLICATE_SAME_ACCESS);
  4895. /* Mark handles that should not be inherited. See
  4896. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4897. */
  4898. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4899. HANDLE_FLAG_INHERIT,
  4900. 0);
  4901. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4902. HANDLE_FLAG_INHERIT,
  4903. 0);
  4904. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4905. HANDLE_FLAG_INHERIT,
  4906. 0);
  4907. /* If CGI file is a script, try to read the interpreter line */
  4908. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4909. if (interp == NULL) {
  4910. buf[0] = buf[1] = '\0';
  4911. /* Read the first line of the script into the buffer */
  4912. mg_snprintf(
  4913. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4914. if (truncated) {
  4915. pi.hProcess = (pid_t)-1;
  4916. goto spawn_cleanup;
  4917. }
  4918. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4919. #if defined(MG_USE_OPEN_FILE)
  4920. p = (char *)file.access.membuf;
  4921. #else
  4922. p = (char *)NULL;
  4923. #endif
  4924. mg_fgets(buf, sizeof(buf), &file, &p);
  4925. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4926. buf[sizeof(buf) - 1] = '\0';
  4927. }
  4928. if ((buf[0] == '#') && (buf[1] == '!')) {
  4929. trim_trailing_whitespaces(buf + 2);
  4930. } else {
  4931. buf[2] = '\0';
  4932. }
  4933. interp = buf + 2;
  4934. }
  4935. if (interp[0] != '\0') {
  4936. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4937. interp = full_interp;
  4938. }
  4939. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4940. if (interp[0] != '\0') {
  4941. mg_snprintf(conn,
  4942. &truncated,
  4943. cmdline,
  4944. sizeof(cmdline),
  4945. "\"%s\" \"%s\\%s\"",
  4946. interp,
  4947. full_dir,
  4948. prog);
  4949. } else {
  4950. mg_snprintf(conn,
  4951. &truncated,
  4952. cmdline,
  4953. sizeof(cmdline),
  4954. "\"%s\\%s\"",
  4955. full_dir,
  4956. prog);
  4957. }
  4958. if (truncated) {
  4959. pi.hProcess = (pid_t)-1;
  4960. goto spawn_cleanup;
  4961. }
  4962. DEBUG_TRACE("Running [%s]", cmdline);
  4963. if (CreateProcessA(NULL,
  4964. cmdline,
  4965. NULL,
  4966. NULL,
  4967. TRUE,
  4968. CREATE_NEW_PROCESS_GROUP,
  4969. envblk,
  4970. NULL,
  4971. &si,
  4972. &pi)
  4973. == 0) {
  4974. mg_cry_internal(
  4975. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4976. pi.hProcess = (pid_t)-1;
  4977. /* goto spawn_cleanup; */
  4978. }
  4979. spawn_cleanup:
  4980. (void)CloseHandle(si.hStdOutput);
  4981. (void)CloseHandle(si.hStdError);
  4982. (void)CloseHandle(si.hStdInput);
  4983. if (pi.hThread != NULL) {
  4984. (void)CloseHandle(pi.hThread);
  4985. }
  4986. return (pid_t)pi.hProcess;
  4987. }
  4988. #endif /* !NO_CGI */
  4989. static int
  4990. set_blocking_mode(SOCKET sock)
  4991. {
  4992. unsigned long non_blocking = 0;
  4993. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4994. }
  4995. static int
  4996. set_non_blocking_mode(SOCKET sock)
  4997. {
  4998. unsigned long non_blocking = 1;
  4999. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5000. }
  5001. #else
  5002. #if !defined(NO_FILESYSTEMS)
  5003. static int
  5004. mg_stat(const struct mg_connection *conn,
  5005. const char *path,
  5006. struct mg_file_stat *filep)
  5007. {
  5008. struct stat st;
  5009. if (!filep) {
  5010. return 0;
  5011. }
  5012. memset(filep, 0, sizeof(*filep));
  5013. if (conn && is_file_in_memory(conn, path)) {
  5014. /* Quick fix (for 1.9.x): */
  5015. /* mg_stat must fill all fields, also for files in memory */
  5016. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5017. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5018. filep->size = tmp_file.stat.size;
  5019. filep->last_modified = time(NULL);
  5020. filep->location = 2;
  5021. /* TODO: remove legacy "files in memory" feature */
  5022. return 1;
  5023. }
  5024. if (0 == stat(path, &st)) {
  5025. filep->size = (uint64_t)(st.st_size);
  5026. filep->last_modified = st.st_mtime;
  5027. filep->is_directory = S_ISDIR(st.st_mode);
  5028. return 1;
  5029. }
  5030. return 0;
  5031. }
  5032. #endif /* NO_FILESYSTEMS */
  5033. static void
  5034. set_close_on_exec(int fd,
  5035. const struct mg_connection *conn /* may be null */,
  5036. struct mg_context *ctx /* may be null */)
  5037. {
  5038. #if defined(__ZEPHYR__)
  5039. (void)fd;
  5040. (void)conn;
  5041. (void)ctx;
  5042. #else
  5043. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5044. if (conn || ctx) {
  5045. struct mg_connection fc;
  5046. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5047. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5048. __func__,
  5049. strerror(ERRNO));
  5050. }
  5051. }
  5052. #endif
  5053. }
  5054. int
  5055. mg_start_thread(mg_thread_func_t func, void *param)
  5056. {
  5057. pthread_t thread_id;
  5058. pthread_attr_t attr;
  5059. int result;
  5060. (void)pthread_attr_init(&attr);
  5061. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5062. #if defined(__ZEPHYR__)
  5063. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5064. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5065. /* Compile-time option to control stack size,
  5066. * e.g. -DUSE_STACK_SIZE=16384 */
  5067. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5068. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5069. result = pthread_create(&thread_id, &attr, func, param);
  5070. pthread_attr_destroy(&attr);
  5071. return result;
  5072. }
  5073. /* Start a thread storing the thread context. */
  5074. static int
  5075. mg_start_thread_with_id(mg_thread_func_t func,
  5076. void *param,
  5077. pthread_t *threadidptr)
  5078. {
  5079. pthread_t thread_id;
  5080. pthread_attr_t attr;
  5081. int result;
  5082. (void)pthread_attr_init(&attr);
  5083. #if defined(__ZEPHYR__)
  5084. pthread_attr_setstack(&attr,
  5085. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5086. ZEPHYR_STACK_SIZE);
  5087. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5088. /* Compile-time option to control stack size,
  5089. * e.g. -DUSE_STACK_SIZE=16384 */
  5090. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5091. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5092. result = pthread_create(&thread_id, &attr, func, param);
  5093. pthread_attr_destroy(&attr);
  5094. if ((result == 0) && (threadidptr != NULL)) {
  5095. *threadidptr = thread_id;
  5096. }
  5097. return result;
  5098. }
  5099. /* Wait for a thread to finish. */
  5100. static int
  5101. mg_join_thread(pthread_t threadid)
  5102. {
  5103. int result;
  5104. result = pthread_join(threadid, NULL);
  5105. return result;
  5106. }
  5107. #if !defined(NO_CGI)
  5108. static pid_t
  5109. spawn_process(struct mg_connection *conn,
  5110. const char *prog,
  5111. char *envblk,
  5112. char *envp[],
  5113. int fdin[2],
  5114. int fdout[2],
  5115. int fderr[2],
  5116. const char *dir)
  5117. {
  5118. pid_t pid;
  5119. const char *interp;
  5120. (void)envblk;
  5121. if ((pid = fork()) == -1) {
  5122. /* Parent */
  5123. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5124. } else if (pid != 0) {
  5125. /* Make sure children close parent-side descriptors.
  5126. * The caller will close the child-side immediately. */
  5127. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5128. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5129. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5130. } else {
  5131. /* Child */
  5132. if (chdir(dir) != 0) {
  5133. mg_cry_internal(
  5134. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5135. } else if (dup2(fdin[0], 0) == -1) {
  5136. mg_cry_internal(conn,
  5137. "%s: dup2(%d, 0): %s",
  5138. __func__,
  5139. fdin[0],
  5140. strerror(ERRNO));
  5141. } else if (dup2(fdout[1], 1) == -1) {
  5142. mg_cry_internal(conn,
  5143. "%s: dup2(%d, 1): %s",
  5144. __func__,
  5145. fdout[1],
  5146. strerror(ERRNO));
  5147. } else if (dup2(fderr[1], 2) == -1) {
  5148. mg_cry_internal(conn,
  5149. "%s: dup2(%d, 2): %s",
  5150. __func__,
  5151. fderr[1],
  5152. strerror(ERRNO));
  5153. } else {
  5154. struct sigaction sa;
  5155. /* Keep stderr and stdout in two different pipes.
  5156. * Stdout will be sent back to the client,
  5157. * stderr should go into a server error log. */
  5158. (void)close(fdin[0]);
  5159. (void)close(fdout[1]);
  5160. (void)close(fderr[1]);
  5161. /* Close write end fdin and read end fdout and fderr */
  5162. (void)close(fdin[1]);
  5163. (void)close(fdout[0]);
  5164. (void)close(fderr[0]);
  5165. /* After exec, all signal handlers are restored to their default
  5166. * values, with one exception of SIGCHLD. According to
  5167. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5168. * will leave unchanged after exec if it was set to be ignored.
  5169. * Restore it to default action. */
  5170. memset(&sa, 0, sizeof(sa));
  5171. sa.sa_handler = SIG_DFL;
  5172. sigaction(SIGCHLD, &sa, NULL);
  5173. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5174. if (interp == NULL) {
  5175. (void)execle(prog, prog, NULL, envp);
  5176. mg_cry_internal(conn,
  5177. "%s: execle(%s): %s",
  5178. __func__,
  5179. prog,
  5180. strerror(ERRNO));
  5181. } else {
  5182. (void)execle(interp, interp, prog, NULL, envp);
  5183. mg_cry_internal(conn,
  5184. "%s: execle(%s %s): %s",
  5185. __func__,
  5186. interp,
  5187. prog,
  5188. strerror(ERRNO));
  5189. }
  5190. }
  5191. exit(EXIT_FAILURE);
  5192. }
  5193. return pid;
  5194. }
  5195. #endif /* !NO_CGI */
  5196. static int
  5197. set_non_blocking_mode(SOCKET sock)
  5198. {
  5199. int flags = fcntl(sock, F_GETFL, 0);
  5200. if (flags < 0) {
  5201. return -1;
  5202. }
  5203. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5204. return -1;
  5205. }
  5206. return 0;
  5207. }
  5208. static int
  5209. set_blocking_mode(SOCKET sock)
  5210. {
  5211. int flags = fcntl(sock, F_GETFL, 0);
  5212. if (flags < 0) {
  5213. return -1;
  5214. }
  5215. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5216. return -1;
  5217. }
  5218. return 0;
  5219. }
  5220. #endif /* _WIN32 / else */
  5221. /* End of initial operating system specific define block. */
  5222. /* Get a random number (independent of C rand function) */
  5223. static uint64_t
  5224. get_random(void)
  5225. {
  5226. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5227. static uint64_t lcg = 0; /* Linear congruential generator */
  5228. uint64_t now = mg_get_current_time_ns();
  5229. if (lfsr == 0) {
  5230. /* lfsr will be only 0 if has not been initialized,
  5231. * so this code is called only once. */
  5232. lfsr = mg_get_current_time_ns();
  5233. lcg = mg_get_current_time_ns();
  5234. } else {
  5235. /* Get the next step of both random number generators. */
  5236. lfsr = (lfsr >> 1)
  5237. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5238. << 63);
  5239. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5240. }
  5241. /* Combining two pseudo-random number generators and a high resolution
  5242. * part
  5243. * of the current server time will make it hard (impossible?) to guess
  5244. * the
  5245. * next number. */
  5246. return (lfsr ^ lcg ^ now);
  5247. }
  5248. static int
  5249. mg_poll(struct mg_pollfd *pfd,
  5250. unsigned int n,
  5251. int milliseconds,
  5252. volatile int *stop_server)
  5253. {
  5254. /* Call poll, but only for a maximum time of a few seconds.
  5255. * This will allow to stop the server after some seconds, instead
  5256. * of having to wait for a long socket timeout. */
  5257. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5258. do {
  5259. int result;
  5260. if (*stop_server) {
  5261. /* Shut down signal */
  5262. return -2;
  5263. }
  5264. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5265. ms_now = milliseconds;
  5266. }
  5267. result = poll(pfd, n, ms_now);
  5268. if (result != 0) {
  5269. /* Poll returned either success (1) or error (-1).
  5270. * Forward both to the caller. */
  5271. return result;
  5272. }
  5273. /* Poll returned timeout (0). */
  5274. if (milliseconds > 0) {
  5275. milliseconds -= ms_now;
  5276. }
  5277. } while (milliseconds != 0);
  5278. /* timeout: return 0 */
  5279. return 0;
  5280. }
  5281. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5282. * descriptor.
  5283. * Return value:
  5284. * >=0 .. number of bytes successfully written
  5285. * -1 .. timeout
  5286. * -2 .. error
  5287. */
  5288. static int
  5289. push_inner(struct mg_context *ctx,
  5290. FILE *fp,
  5291. SOCKET sock,
  5292. SSL *ssl,
  5293. const char *buf,
  5294. int len,
  5295. double timeout)
  5296. {
  5297. uint64_t start = 0, now = 0, timeout_ns = 0;
  5298. int n, err;
  5299. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5300. #if defined(_WIN32)
  5301. typedef int len_t;
  5302. #else
  5303. typedef size_t len_t;
  5304. #endif
  5305. if (timeout > 0) {
  5306. now = mg_get_current_time_ns();
  5307. start = now;
  5308. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5309. }
  5310. if (ctx == NULL) {
  5311. return -2;
  5312. }
  5313. #if defined(NO_SSL)
  5314. if (ssl) {
  5315. return -2;
  5316. }
  5317. #endif
  5318. /* Try to read until it succeeds, fails, times out, or the server
  5319. * shuts down. */
  5320. for (;;) {
  5321. #if !defined(NO_SSL)
  5322. if (ssl != NULL) {
  5323. n = SSL_write(ssl, buf, len);
  5324. if (n <= 0) {
  5325. err = SSL_get_error(ssl, n);
  5326. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5327. err = ERRNO;
  5328. } else if ((err == SSL_ERROR_WANT_READ)
  5329. || (err == SSL_ERROR_WANT_WRITE)) {
  5330. n = 0;
  5331. } else {
  5332. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5333. return -2;
  5334. }
  5335. } else {
  5336. err = 0;
  5337. }
  5338. } else
  5339. #endif
  5340. if (fp != NULL) {
  5341. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5342. if (ferror(fp)) {
  5343. n = -1;
  5344. err = ERRNO;
  5345. } else {
  5346. err = 0;
  5347. }
  5348. } else {
  5349. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5350. err = (n < 0) ? ERRNO : 0;
  5351. #if defined(_WIN32)
  5352. if (err == WSAEWOULDBLOCK) {
  5353. err = 0;
  5354. n = 0;
  5355. }
  5356. #else
  5357. if (err == EWOULDBLOCK) {
  5358. err = 0;
  5359. n = 0;
  5360. }
  5361. #endif
  5362. if (n < 0) {
  5363. /* shutdown of the socket at client side */
  5364. return -2;
  5365. }
  5366. }
  5367. if (ctx->stop_flag) {
  5368. return -2;
  5369. }
  5370. if ((n > 0) || ((n == 0) && (len == 0))) {
  5371. /* some data has been read, or no data was requested */
  5372. return n;
  5373. }
  5374. if (n < 0) {
  5375. /* socket error - check errno */
  5376. DEBUG_TRACE("send() failed, error %d", err);
  5377. /* TODO (mid): error handling depending on the error code.
  5378. * These codes are different between Windows and Linux.
  5379. * Currently there is no problem with failing send calls,
  5380. * if there is a reproducible situation, it should be
  5381. * investigated in detail.
  5382. */
  5383. return -2;
  5384. }
  5385. /* Only in case n=0 (timeout), repeat calling the write function */
  5386. /* If send failed, wait before retry */
  5387. if (fp != NULL) {
  5388. /* For files, just wait a fixed time.
  5389. * Maybe it helps, maybe not. */
  5390. mg_sleep(5);
  5391. } else {
  5392. /* For sockets, wait for the socket using poll */
  5393. struct mg_pollfd pfd[1];
  5394. int pollres;
  5395. pfd[0].fd = sock;
  5396. pfd[0].events = POLLOUT;
  5397. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5398. if (ctx->stop_flag) {
  5399. return -2;
  5400. }
  5401. if (pollres > 0) {
  5402. continue;
  5403. }
  5404. }
  5405. if (timeout > 0) {
  5406. now = mg_get_current_time_ns();
  5407. if ((now - start) > timeout_ns) {
  5408. /* Timeout */
  5409. break;
  5410. }
  5411. }
  5412. }
  5413. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5414. used */
  5415. return -1;
  5416. }
  5417. static int
  5418. push_all(struct mg_context *ctx,
  5419. FILE *fp,
  5420. SOCKET sock,
  5421. SSL *ssl,
  5422. const char *buf,
  5423. int len)
  5424. {
  5425. double timeout = -1.0;
  5426. int n, nwritten = 0;
  5427. if (ctx == NULL) {
  5428. return -1;
  5429. }
  5430. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5431. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5432. }
  5433. while ((len > 0) && (ctx->stop_flag == 0)) {
  5434. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5435. if (n < 0) {
  5436. if (nwritten == 0) {
  5437. nwritten = -1; /* Propagate the error */
  5438. }
  5439. break;
  5440. } else if (n == 0) {
  5441. break; /* No more data to write */
  5442. } else {
  5443. nwritten += n;
  5444. len -= n;
  5445. }
  5446. }
  5447. return nwritten;
  5448. }
  5449. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5450. * Return value:
  5451. * >=0 .. number of bytes successfully read
  5452. * -1 .. timeout
  5453. * -2 .. error
  5454. */
  5455. static int
  5456. pull_inner(FILE *fp,
  5457. struct mg_connection *conn,
  5458. char *buf,
  5459. int len,
  5460. double timeout)
  5461. {
  5462. int nread, err = 0;
  5463. #if defined(_WIN32)
  5464. typedef int len_t;
  5465. #else
  5466. typedef size_t len_t;
  5467. #endif
  5468. #if !defined(NO_SSL)
  5469. int ssl_pending;
  5470. #endif
  5471. /* We need an additional wait loop around this, because in some cases
  5472. * with TLSwe may get data from the socket but not from SSL_read.
  5473. * In this case we need to repeat at least once.
  5474. */
  5475. if (fp != NULL) {
  5476. #if !defined(_WIN32_WCE)
  5477. /* Use read() instead of fread(), because if we're reading from the
  5478. * CGI pipe, fread() may block until IO buffer is filled up. We
  5479. * cannot afford to block and must pass all read bytes immediately
  5480. * to the client. */
  5481. nread = (int)read(fileno(fp), buf, (size_t)len);
  5482. #else
  5483. /* WinCE does not support CGI pipes */
  5484. nread = (int)fread(buf, 1, (size_t)len, fp);
  5485. #endif
  5486. err = (nread < 0) ? ERRNO : 0;
  5487. if ((nread == 0) && (len > 0)) {
  5488. /* Should get data, but got EOL */
  5489. return -2;
  5490. }
  5491. #if !defined(NO_SSL)
  5492. } else if ((conn->ssl != NULL)
  5493. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5494. /* We already know there is no more data buffered in conn->buf
  5495. * but there is more available in the SSL layer. So don't poll
  5496. * conn->client.sock yet. */
  5497. if (ssl_pending > len) {
  5498. ssl_pending = len;
  5499. }
  5500. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5501. if (nread <= 0) {
  5502. err = SSL_get_error(conn->ssl, nread);
  5503. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5504. err = ERRNO;
  5505. } else if ((err == SSL_ERROR_WANT_READ)
  5506. || (err == SSL_ERROR_WANT_WRITE)) {
  5507. nread = 0;
  5508. } else {
  5509. /* All errors should return -2 */
  5510. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5511. return -2;
  5512. }
  5513. ERR_clear_error();
  5514. } else {
  5515. err = 0;
  5516. }
  5517. } else if (conn->ssl != NULL) {
  5518. struct mg_pollfd pfd[1];
  5519. int pollres;
  5520. pfd[0].fd = conn->client.sock;
  5521. pfd[0].events = POLLIN;
  5522. pollres = mg_poll(pfd,
  5523. 1,
  5524. (int)(timeout * 1000.0),
  5525. &(conn->phys_ctx->stop_flag));
  5526. if (conn->phys_ctx->stop_flag) {
  5527. return -2;
  5528. }
  5529. if (pollres > 0) {
  5530. nread = SSL_read(conn->ssl, buf, len);
  5531. if (nread <= 0) {
  5532. err = SSL_get_error(conn->ssl, nread);
  5533. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5534. err = ERRNO;
  5535. } else if ((err == SSL_ERROR_WANT_READ)
  5536. || (err == SSL_ERROR_WANT_WRITE)) {
  5537. nread = 0;
  5538. } else {
  5539. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5540. return -2;
  5541. }
  5542. } else {
  5543. err = 0;
  5544. }
  5545. ERR_clear_error();
  5546. } else if (pollres < 0) {
  5547. /* Error */
  5548. return -2;
  5549. } else {
  5550. /* pollres = 0 means timeout */
  5551. nread = 0;
  5552. }
  5553. #endif
  5554. } else {
  5555. struct mg_pollfd pfd[1];
  5556. int pollres;
  5557. pfd[0].fd = conn->client.sock;
  5558. pfd[0].events = POLLIN;
  5559. pollres = mg_poll(pfd,
  5560. 1,
  5561. (int)(timeout * 1000.0),
  5562. &(conn->phys_ctx->stop_flag));
  5563. if (conn->phys_ctx->stop_flag) {
  5564. return -2;
  5565. }
  5566. if (pollres > 0) {
  5567. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5568. err = (nread < 0) ? ERRNO : 0;
  5569. if (nread <= 0) {
  5570. /* shutdown of the socket at client side */
  5571. return -2;
  5572. }
  5573. } else if (pollres < 0) {
  5574. /* error callint poll */
  5575. return -2;
  5576. } else {
  5577. /* pollres = 0 means timeout */
  5578. nread = 0;
  5579. }
  5580. }
  5581. if (conn->phys_ctx->stop_flag) {
  5582. return -2;
  5583. }
  5584. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5585. /* some data has been read, or no data was requested */
  5586. return nread;
  5587. }
  5588. if (nread < 0) {
  5589. /* socket error - check errno */
  5590. #if defined(_WIN32)
  5591. if (err == WSAEWOULDBLOCK) {
  5592. /* TODO (low): check if this is still required */
  5593. /* standard case if called from close_socket_gracefully */
  5594. return -2;
  5595. } else if (err == WSAETIMEDOUT) {
  5596. /* TODO (low): check if this is still required */
  5597. /* timeout is handled by the while loop */
  5598. return 0;
  5599. } else if (err == WSAECONNABORTED) {
  5600. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5601. return -2;
  5602. } else {
  5603. DEBUG_TRACE("recv() failed, error %d", err);
  5604. return -2;
  5605. }
  5606. #else
  5607. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5608. * if the timeout is reached and if the socket was set to non-
  5609. * blocking in close_socket_gracefully, so we can not distinguish
  5610. * here. We have to wait for the timeout in both cases for now.
  5611. */
  5612. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5613. /* TODO (low): check if this is still required */
  5614. /* EAGAIN/EWOULDBLOCK:
  5615. * standard case if called from close_socket_gracefully
  5616. * => should return -1 */
  5617. /* or timeout occurred
  5618. * => the code must stay in the while loop */
  5619. /* EINTR can be generated on a socket with a timeout set even
  5620. * when SA_RESTART is effective for all relevant signals
  5621. * (see signal(7)).
  5622. * => stay in the while loop */
  5623. } else {
  5624. DEBUG_TRACE("recv() failed, error %d", err);
  5625. return -2;
  5626. }
  5627. #endif
  5628. }
  5629. /* Timeout occurred, but no data available. */
  5630. return -1;
  5631. }
  5632. static int
  5633. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5634. {
  5635. int n, nread = 0;
  5636. double timeout = -1.0;
  5637. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5638. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5639. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5640. }
  5641. if (timeout >= 0.0) {
  5642. start_time = mg_get_current_time_ns();
  5643. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5644. }
  5645. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5646. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5647. if (n == -2) {
  5648. if (nread == 0) {
  5649. nread = -1; /* Propagate the error */
  5650. }
  5651. break;
  5652. } else if (n == -1) {
  5653. /* timeout */
  5654. if (timeout >= 0.0) {
  5655. now = mg_get_current_time_ns();
  5656. if ((now - start_time) <= timeout_ns) {
  5657. continue;
  5658. }
  5659. }
  5660. break;
  5661. } else if (n == 0) {
  5662. break; /* No more data to read */
  5663. } else {
  5664. nread += n;
  5665. len -= n;
  5666. }
  5667. }
  5668. return nread;
  5669. }
  5670. static void
  5671. discard_unread_request_data(struct mg_connection *conn)
  5672. {
  5673. char buf[MG_BUF_LEN];
  5674. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5675. ;
  5676. }
  5677. static int
  5678. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5679. {
  5680. int64_t content_len, n, buffered_len, nread;
  5681. int64_t len64 =
  5682. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5683. * int, we may not read more
  5684. * bytes */
  5685. const char *body;
  5686. if (conn == NULL) {
  5687. return 0;
  5688. }
  5689. /* If Content-Length is not set for a response with body data,
  5690. * we do not know in advance how much data should be read. */
  5691. content_len = conn->content_len;
  5692. if (content_len < 0) {
  5693. /* The body data is completed when the connection is closed. */
  5694. content_len = INT64_MAX;
  5695. }
  5696. nread = 0;
  5697. if (conn->consumed_content < content_len) {
  5698. /* Adjust number of bytes to read. */
  5699. int64_t left_to_read = content_len - conn->consumed_content;
  5700. if (left_to_read < len64) {
  5701. /* Do not read more than the total content length of the
  5702. * request.
  5703. */
  5704. len64 = left_to_read;
  5705. }
  5706. /* Return buffered data */
  5707. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5708. - conn->consumed_content;
  5709. if (buffered_len > 0) {
  5710. if (len64 < buffered_len) {
  5711. buffered_len = len64;
  5712. }
  5713. body = conn->buf + conn->request_len + conn->consumed_content;
  5714. memcpy(buf, body, (size_t)buffered_len);
  5715. len64 -= buffered_len;
  5716. conn->consumed_content += buffered_len;
  5717. nread += buffered_len;
  5718. buf = (char *)buf + buffered_len;
  5719. }
  5720. /* We have returned all buffered data. Read new data from the remote
  5721. * socket.
  5722. */
  5723. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5724. conn->consumed_content += n;
  5725. nread += n;
  5726. } else {
  5727. nread = ((nread > 0) ? nread : n);
  5728. }
  5729. }
  5730. return (int)nread;
  5731. }
  5732. int
  5733. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5734. {
  5735. if (len > INT_MAX) {
  5736. len = INT_MAX;
  5737. }
  5738. if (conn == NULL) {
  5739. return 0;
  5740. }
  5741. if (conn->is_chunked) {
  5742. size_t all_read = 0;
  5743. while (len > 0) {
  5744. if (conn->is_chunked >= 3) {
  5745. /* No more data left to read */
  5746. return 0;
  5747. }
  5748. if (conn->is_chunked != 1) {
  5749. /* Has error */
  5750. return -1;
  5751. }
  5752. if (conn->consumed_content != conn->content_len) {
  5753. /* copy from the current chunk */
  5754. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5755. if (read_ret < 1) {
  5756. /* read error */
  5757. conn->is_chunked = 2;
  5758. return -1;
  5759. }
  5760. all_read += (size_t)read_ret;
  5761. len -= (size_t)read_ret;
  5762. if (conn->consumed_content == conn->content_len) {
  5763. /* Add data bytes in the current chunk have been read,
  5764. * so we are expecting \r\n now. */
  5765. char x[2];
  5766. conn->content_len += 2;
  5767. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5768. || (x[1] != '\n')) {
  5769. /* Protocol violation */
  5770. conn->is_chunked = 2;
  5771. return -1;
  5772. }
  5773. }
  5774. } else {
  5775. /* fetch a new chunk */
  5776. size_t i;
  5777. char lenbuf[64];
  5778. char *end = NULL;
  5779. unsigned long chunkSize = 0;
  5780. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5781. conn->content_len++;
  5782. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5783. lenbuf[i] = 0;
  5784. }
  5785. if ((i > 0) && (lenbuf[i] == '\r')
  5786. && (lenbuf[i - 1] != '\r')) {
  5787. continue;
  5788. }
  5789. if ((i > 1) && (lenbuf[i] == '\n')
  5790. && (lenbuf[i - 1] == '\r')) {
  5791. lenbuf[i + 1] = 0;
  5792. chunkSize = strtoul(lenbuf, &end, 16);
  5793. if (chunkSize == 0) {
  5794. /* regular end of content */
  5795. conn->is_chunked = 3;
  5796. }
  5797. break;
  5798. }
  5799. if (!isxdigit((unsigned char)lenbuf[i])) {
  5800. /* illegal character for chunk length */
  5801. conn->is_chunked = 2;
  5802. return -1;
  5803. }
  5804. }
  5805. if ((end == NULL) || (*end != '\r')) {
  5806. /* chunksize not set correctly */
  5807. conn->is_chunked = 2;
  5808. return -1;
  5809. }
  5810. if (chunkSize == 0) {
  5811. /* try discarding trailer for keep-alive */
  5812. conn->content_len += 2;
  5813. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5814. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5815. conn->is_chunked = 4;
  5816. }
  5817. break;
  5818. }
  5819. /* append a new chunk */
  5820. conn->content_len += chunkSize;
  5821. }
  5822. }
  5823. return (int)all_read;
  5824. }
  5825. return mg_read_inner(conn, buf, len);
  5826. }
  5827. int
  5828. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5829. {
  5830. time_t now;
  5831. int n, total, allowed;
  5832. if (conn == NULL) {
  5833. return 0;
  5834. }
  5835. if (len > INT_MAX) {
  5836. return -1;
  5837. }
  5838. if (conn->throttle > 0) {
  5839. if ((now = time(NULL)) != conn->last_throttle_time) {
  5840. conn->last_throttle_time = now;
  5841. conn->last_throttle_bytes = 0;
  5842. }
  5843. allowed = conn->throttle - conn->last_throttle_bytes;
  5844. if (allowed > (int)len) {
  5845. allowed = (int)len;
  5846. }
  5847. if ((total = push_all(conn->phys_ctx,
  5848. NULL,
  5849. conn->client.sock,
  5850. conn->ssl,
  5851. (const char *)buf,
  5852. allowed))
  5853. == allowed) {
  5854. buf = (const char *)buf + total;
  5855. conn->last_throttle_bytes += total;
  5856. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5857. allowed = (conn->throttle > ((int)len - total))
  5858. ? (int)len - total
  5859. : conn->throttle;
  5860. if ((n = push_all(conn->phys_ctx,
  5861. NULL,
  5862. conn->client.sock,
  5863. conn->ssl,
  5864. (const char *)buf,
  5865. allowed))
  5866. != allowed) {
  5867. break;
  5868. }
  5869. sleep(1);
  5870. conn->last_throttle_bytes = allowed;
  5871. conn->last_throttle_time = time(NULL);
  5872. buf = (const char *)buf + n;
  5873. total += n;
  5874. }
  5875. }
  5876. } else {
  5877. total = push_all(conn->phys_ctx,
  5878. NULL,
  5879. conn->client.sock,
  5880. conn->ssl,
  5881. (const char *)buf,
  5882. (int)len);
  5883. }
  5884. if (total > 0) {
  5885. conn->num_bytes_sent += total;
  5886. }
  5887. return total;
  5888. }
  5889. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5890. int
  5891. mg_send_chunk(struct mg_connection *conn,
  5892. const char *chunk,
  5893. unsigned int chunk_len)
  5894. {
  5895. char lenbuf[16];
  5896. size_t lenbuf_len;
  5897. int ret;
  5898. int t;
  5899. /* First store the length information in a text buffer. */
  5900. sprintf(lenbuf, "%x\r\n", chunk_len);
  5901. lenbuf_len = strlen(lenbuf);
  5902. /* Then send length information, chunk and terminating \r\n. */
  5903. ret = mg_write(conn, lenbuf, lenbuf_len);
  5904. if (ret != (int)lenbuf_len) {
  5905. return -1;
  5906. }
  5907. t = ret;
  5908. ret = mg_write(conn, chunk, chunk_len);
  5909. if (ret != (int)chunk_len) {
  5910. return -1;
  5911. }
  5912. t += ret;
  5913. ret = mg_write(conn, "\r\n", 2);
  5914. if (ret != 2) {
  5915. return -1;
  5916. }
  5917. t += ret;
  5918. return t;
  5919. }
  5920. #if defined(GCC_DIAGNOSTIC)
  5921. /* This block forwards format strings to printf implementations,
  5922. * so we need to disable the format-nonliteral warning. */
  5923. #pragma GCC diagnostic push
  5924. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5925. #endif
  5926. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5927. static int
  5928. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5929. {
  5930. va_list ap_copy;
  5931. size_t size = MG_BUF_LEN / 4;
  5932. int len = -1;
  5933. *buf = NULL;
  5934. while (len < 0) {
  5935. if (*buf) {
  5936. mg_free(*buf);
  5937. }
  5938. size *= 4;
  5939. *buf = (char *)mg_malloc(size);
  5940. if (!*buf) {
  5941. break;
  5942. }
  5943. va_copy(ap_copy, ap);
  5944. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5945. va_end(ap_copy);
  5946. (*buf)[size - 1] = 0;
  5947. }
  5948. return len;
  5949. }
  5950. /* Print message to buffer. If buffer is large enough to hold the message,
  5951. * return buffer. If buffer is to small, allocate large enough buffer on
  5952. * heap,
  5953. * and return allocated buffer. */
  5954. static int
  5955. alloc_vprintf(char **out_buf,
  5956. char *prealloc_buf,
  5957. size_t prealloc_size,
  5958. const char *fmt,
  5959. va_list ap)
  5960. {
  5961. va_list ap_copy;
  5962. int len;
  5963. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5964. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5965. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5966. * Therefore, we make two passes: on first pass, get required message
  5967. * length.
  5968. * On second pass, actually print the message. */
  5969. va_copy(ap_copy, ap);
  5970. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5971. va_end(ap_copy);
  5972. if (len < 0) {
  5973. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5974. * Switch to alternative code path that uses incremental
  5975. * allocations.
  5976. */
  5977. va_copy(ap_copy, ap);
  5978. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5979. va_end(ap_copy);
  5980. } else if ((size_t)(len) >= prealloc_size) {
  5981. /* The pre-allocated buffer not large enough. */
  5982. /* Allocate a new buffer. */
  5983. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5984. if (!*out_buf) {
  5985. /* Allocation failed. Return -1 as "out of memory" error. */
  5986. return -1;
  5987. }
  5988. /* Buffer allocation successful. Store the string there. */
  5989. va_copy(ap_copy, ap);
  5990. IGNORE_UNUSED_RESULT(
  5991. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5992. va_end(ap_copy);
  5993. } else {
  5994. /* The pre-allocated buffer is large enough.
  5995. * Use it to store the string and return the address. */
  5996. va_copy(ap_copy, ap);
  5997. IGNORE_UNUSED_RESULT(
  5998. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5999. va_end(ap_copy);
  6000. *out_buf = prealloc_buf;
  6001. }
  6002. return len;
  6003. }
  6004. #if defined(GCC_DIAGNOSTIC)
  6005. /* Enable format-nonliteral warning again. */
  6006. #pragma GCC diagnostic pop
  6007. #endif
  6008. static int
  6009. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6010. {
  6011. char mem[MG_BUF_LEN];
  6012. char *buf = NULL;
  6013. int len;
  6014. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6015. len = mg_write(conn, buf, (size_t)len);
  6016. }
  6017. if (buf != mem) {
  6018. mg_free(buf);
  6019. }
  6020. return len;
  6021. }
  6022. int
  6023. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6024. {
  6025. va_list ap;
  6026. int result;
  6027. va_start(ap, fmt);
  6028. result = mg_vprintf(conn, fmt, ap);
  6029. va_end(ap);
  6030. return result;
  6031. }
  6032. int
  6033. mg_url_decode(const char *src,
  6034. int src_len,
  6035. char *dst,
  6036. int dst_len,
  6037. int is_form_url_encoded)
  6038. {
  6039. int i, j, a, b;
  6040. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6041. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6042. if ((i < src_len - 2) && (src[i] == '%')
  6043. && isxdigit((unsigned char)src[i + 1])
  6044. && isxdigit((unsigned char)src[i + 2])) {
  6045. a = tolower((unsigned char)src[i + 1]);
  6046. b = tolower((unsigned char)src[i + 2]);
  6047. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6048. i += 2;
  6049. } else if (is_form_url_encoded && (src[i] == '+')) {
  6050. dst[j] = ' ';
  6051. } else {
  6052. dst[j] = src[i];
  6053. }
  6054. }
  6055. dst[j] = '\0'; /* Null-terminate the destination */
  6056. return (i >= src_len) ? j : -1;
  6057. }
  6058. int
  6059. mg_get_var(const char *data,
  6060. size_t data_len,
  6061. const char *name,
  6062. char *dst,
  6063. size_t dst_len)
  6064. {
  6065. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6066. }
  6067. int
  6068. mg_get_var2(const char *data,
  6069. size_t data_len,
  6070. const char *name,
  6071. char *dst,
  6072. size_t dst_len,
  6073. size_t occurrence)
  6074. {
  6075. const char *p, *e, *s;
  6076. size_t name_len;
  6077. int len;
  6078. if ((dst == NULL) || (dst_len == 0)) {
  6079. len = -2;
  6080. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6081. len = -1;
  6082. dst[0] = '\0';
  6083. } else {
  6084. name_len = strlen(name);
  6085. e = data + data_len;
  6086. len = -1;
  6087. dst[0] = '\0';
  6088. /* data is "var1=val1&var2=val2...". Find variable first */
  6089. for (p = data; p + name_len < e; p++) {
  6090. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6091. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6092. /* Point p to variable value */
  6093. p += name_len + 1;
  6094. /* Point s to the end of the value */
  6095. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6096. if (s == NULL) {
  6097. s = e;
  6098. }
  6099. DEBUG_ASSERT(s >= p);
  6100. if (s < p) {
  6101. return -3;
  6102. }
  6103. /* Decode variable into destination buffer */
  6104. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6105. /* Redirect error code from -1 to -2 (destination buffer too
  6106. * small). */
  6107. if (len == -1) {
  6108. len = -2;
  6109. }
  6110. break;
  6111. }
  6112. }
  6113. }
  6114. return len;
  6115. }
  6116. /* HCP24: some changes to compare hole var_name */
  6117. int
  6118. mg_get_cookie(const char *cookie_header,
  6119. const char *var_name,
  6120. char *dst,
  6121. size_t dst_size)
  6122. {
  6123. const char *s, *p, *end;
  6124. int name_len, len = -1;
  6125. if ((dst == NULL) || (dst_size == 0)) {
  6126. return -2;
  6127. }
  6128. dst[0] = '\0';
  6129. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6130. return -1;
  6131. }
  6132. name_len = (int)strlen(var_name);
  6133. end = s + strlen(s);
  6134. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6135. if (s[name_len] == '=') {
  6136. /* HCP24: now check is it a substring or a full cookie name */
  6137. if ((s == cookie_header) || (s[-1] == ' ')) {
  6138. s += name_len + 1;
  6139. if ((p = strchr(s, ' ')) == NULL) {
  6140. p = end;
  6141. }
  6142. if (p[-1] == ';') {
  6143. p--;
  6144. }
  6145. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6146. s++;
  6147. p--;
  6148. }
  6149. if ((size_t)(p - s) < dst_size) {
  6150. len = (int)(p - s);
  6151. mg_strlcpy(dst, s, (size_t)len + 1);
  6152. } else {
  6153. len = -3;
  6154. }
  6155. break;
  6156. }
  6157. }
  6158. }
  6159. return len;
  6160. }
  6161. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6162. static void
  6163. base64_encode(const unsigned char *src, int src_len, char *dst)
  6164. {
  6165. static const char *b64 =
  6166. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6167. int i, j, a, b, c;
  6168. for (i = j = 0; i < src_len; i += 3) {
  6169. a = src[i];
  6170. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6171. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6172. dst[j++] = b64[a >> 2];
  6173. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6174. if (i + 1 < src_len) {
  6175. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6176. }
  6177. if (i + 2 < src_len) {
  6178. dst[j++] = b64[c & 63];
  6179. }
  6180. }
  6181. while (j % 4 != 0) {
  6182. dst[j++] = '=';
  6183. }
  6184. dst[j++] = '\0';
  6185. }
  6186. #endif
  6187. #if defined(USE_LUA)
  6188. static unsigned char
  6189. b64reverse(char letter)
  6190. {
  6191. if ((letter >= 'A') && (letter <= 'Z')) {
  6192. return letter - 'A';
  6193. }
  6194. if ((letter >= 'a') && (letter <= 'z')) {
  6195. return letter - 'a' + 26;
  6196. }
  6197. if ((letter >= '0') && (letter <= '9')) {
  6198. return letter - '0' + 52;
  6199. }
  6200. if (letter == '+') {
  6201. return 62;
  6202. }
  6203. if (letter == '/') {
  6204. return 63;
  6205. }
  6206. if (letter == '=') {
  6207. return 255; /* normal end */
  6208. }
  6209. return 254; /* error */
  6210. }
  6211. static int
  6212. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6213. {
  6214. int i;
  6215. unsigned char a, b, c, d;
  6216. *dst_len = 0;
  6217. for (i = 0; i < src_len; i += 4) {
  6218. a = b64reverse(src[i]);
  6219. if (a >= 254) {
  6220. return i;
  6221. }
  6222. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6223. if (b >= 254) {
  6224. return i + 1;
  6225. }
  6226. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6227. if (c == 254) {
  6228. return i + 2;
  6229. }
  6230. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6231. if (d == 254) {
  6232. return i + 3;
  6233. }
  6234. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6235. if (c != 255) {
  6236. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6237. if (d != 255) {
  6238. dst[(*dst_len)++] = (c << 6) + d;
  6239. }
  6240. }
  6241. }
  6242. return -1;
  6243. }
  6244. #endif
  6245. static int
  6246. is_put_or_delete_method(const struct mg_connection *conn)
  6247. {
  6248. if (conn) {
  6249. const char *s = conn->request_info.request_method;
  6250. return (s != NULL)
  6251. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6252. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6253. }
  6254. return 0;
  6255. }
  6256. #if !defined(NO_FILES)
  6257. static int
  6258. extention_matches_script(
  6259. struct mg_connection *conn, /* in: request (must be valid) */
  6260. const char *filename /* in: filename (must be valid) */
  6261. )
  6262. {
  6263. #if !defined(NO_CGI)
  6264. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6265. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6266. filename)
  6267. > 0) {
  6268. return 1;
  6269. }
  6270. #endif
  6271. #if defined(USE_LUA)
  6272. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6273. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6274. filename)
  6275. > 0) {
  6276. return 1;
  6277. }
  6278. #endif
  6279. #if defined(USE_DUKTAPE)
  6280. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6281. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6282. filename)
  6283. > 0) {
  6284. return 1;
  6285. }
  6286. #endif
  6287. /* filename and conn could be unused, if all preocessor conditions
  6288. * are false (no script language supported). */
  6289. (void)filename;
  6290. (void)conn;
  6291. return 0;
  6292. }
  6293. /* For given directory path, substitute it to valid index file.
  6294. * Return 1 if index file has been found, 0 if not found.
  6295. * If the file is found, it's stats is returned in stp. */
  6296. static int
  6297. substitute_index_file(struct mg_connection *conn,
  6298. char *path,
  6299. size_t path_len,
  6300. struct mg_file_stat *filestat)
  6301. {
  6302. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6303. struct vec filename_vec;
  6304. size_t n = strlen(path);
  6305. int found = 0;
  6306. /* The 'path' given to us points to the directory. Remove all trailing
  6307. * directory separator characters from the end of the path, and
  6308. * then append single directory separator character. */
  6309. while ((n > 0) && (path[n - 1] == '/')) {
  6310. n--;
  6311. }
  6312. path[n] = '/';
  6313. /* Traverse index files list. For each entry, append it to the given
  6314. * path and see if the file exists. If it exists, break the loop */
  6315. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6316. /* Ignore too long entries that may overflow path buffer */
  6317. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6318. continue;
  6319. }
  6320. /* Prepare full path to the index file */
  6321. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6322. /* Does it exist? */
  6323. if (mg_stat(conn, path, filestat)) {
  6324. /* Yes it does, break the loop */
  6325. found = 1;
  6326. break;
  6327. }
  6328. }
  6329. /* If no index file exists, restore directory path */
  6330. if (!found) {
  6331. path[n] = '\0';
  6332. }
  6333. return found;
  6334. }
  6335. #endif
  6336. static void
  6337. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6338. char *filename, /* out: filename */
  6339. size_t filename_buf_len, /* in: size of filename buffer */
  6340. struct mg_file_stat *filestat, /* out: file status structure */
  6341. int *is_found, /* out: file found (directly) */
  6342. int *is_script_resource, /* out: handled by a script? */
  6343. int *is_websocket_request, /* out: websocket connetion? */
  6344. int *is_put_or_delete_request /* out: put/delete a file? */
  6345. )
  6346. {
  6347. char const *accept_encoding;
  6348. #if !defined(NO_FILES)
  6349. const char *uri = conn->request_info.local_uri;
  6350. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6351. const char *rewrite;
  6352. struct vec a, b;
  6353. ptrdiff_t match_len;
  6354. char gz_path[PATH_MAX];
  6355. int truncated;
  6356. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6357. char *tmp_str;
  6358. size_t tmp_str_len, sep_pos;
  6359. int allow_substitute_script_subresources;
  6360. #endif
  6361. #else
  6362. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6363. #endif
  6364. /* Step 1: Set all initially unknown outputs to zero */
  6365. memset(filestat, 0, sizeof(*filestat));
  6366. *filename = 0;
  6367. *is_found = 0;
  6368. *is_script_resource = 0;
  6369. /* Step 2: Check if the request attempts to modify the file system */
  6370. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6371. /* Step 3: Check if it is a websocket request, and modify the document
  6372. * root if required */
  6373. #if defined(USE_WEBSOCKET)
  6374. *is_websocket_request = is_websocket_protocol(conn);
  6375. #if !defined(NO_FILES)
  6376. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6377. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6378. }
  6379. #endif /* !NO_FILES */
  6380. #else /* USE_WEBSOCKET */
  6381. *is_websocket_request = 0;
  6382. #endif /* USE_WEBSOCKET */
  6383. /* Step 4: Check if gzip encoded response is allowed */
  6384. conn->accept_gzip = 0;
  6385. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6386. if (strstr(accept_encoding, "gzip") != NULL) {
  6387. conn->accept_gzip = 1;
  6388. }
  6389. }
  6390. #if !defined(NO_FILES)
  6391. /* Step 5: If there is no root directory, don't look for files. */
  6392. /* Note that root == NULL is a regular use case here. This occurs,
  6393. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6394. * config is not required. */
  6395. if (root == NULL) {
  6396. /* all file related outputs have already been set to 0, just return
  6397. */
  6398. return;
  6399. }
  6400. /* Step 6: Determine the local file path from the root path and the
  6401. * request uri. */
  6402. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6403. * part of the path one byte on the right. */
  6404. mg_snprintf(
  6405. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6406. if (truncated) {
  6407. goto interpret_cleanup;
  6408. }
  6409. /* Step 7: URI rewriting */
  6410. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6411. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6412. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6413. mg_snprintf(conn,
  6414. &truncated,
  6415. filename,
  6416. filename_buf_len - 1,
  6417. "%.*s%s",
  6418. (int)b.len,
  6419. b.ptr,
  6420. uri + match_len);
  6421. break;
  6422. }
  6423. }
  6424. if (truncated) {
  6425. goto interpret_cleanup;
  6426. }
  6427. /* Step 8: Check if the file exists at the server */
  6428. /* Local file path and name, corresponding to requested URI
  6429. * is now stored in "filename" variable. */
  6430. if (mg_stat(conn, filename, filestat)) {
  6431. int uri_len = (int)strlen(uri);
  6432. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6433. /* 8.1: File exists. */
  6434. *is_found = 1;
  6435. /* 8.2: Check if it is a script type. */
  6436. if (extention_matches_script(conn, filename)) {
  6437. /* The request addresses a CGI resource, Lua script or
  6438. * server-side javascript.
  6439. * The URI corresponds to the script itself (like
  6440. * /path/script.cgi), and there is no additional resource
  6441. * path (like /path/script.cgi/something).
  6442. * Requests that modify (replace or delete) a resource, like
  6443. * PUT and DELETE requests, should replace/delete the script
  6444. * file.
  6445. * Requests that read or write from/to a resource, like GET and
  6446. * POST requests, should call the script and return the
  6447. * generated response. */
  6448. *is_script_resource = (!*is_put_or_delete_request);
  6449. }
  6450. /* 8.3: If the request target is a directory, there could be
  6451. * a substitute file (index.html, index.cgi, ...). */
  6452. if (filestat->is_directory && is_uri_end_slash) {
  6453. /* Use a local copy here, since substitute_index_file will
  6454. * change the content of the file status */
  6455. struct mg_file_stat tmp_filestat;
  6456. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6457. if (substitute_index_file(
  6458. conn, filename, filename_buf_len, &tmp_filestat)) {
  6459. /* Substitute file found. Copy stat to the output, then
  6460. * check if the file is a script file */
  6461. *filestat = tmp_filestat;
  6462. if (extention_matches_script(conn, filename)) {
  6463. /* Substitute file is a script file */
  6464. *is_script_resource = 1;
  6465. } else {
  6466. /* Substitute file is a regular file */
  6467. *is_script_resource = 0;
  6468. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6469. }
  6470. }
  6471. /* If there is no substitute file, the server could return
  6472. * a directory listing in a later step */
  6473. }
  6474. return;
  6475. }
  6476. /* Step 9: Check for zipped files: */
  6477. /* If we can't find the actual file, look for the file
  6478. * with the same name but a .gz extension. If we find it,
  6479. * use that and set the gzipped flag in the file struct
  6480. * to indicate that the response need to have the content-
  6481. * encoding: gzip header.
  6482. * We can only do this if the browser declares support. */
  6483. if (conn->accept_gzip) {
  6484. mg_snprintf(
  6485. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6486. if (truncated) {
  6487. goto interpret_cleanup;
  6488. }
  6489. if (mg_stat(conn, gz_path, filestat)) {
  6490. if (filestat) {
  6491. filestat->is_gzipped = 1;
  6492. *is_found = 1;
  6493. }
  6494. /* Currently gz files can not be scripts. */
  6495. return;
  6496. }
  6497. }
  6498. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6499. /* Step 10: Script resources may handle sub-resources */
  6500. /* Support PATH_INFO for CGI scripts. */
  6501. tmp_str_len = strlen(filename);
  6502. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6503. if (!tmp_str) {
  6504. /* Out of memory */
  6505. goto interpret_cleanup;
  6506. }
  6507. memcpy(tmp_str, filename, tmp_str_len + 1);
  6508. /* Check config, if index scripts may have sub-resources */
  6509. allow_substitute_script_subresources =
  6510. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6511. "yes");
  6512. sep_pos = tmp_str_len;
  6513. while (sep_pos > 0) {
  6514. sep_pos--;
  6515. if (tmp_str[sep_pos] == '/') {
  6516. int is_script = 0, does_exist = 0;
  6517. tmp_str[sep_pos] = 0;
  6518. if (tmp_str[0]) {
  6519. is_script = extention_matches_script(conn, tmp_str);
  6520. does_exist = mg_stat(conn, tmp_str, filestat);
  6521. }
  6522. if (does_exist && is_script) {
  6523. filename[sep_pos] = 0;
  6524. memmove(filename + sep_pos + 2,
  6525. filename + sep_pos + 1,
  6526. strlen(filename + sep_pos + 1) + 1);
  6527. conn->path_info = filename + sep_pos + 1;
  6528. filename[sep_pos + 1] = '/';
  6529. *is_script_resource = 1;
  6530. *is_found = 1;
  6531. break;
  6532. }
  6533. if (allow_substitute_script_subresources) {
  6534. if (substitute_index_file(
  6535. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6536. /* some intermediate directory has an index file */
  6537. if (extention_matches_script(conn, tmp_str)) {
  6538. char *tmp_str2;
  6539. DEBUG_TRACE("Substitute script %s serving path %s",
  6540. tmp_str,
  6541. filename);
  6542. /* this index file is a script */
  6543. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6544. conn->phys_ctx);
  6545. mg_snprintf(conn,
  6546. &truncated,
  6547. filename,
  6548. filename_buf_len,
  6549. "%s//%s",
  6550. tmp_str,
  6551. tmp_str2);
  6552. mg_free(tmp_str2);
  6553. if (truncated) {
  6554. mg_free(tmp_str);
  6555. goto interpret_cleanup;
  6556. }
  6557. sep_pos = strlen(tmp_str);
  6558. filename[sep_pos] = 0;
  6559. conn->path_info = filename + sep_pos + 1;
  6560. *is_script_resource = 1;
  6561. *is_found = 1;
  6562. break;
  6563. } else {
  6564. DEBUG_TRACE("Substitute file %s serving path %s",
  6565. tmp_str,
  6566. filename);
  6567. /* non-script files will not have sub-resources */
  6568. filename[sep_pos] = 0;
  6569. conn->path_info = 0;
  6570. *is_script_resource = 0;
  6571. *is_found = 0;
  6572. break;
  6573. }
  6574. }
  6575. }
  6576. tmp_str[sep_pos] = '/';
  6577. }
  6578. }
  6579. mg_free(tmp_str);
  6580. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6581. #endif /* !defined(NO_FILES) */
  6582. return;
  6583. #if !defined(NO_FILES)
  6584. /* Reset all outputs */
  6585. interpret_cleanup:
  6586. memset(filestat, 0, sizeof(*filestat));
  6587. *filename = 0;
  6588. *is_found = 0;
  6589. *is_script_resource = 0;
  6590. *is_websocket_request = 0;
  6591. *is_put_or_delete_request = 0;
  6592. #endif /* !defined(NO_FILES) */
  6593. }
  6594. /* Check whether full request is buffered. Return:
  6595. * -1 if request or response is malformed
  6596. * 0 if request or response is not yet fully buffered
  6597. * >0 actual request length, including last \r\n\r\n */
  6598. static int
  6599. get_http_header_len(const char *buf, int buflen)
  6600. {
  6601. int i;
  6602. for (i = 0; i < buflen; i++) {
  6603. /* Do an unsigned comparison in some conditions below */
  6604. const unsigned char c = (unsigned char)buf[i];
  6605. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6606. && !isprint(c)) {
  6607. /* abort scan as soon as one malformed character is found */
  6608. return -1;
  6609. }
  6610. if (i < buflen - 1) {
  6611. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6612. /* Two newline, no carriage return - not standard compliant,
  6613. * but
  6614. * it
  6615. * should be accepted */
  6616. return i + 2;
  6617. }
  6618. }
  6619. if (i < buflen - 3) {
  6620. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6621. && (buf[i + 3] == '\n')) {
  6622. /* Two \r\n - standard compliant */
  6623. return i + 4;
  6624. }
  6625. }
  6626. }
  6627. return 0;
  6628. }
  6629. #if !defined(NO_CACHING)
  6630. /* Convert month to the month number. Return -1 on error, or month number */
  6631. static int
  6632. get_month_index(const char *s)
  6633. {
  6634. size_t i;
  6635. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6636. if (!strcmp(s, month_names[i])) {
  6637. return (int)i;
  6638. }
  6639. }
  6640. return -1;
  6641. }
  6642. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6643. static time_t
  6644. parse_date_string(const char *datetime)
  6645. {
  6646. char month_str[32] = {0};
  6647. int second, minute, hour, day, month, year;
  6648. time_t result = (time_t)0;
  6649. struct tm tm;
  6650. if ((sscanf(datetime,
  6651. "%d/%3s/%d %d:%d:%d",
  6652. &day,
  6653. month_str,
  6654. &year,
  6655. &hour,
  6656. &minute,
  6657. &second)
  6658. == 6)
  6659. || (sscanf(datetime,
  6660. "%d %3s %d %d:%d:%d",
  6661. &day,
  6662. month_str,
  6663. &year,
  6664. &hour,
  6665. &minute,
  6666. &second)
  6667. == 6)
  6668. || (sscanf(datetime,
  6669. "%*3s, %d %3s %d %d:%d:%d",
  6670. &day,
  6671. month_str,
  6672. &year,
  6673. &hour,
  6674. &minute,
  6675. &second)
  6676. == 6)
  6677. || (sscanf(datetime,
  6678. "%d-%3s-%d %d:%d:%d",
  6679. &day,
  6680. month_str,
  6681. &year,
  6682. &hour,
  6683. &minute,
  6684. &second)
  6685. == 6)) {
  6686. month = get_month_index(month_str);
  6687. if ((month >= 0) && (year >= 1970)) {
  6688. memset(&tm, 0, sizeof(tm));
  6689. tm.tm_year = year - 1900;
  6690. tm.tm_mon = month;
  6691. tm.tm_mday = day;
  6692. tm.tm_hour = hour;
  6693. tm.tm_min = minute;
  6694. tm.tm_sec = second;
  6695. result = timegm(&tm);
  6696. }
  6697. }
  6698. return result;
  6699. }
  6700. #endif /* !NO_CACHING */
  6701. /* Pre-process URIs according to RFC + protect against directory disclosure
  6702. * attacks by removing '..', excessive '/' and '\' characters */
  6703. static void
  6704. remove_dot_segments(char *inout)
  6705. {
  6706. /* Windows backend protection
  6707. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash in
  6708. * URI by slash */
  6709. char *in_copy = mg_strdup(inout);
  6710. char *out_begin = inout;
  6711. char *out_end = inout;
  6712. char *in = in_copy;
  6713. int replaced;
  6714. while (*in) {
  6715. if (*in == '\\') {
  6716. *in = '/';
  6717. }
  6718. in++;
  6719. }
  6720. /* Algorithm "remove_dot_segments" from
  6721. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6722. /* Step 1:
  6723. * The input buffer is initialized.
  6724. * The output buffer is initialized to the empty string.
  6725. */
  6726. in = in_copy;
  6727. /* Step 2:
  6728. * While the input buffer is not empty, loop as follows:
  6729. */
  6730. while (*in) {
  6731. /* Step 2a:
  6732. * If the input buffer begins with a prefix of "../" or "./",
  6733. * then remove that prefix from the input buffer;
  6734. */
  6735. if (!strncmp(in, "../", 3)) {
  6736. in += 3;
  6737. } else if (!strncmp(in, "./", 2)) {
  6738. in += 2;
  6739. }
  6740. /* otherwise */
  6741. /* Step 2b:
  6742. * if the input buffer begins with a prefix of "/./" or "/.",
  6743. * where "." is a complete path segment, then replace that
  6744. * prefix with "/" in the input buffer;
  6745. */
  6746. else if (!strncmp(in, "/./", 3)) {
  6747. in += 2;
  6748. } else if (!strcmp(in, "/.")) {
  6749. in[1] = 0;
  6750. }
  6751. /* otherwise */
  6752. /* Step 2c:
  6753. * if the input buffer begins with a prefix of "/../" or "/..",
  6754. * where ".." is a complete path segment, then replace that
  6755. * prefix with "/" in the input buffer and remove the last
  6756. * segment and its preceding "/" (if any) from the output
  6757. * buffer;
  6758. */
  6759. else if (!strncmp(in, "/../", 4)) {
  6760. in += 3;
  6761. if (out_begin != out_end) {
  6762. /* remove last segment */
  6763. do {
  6764. out_end--;
  6765. *out_end = 0;
  6766. } while ((out_begin != out_end) && (*out_end != '/'));
  6767. }
  6768. } else if (!strcmp(in, "/..")) {
  6769. in[1] = 0;
  6770. if (out_begin != out_end) {
  6771. /* remove last segment */
  6772. do {
  6773. out_end--;
  6774. *out_end = 0;
  6775. } while ((out_begin != out_end) && (*out_end != '/'));
  6776. }
  6777. }
  6778. /* otherwise */
  6779. /* Step 2d:
  6780. * if the input buffer consists only of "." or "..", then remove
  6781. * that from the input buffer;
  6782. */
  6783. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6784. *in = 0;
  6785. }
  6786. /* otherwise */
  6787. /* Step 2e:
  6788. * move the first path segment in the input buffer to the end of
  6789. * the output buffer, including the initial "/" character (if
  6790. * any) and any subsequent characters up to, but not including,
  6791. * the next "/" character or the end of the input buffer.
  6792. */
  6793. else {
  6794. do {
  6795. *out_end = *in;
  6796. out_end++;
  6797. in++;
  6798. } while ((*in != 0) && (*in != '/'));
  6799. }
  6800. }
  6801. /* Step 3:
  6802. * Finally, the output buffer is returned as the result of
  6803. * remove_dot_segments.
  6804. */
  6805. /* Terminate output */
  6806. *out_end = 0;
  6807. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6808. * extension) are identical. Replace all "./" by "/" and remove a "." at the
  6809. * end.
  6810. * Also replace all "//" by "/".
  6811. * Repeat until there is no "./" or "//" anymore.
  6812. */
  6813. do {
  6814. replaced = 0;
  6815. /* replace ./ by / */
  6816. out_end = out_begin;
  6817. while (*out_end) {
  6818. if ((*out_end == '.')
  6819. && ((out_end[1] == '/') || (out_end[1] == 0))) {
  6820. char *r = out_end;
  6821. do {
  6822. r[0] = r[1];
  6823. r++;
  6824. replaced = 1;
  6825. } while (r[0] != 0);
  6826. }
  6827. out_end++;
  6828. }
  6829. /* replace ./ by / */
  6830. out_end = out_begin;
  6831. while (*out_end) {
  6832. if ((out_end[0] == '/') && (out_end[1] == '/')) {
  6833. char *c = out_end;
  6834. while (*c) {
  6835. c[0] = c[1];
  6836. c++;
  6837. }
  6838. replaced = 1;
  6839. }
  6840. out_end++;
  6841. }
  6842. } while (replaced);
  6843. /* Free temporary copies */
  6844. mg_free(in_copy);
  6845. }
  6846. static const struct {
  6847. const char *extension;
  6848. size_t ext_len;
  6849. const char *mime_type;
  6850. } builtin_mime_types[] = {
  6851. /* IANA registered MIME types
  6852. * (http://www.iana.org/assignments/media-types)
  6853. * application types */
  6854. {".doc", 4, "application/msword"},
  6855. {".eps", 4, "application/postscript"},
  6856. {".exe", 4, "application/octet-stream"},
  6857. {".js", 3, "application/javascript"},
  6858. {".json", 5, "application/json"},
  6859. {".pdf", 4, "application/pdf"},
  6860. {".ps", 3, "application/postscript"},
  6861. {".rtf", 4, "application/rtf"},
  6862. {".xhtml", 6, "application/xhtml+xml"},
  6863. {".xsl", 4, "application/xml"},
  6864. {".xslt", 5, "application/xml"},
  6865. /* fonts */
  6866. {".ttf", 4, "application/font-sfnt"},
  6867. {".cff", 4, "application/font-sfnt"},
  6868. {".otf", 4, "application/font-sfnt"},
  6869. {".aat", 4, "application/font-sfnt"},
  6870. {".sil", 4, "application/font-sfnt"},
  6871. {".pfr", 4, "application/font-tdpfr"},
  6872. {".woff", 5, "application/font-woff"},
  6873. /* audio */
  6874. {".mp3", 4, "audio/mpeg"},
  6875. {".oga", 4, "audio/ogg"},
  6876. {".ogg", 4, "audio/ogg"},
  6877. /* image */
  6878. {".gif", 4, "image/gif"},
  6879. {".ief", 4, "image/ief"},
  6880. {".jpeg", 5, "image/jpeg"},
  6881. {".jpg", 4, "image/jpeg"},
  6882. {".jpm", 4, "image/jpm"},
  6883. {".jpx", 4, "image/jpx"},
  6884. {".png", 4, "image/png"},
  6885. {".svg", 4, "image/svg+xml"},
  6886. {".tif", 4, "image/tiff"},
  6887. {".tiff", 5, "image/tiff"},
  6888. /* model */
  6889. {".wrl", 4, "model/vrml"},
  6890. /* text */
  6891. {".css", 4, "text/css"},
  6892. {".csv", 4, "text/csv"},
  6893. {".htm", 4, "text/html"},
  6894. {".html", 5, "text/html"},
  6895. {".sgm", 4, "text/sgml"},
  6896. {".shtm", 5, "text/html"},
  6897. {".shtml", 6, "text/html"},
  6898. {".txt", 4, "text/plain"},
  6899. {".xml", 4, "text/xml"},
  6900. /* video */
  6901. {".mov", 4, "video/quicktime"},
  6902. {".mp4", 4, "video/mp4"},
  6903. {".mpeg", 5, "video/mpeg"},
  6904. {".mpg", 4, "video/mpeg"},
  6905. {".ogv", 4, "video/ogg"},
  6906. {".qt", 3, "video/quicktime"},
  6907. /* not registered types
  6908. * (http://reference.sitepoint.com/html/mime-types-full,
  6909. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6910. {".arj", 4, "application/x-arj-compressed"},
  6911. {".gz", 3, "application/x-gunzip"},
  6912. {".rar", 4, "application/x-arj-compressed"},
  6913. {".swf", 4, "application/x-shockwave-flash"},
  6914. {".tar", 4, "application/x-tar"},
  6915. {".tgz", 4, "application/x-tar-gz"},
  6916. {".torrent", 8, "application/x-bittorrent"},
  6917. {".ppt", 4, "application/x-mspowerpoint"},
  6918. {".xls", 4, "application/x-msexcel"},
  6919. {".zip", 4, "application/x-zip-compressed"},
  6920. {".aac",
  6921. 4,
  6922. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6923. {".aif", 4, "audio/x-aif"},
  6924. {".m3u", 4, "audio/x-mpegurl"},
  6925. {".mid", 4, "audio/x-midi"},
  6926. {".ra", 3, "audio/x-pn-realaudio"},
  6927. {".ram", 4, "audio/x-pn-realaudio"},
  6928. {".wav", 4, "audio/x-wav"},
  6929. {".bmp", 4, "image/bmp"},
  6930. {".ico", 4, "image/x-icon"},
  6931. {".pct", 4, "image/x-pct"},
  6932. {".pict", 5, "image/pict"},
  6933. {".rgb", 4, "image/x-rgb"},
  6934. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6935. {".asf", 4, "video/x-ms-asf"},
  6936. {".avi", 4, "video/x-msvideo"},
  6937. {".m4v", 4, "video/x-m4v"},
  6938. {NULL, 0, NULL}};
  6939. const char *
  6940. mg_get_builtin_mime_type(const char *path)
  6941. {
  6942. const char *ext;
  6943. size_t i, path_len;
  6944. path_len = strlen(path);
  6945. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6946. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6947. if ((path_len > builtin_mime_types[i].ext_len)
  6948. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6949. return builtin_mime_types[i].mime_type;
  6950. }
  6951. }
  6952. return "text/plain";
  6953. }
  6954. /* Look at the "path" extension and figure what mime type it has.
  6955. * Store mime type in the vector. */
  6956. static void
  6957. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6958. {
  6959. struct vec ext_vec, mime_vec;
  6960. const char *list, *ext;
  6961. size_t path_len;
  6962. path_len = strlen(path);
  6963. if ((conn == NULL) || (vec == NULL)) {
  6964. if (vec != NULL) {
  6965. memset(vec, '\0', sizeof(struct vec));
  6966. }
  6967. return;
  6968. }
  6969. /* Scan user-defined mime types first, in case user wants to
  6970. * override default mime types. */
  6971. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6972. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6973. /* ext now points to the path suffix */
  6974. ext = path + path_len - ext_vec.len;
  6975. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6976. *vec = mime_vec;
  6977. return;
  6978. }
  6979. }
  6980. vec->ptr = mg_get_builtin_mime_type(path);
  6981. vec->len = strlen(vec->ptr);
  6982. }
  6983. /* Stringify binary data. Output buffer must be twice as big as input,
  6984. * because each byte takes 2 bytes in string representation */
  6985. static void
  6986. bin2str(char *to, const unsigned char *p, size_t len)
  6987. {
  6988. static const char *hex = "0123456789abcdef";
  6989. for (; len--; p++) {
  6990. *to++ = hex[p[0] >> 4];
  6991. *to++ = hex[p[0] & 0x0f];
  6992. }
  6993. *to = '\0';
  6994. }
  6995. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6996. */
  6997. char *
  6998. mg_md5(char buf[33], ...)
  6999. {
  7000. md5_byte_t hash[16];
  7001. const char *p;
  7002. va_list ap;
  7003. md5_state_t ctx;
  7004. md5_init(&ctx);
  7005. va_start(ap, buf);
  7006. while ((p = va_arg(ap, const char *)) != NULL) {
  7007. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7008. }
  7009. va_end(ap);
  7010. md5_finish(&ctx, hash);
  7011. bin2str(buf, hash, sizeof(hash));
  7012. return buf;
  7013. }
  7014. /* Check the user's password, return 1 if OK */
  7015. static int
  7016. check_password(const char *method,
  7017. const char *ha1,
  7018. const char *uri,
  7019. const char *nonce,
  7020. const char *nc,
  7021. const char *cnonce,
  7022. const char *qop,
  7023. const char *response)
  7024. {
  7025. char ha2[32 + 1], expected_response[32 + 1];
  7026. /* Some of the parameters may be NULL */
  7027. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7028. || (qop == NULL) || (response == NULL)) {
  7029. return 0;
  7030. }
  7031. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7032. if (strlen(response) != 32) {
  7033. return 0;
  7034. }
  7035. mg_md5(ha2, method, ":", uri, NULL);
  7036. mg_md5(expected_response,
  7037. ha1,
  7038. ":",
  7039. nonce,
  7040. ":",
  7041. nc,
  7042. ":",
  7043. cnonce,
  7044. ":",
  7045. qop,
  7046. ":",
  7047. ha2,
  7048. NULL);
  7049. return mg_strcasecmp(response, expected_response) == 0;
  7050. }
  7051. #if !defined(NO_FILESYSTEMS)
  7052. /* Use the global passwords file, if specified by auth_gpass option,
  7053. * or search for .htpasswd in the requested directory. */
  7054. static void
  7055. open_auth_file(struct mg_connection *conn,
  7056. const char *path,
  7057. struct mg_file *filep)
  7058. {
  7059. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7060. char name[PATH_MAX];
  7061. const char *p, *e,
  7062. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7063. int truncated;
  7064. if (gpass != NULL) {
  7065. /* Use global passwords file */
  7066. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7067. #if defined(DEBUG)
  7068. /* Use mg_cry_internal here, since gpass has been configured. */
  7069. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7070. #endif
  7071. }
  7072. /* Important: using local struct mg_file to test path for
  7073. * is_directory flag. If filep is used, mg_stat() makes it
  7074. * appear as if auth file was opened.
  7075. * TODO(mid): Check if this is still required after rewriting
  7076. * mg_stat */
  7077. } else if (mg_stat(conn, path, &filep->stat)
  7078. && filep->stat.is_directory) {
  7079. mg_snprintf(conn,
  7080. &truncated,
  7081. name,
  7082. sizeof(name),
  7083. "%s/%s",
  7084. path,
  7085. PASSWORDS_FILE_NAME);
  7086. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7087. #if defined(DEBUG)
  7088. /* Don't use mg_cry_internal here, but only a trace, since this
  7089. * is
  7090. * a typical case. It will occur for every directory
  7091. * without a password file. */
  7092. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7093. #endif
  7094. }
  7095. } else {
  7096. /* Try to find .htpasswd in requested directory. */
  7097. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7098. if (e[0] == '/') {
  7099. break;
  7100. }
  7101. }
  7102. mg_snprintf(conn,
  7103. &truncated,
  7104. name,
  7105. sizeof(name),
  7106. "%.*s/%s",
  7107. (int)(e - p),
  7108. p,
  7109. PASSWORDS_FILE_NAME);
  7110. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7111. #if defined(DEBUG)
  7112. /* Don't use mg_cry_internal here, but only a trace, since this
  7113. * is
  7114. * a typical case. It will occur for every directory
  7115. * without a password file. */
  7116. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7117. #endif
  7118. }
  7119. }
  7120. }
  7121. }
  7122. #endif /* NO_FILESYSTEMS */
  7123. /* Parsed Authorization header */
  7124. struct ah {
  7125. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7126. };
  7127. /* Return 1 on success. Always initializes the ah structure. */
  7128. static int
  7129. parse_auth_header(struct mg_connection *conn,
  7130. char *buf,
  7131. size_t buf_size,
  7132. struct ah *ah)
  7133. {
  7134. char *name, *value, *s;
  7135. const char *auth_header;
  7136. uint64_t nonce;
  7137. if (!ah || !conn) {
  7138. return 0;
  7139. }
  7140. (void)memset(ah, 0, sizeof(*ah));
  7141. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7142. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7143. return 0;
  7144. }
  7145. /* Make modifiable copy of the auth header */
  7146. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7147. s = buf;
  7148. /* Parse authorization header */
  7149. for (;;) {
  7150. /* Gobble initial spaces */
  7151. while (isspace((unsigned char)*s)) {
  7152. s++;
  7153. }
  7154. name = skip_quoted(&s, "=", " ", 0);
  7155. /* Value is either quote-delimited, or ends at first comma or space.
  7156. */
  7157. if (s[0] == '\"') {
  7158. s++;
  7159. value = skip_quoted(&s, "\"", " ", '\\');
  7160. if (s[0] == ',') {
  7161. s++;
  7162. }
  7163. } else {
  7164. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  7165. * spaces */
  7166. }
  7167. if (*name == '\0') {
  7168. break;
  7169. }
  7170. if (!strcmp(name, "username")) {
  7171. ah->user = value;
  7172. } else if (!strcmp(name, "cnonce")) {
  7173. ah->cnonce = value;
  7174. } else if (!strcmp(name, "response")) {
  7175. ah->response = value;
  7176. } else if (!strcmp(name, "uri")) {
  7177. ah->uri = value;
  7178. } else if (!strcmp(name, "qop")) {
  7179. ah->qop = value;
  7180. } else if (!strcmp(name, "nc")) {
  7181. ah->nc = value;
  7182. } else if (!strcmp(name, "nonce")) {
  7183. ah->nonce = value;
  7184. }
  7185. }
  7186. #if !defined(NO_NONCE_CHECK)
  7187. /* Read the nonce from the response. */
  7188. if (ah->nonce == NULL) {
  7189. return 0;
  7190. }
  7191. s = NULL;
  7192. nonce = strtoull(ah->nonce, &s, 10);
  7193. if ((s == NULL) || (*s != 0)) {
  7194. return 0;
  7195. }
  7196. /* Convert the nonce from the client to a number. */
  7197. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7198. /* The converted number corresponds to the time the nounce has been
  7199. * created. This should not be earlier than the server start. */
  7200. /* Server side nonce check is valuable in all situations but one:
  7201. * if the server restarts frequently, but the client should not see
  7202. * that, so the server should accept nonces from previous starts. */
  7203. /* However, the reasonable default is to not accept a nonce from a
  7204. * previous start, so if anyone changed the access rights between
  7205. * two restarts, a new login is required. */
  7206. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7207. /* nonce is from a previous start of the server and no longer valid
  7208. * (replay attack?) */
  7209. return 0;
  7210. }
  7211. /* Check if the nonce is too high, so it has not (yet) been used by the
  7212. * server. */
  7213. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7214. + conn->dom_ctx->nonce_count)) {
  7215. return 0;
  7216. }
  7217. #else
  7218. (void)nonce;
  7219. #endif
  7220. /* CGI needs it as REMOTE_USER */
  7221. if (ah->user != NULL) {
  7222. conn->request_info.remote_user =
  7223. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7224. } else {
  7225. return 0;
  7226. }
  7227. return 1;
  7228. }
  7229. static const char *
  7230. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7231. {
  7232. #if defined(MG_USE_OPEN_FILE)
  7233. const char *eof;
  7234. size_t len;
  7235. const char *memend;
  7236. #else
  7237. (void)p; /* parameter is unused */
  7238. #endif
  7239. if (!filep) {
  7240. return NULL;
  7241. }
  7242. #if defined(MG_USE_OPEN_FILE)
  7243. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7244. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7245. /* Search for \n from p till the end of stream */
  7246. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7247. if (eof != NULL) {
  7248. eof += 1; /* Include \n */
  7249. } else {
  7250. eof = memend; /* Copy remaining data */
  7251. }
  7252. len =
  7253. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7254. memcpy(buf, *p, len);
  7255. buf[len] = '\0';
  7256. *p += len;
  7257. return len ? eof : NULL;
  7258. } else /* filep->access.fp block below */
  7259. #endif
  7260. if (filep->access.fp != NULL) {
  7261. return fgets(buf, (int)size, filep->access.fp);
  7262. } else {
  7263. return NULL;
  7264. }
  7265. }
  7266. /* Define the initial recursion depth for procesesing htpasswd files that
  7267. * include other htpasswd
  7268. * (or even the same) files. It is not difficult to provide a file or files
  7269. * s.t. they force civetweb
  7270. * to infinitely recurse and then crash.
  7271. */
  7272. #define INITIAL_DEPTH 9
  7273. #if INITIAL_DEPTH <= 0
  7274. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7275. #endif
  7276. #if !defined(NO_FILESYSTEMS)
  7277. struct read_auth_file_struct {
  7278. struct mg_connection *conn;
  7279. struct ah ah;
  7280. const char *domain;
  7281. char buf[256 + 256 + 40];
  7282. const char *f_user;
  7283. const char *f_domain;
  7284. const char *f_ha1;
  7285. };
  7286. static int
  7287. read_auth_file(struct mg_file *filep,
  7288. struct read_auth_file_struct *workdata,
  7289. int depth)
  7290. {
  7291. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7292. int is_authorized = 0;
  7293. struct mg_file fp;
  7294. size_t l;
  7295. if (!filep || !workdata || (0 == depth)) {
  7296. return 0;
  7297. }
  7298. /* Loop over passwords file */
  7299. #if defined(MG_USE_OPEN_FILE)
  7300. p = (char *)filep->access.membuf;
  7301. #endif
  7302. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7303. l = strlen(workdata->buf);
  7304. while (l > 0) {
  7305. if (isspace((unsigned char)workdata->buf[l - 1])
  7306. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7307. l--;
  7308. workdata->buf[l] = 0;
  7309. } else
  7310. break;
  7311. }
  7312. if (l < 1) {
  7313. continue;
  7314. }
  7315. workdata->f_user = workdata->buf;
  7316. if (workdata->f_user[0] == ':') {
  7317. /* user names may not contain a ':' and may not be empty,
  7318. * so lines starting with ':' may be used for a special purpose
  7319. */
  7320. if (workdata->f_user[1] == '#') {
  7321. /* :# is a comment */
  7322. continue;
  7323. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7324. if (mg_fopen(workdata->conn,
  7325. workdata->f_user + 9,
  7326. MG_FOPEN_MODE_READ,
  7327. &fp)) {
  7328. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7329. (void)mg_fclose(
  7330. &fp.access); /* ignore error on read only file */
  7331. /* No need to continue processing files once we have a
  7332. * match, since nothing will reset it back
  7333. * to 0.
  7334. */
  7335. if (is_authorized) {
  7336. return is_authorized;
  7337. }
  7338. } else {
  7339. mg_cry_internal(workdata->conn,
  7340. "%s: cannot open authorization file: %s",
  7341. __func__,
  7342. workdata->buf);
  7343. }
  7344. continue;
  7345. }
  7346. /* everything is invalid for the moment (might change in the
  7347. * future) */
  7348. mg_cry_internal(workdata->conn,
  7349. "%s: syntax error in authorization file: %s",
  7350. __func__,
  7351. workdata->buf);
  7352. continue;
  7353. }
  7354. workdata->f_domain = strchr(workdata->f_user, ':');
  7355. if (workdata->f_domain == NULL) {
  7356. mg_cry_internal(workdata->conn,
  7357. "%s: syntax error in authorization file: %s",
  7358. __func__,
  7359. workdata->buf);
  7360. continue;
  7361. }
  7362. *(char *)(workdata->f_domain) = 0;
  7363. (workdata->f_domain)++;
  7364. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7365. if (workdata->f_ha1 == NULL) {
  7366. mg_cry_internal(workdata->conn,
  7367. "%s: syntax error in authorization file: %s",
  7368. __func__,
  7369. workdata->buf);
  7370. continue;
  7371. }
  7372. *(char *)(workdata->f_ha1) = 0;
  7373. (workdata->f_ha1)++;
  7374. if (!strcmp(workdata->ah.user, workdata->f_user)
  7375. && !strcmp(workdata->domain, workdata->f_domain)) {
  7376. return check_password(workdata->conn->request_info.request_method,
  7377. workdata->f_ha1,
  7378. workdata->ah.uri,
  7379. workdata->ah.nonce,
  7380. workdata->ah.nc,
  7381. workdata->ah.cnonce,
  7382. workdata->ah.qop,
  7383. workdata->ah.response);
  7384. }
  7385. }
  7386. return is_authorized;
  7387. }
  7388. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7389. static int
  7390. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7391. {
  7392. struct read_auth_file_struct workdata;
  7393. char buf[MG_BUF_LEN];
  7394. if (!conn || !conn->dom_ctx) {
  7395. return 0;
  7396. }
  7397. memset(&workdata, 0, sizeof(workdata));
  7398. workdata.conn = conn;
  7399. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7400. return 0;
  7401. }
  7402. if (realm) {
  7403. workdata.domain = realm;
  7404. } else {
  7405. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7406. }
  7407. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7408. }
  7409. /* Public function to check http digest authentication header */
  7410. int
  7411. mg_check_digest_access_authentication(struct mg_connection *conn,
  7412. const char *realm,
  7413. const char *filename)
  7414. {
  7415. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7416. int auth;
  7417. if (!conn || !filename) {
  7418. return -1;
  7419. }
  7420. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7421. return -2;
  7422. }
  7423. auth = authorize(conn, &file, realm);
  7424. mg_fclose(&file.access);
  7425. return auth;
  7426. }
  7427. #endif /* NO_FILESYSTEMS */
  7428. /* Return 1 if request is authorised, 0 otherwise. */
  7429. static int
  7430. check_authorization(struct mg_connection *conn, const char *path)
  7431. {
  7432. #if !defined(NO_FILESYSTEMS)
  7433. char fname[PATH_MAX];
  7434. struct vec uri_vec, filename_vec;
  7435. const char *list;
  7436. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7437. int authorized = 1, truncated;
  7438. if (!conn || !conn->dom_ctx) {
  7439. return 0;
  7440. }
  7441. list = conn->dom_ctx->config[PROTECT_URI];
  7442. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7443. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7444. mg_snprintf(conn,
  7445. &truncated,
  7446. fname,
  7447. sizeof(fname),
  7448. "%.*s",
  7449. (int)filename_vec.len,
  7450. filename_vec.ptr);
  7451. if (truncated
  7452. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7453. mg_cry_internal(conn,
  7454. "%s: cannot open %s: %s",
  7455. __func__,
  7456. fname,
  7457. strerror(errno));
  7458. }
  7459. break;
  7460. }
  7461. }
  7462. if (!is_file_opened(&file.access)) {
  7463. open_auth_file(conn, path, &file);
  7464. }
  7465. if (is_file_opened(&file.access)) {
  7466. authorized = authorize(conn, &file, NULL);
  7467. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7468. }
  7469. return authorized;
  7470. #else
  7471. (void)conn;
  7472. (void)path;
  7473. return 1;
  7474. #endif /* NO_FILESYSTEMS */
  7475. }
  7476. /* Internal function. Assumes conn is valid */
  7477. static void
  7478. send_authorization_request(struct mg_connection *conn, const char *realm)
  7479. {
  7480. char date[64];
  7481. time_t curtime = time(NULL);
  7482. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7483. if (!realm) {
  7484. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7485. }
  7486. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7487. nonce += conn->dom_ctx->nonce_count;
  7488. ++conn->dom_ctx->nonce_count;
  7489. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7490. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7491. conn->status_code = 401;
  7492. conn->must_close = 1;
  7493. gmt_time_string(date, sizeof(date), &curtime);
  7494. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7495. send_no_cache_header(conn);
  7496. send_additional_header(conn);
  7497. mg_printf(conn,
  7498. "Date: %s\r\n"
  7499. "Connection: %s\r\n"
  7500. "Content-Length: 0\r\n"
  7501. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7502. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7503. date,
  7504. suggest_connection_header(conn),
  7505. realm,
  7506. nonce);
  7507. }
  7508. /* Interface function. Parameters are provided by the user, so do
  7509. * at least some basic checks.
  7510. */
  7511. int
  7512. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7513. const char *realm)
  7514. {
  7515. if (conn && conn->dom_ctx) {
  7516. send_authorization_request(conn, realm);
  7517. return 0;
  7518. }
  7519. return -1;
  7520. }
  7521. #if !defined(NO_FILES)
  7522. static int
  7523. is_authorized_for_put(struct mg_connection *conn)
  7524. {
  7525. if (conn) {
  7526. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7527. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7528. int ret = 0;
  7529. if (passfile != NULL
  7530. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7531. ret = authorize(conn, &file, NULL);
  7532. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7533. }
  7534. return ret;
  7535. }
  7536. return 0;
  7537. }
  7538. #endif
  7539. int
  7540. mg_modify_passwords_file(const char *fname,
  7541. const char *domain,
  7542. const char *user,
  7543. const char *pass)
  7544. {
  7545. int found, i;
  7546. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7547. FILE *fp, *fp2;
  7548. found = 0;
  7549. fp = fp2 = NULL;
  7550. /* Regard empty password as no password - remove user record. */
  7551. if ((pass != NULL) && (pass[0] == '\0')) {
  7552. pass = NULL;
  7553. }
  7554. /* Other arguments must not be empty */
  7555. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7556. return 0;
  7557. }
  7558. /* Using the given file format, user name and domain must not contain
  7559. * ':'
  7560. */
  7561. if (strchr(user, ':') != NULL) {
  7562. return 0;
  7563. }
  7564. if (strchr(domain, ':') != NULL) {
  7565. return 0;
  7566. }
  7567. /* Do not allow control characters like newline in user name and domain.
  7568. * Do not allow excessively long names either. */
  7569. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7570. if (iscntrl((unsigned char)user[i])) {
  7571. return 0;
  7572. }
  7573. }
  7574. if (user[i]) {
  7575. return 0;
  7576. }
  7577. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7578. if (iscntrl((unsigned char)domain[i])) {
  7579. return 0;
  7580. }
  7581. }
  7582. if (domain[i]) {
  7583. return 0;
  7584. }
  7585. /* The maximum length of the path to the password file is limited */
  7586. if ((strlen(fname) + 4) >= PATH_MAX) {
  7587. return 0;
  7588. }
  7589. /* Create a temporary file name. Length has been checked before. */
  7590. strcpy(tmp, fname);
  7591. strcat(tmp, ".tmp");
  7592. /* Create the file if does not exist */
  7593. /* Use of fopen here is OK, since fname is only ASCII */
  7594. if ((fp = fopen(fname, "a+")) != NULL) {
  7595. (void)fclose(fp);
  7596. }
  7597. /* Open the given file and temporary file */
  7598. if ((fp = fopen(fname, "r")) == NULL) {
  7599. return 0;
  7600. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7601. fclose(fp);
  7602. return 0;
  7603. }
  7604. /* Copy the stuff to temporary file */
  7605. while (fgets(line, sizeof(line), fp) != NULL) {
  7606. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7607. continue;
  7608. }
  7609. u[255] = 0;
  7610. d[255] = 0;
  7611. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7612. found++;
  7613. if (pass != NULL) {
  7614. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7615. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7616. }
  7617. } else {
  7618. fprintf(fp2, "%s", line);
  7619. }
  7620. }
  7621. /* If new user, just add it */
  7622. if (!found && (pass != NULL)) {
  7623. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7624. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7625. }
  7626. /* Close files */
  7627. fclose(fp);
  7628. fclose(fp2);
  7629. /* Put the temp file in place of real file */
  7630. IGNORE_UNUSED_RESULT(remove(fname));
  7631. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7632. return 1;
  7633. }
  7634. static int
  7635. is_valid_port(unsigned long port)
  7636. {
  7637. return (port <= 0xffff);
  7638. }
  7639. static int
  7640. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7641. {
  7642. struct addrinfo hints, *res, *ressave;
  7643. int func_ret = 0;
  7644. int gai_ret;
  7645. memset(&hints, 0, sizeof(struct addrinfo));
  7646. hints.ai_family = af;
  7647. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7648. if (gai_ret != 0) {
  7649. /* gai_strerror could be used to convert gai_ret to a string */
  7650. /* POSIX return values: see
  7651. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7652. */
  7653. /* Windows return values: see
  7654. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7655. */
  7656. return 0;
  7657. }
  7658. ressave = res;
  7659. while (res) {
  7660. if (dstlen >= (size_t)res->ai_addrlen) {
  7661. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7662. func_ret = 1;
  7663. }
  7664. res = res->ai_next;
  7665. }
  7666. freeaddrinfo(ressave);
  7667. return func_ret;
  7668. }
  7669. static int
  7670. connect_socket(struct mg_context *ctx /* may be NULL */,
  7671. const char *host,
  7672. int port,
  7673. int use_ssl,
  7674. char *ebuf,
  7675. size_t ebuf_len,
  7676. SOCKET *sock /* output: socket, must not be NULL */,
  7677. union usa *sa /* output: socket address, must not be NULL */
  7678. )
  7679. {
  7680. int ip_ver = 0;
  7681. int conn_ret = -1;
  7682. int sockerr = 0;
  7683. *sock = INVALID_SOCKET;
  7684. memset(sa, 0, sizeof(*sa));
  7685. if (ebuf_len > 0) {
  7686. *ebuf = 0;
  7687. }
  7688. if (host == NULL) {
  7689. mg_snprintf(NULL,
  7690. NULL, /* No truncation check for ebuf */
  7691. ebuf,
  7692. ebuf_len,
  7693. "%s",
  7694. "NULL host");
  7695. return 0;
  7696. }
  7697. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7698. mg_snprintf(NULL,
  7699. NULL, /* No truncation check for ebuf */
  7700. ebuf,
  7701. ebuf_len,
  7702. "%s",
  7703. "invalid port");
  7704. return 0;
  7705. }
  7706. #if !defined(NO_SSL)
  7707. #if !defined(NO_SSL_DL)
  7708. #if defined(OPENSSL_API_1_1)
  7709. if (use_ssl && (TLS_client_method == NULL)) {
  7710. mg_snprintf(NULL,
  7711. NULL, /* No truncation check for ebuf */
  7712. ebuf,
  7713. ebuf_len,
  7714. "%s",
  7715. "SSL is not initialized");
  7716. return 0;
  7717. }
  7718. #else
  7719. if (use_ssl && (SSLv23_client_method == NULL)) {
  7720. mg_snprintf(NULL,
  7721. NULL, /* No truncation check for ebuf */
  7722. ebuf,
  7723. ebuf_len,
  7724. "%s",
  7725. "SSL is not initialized");
  7726. return 0;
  7727. }
  7728. #endif /* OPENSSL_API_1_1 */
  7729. #else
  7730. (void)use_ssl;
  7731. #endif /* NO_SSL_DL */
  7732. #else
  7733. (void)use_ssl;
  7734. #endif /* !defined(NO_SSL) */
  7735. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7736. sa->sin.sin_family = AF_INET;
  7737. sa->sin.sin_port = htons((uint16_t)port);
  7738. ip_ver = 4;
  7739. #if defined(USE_IPV6)
  7740. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7741. sa->sin6.sin6_family = AF_INET6;
  7742. sa->sin6.sin6_port = htons((uint16_t)port);
  7743. ip_ver = 6;
  7744. } else if (host[0] == '[') {
  7745. /* While getaddrinfo on Windows will work with [::1],
  7746. * getaddrinfo on Linux only works with ::1 (without []). */
  7747. size_t l = strlen(host + 1);
  7748. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7749. if (h) {
  7750. h[l - 1] = 0;
  7751. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7752. sa->sin6.sin6_family = AF_INET6;
  7753. sa->sin6.sin6_port = htons((uint16_t)port);
  7754. ip_ver = 6;
  7755. }
  7756. mg_free(h);
  7757. }
  7758. #endif
  7759. }
  7760. if (ip_ver == 0) {
  7761. mg_snprintf(NULL,
  7762. NULL, /* No truncation check for ebuf */
  7763. ebuf,
  7764. ebuf_len,
  7765. "%s",
  7766. "host not found");
  7767. return 0;
  7768. }
  7769. if (ip_ver == 4) {
  7770. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7771. }
  7772. #if defined(USE_IPV6)
  7773. else if (ip_ver == 6) {
  7774. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7775. }
  7776. #endif
  7777. if (*sock == INVALID_SOCKET) {
  7778. mg_snprintf(NULL,
  7779. NULL, /* No truncation check for ebuf */
  7780. ebuf,
  7781. ebuf_len,
  7782. "socket(): %s",
  7783. strerror(ERRNO));
  7784. return 0;
  7785. }
  7786. if (0 != set_non_blocking_mode(*sock)) {
  7787. mg_snprintf(NULL,
  7788. NULL, /* No truncation check for ebuf */
  7789. ebuf,
  7790. ebuf_len,
  7791. "Cannot set socket to non-blocking: %s",
  7792. strerror(ERRNO));
  7793. closesocket(*sock);
  7794. *sock = INVALID_SOCKET;
  7795. return 0;
  7796. }
  7797. set_close_on_exec(*sock, NULL, ctx);
  7798. if (ip_ver == 4) {
  7799. /* connected with IPv4 */
  7800. conn_ret = connect(*sock,
  7801. (struct sockaddr *)((void *)&sa->sin),
  7802. sizeof(sa->sin));
  7803. }
  7804. #if defined(USE_IPV6)
  7805. else if (ip_ver == 6) {
  7806. /* connected with IPv6 */
  7807. conn_ret = connect(*sock,
  7808. (struct sockaddr *)((void *)&sa->sin6),
  7809. sizeof(sa->sin6));
  7810. }
  7811. #endif
  7812. if (conn_ret != 0) {
  7813. sockerr = ERRNO;
  7814. }
  7815. #if defined(_WIN32)
  7816. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7817. #else
  7818. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7819. #endif
  7820. /* Data for getsockopt */
  7821. void *psockerr = &sockerr;
  7822. int ret;
  7823. #if defined(_WIN32)
  7824. int len = (int)sizeof(sockerr);
  7825. #else
  7826. socklen_t len = (socklen_t)sizeof(sockerr);
  7827. #endif
  7828. /* Data for poll */
  7829. struct mg_pollfd pfd[1];
  7830. int pollres;
  7831. int ms_wait = 10000; /* 10 second timeout */
  7832. int nonstop = 0;
  7833. /* For a non-blocking socket, the connect sequence is:
  7834. * 1) call connect (will not block)
  7835. * 2) wait until the socket is ready for writing (select or poll)
  7836. * 3) check connection state with getsockopt
  7837. */
  7838. pfd[0].fd = *sock;
  7839. pfd[0].events = POLLOUT;
  7840. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7841. if (pollres != 1) {
  7842. /* Not connected */
  7843. mg_snprintf(NULL,
  7844. NULL, /* No truncation check for ebuf */
  7845. ebuf,
  7846. ebuf_len,
  7847. "connect(%s:%d): timeout",
  7848. host,
  7849. port);
  7850. closesocket(*sock);
  7851. *sock = INVALID_SOCKET;
  7852. return 0;
  7853. }
  7854. #if defined(_WIN32)
  7855. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7856. #else
  7857. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7858. #endif
  7859. if ((ret == 0) && (sockerr == 0)) {
  7860. conn_ret = 0;
  7861. }
  7862. }
  7863. if (conn_ret != 0) {
  7864. /* Not connected */
  7865. mg_snprintf(NULL,
  7866. NULL, /* No truncation check for ebuf */
  7867. ebuf,
  7868. ebuf_len,
  7869. "connect(%s:%d): error %s",
  7870. host,
  7871. port,
  7872. strerror(sockerr));
  7873. closesocket(*sock);
  7874. *sock = INVALID_SOCKET;
  7875. return 0;
  7876. }
  7877. return 1;
  7878. }
  7879. int
  7880. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7881. {
  7882. static const char *dont_escape = "._-$,;~()";
  7883. static const char *hex = "0123456789abcdef";
  7884. char *pos = dst;
  7885. const char *end = dst + dst_len - 1;
  7886. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7887. if (isalnum((unsigned char)*src)
  7888. || (strchr(dont_escape, *src) != NULL)) {
  7889. *pos = *src;
  7890. } else if (pos + 2 < end) {
  7891. pos[0] = '%';
  7892. pos[1] = hex[(unsigned char)*src >> 4];
  7893. pos[2] = hex[(unsigned char)*src & 0xf];
  7894. pos += 2;
  7895. } else {
  7896. break;
  7897. }
  7898. }
  7899. *pos = '\0';
  7900. return (*src == '\0') ? (int)(pos - dst) : -1;
  7901. }
  7902. /* Return 0 on success, non-zero if an error occurs. */
  7903. static int
  7904. print_dir_entry(struct de *de)
  7905. {
  7906. size_t namesize, escsize, i;
  7907. char *href, *esc, *p;
  7908. char size[64], mod[64];
  7909. #if defined(REENTRANT_TIME)
  7910. struct tm _tm;
  7911. struct tm *tm = &_tm;
  7912. #else
  7913. struct tm *tm;
  7914. #endif
  7915. /* Estimate worst case size for encoding and escaping */
  7916. namesize = strlen(de->file_name) + 1;
  7917. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7918. href = (char *)mg_malloc(namesize * 3 + escsize);
  7919. if (href == NULL) {
  7920. return -1;
  7921. }
  7922. mg_url_encode(de->file_name, href, namesize * 3);
  7923. esc = NULL;
  7924. if (escsize > 0) {
  7925. /* HTML escaping needed */
  7926. esc = href + namesize * 3;
  7927. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7928. mg_strlcpy(p, de->file_name + i, 2);
  7929. if (*p == '&') {
  7930. strcpy(p, "&amp;");
  7931. } else if (*p == '<') {
  7932. strcpy(p, "&lt;");
  7933. } else if (*p == '>') {
  7934. strcpy(p, "&gt;");
  7935. }
  7936. }
  7937. }
  7938. if (de->file.is_directory) {
  7939. mg_snprintf(de->conn,
  7940. NULL, /* Buffer is big enough */
  7941. size,
  7942. sizeof(size),
  7943. "%s",
  7944. "[DIRECTORY]");
  7945. } else {
  7946. /* We use (signed) cast below because MSVC 6 compiler cannot
  7947. * convert unsigned __int64 to double. Sigh. */
  7948. if (de->file.size < 1024) {
  7949. mg_snprintf(de->conn,
  7950. NULL, /* Buffer is big enough */
  7951. size,
  7952. sizeof(size),
  7953. "%d",
  7954. (int)de->file.size);
  7955. } else if (de->file.size < 0x100000) {
  7956. mg_snprintf(de->conn,
  7957. NULL, /* Buffer is big enough */
  7958. size,
  7959. sizeof(size),
  7960. "%.1fk",
  7961. (double)de->file.size / 1024.0);
  7962. } else if (de->file.size < 0x40000000) {
  7963. mg_snprintf(de->conn,
  7964. NULL, /* Buffer is big enough */
  7965. size,
  7966. sizeof(size),
  7967. "%.1fM",
  7968. (double)de->file.size / 1048576);
  7969. } else {
  7970. mg_snprintf(de->conn,
  7971. NULL, /* Buffer is big enough */
  7972. size,
  7973. sizeof(size),
  7974. "%.1fG",
  7975. (double)de->file.size / 1073741824);
  7976. }
  7977. }
  7978. /* Note: mg_snprintf will not cause a buffer overflow above.
  7979. * So, string truncation checks are not required here. */
  7980. #if defined(REENTRANT_TIME)
  7981. localtime_r(&de->file.last_modified, tm);
  7982. #else
  7983. tm = localtime(&de->file.last_modified);
  7984. #endif
  7985. if (tm != NULL) {
  7986. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7987. } else {
  7988. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7989. mod[sizeof(mod) - 1] = '\0';
  7990. }
  7991. mg_printf(de->conn,
  7992. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7993. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7994. href,
  7995. de->file.is_directory ? "/" : "",
  7996. esc ? esc : de->file_name,
  7997. de->file.is_directory ? "/" : "",
  7998. mod,
  7999. size);
  8000. mg_free(href);
  8001. return 0;
  8002. }
  8003. /* This function is called from send_directory() and used for
  8004. * sorting directory entries by size, or name, or modification time.
  8005. * On windows, __cdecl specification is needed in case if project is built
  8006. * with __stdcall convention. qsort always requires __cdels callback. */
  8007. static int WINCDECL
  8008. compare_dir_entries(const void *p1, const void *p2)
  8009. {
  8010. if (p1 && p2) {
  8011. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8012. const char *query_string = a->conn->request_info.query_string;
  8013. int cmp_result = 0;
  8014. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8015. query_string = "n";
  8016. }
  8017. if (a->file.is_directory && !b->file.is_directory) {
  8018. return -1; /* Always put directories on top */
  8019. } else if (!a->file.is_directory && b->file.is_directory) {
  8020. return 1; /* Always put directories on top */
  8021. } else if (*query_string == 'n') {
  8022. cmp_result = strcmp(a->file_name, b->file_name);
  8023. } else if (*query_string == 's') {
  8024. cmp_result = (a->file.size == b->file.size)
  8025. ? 0
  8026. : ((a->file.size > b->file.size) ? 1 : -1);
  8027. } else if (*query_string == 'd') {
  8028. cmp_result =
  8029. (a->file.last_modified == b->file.last_modified)
  8030. ? 0
  8031. : ((a->file.last_modified > b->file.last_modified) ? 1
  8032. : -1);
  8033. }
  8034. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8035. }
  8036. return 0;
  8037. }
  8038. static int
  8039. must_hide_file(struct mg_connection *conn, const char *path)
  8040. {
  8041. if (conn && conn->dom_ctx) {
  8042. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8043. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8044. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8045. || ((pattern != NULL)
  8046. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8047. }
  8048. return 0;
  8049. }
  8050. #if !defined(NO_FILESYSTEMS)
  8051. static int
  8052. scan_directory(struct mg_connection *conn,
  8053. const char *dir,
  8054. void *data,
  8055. int (*cb)(struct de *, void *))
  8056. {
  8057. char path[PATH_MAX];
  8058. struct dirent *dp;
  8059. DIR *dirp;
  8060. struct de de;
  8061. int truncated;
  8062. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8063. return 0;
  8064. } else {
  8065. de.conn = conn;
  8066. while ((dp = mg_readdir(dirp)) != NULL) {
  8067. /* Do not show current dir and hidden files */
  8068. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8069. || must_hide_file(conn, dp->d_name)) {
  8070. continue;
  8071. }
  8072. mg_snprintf(
  8073. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8074. /* If we don't memset stat structure to zero, mtime will have
  8075. * garbage and strftime() will segfault later on in
  8076. * print_dir_entry(). memset is required only if mg_stat()
  8077. * fails. For more details, see
  8078. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8079. memset(&de.file, 0, sizeof(de.file));
  8080. if (truncated) {
  8081. /* If the path is not complete, skip processing. */
  8082. continue;
  8083. }
  8084. if (!mg_stat(conn, path, &de.file)) {
  8085. mg_cry_internal(conn,
  8086. "%s: mg_stat(%s) failed: %s",
  8087. __func__,
  8088. path,
  8089. strerror(ERRNO));
  8090. }
  8091. de.file_name = dp->d_name;
  8092. cb(&de, data);
  8093. }
  8094. (void)mg_closedir(dirp);
  8095. }
  8096. return 1;
  8097. }
  8098. #endif /* NO_FILESYSTEMS */
  8099. #if !defined(NO_FILES)
  8100. static int
  8101. remove_directory(struct mg_connection *conn, const char *dir)
  8102. {
  8103. char path[PATH_MAX];
  8104. struct dirent *dp;
  8105. DIR *dirp;
  8106. struct de de;
  8107. int truncated;
  8108. int ok = 1;
  8109. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8110. return 0;
  8111. } else {
  8112. de.conn = conn;
  8113. while ((dp = mg_readdir(dirp)) != NULL) {
  8114. /* Do not show current dir (but show hidden files as they will
  8115. * also be removed) */
  8116. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8117. continue;
  8118. }
  8119. mg_snprintf(
  8120. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8121. /* If we don't memset stat structure to zero, mtime will have
  8122. * garbage and strftime() will segfault later on in
  8123. * print_dir_entry(). memset is required only if mg_stat()
  8124. * fails. For more details, see
  8125. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8126. memset(&de.file, 0, sizeof(de.file));
  8127. if (truncated) {
  8128. /* Do not delete anything shorter */
  8129. ok = 0;
  8130. continue;
  8131. }
  8132. if (!mg_stat(conn, path, &de.file)) {
  8133. mg_cry_internal(conn,
  8134. "%s: mg_stat(%s) failed: %s",
  8135. __func__,
  8136. path,
  8137. strerror(ERRNO));
  8138. ok = 0;
  8139. }
  8140. if (de.file.is_directory) {
  8141. if (remove_directory(conn, path) == 0) {
  8142. ok = 0;
  8143. }
  8144. } else {
  8145. /* This will fail file is the file is in memory */
  8146. if (mg_remove(conn, path) == 0) {
  8147. ok = 0;
  8148. }
  8149. }
  8150. }
  8151. (void)mg_closedir(dirp);
  8152. IGNORE_UNUSED_RESULT(rmdir(dir));
  8153. }
  8154. return ok;
  8155. }
  8156. #endif
  8157. struct dir_scan_data {
  8158. struct de *entries;
  8159. unsigned int num_entries;
  8160. unsigned int arr_size;
  8161. };
  8162. /* Behaves like realloc(), but frees original pointer on failure */
  8163. static void *
  8164. realloc2(void *ptr, size_t size)
  8165. {
  8166. void *new_ptr = mg_realloc(ptr, size);
  8167. if (new_ptr == NULL) {
  8168. mg_free(ptr);
  8169. }
  8170. return new_ptr;
  8171. }
  8172. #if !defined(NO_FILESYSTEMS)
  8173. static int
  8174. dir_scan_callback(struct de *de, void *data)
  8175. {
  8176. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8177. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8178. dsd->arr_size *= 2;
  8179. dsd->entries =
  8180. (struct de *)realloc2(dsd->entries,
  8181. dsd->arr_size * sizeof(dsd->entries[0]));
  8182. }
  8183. if (dsd->entries == NULL) {
  8184. /* TODO(lsm, low): propagate an error to the caller */
  8185. dsd->num_entries = 0;
  8186. } else {
  8187. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8188. dsd->entries[dsd->num_entries].file = de->file;
  8189. dsd->entries[dsd->num_entries].conn = de->conn;
  8190. dsd->num_entries++;
  8191. }
  8192. return 0;
  8193. }
  8194. static void
  8195. handle_directory_request(struct mg_connection *conn, const char *dir)
  8196. {
  8197. unsigned int i;
  8198. int sort_direction;
  8199. struct dir_scan_data data = {NULL, 0, 128};
  8200. char date[64], *esc, *p;
  8201. const char *title;
  8202. time_t curtime = time(NULL);
  8203. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8204. mg_send_http_error(conn,
  8205. 500,
  8206. "Error: Cannot open directory\nopendir(%s): %s",
  8207. dir,
  8208. strerror(ERRNO));
  8209. return;
  8210. }
  8211. gmt_time_string(date, sizeof(date), &curtime);
  8212. if (!conn) {
  8213. return;
  8214. }
  8215. esc = NULL;
  8216. title = conn->request_info.local_uri;
  8217. if (title[strcspn(title, "&<>")]) {
  8218. /* HTML escaping needed */
  8219. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8220. if (esc) {
  8221. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8222. mg_strlcpy(p, title + i, 2);
  8223. if (*p == '&') {
  8224. strcpy(p, "&amp;");
  8225. } else if (*p == '<') {
  8226. strcpy(p, "&lt;");
  8227. } else if (*p == '>') {
  8228. strcpy(p, "&gt;");
  8229. }
  8230. }
  8231. } else {
  8232. title = "";
  8233. }
  8234. }
  8235. sort_direction = ((conn->request_info.query_string != NULL)
  8236. && (conn->request_info.query_string[0] != '\0')
  8237. && (conn->request_info.query_string[1] == 'd'))
  8238. ? 'a'
  8239. : 'd';
  8240. conn->must_close = 1;
  8241. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8242. send_static_cache_header(conn);
  8243. send_additional_header(conn);
  8244. mg_printf(conn,
  8245. "Date: %s\r\n"
  8246. "Connection: close\r\n"
  8247. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8248. date);
  8249. mg_printf(conn,
  8250. "<html><head><title>Index of %s</title>"
  8251. "<style>th {text-align: left;}</style></head>"
  8252. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8253. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8254. "<th><a href=\"?d%c\">Modified</a></th>"
  8255. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8256. "<tr><td colspan=\"3\"><hr></td></tr>",
  8257. esc ? esc : title,
  8258. esc ? esc : title,
  8259. sort_direction,
  8260. sort_direction,
  8261. sort_direction);
  8262. mg_free(esc);
  8263. /* Print first entry - link to a parent directory */
  8264. mg_printf(conn,
  8265. "<tr><td><a href=\"%s\">%s</a></td>"
  8266. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8267. "..",
  8268. "Parent directory",
  8269. "-",
  8270. "-");
  8271. /* Sort and print directory entries */
  8272. if (data.entries != NULL) {
  8273. qsort(data.entries,
  8274. (size_t)data.num_entries,
  8275. sizeof(data.entries[0]),
  8276. compare_dir_entries);
  8277. for (i = 0; i < data.num_entries; i++) {
  8278. print_dir_entry(&data.entries[i]);
  8279. mg_free(data.entries[i].file_name);
  8280. }
  8281. mg_free(data.entries);
  8282. }
  8283. mg_printf(conn, "%s", "</table></pre></body></html>");
  8284. conn->status_code = 200;
  8285. }
  8286. #endif /* NO_FILESYSTEMS */
  8287. /* Send len bytes from the opened file to the client. */
  8288. static void
  8289. send_file_data(struct mg_connection *conn,
  8290. struct mg_file *filep,
  8291. int64_t offset,
  8292. int64_t len)
  8293. {
  8294. char buf[MG_BUF_LEN];
  8295. int to_read, num_read, num_written;
  8296. int64_t size;
  8297. if (!filep || !conn) {
  8298. return;
  8299. }
  8300. /* Sanity check the offset */
  8301. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8302. : (int64_t)(filep->stat.size);
  8303. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8304. #if defined(MG_USE_OPEN_FILE)
  8305. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8306. /* file stored in memory */
  8307. if (len > size - offset) {
  8308. len = size - offset;
  8309. }
  8310. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8311. } else /* else block below */
  8312. #endif
  8313. if (len > 0 && filep->access.fp != NULL) {
  8314. /* file stored on disk */
  8315. #if defined(__linux__)
  8316. /* sendfile is only available for Linux */
  8317. if ((conn->ssl == 0) && (conn->throttle == 0)
  8318. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8319. "yes"))) {
  8320. off_t sf_offs = (off_t)offset;
  8321. ssize_t sf_sent;
  8322. int sf_file = fileno(filep->access.fp);
  8323. int loop_cnt = 0;
  8324. do {
  8325. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8326. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8327. size_t sf_tosend =
  8328. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8329. sf_sent =
  8330. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8331. if (sf_sent > 0) {
  8332. len -= sf_sent;
  8333. offset += sf_sent;
  8334. } else if (loop_cnt == 0) {
  8335. /* This file can not be sent using sendfile.
  8336. * This might be the case for pseudo-files in the
  8337. * /sys/ and /proc/ file system.
  8338. * Use the regular user mode copy code instead. */
  8339. break;
  8340. } else if (sf_sent == 0) {
  8341. /* No error, but 0 bytes sent. May be EOF? */
  8342. return;
  8343. }
  8344. loop_cnt++;
  8345. } while ((len > 0) && (sf_sent >= 0));
  8346. if (sf_sent > 0) {
  8347. return; /* OK */
  8348. }
  8349. /* sf_sent<0 means error, thus fall back to the classic way */
  8350. /* This is always the case, if sf_file is not a "normal" file,
  8351. * e.g., for sending data from the output of a CGI process. */
  8352. offset = (int64_t)sf_offs;
  8353. }
  8354. #endif
  8355. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8356. mg_cry_internal(conn,
  8357. "%s: fseeko() failed: %s",
  8358. __func__,
  8359. strerror(ERRNO));
  8360. mg_send_http_error(
  8361. conn,
  8362. 500,
  8363. "%s",
  8364. "Error: Unable to access file at requested position.");
  8365. } else {
  8366. while (len > 0) {
  8367. /* Calculate how much to read from the file in the buffer */
  8368. to_read = sizeof(buf);
  8369. if ((int64_t)to_read > len) {
  8370. to_read = (int)len;
  8371. }
  8372. /* Read from file, exit the loop on error */
  8373. if ((num_read =
  8374. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8375. <= 0) {
  8376. break;
  8377. }
  8378. /* Send read bytes to the client, exit the loop on error */
  8379. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8380. != num_read) {
  8381. break;
  8382. }
  8383. /* Both read and were successful, adjust counters */
  8384. len -= num_written;
  8385. }
  8386. }
  8387. }
  8388. }
  8389. static int
  8390. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8391. {
  8392. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8393. }
  8394. static void
  8395. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8396. {
  8397. if ((filestat != NULL) && (buf != NULL)) {
  8398. mg_snprintf(NULL,
  8399. NULL, /* All calls to construct_etag use 64 byte buffer */
  8400. buf,
  8401. buf_len,
  8402. "\"%lx.%" INT64_FMT "\"",
  8403. (unsigned long)filestat->last_modified,
  8404. filestat->size);
  8405. }
  8406. }
  8407. static void
  8408. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8409. {
  8410. if (filep != NULL && filep->fp != NULL) {
  8411. #if defined(_WIN32)
  8412. (void)conn; /* Unused. */
  8413. #else
  8414. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8415. mg_cry_internal(conn,
  8416. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8417. __func__,
  8418. strerror(ERRNO));
  8419. }
  8420. #endif
  8421. }
  8422. }
  8423. #if defined(USE_ZLIB)
  8424. #include "mod_zlib.inl"
  8425. #endif
  8426. #if !defined(NO_FILESYSTEMS)
  8427. static void
  8428. handle_static_file_request(struct mg_connection *conn,
  8429. const char *path,
  8430. struct mg_file *filep,
  8431. const char *mime_type,
  8432. const char *additional_headers)
  8433. {
  8434. char date[64], lm[64], etag[64];
  8435. char range[128]; /* large enough, so there will be no overflow */
  8436. const char *msg = "OK";
  8437. const char *range_hdr;
  8438. time_t curtime = time(NULL);
  8439. int64_t cl, r1, r2;
  8440. struct vec mime_vec;
  8441. int n, truncated;
  8442. char gz_path[PATH_MAX];
  8443. const char *encoding = "";
  8444. const char *origin_hdr;
  8445. const char *cors_orig_cfg;
  8446. const char *cors1, *cors2, *cors3;
  8447. int is_head_request;
  8448. #if defined(USE_ZLIB)
  8449. /* Compression is allowed, unless there is a reason not to use compression.
  8450. * If the file is already compressed, too small or a "range" request was
  8451. * made, on the fly compression is not possible. */
  8452. int allow_on_the_fly_compression = 1;
  8453. #endif
  8454. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8455. return;
  8456. }
  8457. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8458. if (mime_type == NULL) {
  8459. get_mime_type(conn, path, &mime_vec);
  8460. } else {
  8461. mime_vec.ptr = mime_type;
  8462. mime_vec.len = strlen(mime_type);
  8463. }
  8464. if (filep->stat.size > INT64_MAX) {
  8465. mg_send_http_error(conn,
  8466. 500,
  8467. "Error: File size is too large to send\n%" INT64_FMT,
  8468. filep->stat.size);
  8469. return;
  8470. }
  8471. cl = (int64_t)filep->stat.size;
  8472. conn->status_code = 200;
  8473. range[0] = '\0';
  8474. #if defined(USE_ZLIB)
  8475. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8476. * it's important to rewrite the filename after resolving
  8477. * the mime type from it, to preserve the actual file's type */
  8478. if (!conn->accept_gzip) {
  8479. allow_on_the_fly_compression = 0;
  8480. }
  8481. #endif
  8482. /* Check if there is a range header */
  8483. range_hdr = mg_get_header(conn, "Range");
  8484. /* For gzipped files, add *.gz */
  8485. if (filep->stat.is_gzipped) {
  8486. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8487. if (truncated) {
  8488. mg_send_http_error(conn,
  8489. 500,
  8490. "Error: Path of zipped file too long (%s)",
  8491. path);
  8492. return;
  8493. }
  8494. path = gz_path;
  8495. encoding = "Content-Encoding: gzip\r\n";
  8496. #if defined(USE_ZLIB)
  8497. /* File is already compressed. No "on the fly" compression. */
  8498. allow_on_the_fly_compression = 0;
  8499. #endif
  8500. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8501. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8502. struct mg_file_stat file_stat;
  8503. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8504. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8505. && !file_stat.is_directory) {
  8506. file_stat.is_gzipped = 1;
  8507. filep->stat = file_stat;
  8508. cl = (int64_t)filep->stat.size;
  8509. path = gz_path;
  8510. encoding = "Content-Encoding: gzip\r\n";
  8511. #if defined(USE_ZLIB)
  8512. /* File is already compressed. No "on the fly" compression. */
  8513. allow_on_the_fly_compression = 0;
  8514. #endif
  8515. }
  8516. }
  8517. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8518. mg_send_http_error(conn,
  8519. 500,
  8520. "Error: Cannot open file\nfopen(%s): %s",
  8521. path,
  8522. strerror(ERRNO));
  8523. return;
  8524. }
  8525. fclose_on_exec(&filep->access, conn);
  8526. /* If "Range" request was made: parse header, send only selected part
  8527. * of the file. */
  8528. r1 = r2 = 0;
  8529. if ((range_hdr != NULL)
  8530. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8531. && (r2 >= 0)) {
  8532. /* actually, range requests don't play well with a pre-gzipped
  8533. * file (since the range is specified in the uncompressed space) */
  8534. if (filep->stat.is_gzipped) {
  8535. mg_send_http_error(
  8536. conn,
  8537. 416, /* 416 = Range Not Satisfiable */
  8538. "%s",
  8539. "Error: Range requests in gzipped files are not supported");
  8540. (void)mg_fclose(
  8541. &filep->access); /* ignore error on read only file */
  8542. return;
  8543. }
  8544. conn->status_code = 206;
  8545. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8546. mg_snprintf(conn,
  8547. NULL, /* range buffer is big enough */
  8548. range,
  8549. sizeof(range),
  8550. "Content-Range: bytes "
  8551. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8552. r1,
  8553. r1 + cl - 1,
  8554. filep->stat.size);
  8555. msg = "Partial Content";
  8556. #if defined(USE_ZLIB)
  8557. /* Do not compress ranges. */
  8558. allow_on_the_fly_compression = 0;
  8559. #endif
  8560. }
  8561. /* Do not compress small files. Small files do not benefit from file
  8562. * compression, but there is still some overhead. */
  8563. #if defined(USE_ZLIB)
  8564. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8565. /* File is below the size limit. */
  8566. allow_on_the_fly_compression = 0;
  8567. }
  8568. #endif
  8569. /* Standard CORS header */
  8570. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8571. origin_hdr = mg_get_header(conn, "Origin");
  8572. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8573. /* Cross-origin resource sharing (CORS), see
  8574. * http://www.html5rocks.com/en/tutorials/cors/,
  8575. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8576. * -
  8577. * preflight is not supported for files. */
  8578. cors1 = "Access-Control-Allow-Origin: ";
  8579. cors2 = cors_orig_cfg;
  8580. cors3 = "\r\n";
  8581. } else {
  8582. cors1 = cors2 = cors3 = "";
  8583. }
  8584. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8585. * according to
  8586. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8587. gmt_time_string(date, sizeof(date), &curtime);
  8588. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8589. construct_etag(etag, sizeof(etag), &filep->stat);
  8590. /* Send header */
  8591. (void)mg_printf(conn,
  8592. "HTTP/1.1 %d %s\r\n"
  8593. "%s%s%s" /* CORS */
  8594. "Date: %s\r\n"
  8595. "Last-Modified: %s\r\n"
  8596. "Etag: %s\r\n"
  8597. "Content-Type: %.*s\r\n"
  8598. "Connection: %s\r\n",
  8599. conn->status_code,
  8600. msg,
  8601. cors1,
  8602. cors2,
  8603. cors3,
  8604. date,
  8605. lm,
  8606. etag,
  8607. (int)mime_vec.len,
  8608. mime_vec.ptr,
  8609. suggest_connection_header(conn));
  8610. send_static_cache_header(conn);
  8611. send_additional_header(conn);
  8612. #if defined(USE_ZLIB)
  8613. /* On the fly compression allowed */
  8614. if (allow_on_the_fly_compression) {
  8615. /* For on the fly compression, we don't know the content size in
  8616. * advance, so we have to use chunked encoding */
  8617. (void)mg_printf(conn,
  8618. "Content-Encoding: gzip\r\n"
  8619. "Transfer-Encoding: chunked\r\n");
  8620. } else
  8621. #endif
  8622. {
  8623. /* Without on-the-fly compression, we know the content-length
  8624. * and we can use ranges (with on-the-fly compression we cannot).
  8625. * So we send these response headers only in this case. */
  8626. (void)mg_printf(conn,
  8627. "Content-Length: %" INT64_FMT "\r\n"
  8628. "Accept-Ranges: bytes\r\n"
  8629. "%s" /* range */
  8630. "%s" /* encoding */,
  8631. cl,
  8632. range,
  8633. encoding);
  8634. }
  8635. /* The previous code must not add any header starting with X- to make
  8636. * sure no one of the additional_headers is included twice */
  8637. if (additional_headers != NULL) {
  8638. (void)mg_printf(conn,
  8639. "%.*s\r\n\r\n",
  8640. (int)strlen(additional_headers),
  8641. additional_headers);
  8642. } else {
  8643. (void)mg_printf(conn, "\r\n");
  8644. }
  8645. if (!is_head_request) {
  8646. #if defined(USE_ZLIB)
  8647. if (allow_on_the_fly_compression) {
  8648. /* Compress and send */
  8649. send_compressed_data(conn, filep);
  8650. } else
  8651. #endif
  8652. {
  8653. /* Send file directly */
  8654. send_file_data(conn, filep, r1, cl);
  8655. }
  8656. }
  8657. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8658. }
  8659. int
  8660. mg_send_file_body(struct mg_connection *conn, const char *path)
  8661. {
  8662. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8663. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8664. return -1;
  8665. }
  8666. fclose_on_exec(&file.access, conn);
  8667. send_file_data(conn, &file, 0, INT64_MAX);
  8668. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8669. return 0; /* >= 0 for OK */
  8670. }
  8671. #endif /* NO_FILESYSTEMS */
  8672. #if !defined(NO_CACHING)
  8673. /* Return True if we should reply 304 Not Modified. */
  8674. static int
  8675. is_not_modified(const struct mg_connection *conn,
  8676. const struct mg_file_stat *filestat)
  8677. {
  8678. char etag[64];
  8679. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8680. const char *inm = mg_get_header(conn, "If-None-Match");
  8681. construct_etag(etag, sizeof(etag), filestat);
  8682. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8683. || ((ims != NULL)
  8684. && (filestat->last_modified <= parse_date_string(ims)));
  8685. }
  8686. static void
  8687. handle_not_modified_static_file_request(struct mg_connection *conn,
  8688. struct mg_file *filep)
  8689. {
  8690. char date[64], lm[64], etag[64];
  8691. time_t curtime = time(NULL);
  8692. if ((conn == NULL) || (filep == NULL)) {
  8693. return;
  8694. }
  8695. conn->status_code = 304;
  8696. gmt_time_string(date, sizeof(date), &curtime);
  8697. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8698. construct_etag(etag, sizeof(etag), &filep->stat);
  8699. (void)mg_printf(conn,
  8700. "HTTP/1.1 %d %s\r\n"
  8701. "Date: %s\r\n",
  8702. conn->status_code,
  8703. mg_get_response_code_text(conn, conn->status_code),
  8704. date);
  8705. send_static_cache_header(conn);
  8706. send_additional_header(conn);
  8707. (void)mg_printf(conn,
  8708. "Last-Modified: %s\r\n"
  8709. "Etag: %s\r\n"
  8710. "Connection: %s\r\n"
  8711. "\r\n",
  8712. lm,
  8713. etag,
  8714. suggest_connection_header(conn));
  8715. }
  8716. #endif
  8717. #if !defined(NO_FILESYSTEMS)
  8718. void
  8719. mg_send_file(struct mg_connection *conn, const char *path)
  8720. {
  8721. mg_send_mime_file2(conn, path, NULL, NULL);
  8722. }
  8723. void
  8724. mg_send_mime_file(struct mg_connection *conn,
  8725. const char *path,
  8726. const char *mime_type)
  8727. {
  8728. mg_send_mime_file2(conn, path, mime_type, NULL);
  8729. }
  8730. void
  8731. mg_send_mime_file2(struct mg_connection *conn,
  8732. const char *path,
  8733. const char *mime_type,
  8734. const char *additional_headers)
  8735. {
  8736. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8737. if (!conn) {
  8738. /* No conn */
  8739. return;
  8740. }
  8741. if (mg_stat(conn, path, &file.stat)) {
  8742. #if !defined(NO_CACHING)
  8743. if (is_not_modified(conn, &file.stat)) {
  8744. /* Send 304 "Not Modified" - this must not send any body data */
  8745. handle_not_modified_static_file_request(conn, &file);
  8746. } else
  8747. #endif /* NO_CACHING */
  8748. if (file.stat.is_directory) {
  8749. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8750. "yes")) {
  8751. handle_directory_request(conn, path);
  8752. } else {
  8753. mg_send_http_error(conn,
  8754. 403,
  8755. "%s",
  8756. "Error: Directory listing denied");
  8757. }
  8758. } else {
  8759. handle_static_file_request(
  8760. conn, path, &file, mime_type, additional_headers);
  8761. }
  8762. } else {
  8763. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8764. }
  8765. }
  8766. /* For a given PUT path, create all intermediate subdirectories.
  8767. * Return 0 if the path itself is a directory.
  8768. * Return 1 if the path leads to a file.
  8769. * Return -1 for if the path is too long.
  8770. * Return -2 if path can not be created.
  8771. */
  8772. static int
  8773. put_dir(struct mg_connection *conn, const char *path)
  8774. {
  8775. char buf[PATH_MAX];
  8776. const char *s, *p;
  8777. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8778. size_t len;
  8779. int res = 1;
  8780. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8781. len = (size_t)(p - path);
  8782. if (len >= sizeof(buf)) {
  8783. /* path too long */
  8784. res = -1;
  8785. break;
  8786. }
  8787. memcpy(buf, path, len);
  8788. buf[len] = '\0';
  8789. /* Try to create intermediate directory */
  8790. DEBUG_TRACE("mkdir(%s)", buf);
  8791. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8792. /* path does not exixt and can not be created */
  8793. res = -2;
  8794. break;
  8795. }
  8796. /* Is path itself a directory? */
  8797. if (p[1] == '\0') {
  8798. res = 0;
  8799. }
  8800. }
  8801. return res;
  8802. }
  8803. static void
  8804. remove_bad_file(const struct mg_connection *conn, const char *path)
  8805. {
  8806. int r = mg_remove(conn, path);
  8807. if (r != 0) {
  8808. mg_cry_internal(conn,
  8809. "%s: Cannot remove invalid file %s",
  8810. __func__,
  8811. path);
  8812. }
  8813. }
  8814. long long
  8815. mg_store_body(struct mg_connection *conn, const char *path)
  8816. {
  8817. char buf[MG_BUF_LEN];
  8818. long long len = 0;
  8819. int ret, n;
  8820. struct mg_file fi;
  8821. if (conn->consumed_content != 0) {
  8822. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8823. return -11;
  8824. }
  8825. ret = put_dir(conn, path);
  8826. if (ret < 0) {
  8827. /* -1 for path too long,
  8828. * -2 for path can not be created. */
  8829. return ret;
  8830. }
  8831. if (ret != 1) {
  8832. /* Return 0 means, path itself is a directory. */
  8833. return 0;
  8834. }
  8835. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8836. return -12;
  8837. }
  8838. ret = mg_read(conn, buf, sizeof(buf));
  8839. while (ret > 0) {
  8840. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8841. if (n != ret) {
  8842. (void)mg_fclose(
  8843. &fi.access); /* File is bad and will be removed anyway. */
  8844. remove_bad_file(conn, path);
  8845. return -13;
  8846. }
  8847. len += ret;
  8848. ret = mg_read(conn, buf, sizeof(buf));
  8849. }
  8850. /* File is open for writing. If fclose fails, there was probably an
  8851. * error flushing the buffer to disk, so the file on disk might be
  8852. * broken. Delete it and return an error to the caller. */
  8853. if (mg_fclose(&fi.access) != 0) {
  8854. remove_bad_file(conn, path);
  8855. return -14;
  8856. }
  8857. return len;
  8858. }
  8859. #endif /* NO_FILESYSTEMS */
  8860. /* Parse a buffer:
  8861. * Forward the string pointer till the end of a word, then
  8862. * terminate it and forward till the begin of the next word.
  8863. */
  8864. static int
  8865. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8866. {
  8867. /* Forward until a space is found - use isgraph here */
  8868. /* See http://www.cplusplus.com/reference/cctype/ */
  8869. while (isgraph((unsigned char)**ppw)) {
  8870. (*ppw)++;
  8871. }
  8872. /* Check end of word */
  8873. if (eol) {
  8874. /* must be a end of line */
  8875. if ((**ppw != '\r') && (**ppw != '\n')) {
  8876. return -1;
  8877. }
  8878. } else {
  8879. /* must be a end of a word, but not a line */
  8880. if (**ppw != ' ') {
  8881. return -1;
  8882. }
  8883. }
  8884. /* Terminate and forward to the next word */
  8885. do {
  8886. **ppw = 0;
  8887. (*ppw)++;
  8888. } while (isspace((unsigned char)**ppw));
  8889. /* Check after term */
  8890. if (!eol) {
  8891. /* if it's not the end of line, there must be a next word */
  8892. if (!isgraph((unsigned char)**ppw)) {
  8893. return -1;
  8894. }
  8895. }
  8896. /* ok */
  8897. return 1;
  8898. }
  8899. /* Parse HTTP headers from the given buffer, advance buf pointer
  8900. * to the point where parsing stopped.
  8901. * All parameters must be valid pointers (not NULL).
  8902. * Return <0 on error. */
  8903. static int
  8904. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8905. {
  8906. int i;
  8907. int num_headers = 0;
  8908. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8909. char *dp = *buf;
  8910. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8911. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8912. dp++;
  8913. }
  8914. if (dp == *buf) {
  8915. /* End of headers reached. */
  8916. break;
  8917. }
  8918. if (*dp != ':') {
  8919. /* This is not a valid field. */
  8920. return -1;
  8921. }
  8922. /* End of header key (*dp == ':') */
  8923. /* Truncate here and set the key name */
  8924. *dp = 0;
  8925. hdr[i].name = *buf;
  8926. /* Skip all spaces */
  8927. do {
  8928. dp++;
  8929. } while ((*dp == ' ') || (*dp == '\t'));
  8930. /* The rest of the line is the value */
  8931. hdr[i].value = dp;
  8932. /* Find end of line */
  8933. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8934. dp++;
  8935. };
  8936. /* eliminate \r */
  8937. if (*dp == '\r') {
  8938. *dp = 0;
  8939. dp++;
  8940. if (*dp != '\n') {
  8941. /* This is not a valid line. */
  8942. return -1;
  8943. }
  8944. }
  8945. /* here *dp is either 0 or '\n' */
  8946. /* in any case, we have a new header */
  8947. num_headers = i + 1;
  8948. if (*dp) {
  8949. *dp = 0;
  8950. dp++;
  8951. *buf = dp;
  8952. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8953. /* This is the end of the header */
  8954. break;
  8955. }
  8956. } else {
  8957. *buf = dp;
  8958. break;
  8959. }
  8960. }
  8961. return num_headers;
  8962. }
  8963. struct mg_http_method_info {
  8964. const char *name;
  8965. int request_has_body;
  8966. int response_has_body;
  8967. int is_safe;
  8968. int is_idempotent;
  8969. int is_cacheable;
  8970. };
  8971. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8972. static struct mg_http_method_info http_methods[] = {
  8973. /* HTTP (RFC 2616) */
  8974. {"GET", 0, 1, 1, 1, 1},
  8975. {"POST", 1, 1, 0, 0, 0},
  8976. {"PUT", 1, 0, 0, 1, 0},
  8977. {"DELETE", 0, 0, 0, 1, 0},
  8978. {"HEAD", 0, 0, 1, 1, 1},
  8979. {"OPTIONS", 0, 0, 1, 1, 0},
  8980. {"CONNECT", 1, 1, 0, 0, 0},
  8981. /* TRACE method (RFC 2616) is not supported for security reasons */
  8982. /* PATCH method (RFC 5789) */
  8983. {"PATCH", 1, 0, 0, 0, 0},
  8984. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8985. /* WEBDAV (RFC 2518) */
  8986. {"PROPFIND", 0, 1, 1, 1, 0},
  8987. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8988. * Some PROPFIND results MAY be cached, with care,
  8989. * as there is no cache validation mechanism for
  8990. * most properties. This method is both safe and
  8991. * idempotent (see Section 9.1 of [RFC2616]). */
  8992. {"MKCOL", 0, 0, 0, 1, 0},
  8993. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8994. * When MKCOL is invoked without a request body,
  8995. * the newly created collection SHOULD have no
  8996. * members. A MKCOL request message may contain
  8997. * a message body. The precise behavior of a MKCOL
  8998. * request when the body is present is undefined,
  8999. * ... ==> We do not support MKCOL with body data.
  9000. * This method is idempotent, but not safe (see
  9001. * Section 9.1 of [RFC2616]). Responses to this
  9002. * method MUST NOT be cached. */
  9003. /* Unsupported WEBDAV Methods: */
  9004. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9005. /* + 11 methods from RFC 3253 */
  9006. /* ORDERPATCH (RFC 3648) */
  9007. /* ACL (RFC 3744) */
  9008. /* SEARCH (RFC 5323) */
  9009. /* + MicroSoft extensions
  9010. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9011. /* REPORT method (RFC 3253) */
  9012. {"REPORT", 1, 1, 1, 1, 1},
  9013. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9014. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9015. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9016. * to be useful for REST in case a "GET request with body" is
  9017. * required. */
  9018. {NULL, 0, 0, 0, 0, 0}
  9019. /* end of list */
  9020. };
  9021. static const struct mg_http_method_info *
  9022. get_http_method_info(const char *method)
  9023. {
  9024. /* Check if the method is known to the server. The list of all known
  9025. * HTTP methods can be found here at
  9026. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9027. */
  9028. const struct mg_http_method_info *m = http_methods;
  9029. while (m->name) {
  9030. if (!strcmp(m->name, method)) {
  9031. return m;
  9032. }
  9033. m++;
  9034. }
  9035. return NULL;
  9036. }
  9037. static int
  9038. is_valid_http_method(const char *method)
  9039. {
  9040. return (get_http_method_info(method) != NULL);
  9041. }
  9042. /* Parse HTTP request, fill in mg_request_info structure.
  9043. * This function modifies the buffer by NUL-terminating
  9044. * HTTP request components, header names and header values.
  9045. * Parameters:
  9046. * buf (in/out): pointer to the HTTP header to parse and split
  9047. * len (in): length of HTTP header buffer
  9048. * re (out): parsed header as mg_request_info
  9049. * buf and ri must be valid pointers (not NULL), len>0.
  9050. * Returns <0 on error. */
  9051. static int
  9052. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9053. {
  9054. int request_length;
  9055. int init_skip = 0;
  9056. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9057. * remote_port */
  9058. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9059. NULL;
  9060. ri->num_headers = 0;
  9061. /* RFC says that all initial whitespaces should be ingored */
  9062. /* This included all leading \r and \n (isspace) */
  9063. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9064. while ((len > 0) && isspace((unsigned char)*buf)) {
  9065. buf++;
  9066. len--;
  9067. init_skip++;
  9068. }
  9069. if (len == 0) {
  9070. /* Incomplete request */
  9071. return 0;
  9072. }
  9073. /* Control characters are not allowed, including zero */
  9074. if (iscntrl((unsigned char)*buf)) {
  9075. return -1;
  9076. }
  9077. /* Find end of HTTP header */
  9078. request_length = get_http_header_len(buf, len);
  9079. if (request_length <= 0) {
  9080. return request_length;
  9081. }
  9082. buf[request_length - 1] = '\0';
  9083. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9084. return -1;
  9085. }
  9086. /* The first word has to be the HTTP method */
  9087. ri->request_method = buf;
  9088. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9089. return -1;
  9090. }
  9091. /* Check for a valid http method */
  9092. if (!is_valid_http_method(ri->request_method)) {
  9093. return -1;
  9094. }
  9095. /* The second word is the URI */
  9096. ri->request_uri = buf;
  9097. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9098. return -1;
  9099. }
  9100. /* Next would be the HTTP version */
  9101. ri->http_version = buf;
  9102. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9103. return -1;
  9104. }
  9105. /* Check for a valid HTTP version key */
  9106. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9107. /* Invalid request */
  9108. return -1;
  9109. }
  9110. ri->http_version += 5;
  9111. /* Parse all HTTP headers */
  9112. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9113. if (ri->num_headers < 0) {
  9114. /* Error while parsing headers */
  9115. return -1;
  9116. }
  9117. return request_length + init_skip;
  9118. }
  9119. static int
  9120. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9121. {
  9122. int response_length;
  9123. int init_skip = 0;
  9124. char *tmp, *tmp2;
  9125. long l;
  9126. /* Initialize elements. */
  9127. ri->http_version = ri->status_text = NULL;
  9128. ri->num_headers = ri->status_code = 0;
  9129. /* RFC says that all initial whitespaces should be ingored */
  9130. /* This included all leading \r and \n (isspace) */
  9131. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9132. while ((len > 0) && isspace((unsigned char)*buf)) {
  9133. buf++;
  9134. len--;
  9135. init_skip++;
  9136. }
  9137. if (len == 0) {
  9138. /* Incomplete request */
  9139. return 0;
  9140. }
  9141. /* Control characters are not allowed, including zero */
  9142. if (iscntrl((unsigned char)*buf)) {
  9143. return -1;
  9144. }
  9145. /* Find end of HTTP header */
  9146. response_length = get_http_header_len(buf, len);
  9147. if (response_length <= 0) {
  9148. return response_length;
  9149. }
  9150. buf[response_length - 1] = '\0';
  9151. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9152. return -1;
  9153. }
  9154. /* The first word is the HTTP version */
  9155. /* Check for a valid HTTP version key */
  9156. if (strncmp(buf, "HTTP/", 5) != 0) {
  9157. /* Invalid request */
  9158. return -1;
  9159. }
  9160. buf += 5;
  9161. if (!isgraph((unsigned char)buf[0])) {
  9162. /* Invalid request */
  9163. return -1;
  9164. }
  9165. ri->http_version = buf;
  9166. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9167. return -1;
  9168. }
  9169. /* The second word is the status as a number */
  9170. tmp = buf;
  9171. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9172. return -1;
  9173. }
  9174. l = strtol(tmp, &tmp2, 10);
  9175. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9176. /* Everything else but a 3 digit code is invalid */
  9177. return -1;
  9178. }
  9179. ri->status_code = (int)l;
  9180. /* The rest of the line is the status text */
  9181. ri->status_text = buf;
  9182. /* Find end of status text */
  9183. /* isgraph or isspace = isprint */
  9184. while (isprint((unsigned char)*buf)) {
  9185. buf++;
  9186. }
  9187. if ((*buf != '\r') && (*buf != '\n')) {
  9188. return -1;
  9189. }
  9190. /* Terminate string and forward buf to next line */
  9191. do {
  9192. *buf = 0;
  9193. buf++;
  9194. } while (isspace((unsigned char)*buf));
  9195. /* Parse all HTTP headers */
  9196. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9197. if (ri->num_headers < 0) {
  9198. /* Error while parsing headers */
  9199. return -1;
  9200. }
  9201. return response_length + init_skip;
  9202. }
  9203. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9204. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9205. * buffer (which marks the end of HTTP request). Buffer buf may already
  9206. * have some data. The length of the data is stored in nread.
  9207. * Upon every read operation, increase nread by the number of bytes read. */
  9208. static int
  9209. read_message(FILE *fp,
  9210. struct mg_connection *conn,
  9211. char *buf,
  9212. int bufsiz,
  9213. int *nread)
  9214. {
  9215. int request_len, n = 0;
  9216. struct timespec last_action_time;
  9217. double request_timeout;
  9218. if (!conn) {
  9219. return 0;
  9220. }
  9221. memset(&last_action_time, 0, sizeof(last_action_time));
  9222. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9223. /* value of request_timeout is in seconds, config in milliseconds */
  9224. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9225. } else {
  9226. request_timeout = -1.0;
  9227. }
  9228. if (conn->handled_requests > 0) {
  9229. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9230. request_timeout =
  9231. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9232. }
  9233. }
  9234. request_len = get_http_header_len(buf, *nread);
  9235. while (request_len == 0) {
  9236. /* Full request not yet received */
  9237. if (conn->phys_ctx->stop_flag != 0) {
  9238. /* Server is to be stopped. */
  9239. return -1;
  9240. }
  9241. if (*nread >= bufsiz) {
  9242. /* Request too long */
  9243. return -2;
  9244. }
  9245. n = pull_inner(
  9246. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9247. if (n == -2) {
  9248. /* Receive error */
  9249. return -1;
  9250. }
  9251. /* update clock after every read request */
  9252. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9253. if (n > 0) {
  9254. *nread += n;
  9255. request_len = get_http_header_len(buf, *nread);
  9256. } else {
  9257. request_len = 0;
  9258. }
  9259. if ((request_len == 0) && (request_timeout >= 0)) {
  9260. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9261. > request_timeout) {
  9262. /* Timeout */
  9263. return -1;
  9264. }
  9265. }
  9266. }
  9267. return request_len;
  9268. }
  9269. #if !defined(NO_CGI) || !defined(NO_FILES)
  9270. static int
  9271. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9272. {
  9273. const char *expect;
  9274. char buf[MG_BUF_LEN];
  9275. int success = 0;
  9276. if (!conn) {
  9277. return 0;
  9278. }
  9279. expect = mg_get_header(conn, "Expect");
  9280. DEBUG_ASSERT(fp != NULL);
  9281. if (!fp) {
  9282. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9283. return 0;
  9284. }
  9285. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9286. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9287. */
  9288. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9289. } else {
  9290. if (expect != NULL) {
  9291. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9292. conn->status_code = 100;
  9293. } else {
  9294. conn->status_code = 200;
  9295. }
  9296. DEBUG_ASSERT(conn->consumed_content == 0);
  9297. if (conn->consumed_content != 0) {
  9298. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9299. return 0;
  9300. }
  9301. for (;;) {
  9302. int nread = mg_read(conn, buf, sizeof(buf));
  9303. if (nread <= 0) {
  9304. success = (nread == 0);
  9305. break;
  9306. }
  9307. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9308. break;
  9309. }
  9310. }
  9311. /* Each error code path in this function must send an error */
  9312. if (!success) {
  9313. /* NOTE: Maybe some data has already been sent. */
  9314. /* TODO (low): If some data has been sent, a correct error
  9315. * reply can no longer be sent, so just close the connection */
  9316. mg_send_http_error(conn, 500, "%s", "");
  9317. }
  9318. }
  9319. return success;
  9320. }
  9321. #endif
  9322. #if defined(USE_TIMERS)
  9323. #define TIMER_API static
  9324. #include "timer.inl"
  9325. #endif /* USE_TIMERS */
  9326. #if !defined(NO_CGI)
  9327. /* This structure helps to create an environment for the spawned CGI
  9328. * program.
  9329. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9330. * last element must be NULL.
  9331. * However, on Windows there is a requirement that all these
  9332. * VARIABLE=VALUE\0
  9333. * strings must reside in a contiguous buffer. The end of the buffer is
  9334. * marked by two '\0' characters.
  9335. * We satisfy both worlds: we create an envp array (which is vars), all
  9336. * entries are actually pointers inside buf. */
  9337. struct cgi_environment {
  9338. struct mg_connection *conn;
  9339. /* Data block */
  9340. char *buf; /* Environment buffer */
  9341. size_t buflen; /* Space available in buf */
  9342. size_t bufused; /* Space taken in buf */
  9343. /* Index block */
  9344. char **var; /* char **envp */
  9345. size_t varlen; /* Number of variables available in var */
  9346. size_t varused; /* Number of variables stored in var */
  9347. };
  9348. static void addenv(struct cgi_environment *env,
  9349. PRINTF_FORMAT_STRING(const char *fmt),
  9350. ...) PRINTF_ARGS(2, 3);
  9351. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9352. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9353. static void
  9354. addenv(struct cgi_environment *env, const char *fmt, ...)
  9355. {
  9356. size_t i, n, space;
  9357. int truncated = 0;
  9358. char *added;
  9359. va_list ap;
  9360. if ((env->varlen - env->varused) < 2) {
  9361. mg_cry_internal(env->conn,
  9362. "%s: Cannot register CGI variable [%s]",
  9363. __func__,
  9364. fmt);
  9365. return;
  9366. }
  9367. /* Calculate how much space is left in the buffer */
  9368. space = (env->buflen - env->bufused);
  9369. do {
  9370. /* Space for "\0\0" is always needed. */
  9371. if (space <= 2) {
  9372. /* Allocate new buffer */
  9373. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9374. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9375. if (!added) {
  9376. /* Out of memory */
  9377. mg_cry_internal(
  9378. env->conn,
  9379. "%s: Cannot allocate memory for CGI variable [%s]",
  9380. __func__,
  9381. fmt);
  9382. return;
  9383. }
  9384. /* Retarget pointers */
  9385. env->buf = added;
  9386. env->buflen = n;
  9387. for (i = 0, n = 0; i < env->varused; i++) {
  9388. env->var[i] = added + n;
  9389. n += strlen(added + n) + 1;
  9390. }
  9391. space = (env->buflen - env->bufused);
  9392. }
  9393. /* Make a pointer to the free space int the buffer */
  9394. added = env->buf + env->bufused;
  9395. /* Copy VARIABLE=VALUE\0 string into the free space */
  9396. va_start(ap, fmt);
  9397. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9398. va_end(ap);
  9399. /* Do not add truncated strings to the environment */
  9400. if (truncated) {
  9401. /* Reallocate the buffer */
  9402. space = 0;
  9403. }
  9404. } while (truncated);
  9405. /* Calculate number of bytes added to the environment */
  9406. n = strlen(added) + 1;
  9407. env->bufused += n;
  9408. /* Append a pointer to the added string into the envp array */
  9409. env->var[env->varused] = added;
  9410. env->varused++;
  9411. }
  9412. /* Return 0 on success, non-zero if an error occurs. */
  9413. static int
  9414. prepare_cgi_environment(struct mg_connection *conn,
  9415. const char *prog,
  9416. struct cgi_environment *env)
  9417. {
  9418. const char *s;
  9419. struct vec var_vec;
  9420. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9421. int i, truncated, uri_len;
  9422. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9423. return -1;
  9424. }
  9425. env->conn = conn;
  9426. env->buflen = CGI_ENVIRONMENT_SIZE;
  9427. env->bufused = 0;
  9428. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9429. if (env->buf == NULL) {
  9430. mg_cry_internal(conn,
  9431. "%s: Not enough memory for environmental buffer",
  9432. __func__);
  9433. return -1;
  9434. }
  9435. env->varlen = MAX_CGI_ENVIR_VARS;
  9436. env->varused = 0;
  9437. env->var =
  9438. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9439. if (env->var == NULL) {
  9440. mg_cry_internal(conn,
  9441. "%s: Not enough memory for environmental variables",
  9442. __func__);
  9443. mg_free(env->buf);
  9444. return -1;
  9445. }
  9446. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9447. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9448. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9449. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9450. /* Prepare the environment block */
  9451. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9452. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9453. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9454. #if defined(USE_IPV6)
  9455. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9456. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9457. } else
  9458. #endif
  9459. {
  9460. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9461. }
  9462. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9463. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9464. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9465. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9466. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9467. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9468. /* SCRIPT_NAME */
  9469. uri_len = (int)strlen(conn->request_info.local_uri);
  9470. if (conn->path_info == NULL) {
  9471. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9472. /* URI: /path_to_script/script.cgi */
  9473. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9474. } else {
  9475. /* URI: /path_to_script/ ... using index.cgi */
  9476. const char *index_file = strrchr(prog, '/');
  9477. if (index_file) {
  9478. addenv(env,
  9479. "SCRIPT_NAME=%s%s",
  9480. conn->request_info.local_uri,
  9481. index_file + 1);
  9482. }
  9483. }
  9484. } else {
  9485. /* URI: /path_to_script/script.cgi/path_info */
  9486. addenv(env,
  9487. "SCRIPT_NAME=%.*s",
  9488. uri_len - (int)strlen(conn->path_info),
  9489. conn->request_info.local_uri);
  9490. }
  9491. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9492. if (conn->path_info == NULL) {
  9493. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9494. } else {
  9495. addenv(env,
  9496. "PATH_TRANSLATED=%s%s",
  9497. conn->dom_ctx->config[DOCUMENT_ROOT],
  9498. conn->path_info);
  9499. }
  9500. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9501. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9502. addenv(env, "CONTENT_TYPE=%s", s);
  9503. }
  9504. if (conn->request_info.query_string != NULL) {
  9505. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9506. }
  9507. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9508. addenv(env, "CONTENT_LENGTH=%s", s);
  9509. }
  9510. if ((s = getenv("PATH")) != NULL) {
  9511. addenv(env, "PATH=%s", s);
  9512. }
  9513. if (conn->path_info != NULL) {
  9514. addenv(env, "PATH_INFO=%s", conn->path_info);
  9515. }
  9516. if (conn->status_code > 0) {
  9517. /* CGI error handler should show the status code */
  9518. addenv(env, "STATUS=%d", conn->status_code);
  9519. }
  9520. #if defined(_WIN32)
  9521. if ((s = getenv("COMSPEC")) != NULL) {
  9522. addenv(env, "COMSPEC=%s", s);
  9523. }
  9524. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9525. addenv(env, "SYSTEMROOT=%s", s);
  9526. }
  9527. if ((s = getenv("SystemDrive")) != NULL) {
  9528. addenv(env, "SystemDrive=%s", s);
  9529. }
  9530. if ((s = getenv("ProgramFiles")) != NULL) {
  9531. addenv(env, "ProgramFiles=%s", s);
  9532. }
  9533. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9534. addenv(env, "ProgramFiles(x86)=%s", s);
  9535. }
  9536. #else
  9537. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9538. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9539. }
  9540. #endif /* _WIN32 */
  9541. if ((s = getenv("PERLLIB")) != NULL) {
  9542. addenv(env, "PERLLIB=%s", s);
  9543. }
  9544. if (conn->request_info.remote_user != NULL) {
  9545. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9546. addenv(env, "%s", "AUTH_TYPE=Digest");
  9547. }
  9548. /* Add all headers as HTTP_* variables */
  9549. for (i = 0; i < conn->request_info.num_headers; i++) {
  9550. (void)mg_snprintf(conn,
  9551. &truncated,
  9552. http_var_name,
  9553. sizeof(http_var_name),
  9554. "HTTP_%s",
  9555. conn->request_info.http_headers[i].name);
  9556. if (truncated) {
  9557. mg_cry_internal(conn,
  9558. "%s: HTTP header variable too long [%s]",
  9559. __func__,
  9560. conn->request_info.http_headers[i].name);
  9561. continue;
  9562. }
  9563. /* Convert variable name into uppercase, and change - to _ */
  9564. for (p = http_var_name; *p != '\0'; p++) {
  9565. if (*p == '-') {
  9566. *p = '_';
  9567. }
  9568. *p = (char)toupper((unsigned char)*p);
  9569. }
  9570. addenv(env,
  9571. "%s=%s",
  9572. http_var_name,
  9573. conn->request_info.http_headers[i].value);
  9574. }
  9575. /* Add user-specified variables */
  9576. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9577. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9578. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9579. }
  9580. env->var[env->varused] = NULL;
  9581. env->buf[env->bufused] = '\0';
  9582. return 0;
  9583. }
  9584. /* Data for CGI process control: PID and number of references */
  9585. struct process_control_data {
  9586. pid_t pid;
  9587. int references;
  9588. };
  9589. static int
  9590. abort_process(void *data)
  9591. {
  9592. /* Waitpid checks for child status and won't work for a pid that does not
  9593. * identify a child of the current process. Thus, if the pid is reused,
  9594. * we will not affect a different process. */
  9595. struct process_control_data *proc = (struct process_control_data *)data;
  9596. int status = 0;
  9597. int refs;
  9598. pid_t ret_pid;
  9599. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9600. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9601. /* Stop child process */
  9602. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9603. kill(proc->pid, SIGABRT);
  9604. /* Wait until process is terminated (don't leave zombies) */
  9605. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9606. ;
  9607. } else {
  9608. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9609. }
  9610. /* Dec reference counter */
  9611. refs = mg_atomic_dec(&proc->references);
  9612. if (refs == 0) {
  9613. /* no more references - free data */
  9614. mg_free(data);
  9615. }
  9616. return 0;
  9617. }
  9618. /* Local (static) function assumes all arguments are valid. */
  9619. static void
  9620. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9621. {
  9622. char *buf;
  9623. size_t buflen;
  9624. int headers_len, data_len, i, truncated;
  9625. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9626. const char *status, *status_text, *connection_state;
  9627. char *pbuf, dir[PATH_MAX], *p;
  9628. struct mg_request_info ri;
  9629. struct cgi_environment blk;
  9630. FILE *in = NULL, *out = NULL, *err = NULL;
  9631. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9632. pid_t pid = (pid_t)-1;
  9633. struct process_control_data *proc = NULL;
  9634. #if defined(USE_TIMERS)
  9635. double cgi_timeout = -1.0;
  9636. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9637. /* Get timeout in seconds */
  9638. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9639. }
  9640. #endif
  9641. buf = NULL;
  9642. buflen = conn->phys_ctx->max_request_size;
  9643. i = prepare_cgi_environment(conn, prog, &blk);
  9644. if (i != 0) {
  9645. blk.buf = NULL;
  9646. blk.var = NULL;
  9647. goto done;
  9648. }
  9649. /* CGI must be executed in its own directory. 'dir' must point to the
  9650. * directory containing executable program, 'p' must point to the
  9651. * executable program name relative to 'dir'. */
  9652. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9653. if (truncated) {
  9654. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9655. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9656. goto done;
  9657. }
  9658. if ((p = strrchr(dir, '/')) != NULL) {
  9659. *p++ = '\0';
  9660. } else {
  9661. dir[0] = '.';
  9662. dir[1] = '\0';
  9663. p = (char *)prog;
  9664. }
  9665. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9666. status = strerror(ERRNO);
  9667. mg_cry_internal(
  9668. conn,
  9669. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9670. prog,
  9671. status);
  9672. mg_send_http_error(conn,
  9673. 500,
  9674. "Error: Cannot create CGI pipe: %s",
  9675. status);
  9676. goto done;
  9677. }
  9678. proc = (struct process_control_data *)
  9679. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9680. if (proc == NULL) {
  9681. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9682. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9683. goto done;
  9684. }
  9685. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9686. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9687. if (pid == (pid_t)-1) {
  9688. status = strerror(ERRNO);
  9689. mg_cry_internal(
  9690. conn,
  9691. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9692. prog,
  9693. status);
  9694. mg_send_http_error(conn,
  9695. 500,
  9696. "Error: Cannot spawn CGI process [%s]: %s",
  9697. prog,
  9698. status);
  9699. mg_free(proc);
  9700. proc = NULL;
  9701. goto done;
  9702. }
  9703. /* Store data in shared process_control_data */
  9704. proc->pid = pid;
  9705. proc->references = 1;
  9706. #if defined(USE_TIMERS)
  9707. if (cgi_timeout > 0.0) {
  9708. proc->references = 2;
  9709. // Start a timer for CGI
  9710. timer_add(conn->phys_ctx,
  9711. cgi_timeout /* in seconds */,
  9712. 0.0,
  9713. 1,
  9714. abort_process,
  9715. (void *)proc);
  9716. }
  9717. #endif
  9718. /* Parent closes only one side of the pipes.
  9719. * If we don't mark them as closed, close() attempt before
  9720. * return from this function throws an exception on Windows.
  9721. * Windows does not like when closed descriptor is closed again. */
  9722. (void)close(fdin[0]);
  9723. (void)close(fdout[1]);
  9724. (void)close(fderr[1]);
  9725. fdin[0] = fdout[1] = fderr[1] = -1;
  9726. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9727. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9728. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9729. status = strerror(ERRNO);
  9730. mg_cry_internal(conn,
  9731. "Error: CGI program \"%s\": Can not open fd: %s",
  9732. prog,
  9733. status);
  9734. mg_send_http_error(conn,
  9735. 500,
  9736. "Error: CGI can not open fd\nfdopen: %s",
  9737. status);
  9738. goto done;
  9739. }
  9740. setbuf(in, NULL);
  9741. setbuf(out, NULL);
  9742. setbuf(err, NULL);
  9743. fout.access.fp = out;
  9744. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9745. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9746. conn->content_len);
  9747. /* This is a POST/PUT request, or another request with body data. */
  9748. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9749. /* Error sending the body data */
  9750. mg_cry_internal(
  9751. conn,
  9752. "Error: CGI program \"%s\": Forward body data failed",
  9753. prog);
  9754. goto done;
  9755. }
  9756. }
  9757. /* Close so child gets an EOF. */
  9758. fclose(in);
  9759. in = NULL;
  9760. fdin[1] = -1;
  9761. /* Now read CGI reply into a buffer. We need to set correct
  9762. * status code, thus we need to see all HTTP headers first.
  9763. * Do not send anything back to client, until we buffer in all
  9764. * HTTP headers. */
  9765. data_len = 0;
  9766. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9767. if (buf == NULL) {
  9768. mg_send_http_error(conn,
  9769. 500,
  9770. "Error: Not enough memory for CGI buffer (%u bytes)",
  9771. (unsigned int)buflen);
  9772. mg_cry_internal(
  9773. conn,
  9774. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9775. "bytes)",
  9776. prog,
  9777. (unsigned int)buflen);
  9778. goto done;
  9779. }
  9780. DEBUG_TRACE("CGI: %s", "wait for response");
  9781. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9782. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9783. if (headers_len <= 0) {
  9784. /* Could not parse the CGI response. Check if some error message on
  9785. * stderr. */
  9786. i = pull_all(err, conn, buf, (int)buflen);
  9787. if (i > 0) {
  9788. /* CGI program explicitly sent an error */
  9789. /* Write the error message to the internal log */
  9790. mg_cry_internal(conn,
  9791. "Error: CGI program \"%s\" sent error "
  9792. "message: [%.*s]",
  9793. prog,
  9794. i,
  9795. buf);
  9796. /* Don't send the error message back to the client */
  9797. mg_send_http_error(conn,
  9798. 500,
  9799. "Error: CGI program \"%s\" failed.",
  9800. prog);
  9801. } else {
  9802. /* CGI program did not explicitly send an error, but a broken
  9803. * respon header */
  9804. mg_cry_internal(conn,
  9805. "Error: CGI program sent malformed or too big "
  9806. "(>%u bytes) HTTP headers: [%.*s]",
  9807. (unsigned)buflen,
  9808. data_len,
  9809. buf);
  9810. mg_send_http_error(conn,
  9811. 500,
  9812. "Error: CGI program sent malformed or too big "
  9813. "(>%u bytes) HTTP headers: [%.*s]",
  9814. (unsigned)buflen,
  9815. data_len,
  9816. buf);
  9817. }
  9818. /* in both cases, abort processing CGI */
  9819. goto done;
  9820. }
  9821. pbuf = buf;
  9822. buf[headers_len - 1] = '\0';
  9823. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9824. /* Make up and send the status line */
  9825. status_text = "OK";
  9826. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9827. != NULL) {
  9828. conn->status_code = atoi(status);
  9829. status_text = status;
  9830. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9831. status_text++;
  9832. }
  9833. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9834. != NULL) {
  9835. conn->status_code = 307;
  9836. } else {
  9837. conn->status_code = 200;
  9838. }
  9839. connection_state =
  9840. get_header(ri.http_headers, ri.num_headers, "Connection");
  9841. if (!header_has_option(connection_state, "keep-alive")) {
  9842. conn->must_close = 1;
  9843. }
  9844. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9845. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9846. /* Send headers */
  9847. for (i = 0; i < ri.num_headers; i++) {
  9848. DEBUG_TRACE("CGI header: %s: %s",
  9849. ri.http_headers[i].name,
  9850. ri.http_headers[i].value);
  9851. mg_printf(conn,
  9852. "%s: %s\r\n",
  9853. ri.http_headers[i].name,
  9854. ri.http_headers[i].value);
  9855. }
  9856. mg_write(conn, "\r\n", 2);
  9857. /* Send chunk of data that may have been read after the headers */
  9858. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9859. /* Read the rest of CGI output and send to the client */
  9860. DEBUG_TRACE("CGI: %s", "forward all data");
  9861. send_file_data(conn, &fout, 0, INT64_MAX);
  9862. DEBUG_TRACE("CGI: %s", "all data sent");
  9863. done:
  9864. mg_free(blk.var);
  9865. mg_free(blk.buf);
  9866. if (pid != (pid_t)-1) {
  9867. abort_process((void *)proc);
  9868. }
  9869. if (fdin[0] != -1) {
  9870. close(fdin[0]);
  9871. }
  9872. if (fdout[1] != -1) {
  9873. close(fdout[1]);
  9874. }
  9875. if (fderr[1] != -1) {
  9876. close(fderr[1]);
  9877. }
  9878. if (in != NULL) {
  9879. fclose(in);
  9880. } else if (fdin[1] != -1) {
  9881. close(fdin[1]);
  9882. }
  9883. if (out != NULL) {
  9884. fclose(out);
  9885. } else if (fdout[0] != -1) {
  9886. close(fdout[0]);
  9887. }
  9888. if (err != NULL) {
  9889. fclose(err);
  9890. } else if (fderr[0] != -1) {
  9891. close(fderr[0]);
  9892. }
  9893. mg_free(buf);
  9894. }
  9895. #endif /* !NO_CGI */
  9896. #if !defined(NO_FILES)
  9897. static void
  9898. mkcol(struct mg_connection *conn, const char *path)
  9899. {
  9900. int rc, body_len;
  9901. struct de de;
  9902. char date[64];
  9903. time_t curtime = time(NULL);
  9904. if (conn == NULL) {
  9905. return;
  9906. }
  9907. /* TODO (mid): Check the mg_send_http_error situations in this function
  9908. */
  9909. memset(&de.file, 0, sizeof(de.file));
  9910. if (!mg_stat(conn, path, &de.file)) {
  9911. mg_cry_internal(conn,
  9912. "%s: mg_stat(%s) failed: %s",
  9913. __func__,
  9914. path,
  9915. strerror(ERRNO));
  9916. }
  9917. if (de.file.last_modified) {
  9918. /* TODO (mid): This check does not seem to make any sense ! */
  9919. /* TODO (mid): Add a webdav unit test first, before changing
  9920. * anything here. */
  9921. mg_send_http_error(
  9922. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9923. return;
  9924. }
  9925. body_len = conn->data_len - conn->request_len;
  9926. if (body_len > 0) {
  9927. mg_send_http_error(
  9928. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9929. return;
  9930. }
  9931. rc = mg_mkdir(conn, path, 0755);
  9932. if (rc == 0) {
  9933. conn->status_code = 201;
  9934. gmt_time_string(date, sizeof(date), &curtime);
  9935. mg_printf(conn,
  9936. "HTTP/1.1 %d Created\r\n"
  9937. "Date: %s\r\n",
  9938. conn->status_code,
  9939. date);
  9940. send_static_cache_header(conn);
  9941. send_additional_header(conn);
  9942. mg_printf(conn,
  9943. "Content-Length: 0\r\n"
  9944. "Connection: %s\r\n\r\n",
  9945. suggest_connection_header(conn));
  9946. } else {
  9947. if (errno == EEXIST) {
  9948. mg_send_http_error(
  9949. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9950. } else if (errno == EACCES) {
  9951. mg_send_http_error(
  9952. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9953. } else if (errno == ENOENT) {
  9954. mg_send_http_error(
  9955. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9956. } else {
  9957. mg_send_http_error(
  9958. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9959. }
  9960. }
  9961. }
  9962. static void
  9963. put_file(struct mg_connection *conn, const char *path)
  9964. {
  9965. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9966. const char *range;
  9967. int64_t r1, r2;
  9968. int rc;
  9969. char date[64];
  9970. time_t curtime = time(NULL);
  9971. if (conn == NULL) {
  9972. return;
  9973. }
  9974. if (mg_stat(conn, path, &file.stat)) {
  9975. /* File already exists */
  9976. conn->status_code = 200;
  9977. if (file.stat.is_directory) {
  9978. /* This is an already existing directory,
  9979. * so there is nothing to do for the server. */
  9980. rc = 0;
  9981. } else {
  9982. /* File exists and is not a directory. */
  9983. /* Can it be replaced? */
  9984. #if defined(MG_USE_OPEN_FILE)
  9985. if (file.access.membuf != NULL) {
  9986. /* This is an "in-memory" file, that can not be replaced */
  9987. mg_send_http_error(conn,
  9988. 405,
  9989. "Error: Put not possible\nReplacing %s "
  9990. "is not supported",
  9991. path);
  9992. return;
  9993. }
  9994. #endif
  9995. /* Check if the server may write this file */
  9996. if (access(path, W_OK) == 0) {
  9997. /* Access granted */
  9998. conn->status_code = 200;
  9999. rc = 1;
  10000. } else {
  10001. mg_send_http_error(
  10002. conn,
  10003. 403,
  10004. "Error: Put not possible\nReplacing %s is not allowed",
  10005. path);
  10006. return;
  10007. }
  10008. }
  10009. } else {
  10010. /* File should be created */
  10011. conn->status_code = 201;
  10012. rc = put_dir(conn, path);
  10013. }
  10014. if (rc == 0) {
  10015. /* put_dir returns 0 if path is a directory */
  10016. gmt_time_string(date, sizeof(date), &curtime);
  10017. mg_printf(conn,
  10018. "HTTP/1.1 %d %s\r\n",
  10019. conn->status_code,
  10020. mg_get_response_code_text(NULL, conn->status_code));
  10021. send_no_cache_header(conn);
  10022. send_additional_header(conn);
  10023. mg_printf(conn,
  10024. "Date: %s\r\n"
  10025. "Content-Length: 0\r\n"
  10026. "Connection: %s\r\n\r\n",
  10027. date,
  10028. suggest_connection_header(conn));
  10029. /* Request to create a directory has been fulfilled successfully.
  10030. * No need to put a file. */
  10031. return;
  10032. }
  10033. if (rc == -1) {
  10034. /* put_dir returns -1 if the path is too long */
  10035. mg_send_http_error(conn,
  10036. 414,
  10037. "Error: Path too long\nput_dir(%s): %s",
  10038. path,
  10039. strerror(ERRNO));
  10040. return;
  10041. }
  10042. if (rc == -2) {
  10043. /* put_dir returns -2 if the directory can not be created */
  10044. mg_send_http_error(conn,
  10045. 500,
  10046. "Error: Can not create directory\nput_dir(%s): %s",
  10047. path,
  10048. strerror(ERRNO));
  10049. return;
  10050. }
  10051. /* A file should be created or overwritten. */
  10052. /* Currently CivetWeb does not nead read+write access. */
  10053. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10054. || file.access.fp == NULL) {
  10055. (void)mg_fclose(&file.access);
  10056. mg_send_http_error(conn,
  10057. 500,
  10058. "Error: Can not create file\nfopen(%s): %s",
  10059. path,
  10060. strerror(ERRNO));
  10061. return;
  10062. }
  10063. fclose_on_exec(&file.access, conn);
  10064. range = mg_get_header(conn, "Content-Range");
  10065. r1 = r2 = 0;
  10066. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10067. conn->status_code = 206; /* Partial content */
  10068. fseeko(file.access.fp, r1, SEEK_SET);
  10069. }
  10070. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10071. /* forward_body_data failed.
  10072. * The error code has already been sent to the client,
  10073. * and conn->status_code is already set. */
  10074. (void)mg_fclose(&file.access);
  10075. return;
  10076. }
  10077. if (mg_fclose(&file.access) != 0) {
  10078. /* fclose failed. This might have different reasons, but a likely
  10079. * one is "no space on disk", http 507. */
  10080. conn->status_code = 507;
  10081. }
  10082. gmt_time_string(date, sizeof(date), &curtime);
  10083. mg_printf(conn,
  10084. "HTTP/1.1 %d %s\r\n",
  10085. conn->status_code,
  10086. mg_get_response_code_text(NULL, conn->status_code));
  10087. send_no_cache_header(conn);
  10088. send_additional_header(conn);
  10089. mg_printf(conn,
  10090. "Date: %s\r\n"
  10091. "Content-Length: 0\r\n"
  10092. "Connection: %s\r\n\r\n",
  10093. date,
  10094. suggest_connection_header(conn));
  10095. }
  10096. static void
  10097. delete_file(struct mg_connection *conn, const char *path)
  10098. {
  10099. struct de de;
  10100. memset(&de.file, 0, sizeof(de.file));
  10101. if (!mg_stat(conn, path, &de.file)) {
  10102. /* mg_stat returns 0 if the file does not exist */
  10103. mg_send_http_error(conn,
  10104. 404,
  10105. "Error: Cannot delete file\nFile %s not found",
  10106. path);
  10107. return;
  10108. }
  10109. #if 0 /* Ignore if a file in memory is inside a folder */
  10110. if (de.access.membuf != NULL) {
  10111. /* the file is cached in memory */
  10112. mg_send_http_error(
  10113. conn,
  10114. 405,
  10115. "Error: Delete not possible\nDeleting %s is not supported",
  10116. path);
  10117. return;
  10118. }
  10119. #endif
  10120. if (de.file.is_directory) {
  10121. if (remove_directory(conn, path)) {
  10122. /* Delete is successful: Return 204 without content. */
  10123. mg_send_http_error(conn, 204, "%s", "");
  10124. } else {
  10125. /* Delete is not successful: Return 500 (Server error). */
  10126. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10127. }
  10128. return;
  10129. }
  10130. /* This is an existing file (not a directory).
  10131. * Check if write permission is granted. */
  10132. if (access(path, W_OK) != 0) {
  10133. /* File is read only */
  10134. mg_send_http_error(
  10135. conn,
  10136. 403,
  10137. "Error: Delete not possible\nDeleting %s is not allowed",
  10138. path);
  10139. return;
  10140. }
  10141. /* Try to delete it. */
  10142. if (mg_remove(conn, path) == 0) {
  10143. /* Delete was successful: Return 204 without content. */
  10144. mg_send_http_error(conn, 204, "%s", "");
  10145. } else {
  10146. /* Delete not successful (file locked). */
  10147. mg_send_http_error(conn,
  10148. 423,
  10149. "Error: Cannot delete file\nremove(%s): %s",
  10150. path,
  10151. strerror(ERRNO));
  10152. }
  10153. }
  10154. #endif /* !NO_FILES */
  10155. #if !defined(NO_FILESYSTEMS)
  10156. static void
  10157. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10158. static void
  10159. do_ssi_include(struct mg_connection *conn,
  10160. const char *ssi,
  10161. char *tag,
  10162. int include_level)
  10163. {
  10164. char file_name[MG_BUF_LEN], path[512], *p;
  10165. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10166. size_t len;
  10167. int truncated = 0;
  10168. if (conn == NULL) {
  10169. return;
  10170. }
  10171. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10172. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10173. * always < MG_BUF_LEN. */
  10174. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10175. /* File name is relative to the webserver root */
  10176. file_name[511] = 0;
  10177. (void)mg_snprintf(conn,
  10178. &truncated,
  10179. path,
  10180. sizeof(path),
  10181. "%s/%s",
  10182. conn->dom_ctx->config[DOCUMENT_ROOT],
  10183. file_name);
  10184. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10185. /* File name is relative to the webserver working directory
  10186. * or it is absolute system path */
  10187. file_name[511] = 0;
  10188. (void)
  10189. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10190. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10191. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10192. /* File name is relative to the currect document */
  10193. file_name[511] = 0;
  10194. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10195. if (!truncated) {
  10196. if ((p = strrchr(path, '/')) != NULL) {
  10197. p[1] = '\0';
  10198. }
  10199. len = strlen(path);
  10200. (void)mg_snprintf(conn,
  10201. &truncated,
  10202. path + len,
  10203. sizeof(path) - len,
  10204. "%s",
  10205. file_name);
  10206. }
  10207. } else {
  10208. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10209. return;
  10210. }
  10211. if (truncated) {
  10212. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10213. return;
  10214. }
  10215. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10216. mg_cry_internal(conn,
  10217. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10218. tag,
  10219. path,
  10220. strerror(ERRNO));
  10221. } else {
  10222. fclose_on_exec(&file.access, conn);
  10223. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10224. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10225. path)
  10226. > 0) {
  10227. send_ssi_file(conn, path, &file, include_level + 1);
  10228. } else {
  10229. send_file_data(conn, &file, 0, INT64_MAX);
  10230. }
  10231. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10232. }
  10233. }
  10234. #if !defined(NO_POPEN)
  10235. static void
  10236. do_ssi_exec(struct mg_connection *conn, char *tag)
  10237. {
  10238. char cmd[1024] = "";
  10239. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10240. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10241. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10242. } else {
  10243. cmd[1023] = 0;
  10244. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10245. mg_cry_internal(conn,
  10246. "Cannot SSI #exec: [%s]: %s",
  10247. cmd,
  10248. strerror(ERRNO));
  10249. } else {
  10250. send_file_data(conn, &file, 0, INT64_MAX);
  10251. pclose(file.access.fp);
  10252. }
  10253. }
  10254. }
  10255. #endif /* !NO_POPEN */
  10256. static int
  10257. mg_fgetc(struct mg_file *filep, int offset)
  10258. {
  10259. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10260. if (filep == NULL) {
  10261. return EOF;
  10262. }
  10263. #if defined(MG_USE_OPEN_FILE)
  10264. if ((filep->access.membuf != NULL) && (offset >= 0)
  10265. && (((unsigned int)(offset)) < filep->stat.size)) {
  10266. return ((const unsigned char *)filep->access.membuf)[offset];
  10267. } else /* else block below */
  10268. #endif
  10269. if (filep->access.fp != NULL) {
  10270. return fgetc(filep->access.fp);
  10271. } else {
  10272. return EOF;
  10273. }
  10274. }
  10275. static void
  10276. send_ssi_file(struct mg_connection *conn,
  10277. const char *path,
  10278. struct mg_file *filep,
  10279. int include_level)
  10280. {
  10281. char buf[MG_BUF_LEN];
  10282. int ch, offset, len, in_tag, in_ssi_tag;
  10283. if (include_level > 10) {
  10284. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10285. return;
  10286. }
  10287. in_tag = in_ssi_tag = len = offset = 0;
  10288. /* Read file, byte by byte, and look for SSI include tags */
  10289. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10290. if (in_tag) {
  10291. /* We are in a tag, either SSI tag or html tag */
  10292. if (ch == '>') {
  10293. /* Tag is closing */
  10294. buf[len++] = '>';
  10295. if (in_ssi_tag) {
  10296. /* Handle SSI tag */
  10297. buf[len] = 0;
  10298. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10299. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10300. #if !defined(NO_POPEN)
  10301. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10302. do_ssi_exec(conn, buf + 9);
  10303. #endif /* !NO_POPEN */
  10304. } else {
  10305. mg_cry_internal(conn,
  10306. "%s: unknown SSI "
  10307. "command: \"%s\"",
  10308. path,
  10309. buf);
  10310. }
  10311. len = 0;
  10312. in_ssi_tag = in_tag = 0;
  10313. } else {
  10314. /* Not an SSI tag */
  10315. /* Flush buffer */
  10316. (void)mg_write(conn, buf, (size_t)len);
  10317. len = 0;
  10318. in_tag = 0;
  10319. }
  10320. } else {
  10321. /* Tag is still open */
  10322. buf[len++] = (char)(ch & 0xff);
  10323. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10324. /* All SSI tags start with <!--# */
  10325. in_ssi_tag = 1;
  10326. }
  10327. if ((len + 2) > (int)sizeof(buf)) {
  10328. /* Tag to long for buffer */
  10329. mg_cry_internal(conn, "%s: tag is too large", path);
  10330. return;
  10331. }
  10332. }
  10333. } else {
  10334. /* We are not in a tag yet. */
  10335. if (ch == '<') {
  10336. /* Tag is opening */
  10337. in_tag = 1;
  10338. if (len > 0) {
  10339. /* Flush current buffer.
  10340. * Buffer is filled with "len" bytes. */
  10341. (void)mg_write(conn, buf, (size_t)len);
  10342. }
  10343. /* Store the < */
  10344. len = 1;
  10345. buf[0] = '<';
  10346. } else {
  10347. /* No Tag */
  10348. /* Add data to buffer */
  10349. buf[len++] = (char)(ch & 0xff);
  10350. /* Flush if buffer is full */
  10351. if (len == (int)sizeof(buf)) {
  10352. mg_write(conn, buf, (size_t)len);
  10353. len = 0;
  10354. }
  10355. }
  10356. }
  10357. }
  10358. /* Send the rest of buffered data */
  10359. if (len > 0) {
  10360. mg_write(conn, buf, (size_t)len);
  10361. }
  10362. }
  10363. static void
  10364. handle_ssi_file_request(struct mg_connection *conn,
  10365. const char *path,
  10366. struct mg_file *filep)
  10367. {
  10368. char date[64];
  10369. time_t curtime = time(NULL);
  10370. const char *cors_orig_cfg;
  10371. const char *cors1, *cors2, *cors3;
  10372. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10373. return;
  10374. }
  10375. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10376. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10377. /* Cross-origin resource sharing (CORS). */
  10378. cors1 = "Access-Control-Allow-Origin: ";
  10379. cors2 = cors_orig_cfg;
  10380. cors3 = "\r\n";
  10381. } else {
  10382. cors1 = cors2 = cors3 = "";
  10383. }
  10384. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10385. /* File exists (precondition for calling this function),
  10386. * but can not be opened by the server. */
  10387. mg_send_http_error(conn,
  10388. 500,
  10389. "Error: Cannot read file\nfopen(%s): %s",
  10390. path,
  10391. strerror(ERRNO));
  10392. } else {
  10393. conn->must_close = 1;
  10394. gmt_time_string(date, sizeof(date), &curtime);
  10395. fclose_on_exec(&filep->access, conn);
  10396. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10397. send_no_cache_header(conn);
  10398. send_additional_header(conn);
  10399. mg_printf(conn,
  10400. "%s%s%s"
  10401. "Date: %s\r\n"
  10402. "Content-Type: text/html\r\n"
  10403. "Connection: %s\r\n\r\n",
  10404. cors1,
  10405. cors2,
  10406. cors3,
  10407. date,
  10408. suggest_connection_header(conn));
  10409. send_ssi_file(conn, path, filep, 0);
  10410. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10411. }
  10412. }
  10413. #endif /* NO_FILESYSTEMS */
  10414. #if !defined(NO_FILES)
  10415. static void
  10416. send_options(struct mg_connection *conn)
  10417. {
  10418. char date[64];
  10419. time_t curtime = time(NULL);
  10420. if (!conn) {
  10421. return;
  10422. }
  10423. conn->status_code = 200;
  10424. conn->must_close = 1;
  10425. gmt_time_string(date, sizeof(date), &curtime);
  10426. /* We do not set a "Cache-Control" header here, but leave the default.
  10427. * Since browsers do not send an OPTIONS request, we can not test the
  10428. * effect anyway. */
  10429. mg_printf(conn,
  10430. "HTTP/1.1 200 OK\r\n"
  10431. "Date: %s\r\n"
  10432. "Connection: %s\r\n"
  10433. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10434. "PROPFIND, MKCOL\r\n"
  10435. "DAV: 1\r\n",
  10436. date,
  10437. suggest_connection_header(conn));
  10438. send_additional_header(conn);
  10439. mg_printf(conn, "\r\n");
  10440. }
  10441. /* Writes PROPFIND properties for a collection element */
  10442. static int
  10443. print_props(struct mg_connection *conn,
  10444. const char *uri,
  10445. const char *name,
  10446. struct mg_file_stat *filep)
  10447. {
  10448. size_t href_size, i, j;
  10449. int len;
  10450. char *href, mtime[64];
  10451. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10452. return 0;
  10453. }
  10454. /* Estimate worst case size for encoding */
  10455. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10456. href = (char *)mg_malloc(href_size);
  10457. if (href == NULL) {
  10458. return 0;
  10459. }
  10460. len = mg_url_encode(uri, href, href_size);
  10461. if (len >= 0) {
  10462. /* Append an extra string */
  10463. mg_url_encode(name, href + len, href_size - (size_t)len);
  10464. }
  10465. /* Directory separator should be preserved. */
  10466. for (i = j = 0; href[i]; j++) {
  10467. if (!strncmp(href + i, "%2f", 3)) {
  10468. href[j] = '/';
  10469. i += 3;
  10470. } else {
  10471. href[j] = href[i++];
  10472. }
  10473. }
  10474. href[j] = '\0';
  10475. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10476. mg_printf(conn,
  10477. "<d:response>"
  10478. "<d:href>%s</d:href>"
  10479. "<d:propstat>"
  10480. "<d:prop>"
  10481. "<d:resourcetype>%s</d:resourcetype>"
  10482. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10483. "<d:getlastmodified>%s</d:getlastmodified>"
  10484. "</d:prop>"
  10485. "<d:status>HTTP/1.1 200 OK</d:status>"
  10486. "</d:propstat>"
  10487. "</d:response>\n",
  10488. href,
  10489. filep->is_directory ? "<d:collection/>" : "",
  10490. filep->size,
  10491. mtime);
  10492. mg_free(href);
  10493. return 1;
  10494. }
  10495. static int
  10496. print_dav_dir_entry(struct de *de, void *data)
  10497. {
  10498. struct mg_connection *conn = (struct mg_connection *)data;
  10499. if (!de || !conn
  10500. || !print_props(
  10501. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10502. return -1;
  10503. }
  10504. return 0;
  10505. }
  10506. static void
  10507. handle_propfind(struct mg_connection *conn,
  10508. const char *path,
  10509. struct mg_file_stat *filep)
  10510. {
  10511. const char *depth = mg_get_header(conn, "Depth");
  10512. char date[64];
  10513. time_t curtime = time(NULL);
  10514. gmt_time_string(date, sizeof(date), &curtime);
  10515. if (!conn || !path || !filep || !conn->dom_ctx) {
  10516. return;
  10517. }
  10518. conn->must_close = 1;
  10519. conn->status_code = 207;
  10520. mg_printf(conn,
  10521. "HTTP/1.1 207 Multi-Status\r\n"
  10522. "Date: %s\r\n",
  10523. date);
  10524. send_static_cache_header(conn);
  10525. send_additional_header(conn);
  10526. mg_printf(conn,
  10527. "Connection: %s\r\n"
  10528. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10529. suggest_connection_header(conn));
  10530. mg_printf(conn,
  10531. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10532. "<d:multistatus xmlns:d='DAV:'>\n");
  10533. /* Print properties for the requested resource itself */
  10534. print_props(conn, conn->request_info.local_uri, "", filep);
  10535. /* If it is a directory, print directory entries too if Depth is not 0
  10536. */
  10537. if (filep->is_directory
  10538. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10539. "yes")
  10540. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10541. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10542. }
  10543. mg_printf(conn, "%s\n", "</d:multistatus>");
  10544. }
  10545. #endif
  10546. void
  10547. mg_lock_connection(struct mg_connection *conn)
  10548. {
  10549. if (conn) {
  10550. (void)pthread_mutex_lock(&conn->mutex);
  10551. }
  10552. }
  10553. void
  10554. mg_unlock_connection(struct mg_connection *conn)
  10555. {
  10556. if (conn) {
  10557. (void)pthread_mutex_unlock(&conn->mutex);
  10558. }
  10559. }
  10560. void
  10561. mg_lock_context(struct mg_context *ctx)
  10562. {
  10563. if (ctx) {
  10564. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10565. }
  10566. }
  10567. void
  10568. mg_unlock_context(struct mg_context *ctx)
  10569. {
  10570. if (ctx) {
  10571. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10572. }
  10573. }
  10574. #if defined(USE_LUA)
  10575. #include "mod_lua.inl"
  10576. #endif /* USE_LUA */
  10577. #if defined(USE_DUKTAPE)
  10578. #include "mod_duktape.inl"
  10579. #endif /* USE_DUKTAPE */
  10580. #if defined(USE_WEBSOCKET)
  10581. #if !defined(NO_SSL_DL)
  10582. #define SHA_API static
  10583. #include "sha1.inl"
  10584. #endif
  10585. static int
  10586. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10587. {
  10588. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10589. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10590. SHA_CTX sha_ctx;
  10591. int truncated;
  10592. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10593. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10594. if (truncated) {
  10595. conn->must_close = 1;
  10596. return 0;
  10597. }
  10598. DEBUG_TRACE("%s", "Send websocket handshake");
  10599. SHA1_Init(&sha_ctx);
  10600. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10601. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10602. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10603. mg_printf(conn,
  10604. "HTTP/1.1 101 Switching Protocols\r\n"
  10605. "Upgrade: websocket\r\n"
  10606. "Connection: Upgrade\r\n"
  10607. "Sec-WebSocket-Accept: %s\r\n",
  10608. b64_sha);
  10609. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10610. mg_printf(conn,
  10611. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10612. conn->request_info.acceptedWebSocketSubprotocol);
  10613. } else {
  10614. mg_printf(conn, "%s", "\r\n");
  10615. }
  10616. return 1;
  10617. }
  10618. #if !defined(MG_MAX_UNANSWERED_PING)
  10619. /* Configuration of the maximum number of websocket PINGs that might
  10620. * stay unanswered before the connection is considered broken.
  10621. * Note: The name of this define may still change (until it is
  10622. * defined as a compile parameter in a documentation).
  10623. */
  10624. #define MG_MAX_UNANSWERED_PING (5)
  10625. #endif
  10626. static void
  10627. read_websocket(struct mg_connection *conn,
  10628. mg_websocket_data_handler ws_data_handler,
  10629. void *callback_data)
  10630. {
  10631. /* Pointer to the beginning of the portion of the incoming websocket
  10632. * message queue.
  10633. * The original websocket upgrade request is never removed, so the queue
  10634. * begins after it. */
  10635. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10636. int n, error, exit_by_callback;
  10637. int ret;
  10638. /* body_len is the length of the entire queue in bytes
  10639. * len is the length of the current message
  10640. * data_len is the length of the current message's data payload
  10641. * header_len is the length of the current message's header */
  10642. size_t i, len, mask_len = 0, header_len, body_len;
  10643. uint64_t data_len = 0;
  10644. /* "The masking key is a 32-bit value chosen at random by the client."
  10645. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10646. */
  10647. unsigned char mask[4];
  10648. /* data points to the place where the message is stored when passed to
  10649. * the websocket_data callback. This is either mem on the stack, or a
  10650. * dynamically allocated buffer if it is too large. */
  10651. unsigned char mem[4096];
  10652. unsigned char mop; /* mask flag and opcode */
  10653. /* Variables used for connection monitoring */
  10654. double timeout = -1.0;
  10655. int enable_ping_pong = 0;
  10656. int ping_count = 0;
  10657. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10658. enable_ping_pong =
  10659. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10660. "yes");
  10661. }
  10662. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10663. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10664. }
  10665. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10666. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10667. }
  10668. /* Enter data processing loop */
  10669. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10670. conn->request_info.remote_addr,
  10671. conn->request_info.remote_port);
  10672. conn->in_websocket_handling = 1;
  10673. mg_set_thread_name("wsock");
  10674. /* Loop continuously, reading messages from the socket, invoking the
  10675. * callback, and waiting repeatedly until an error occurs. */
  10676. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10677. header_len = 0;
  10678. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10679. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10680. len = buf[1] & 127;
  10681. mask_len = (buf[1] & 128) ? 4 : 0;
  10682. if ((len < 126) && (body_len >= mask_len)) {
  10683. /* inline 7-bit length field */
  10684. data_len = len;
  10685. header_len = 2 + mask_len;
  10686. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10687. /* 16-bit length field */
  10688. header_len = 4 + mask_len;
  10689. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10690. } else if (body_len >= (10 + mask_len)) {
  10691. /* 64-bit length field */
  10692. uint32_t l1, l2;
  10693. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10694. memcpy(&l2, &buf[6], 4);
  10695. header_len = 10 + mask_len;
  10696. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10697. if (data_len > (uint64_t)0x7FFF0000ul) {
  10698. /* no can do */
  10699. mg_cry_internal(
  10700. conn,
  10701. "%s",
  10702. "websocket out of memory; closing connection");
  10703. break;
  10704. }
  10705. }
  10706. }
  10707. if ((header_len > 0) && (body_len >= header_len)) {
  10708. /* Allocate space to hold websocket payload */
  10709. unsigned char *data = mem;
  10710. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10711. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10712. conn->phys_ctx);
  10713. if (data == NULL) {
  10714. /* Allocation failed, exit the loop and then close the
  10715. * connection */
  10716. mg_cry_internal(
  10717. conn,
  10718. "%s",
  10719. "websocket out of memory; closing connection");
  10720. break;
  10721. }
  10722. }
  10723. /* Copy the mask before we shift the queue and destroy it */
  10724. if (mask_len > 0) {
  10725. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10726. } else {
  10727. memset(mask, 0, sizeof(mask));
  10728. }
  10729. /* Read frame payload from the first message in the queue into
  10730. * data and advance the queue by moving the memory in place. */
  10731. DEBUG_ASSERT(body_len >= header_len);
  10732. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10733. mop = buf[0]; /* current mask and opcode */
  10734. /* Overflow case */
  10735. len = body_len - header_len;
  10736. memcpy(data, buf + header_len, len);
  10737. error = 0;
  10738. while ((uint64_t)len < data_len) {
  10739. n = pull_inner(NULL,
  10740. conn,
  10741. (char *)(data + len),
  10742. (int)(data_len - len),
  10743. timeout);
  10744. if (n <= -2) {
  10745. error = 1;
  10746. break;
  10747. } else if (n > 0) {
  10748. len += (size_t)n;
  10749. } else {
  10750. /* Timeout: should retry */
  10751. /* TODO: retry condition */
  10752. }
  10753. }
  10754. if (error) {
  10755. mg_cry_internal(
  10756. conn,
  10757. "%s",
  10758. "Websocket pull failed; closing connection");
  10759. if (data != mem) {
  10760. mg_free(data);
  10761. }
  10762. break;
  10763. }
  10764. conn->data_len = conn->request_len;
  10765. } else {
  10766. mop = buf[0]; /* current mask and opcode, overwritten by
  10767. * memmove() */
  10768. /* Length of the message being read at the front of the
  10769. * queue. Cast to 31 bit is OK, since we limited
  10770. * data_len before. */
  10771. len = (size_t)data_len + header_len;
  10772. /* Copy the data payload into the data pointer for the
  10773. * callback. Cast to 31 bit is OK, since we
  10774. * limited data_len */
  10775. memcpy(data, buf + header_len, (size_t)data_len);
  10776. /* Move the queue forward len bytes */
  10777. memmove(buf, buf + len, body_len - len);
  10778. /* Mark the queue as advanced */
  10779. conn->data_len -= (int)len;
  10780. }
  10781. /* Apply mask if necessary */
  10782. if (mask_len > 0) {
  10783. for (i = 0; i < (size_t)data_len; i++) {
  10784. data[i] ^= mask[i & 3];
  10785. }
  10786. }
  10787. exit_by_callback = 0;
  10788. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10789. /* filter PONG messages */
  10790. DEBUG_TRACE("PONG from %s:%u",
  10791. conn->request_info.remote_addr,
  10792. conn->request_info.remote_port);
  10793. /* No unanwered PINGs left */
  10794. ping_count = 0;
  10795. } else if (enable_ping_pong
  10796. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10797. /* reply PING messages */
  10798. DEBUG_TRACE("Reply PING from %s:%u",
  10799. conn->request_info.remote_addr,
  10800. conn->request_info.remote_port);
  10801. ret = mg_websocket_write(conn,
  10802. MG_WEBSOCKET_OPCODE_PONG,
  10803. (char *)data,
  10804. (size_t)data_len);
  10805. if (ret <= 0) {
  10806. /* Error: send failed */
  10807. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10808. break;
  10809. }
  10810. } else {
  10811. /* Exit the loop if callback signals to exit (server side),
  10812. * or "connection close" opcode received (client side). */
  10813. if ((ws_data_handler != NULL)
  10814. && !ws_data_handler(conn,
  10815. mop,
  10816. (char *)data,
  10817. (size_t)data_len,
  10818. callback_data)) {
  10819. exit_by_callback = 1;
  10820. }
  10821. }
  10822. /* It a buffer has been allocated, free it again */
  10823. if (data != mem) {
  10824. mg_free(data);
  10825. }
  10826. if (exit_by_callback) {
  10827. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10828. conn->request_info.remote_addr,
  10829. conn->request_info.remote_port);
  10830. break;
  10831. }
  10832. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10833. /* Opcode == 8, connection close */
  10834. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10835. conn->request_info.remote_addr,
  10836. conn->request_info.remote_port);
  10837. break;
  10838. }
  10839. /* Not breaking the loop, process next websocket frame. */
  10840. } else {
  10841. /* Read from the socket into the next available location in the
  10842. * message queue. */
  10843. n = pull_inner(NULL,
  10844. conn,
  10845. conn->buf + conn->data_len,
  10846. conn->buf_size - conn->data_len,
  10847. timeout);
  10848. if (n <= -2) {
  10849. /* Error, no bytes read */
  10850. DEBUG_TRACE("PULL from %s:%u failed",
  10851. conn->request_info.remote_addr,
  10852. conn->request_info.remote_port);
  10853. break;
  10854. }
  10855. if (n > 0) {
  10856. conn->data_len += n;
  10857. /* Reset open PING count */
  10858. ping_count = 0;
  10859. } else {
  10860. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10861. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10862. /* Stop sending PING */
  10863. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10864. "- closing connection",
  10865. ping_count,
  10866. conn->request_info.remote_addr,
  10867. conn->request_info.remote_port);
  10868. break;
  10869. }
  10870. if (enable_ping_pong) {
  10871. /* Send Websocket PING message */
  10872. DEBUG_TRACE("PING to %s:%u",
  10873. conn->request_info.remote_addr,
  10874. conn->request_info.remote_port);
  10875. ret = mg_websocket_write(conn,
  10876. MG_WEBSOCKET_OPCODE_PING,
  10877. NULL,
  10878. 0);
  10879. if (ret <= 0) {
  10880. /* Error: send failed */
  10881. DEBUG_TRACE("Send PING failed (%i)", ret);
  10882. break;
  10883. }
  10884. ping_count++;
  10885. }
  10886. }
  10887. /* Timeout: should retry */
  10888. /* TODO: get timeout def */
  10889. }
  10890. }
  10891. }
  10892. /* Leave data processing loop */
  10893. mg_set_thread_name("worker");
  10894. conn->in_websocket_handling = 0;
  10895. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10896. conn->request_info.remote_addr,
  10897. conn->request_info.remote_port);
  10898. }
  10899. static int
  10900. mg_websocket_write_exec(struct mg_connection *conn,
  10901. int opcode,
  10902. const char *data,
  10903. size_t dataLen,
  10904. uint32_t masking_key)
  10905. {
  10906. unsigned char header[14];
  10907. size_t headerLen;
  10908. int retval;
  10909. #if defined(GCC_DIAGNOSTIC)
  10910. /* Disable spurious conversion warning for GCC */
  10911. #pragma GCC diagnostic push
  10912. #pragma GCC diagnostic ignored "-Wconversion"
  10913. #endif
  10914. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10915. #if defined(GCC_DIAGNOSTIC)
  10916. #pragma GCC diagnostic pop
  10917. #endif
  10918. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10919. if (dataLen < 126) {
  10920. /* inline 7-bit length field */
  10921. header[1] = (unsigned char)dataLen;
  10922. headerLen = 2;
  10923. } else if (dataLen <= 0xFFFF) {
  10924. /* 16-bit length field */
  10925. uint16_t len = htons((uint16_t)dataLen);
  10926. header[1] = 126;
  10927. memcpy(header + 2, &len, 2);
  10928. headerLen = 4;
  10929. } else {
  10930. /* 64-bit length field */
  10931. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10932. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10933. header[1] = 127;
  10934. memcpy(header + 2, &len1, 4);
  10935. memcpy(header + 6, &len2, 4);
  10936. headerLen = 10;
  10937. }
  10938. if (masking_key) {
  10939. /* add mask */
  10940. header[1] |= 0x80;
  10941. memcpy(header + headerLen, &masking_key, 4);
  10942. headerLen += 4;
  10943. }
  10944. /* Note that POSIX/Winsock's send() is threadsafe
  10945. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10946. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10947. * push(), although that is only a problem if the packet is large or
  10948. * outgoing buffer is full). */
  10949. /* TODO: Check if this lock should be moved to user land.
  10950. * Currently the server sets this lock for websockets, but
  10951. * not for any other connection. It must be set for every
  10952. * conn read/written by more than one thread, no matter if
  10953. * it is a websocket or regular connection. */
  10954. (void)mg_lock_connection(conn);
  10955. retval = mg_write(conn, header, headerLen);
  10956. if (retval != (int)headerLen) {
  10957. /* Did not send complete header */
  10958. retval = -1;
  10959. } else {
  10960. if (dataLen > 0) {
  10961. retval = mg_write(conn, data, dataLen);
  10962. }
  10963. /* if dataLen == 0, the header length (2) is returned */
  10964. }
  10965. /* TODO: Remove this unlock as well, when lock is removed. */
  10966. mg_unlock_connection(conn);
  10967. return retval;
  10968. }
  10969. int
  10970. mg_websocket_write(struct mg_connection *conn,
  10971. int opcode,
  10972. const char *data,
  10973. size_t dataLen)
  10974. {
  10975. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10976. }
  10977. static void
  10978. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10979. {
  10980. size_t i = 0;
  10981. i = 0;
  10982. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10983. /* Convert in 32 bit words, if data is 4 byte aligned */
  10984. while (i < (in_len - 3)) {
  10985. *(uint32_t *)(void *)(out + i) =
  10986. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10987. i += 4;
  10988. }
  10989. }
  10990. if (i != in_len) {
  10991. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10992. while (i < in_len) {
  10993. *(uint8_t *)(void *)(out + i) =
  10994. *(uint8_t *)(void *)(in + i)
  10995. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10996. i++;
  10997. }
  10998. }
  10999. }
  11000. int
  11001. mg_websocket_client_write(struct mg_connection *conn,
  11002. int opcode,
  11003. const char *data,
  11004. size_t dataLen)
  11005. {
  11006. int retval = -1;
  11007. char *masked_data =
  11008. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11009. uint32_t masking_key = 0;
  11010. if (masked_data == NULL) {
  11011. /* Return -1 in an error case */
  11012. mg_cry_internal(conn,
  11013. "%s",
  11014. "Cannot allocate buffer for masked websocket response: "
  11015. "Out of memory");
  11016. return -1;
  11017. }
  11018. do {
  11019. /* Get a masking key - but not 0 */
  11020. masking_key = (uint32_t)get_random();
  11021. } while (masking_key == 0);
  11022. mask_data(data, dataLen, masking_key, masked_data);
  11023. retval = mg_websocket_write_exec(
  11024. conn, opcode, masked_data, dataLen, masking_key);
  11025. mg_free(masked_data);
  11026. return retval;
  11027. }
  11028. static void
  11029. handle_websocket_request(struct mg_connection *conn,
  11030. const char *path,
  11031. int is_callback_resource,
  11032. struct mg_websocket_subprotocols *subprotocols,
  11033. mg_websocket_connect_handler ws_connect_handler,
  11034. mg_websocket_ready_handler ws_ready_handler,
  11035. mg_websocket_data_handler ws_data_handler,
  11036. mg_websocket_close_handler ws_close_handler,
  11037. void *cbData)
  11038. {
  11039. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11040. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11041. ptrdiff_t lua_websock = 0;
  11042. #if !defined(USE_LUA)
  11043. (void)path;
  11044. #endif
  11045. /* Step 1: Check websocket protocol version. */
  11046. /* Step 1.1: Check Sec-WebSocket-Key. */
  11047. if (!websock_key) {
  11048. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11049. * requires a Sec-WebSocket-Key header.
  11050. */
  11051. /* It could be the hixie draft version
  11052. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11053. */
  11054. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11055. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11056. char key3[8];
  11057. if ((key1 != NULL) && (key2 != NULL)) {
  11058. /* This version uses 8 byte body data in a GET request */
  11059. conn->content_len = 8;
  11060. if (8 == mg_read(conn, key3, 8)) {
  11061. /* This is the hixie version */
  11062. mg_send_http_error(conn,
  11063. 426,
  11064. "%s",
  11065. "Protocol upgrade to RFC 6455 required");
  11066. return;
  11067. }
  11068. }
  11069. /* This is an unknown version */
  11070. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11071. return;
  11072. }
  11073. /* Step 1.2: Check websocket protocol version. */
  11074. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11075. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11076. /* Reject wrong versions */
  11077. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11078. return;
  11079. }
  11080. /* Step 1.3: Could check for "Host", but we do not really nead this
  11081. * value for anything, so just ignore it. */
  11082. /* Step 2: If a callback is responsible, call it. */
  11083. if (is_callback_resource) {
  11084. /* Step 2.1 check and select subprotocol */
  11085. const char *protocols[64]; // max 64 headers
  11086. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11087. "Sec-WebSocket-Protocol",
  11088. protocols,
  11089. 64);
  11090. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11091. int cnt = 0;
  11092. int idx;
  11093. unsigned long len;
  11094. const char *sep, *curSubProtocol,
  11095. *acceptedWebSocketSubprotocol = NULL;
  11096. /* look for matching subprotocol */
  11097. do {
  11098. const char *protocol = protocols[cnt];
  11099. do {
  11100. sep = strchr(protocol, ',');
  11101. curSubProtocol = protocol;
  11102. len = sep ? (unsigned long)(sep - protocol)
  11103. : (unsigned long)strlen(protocol);
  11104. while (sep && isspace((unsigned char)*++sep))
  11105. ; // ignore leading whitespaces
  11106. protocol = sep;
  11107. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11108. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11109. && (strncmp(curSubProtocol,
  11110. subprotocols->subprotocols[idx],
  11111. len)
  11112. == 0)) {
  11113. acceptedWebSocketSubprotocol =
  11114. subprotocols->subprotocols[idx];
  11115. break;
  11116. }
  11117. }
  11118. } while (sep && !acceptedWebSocketSubprotocol);
  11119. } while (++cnt < nbSubprotocolHeader
  11120. && !acceptedWebSocketSubprotocol);
  11121. conn->request_info.acceptedWebSocketSubprotocol =
  11122. acceptedWebSocketSubprotocol;
  11123. } else if (nbSubprotocolHeader > 0) {
  11124. /* keep legacy behavior */
  11125. const char *protocol = protocols[0];
  11126. /* The protocol is a comma separated list of names. */
  11127. /* The server must only return one value from this list. */
  11128. /* First check if it is a list or just a single value. */
  11129. const char *sep = strrchr(protocol, ',');
  11130. if (sep == NULL) {
  11131. /* Just a single protocol -> accept it. */
  11132. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11133. } else {
  11134. /* Multiple protocols -> accept the last one. */
  11135. /* This is just a quick fix if the client offers multiple
  11136. * protocols. The handler should have a list of accepted
  11137. * protocols on his own
  11138. * and use it to select one protocol among those the client
  11139. * has
  11140. * offered.
  11141. */
  11142. while (isspace((unsigned char)*++sep)) {
  11143. ; /* ignore leading whitespaces */
  11144. }
  11145. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11146. }
  11147. }
  11148. if ((ws_connect_handler != NULL)
  11149. && (ws_connect_handler(conn, cbData) != 0)) {
  11150. /* C callback has returned non-zero, do not proceed with
  11151. * handshake.
  11152. */
  11153. /* Note that C callbacks are no longer called when Lua is
  11154. * responsible, so C can no longer filter callbacks for Lua. */
  11155. return;
  11156. }
  11157. }
  11158. #if defined(USE_LUA)
  11159. /* Step 3: No callback. Check if Lua is responsible. */
  11160. else {
  11161. /* Step 3.1: Check if Lua is responsible. */
  11162. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11163. lua_websock = match_prefix(
  11164. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11165. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11166. path);
  11167. }
  11168. if (lua_websock) {
  11169. /* Step 3.2: Lua is responsible: call it. */
  11170. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11171. if (!conn->lua_websocket_state) {
  11172. /* Lua rejected the new client */
  11173. return;
  11174. }
  11175. }
  11176. }
  11177. #endif
  11178. /* Step 4: Check if there is a responsible websocket handler. */
  11179. if (!is_callback_resource && !lua_websock) {
  11180. /* There is no callback, and Lua is not responsible either. */
  11181. /* Reply with a 404 Not Found. We are still at a standard
  11182. * HTTP request here, before the websocket handshake, so
  11183. * we can still send standard HTTP error replies. */
  11184. mg_send_http_error(conn, 404, "%s", "Not found");
  11185. return;
  11186. }
  11187. /* Step 5: The websocket connection has been accepted */
  11188. if (!send_websocket_handshake(conn, websock_key)) {
  11189. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11190. return;
  11191. }
  11192. /* Step 6: Call the ready handler */
  11193. if (is_callback_resource) {
  11194. if (ws_ready_handler != NULL) {
  11195. ws_ready_handler(conn, cbData);
  11196. }
  11197. #if defined(USE_LUA)
  11198. } else if (lua_websock) {
  11199. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11200. /* the ready handler returned false */
  11201. return;
  11202. }
  11203. #endif
  11204. }
  11205. /* Step 7: Enter the read loop */
  11206. if (is_callback_resource) {
  11207. read_websocket(conn, ws_data_handler, cbData);
  11208. #if defined(USE_LUA)
  11209. } else if (lua_websock) {
  11210. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11211. #endif
  11212. }
  11213. /* Step 8: Call the close handler */
  11214. if (ws_close_handler) {
  11215. ws_close_handler(conn, cbData);
  11216. }
  11217. }
  11218. static int
  11219. is_websocket_protocol(const struct mg_connection *conn)
  11220. {
  11221. const char *upgrade, *connection;
  11222. /* A websocket protocoll has the following HTTP headers:
  11223. *
  11224. * Connection: Upgrade
  11225. * Upgrade: Websocket
  11226. */
  11227. upgrade = mg_get_header(conn, "Upgrade");
  11228. if (upgrade == NULL) {
  11229. return 0; /* fail early, don't waste time checking other header
  11230. * fields
  11231. */
  11232. }
  11233. DEBUG_TRACE("Upgrade: %s", upgrade);
  11234. if (!mg_strcasestr(upgrade, "websocket")) {
  11235. return 0;
  11236. }
  11237. connection = mg_get_header(conn, "Connection");
  11238. if (connection == NULL) {
  11239. return 0;
  11240. }
  11241. if (!mg_strcasestr(connection, "upgrade")) {
  11242. return 0;
  11243. }
  11244. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11245. * "Sec-WebSocket-Version" are also required.
  11246. * Don't check them here, since even an unsupported websocket protocol
  11247. * request still IS a websocket request (in contrast to a standard HTTP
  11248. * request). It will fail later in handle_websocket_request.
  11249. */
  11250. return 1;
  11251. }
  11252. #endif /* !USE_WEBSOCKET */
  11253. static int
  11254. isbyte(int n)
  11255. {
  11256. return (n >= 0) && (n <= 255);
  11257. }
  11258. static int
  11259. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11260. {
  11261. int n, a, b, c, d, slash = 32, len = 0;
  11262. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11263. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11264. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11265. && (slash < 33)) {
  11266. len = n;
  11267. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11268. | (uint32_t)d;
  11269. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11270. }
  11271. return len;
  11272. }
  11273. static int
  11274. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11275. {
  11276. int throttle = 0;
  11277. struct vec vec, val;
  11278. uint32_t net, mask;
  11279. char mult;
  11280. double v;
  11281. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11282. mult = ',';
  11283. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11284. || (v < 0)
  11285. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11286. && (mult != ','))) {
  11287. continue;
  11288. }
  11289. v *= (lowercase(&mult) == 'k')
  11290. ? 1024
  11291. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11292. if (vec.len == 1 && vec.ptr[0] == '*') {
  11293. throttle = (int)v;
  11294. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11295. if ((remote_ip & mask) == net) {
  11296. throttle = (int)v;
  11297. }
  11298. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11299. throttle = (int)v;
  11300. }
  11301. }
  11302. return throttle;
  11303. }
  11304. static uint32_t
  11305. get_remote_ip(const struct mg_connection *conn)
  11306. {
  11307. if (!conn) {
  11308. return 0;
  11309. }
  11310. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11311. }
  11312. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11313. #include "handle_form.inl"
  11314. #if defined(MG_LEGACY_INTERFACE)
  11315. /* Implement the deprecated mg_upload function by calling the new
  11316. * mg_handle_form_request function. While mg_upload could only handle
  11317. * HTML forms sent as POST request in multipart/form-data format
  11318. * containing only file input elements, mg_handle_form_request can
  11319. * handle all form input elements and all standard request methods. */
  11320. struct mg_upload_user_data {
  11321. struct mg_connection *conn;
  11322. const char *destination_dir;
  11323. int num_uploaded_files;
  11324. };
  11325. /* Helper function for deprecated mg_upload. */
  11326. static int
  11327. mg_upload_field_found(const char *key,
  11328. const char *filename,
  11329. char *path,
  11330. size_t pathlen,
  11331. void *user_data)
  11332. {
  11333. int truncated = 0;
  11334. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11335. (void)key;
  11336. if (!filename) {
  11337. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11338. return FORM_FIELD_STORAGE_ABORT;
  11339. }
  11340. mg_snprintf(fud->conn,
  11341. &truncated,
  11342. path,
  11343. pathlen - 1,
  11344. "%s/%s",
  11345. fud->destination_dir,
  11346. filename);
  11347. if (truncated) {
  11348. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11349. return FORM_FIELD_STORAGE_ABORT;
  11350. }
  11351. return FORM_FIELD_STORAGE_STORE;
  11352. }
  11353. /* Helper function for deprecated mg_upload. */
  11354. static int
  11355. mg_upload_field_get(const char *key,
  11356. const char *value,
  11357. size_t value_size,
  11358. void *user_data)
  11359. {
  11360. /* Function should never be called */
  11361. (void)key;
  11362. (void)value;
  11363. (void)value_size;
  11364. (void)user_data;
  11365. return 0;
  11366. }
  11367. /* Helper function for deprecated mg_upload. */
  11368. static int
  11369. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11370. {
  11371. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11372. (void)file_size;
  11373. fud->num_uploaded_files++;
  11374. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11375. return 0;
  11376. }
  11377. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11378. int
  11379. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11380. {
  11381. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11382. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11383. mg_upload_field_get,
  11384. mg_upload_field_stored,
  11385. 0};
  11386. int ret;
  11387. fdh.user_data = (void *)&fud;
  11388. ret = mg_handle_form_request(conn, &fdh);
  11389. if (ret < 0) {
  11390. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11391. }
  11392. return fud.num_uploaded_files;
  11393. }
  11394. #endif
  11395. static int
  11396. get_first_ssl_listener_index(const struct mg_context *ctx)
  11397. {
  11398. unsigned int i;
  11399. int idx = -1;
  11400. if (ctx) {
  11401. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11402. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11403. }
  11404. }
  11405. return idx;
  11406. }
  11407. /* Return host (without port) */
  11408. /* Use mg_free to free the result */
  11409. static const char *
  11410. alloc_get_host(struct mg_connection *conn)
  11411. {
  11412. char buf[1025];
  11413. size_t buflen = sizeof(buf);
  11414. const char *host_header = get_header(conn->request_info.http_headers,
  11415. conn->request_info.num_headers,
  11416. "Host");
  11417. char *host;
  11418. if (host_header != NULL) {
  11419. char *pos;
  11420. /* Create a local copy of the "Host" header, since it might be
  11421. * modified here. */
  11422. mg_strlcpy(buf, host_header, buflen);
  11423. buf[buflen - 1] = '\0';
  11424. host = buf;
  11425. while (isspace((unsigned char)*host)) {
  11426. host++;
  11427. }
  11428. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11429. * is found. */
  11430. if (*host == '[') {
  11431. pos = strchr(host, ']');
  11432. if (!pos) {
  11433. /* Malformed hostname starts with '[', but no ']' found */
  11434. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11435. return NULL;
  11436. }
  11437. /* terminate after ']' */
  11438. pos[1] = 0;
  11439. } else {
  11440. /* Otherwise, a ':' separates hostname and port number */
  11441. pos = strchr(host, ':');
  11442. if (pos != NULL) {
  11443. *pos = '\0';
  11444. }
  11445. }
  11446. if (conn->ssl) {
  11447. /* This is a HTTPS connection, maybe we have a hostname
  11448. * from SNI (set in ssl_servername_callback). */
  11449. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11450. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11451. /* We are not using the default domain */
  11452. if (mg_strcasecmp(host, sslhost)) {
  11453. /* Mismatch between SNI domain and HTTP domain */
  11454. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11455. sslhost,
  11456. host);
  11457. return NULL;
  11458. }
  11459. }
  11460. DEBUG_TRACE("HTTPS Host: %s", host);
  11461. } else {
  11462. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11463. while (dom) {
  11464. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11465. /* Found matching domain */
  11466. DEBUG_TRACE("HTTP domain %s found",
  11467. dom->config[AUTHENTICATION_DOMAIN]);
  11468. /* TODO: Check if this is a HTTP or HTTPS domain */
  11469. conn->dom_ctx = dom;
  11470. break;
  11471. }
  11472. dom = dom->next;
  11473. }
  11474. DEBUG_TRACE("HTTP Host: %s", host);
  11475. }
  11476. } else {
  11477. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11478. host = buf;
  11479. DEBUG_TRACE("IP: %s", host);
  11480. }
  11481. return mg_strdup_ctx(host, conn->phys_ctx);
  11482. }
  11483. static void
  11484. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11485. {
  11486. char target_url[MG_BUF_LEN];
  11487. int truncated = 0;
  11488. conn->must_close = 1;
  11489. /* Send host, port, uri and (if it exists) ?query_string */
  11490. if (conn->host) {
  11491. /* Use "308 Permanent Redirect" */
  11492. int redirect_code = 308;
  11493. /* Create target URL */
  11494. mg_snprintf(
  11495. conn,
  11496. &truncated,
  11497. target_url,
  11498. sizeof(target_url),
  11499. "https://%s:%d%s%s%s",
  11500. conn->host,
  11501. #if defined(USE_IPV6)
  11502. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11503. == AF_INET6)
  11504. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11505. .lsa.sin6.sin6_port)
  11506. :
  11507. #endif
  11508. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11509. .lsa.sin.sin_port),
  11510. conn->request_info.local_uri,
  11511. (conn->request_info.query_string == NULL) ? "" : "?",
  11512. (conn->request_info.query_string == NULL)
  11513. ? ""
  11514. : conn->request_info.query_string);
  11515. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11516. * is used as buffer size) */
  11517. if (truncated) {
  11518. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11519. return;
  11520. }
  11521. /* Use redirect helper function */
  11522. mg_send_http_redirect(conn, target_url, redirect_code);
  11523. }
  11524. }
  11525. static void
  11526. handler_info_acquire(struct mg_handler_info *handler_info)
  11527. {
  11528. pthread_mutex_lock(&handler_info->refcount_mutex);
  11529. handler_info->refcount++;
  11530. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11531. }
  11532. static void
  11533. handler_info_release(struct mg_handler_info *handler_info)
  11534. {
  11535. pthread_mutex_lock(&handler_info->refcount_mutex);
  11536. handler_info->refcount--;
  11537. pthread_cond_signal(&handler_info->refcount_cond);
  11538. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11539. }
  11540. static void
  11541. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11542. {
  11543. pthread_mutex_lock(&handler_info->refcount_mutex);
  11544. while (handler_info->refcount) {
  11545. pthread_cond_wait(&handler_info->refcount_cond,
  11546. &handler_info->refcount_mutex);
  11547. }
  11548. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11549. }
  11550. static void
  11551. mg_set_handler_type(struct mg_context *phys_ctx,
  11552. struct mg_domain_context *dom_ctx,
  11553. const char *uri,
  11554. int handler_type,
  11555. int is_delete_request,
  11556. mg_request_handler handler,
  11557. struct mg_websocket_subprotocols *subprotocols,
  11558. mg_websocket_connect_handler connect_handler,
  11559. mg_websocket_ready_handler ready_handler,
  11560. mg_websocket_data_handler data_handler,
  11561. mg_websocket_close_handler close_handler,
  11562. mg_authorization_handler auth_handler,
  11563. void *cbdata)
  11564. {
  11565. struct mg_handler_info *tmp_rh, **lastref;
  11566. size_t urilen = strlen(uri);
  11567. struct mg_workerTLS tls;
  11568. int is_tls_set = 0;
  11569. if (handler_type == WEBSOCKET_HANDLER) {
  11570. DEBUG_ASSERT(handler == NULL);
  11571. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11572. || ready_handler != NULL || data_handler != NULL
  11573. || close_handler != NULL);
  11574. DEBUG_ASSERT(auth_handler == NULL);
  11575. if (handler != NULL) {
  11576. return;
  11577. }
  11578. if (!is_delete_request && (connect_handler == NULL)
  11579. && (ready_handler == NULL) && (data_handler == NULL)
  11580. && (close_handler == NULL)) {
  11581. return;
  11582. }
  11583. if (auth_handler != NULL) {
  11584. return;
  11585. }
  11586. } else if (handler_type == REQUEST_HANDLER) {
  11587. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11588. && data_handler == NULL && close_handler == NULL);
  11589. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11590. DEBUG_ASSERT(auth_handler == NULL);
  11591. if ((connect_handler != NULL) || (ready_handler != NULL)
  11592. || (data_handler != NULL) || (close_handler != NULL)) {
  11593. return;
  11594. }
  11595. if (!is_delete_request && (handler == NULL)) {
  11596. return;
  11597. }
  11598. if (auth_handler != NULL) {
  11599. return;
  11600. }
  11601. } else { /* AUTH_HANDLER */
  11602. DEBUG_ASSERT(handler == NULL);
  11603. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11604. && data_handler == NULL && close_handler == NULL);
  11605. DEBUG_ASSERT(auth_handler != NULL);
  11606. if (handler != NULL) {
  11607. return;
  11608. }
  11609. if ((connect_handler != NULL) || (ready_handler != NULL)
  11610. || (data_handler != NULL) || (close_handler != NULL)) {
  11611. return;
  11612. }
  11613. if (!is_delete_request && (auth_handler == NULL)) {
  11614. return;
  11615. }
  11616. }
  11617. if (!phys_ctx || !dom_ctx) {
  11618. return;
  11619. }
  11620. /* Internal callbacks have their contexts set
  11621. * if called from non-related thread, context must be set
  11622. * since internal function assumes it exists.
  11623. * For an example see how handler_info_wait_unused()
  11624. * waits for reference to become zero
  11625. */
  11626. if (NULL == pthread_getspecific(sTlsKey))
  11627. {
  11628. is_tls_set = 1;
  11629. tls.is_master = -1;
  11630. tls.thread_idx = phys_ctx->starter_thread_idx;
  11631. #if defined(_WIN32)
  11632. tls.pthread_cond_helper_mutex = NULL;
  11633. #endif
  11634. pthread_setspecific(sTlsKey, &tls);
  11635. }
  11636. mg_lock_context(phys_ctx);
  11637. /* first try to find an existing handler */
  11638. lastref = &(dom_ctx->handlers);
  11639. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11640. if (tmp_rh->handler_type == handler_type) {
  11641. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11642. if (!is_delete_request) {
  11643. /* update existing handler */
  11644. if (handler_type == REQUEST_HANDLER) {
  11645. /* Wait for end of use before updating */
  11646. handler_info_wait_unused(tmp_rh);
  11647. /* Ok, the handler is no more use -> Update it */
  11648. tmp_rh->handler = handler;
  11649. } else if (handler_type == WEBSOCKET_HANDLER) {
  11650. tmp_rh->subprotocols = subprotocols;
  11651. tmp_rh->connect_handler = connect_handler;
  11652. tmp_rh->ready_handler = ready_handler;
  11653. tmp_rh->data_handler = data_handler;
  11654. tmp_rh->close_handler = close_handler;
  11655. } else { /* AUTH_HANDLER */
  11656. tmp_rh->auth_handler = auth_handler;
  11657. }
  11658. tmp_rh->cbdata = cbdata;
  11659. } else {
  11660. /* remove existing handler */
  11661. if (handler_type == REQUEST_HANDLER) {
  11662. /* Wait for end of use before removing */
  11663. handler_info_wait_unused(tmp_rh);
  11664. /* Ok, the handler is no more used -> Destroy resources
  11665. */
  11666. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11667. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11668. }
  11669. *lastref = tmp_rh->next;
  11670. mg_free(tmp_rh->uri);
  11671. mg_free(tmp_rh);
  11672. }
  11673. mg_unlock_context(phys_ctx);
  11674. if (is_tls_set) {
  11675. pthread_setspecific(sTlsKey, NULL);
  11676. }
  11677. return;
  11678. }
  11679. }
  11680. lastref = &(tmp_rh->next);
  11681. }
  11682. if (is_delete_request) {
  11683. /* no handler to set, this was a remove request to a non-existing
  11684. * handler */
  11685. mg_unlock_context(phys_ctx);
  11686. if (is_tls_set) {
  11687. pthread_setspecific(sTlsKey, NULL);
  11688. }
  11689. return;
  11690. }
  11691. tmp_rh =
  11692. (struct mg_handler_info *)mg_calloc_ctx(1,
  11693. sizeof(struct mg_handler_info),
  11694. phys_ctx);
  11695. if (tmp_rh == NULL) {
  11696. mg_unlock_context(phys_ctx);
  11697. mg_cry_ctx_internal(phys_ctx,
  11698. "%s",
  11699. "Cannot create new request handler struct, OOM");
  11700. if (is_tls_set) {
  11701. pthread_setspecific(sTlsKey, NULL);
  11702. }
  11703. return;
  11704. }
  11705. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11706. if (!tmp_rh->uri) {
  11707. mg_unlock_context(phys_ctx);
  11708. mg_free(tmp_rh);
  11709. mg_cry_ctx_internal(phys_ctx,
  11710. "%s",
  11711. "Cannot create new request handler struct, OOM");
  11712. if (is_tls_set) {
  11713. pthread_setspecific(sTlsKey, NULL);
  11714. }
  11715. return;
  11716. }
  11717. tmp_rh->uri_len = urilen;
  11718. if (handler_type == REQUEST_HANDLER) {
  11719. /* Init refcount mutex and condition */
  11720. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11721. mg_unlock_context(phys_ctx);
  11722. mg_free(tmp_rh);
  11723. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11724. if (is_tls_set) {
  11725. pthread_setspecific(sTlsKey, NULL);
  11726. }
  11727. return;
  11728. }
  11729. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11730. mg_unlock_context(phys_ctx);
  11731. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11732. mg_free(tmp_rh);
  11733. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11734. if (is_tls_set) {
  11735. pthread_setspecific(sTlsKey, NULL);
  11736. }
  11737. return;
  11738. }
  11739. tmp_rh->refcount = 0;
  11740. tmp_rh->handler = handler;
  11741. } else if (handler_type == WEBSOCKET_HANDLER) {
  11742. tmp_rh->subprotocols = subprotocols;
  11743. tmp_rh->connect_handler = connect_handler;
  11744. tmp_rh->ready_handler = ready_handler;
  11745. tmp_rh->data_handler = data_handler;
  11746. tmp_rh->close_handler = close_handler;
  11747. } else { /* AUTH_HANDLER */
  11748. tmp_rh->auth_handler = auth_handler;
  11749. }
  11750. tmp_rh->cbdata = cbdata;
  11751. tmp_rh->handler_type = handler_type;
  11752. tmp_rh->next = NULL;
  11753. *lastref = tmp_rh;
  11754. mg_unlock_context(phys_ctx);
  11755. if (is_tls_set) {
  11756. pthread_setspecific(sTlsKey, NULL);
  11757. }
  11758. }
  11759. void
  11760. mg_set_request_handler(struct mg_context *ctx,
  11761. const char *uri,
  11762. mg_request_handler handler,
  11763. void *cbdata)
  11764. {
  11765. mg_set_handler_type(ctx,
  11766. &(ctx->dd),
  11767. uri,
  11768. REQUEST_HANDLER,
  11769. handler == NULL,
  11770. handler,
  11771. NULL,
  11772. NULL,
  11773. NULL,
  11774. NULL,
  11775. NULL,
  11776. NULL,
  11777. cbdata);
  11778. }
  11779. void
  11780. mg_set_websocket_handler(struct mg_context *ctx,
  11781. const char *uri,
  11782. mg_websocket_connect_handler connect_handler,
  11783. mg_websocket_ready_handler ready_handler,
  11784. mg_websocket_data_handler data_handler,
  11785. mg_websocket_close_handler close_handler,
  11786. void *cbdata)
  11787. {
  11788. mg_set_websocket_handler_with_subprotocols(ctx,
  11789. uri,
  11790. NULL,
  11791. connect_handler,
  11792. ready_handler,
  11793. data_handler,
  11794. close_handler,
  11795. cbdata);
  11796. }
  11797. void
  11798. mg_set_websocket_handler_with_subprotocols(
  11799. struct mg_context *ctx,
  11800. const char *uri,
  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. void *cbdata)
  11807. {
  11808. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11809. && (data_handler == NULL)
  11810. && (close_handler == NULL);
  11811. mg_set_handler_type(ctx,
  11812. &(ctx->dd),
  11813. uri,
  11814. WEBSOCKET_HANDLER,
  11815. is_delete_request,
  11816. NULL,
  11817. subprotocols,
  11818. connect_handler,
  11819. ready_handler,
  11820. data_handler,
  11821. close_handler,
  11822. NULL,
  11823. cbdata);
  11824. }
  11825. void
  11826. mg_set_auth_handler(struct mg_context *ctx,
  11827. const char *uri,
  11828. mg_authorization_handler handler,
  11829. void *cbdata)
  11830. {
  11831. mg_set_handler_type(ctx,
  11832. &(ctx->dd),
  11833. uri,
  11834. AUTH_HANDLER,
  11835. handler == NULL,
  11836. NULL,
  11837. NULL,
  11838. NULL,
  11839. NULL,
  11840. NULL,
  11841. NULL,
  11842. handler,
  11843. cbdata);
  11844. }
  11845. static int
  11846. get_request_handler(struct mg_connection *conn,
  11847. int handler_type,
  11848. mg_request_handler *handler,
  11849. struct mg_websocket_subprotocols **subprotocols,
  11850. mg_websocket_connect_handler *connect_handler,
  11851. mg_websocket_ready_handler *ready_handler,
  11852. mg_websocket_data_handler *data_handler,
  11853. mg_websocket_close_handler *close_handler,
  11854. mg_authorization_handler *auth_handler,
  11855. void **cbdata,
  11856. struct mg_handler_info **handler_info)
  11857. {
  11858. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11859. if (request_info) {
  11860. const char *uri = request_info->local_uri;
  11861. size_t urilen = strlen(uri);
  11862. struct mg_handler_info *tmp_rh;
  11863. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11864. return 0;
  11865. }
  11866. mg_lock_context(conn->phys_ctx);
  11867. /* first try for an exact match */
  11868. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11869. tmp_rh = tmp_rh->next) {
  11870. if (tmp_rh->handler_type == handler_type) {
  11871. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11872. if (handler_type == WEBSOCKET_HANDLER) {
  11873. *subprotocols = tmp_rh->subprotocols;
  11874. *connect_handler = tmp_rh->connect_handler;
  11875. *ready_handler = tmp_rh->ready_handler;
  11876. *data_handler = tmp_rh->data_handler;
  11877. *close_handler = tmp_rh->close_handler;
  11878. } else if (handler_type == REQUEST_HANDLER) {
  11879. *handler = tmp_rh->handler;
  11880. /* Acquire handler and give it back */
  11881. handler_info_acquire(tmp_rh);
  11882. *handler_info = tmp_rh;
  11883. } else { /* AUTH_HANDLER */
  11884. *auth_handler = tmp_rh->auth_handler;
  11885. }
  11886. *cbdata = tmp_rh->cbdata;
  11887. mg_unlock_context(conn->phys_ctx);
  11888. return 1;
  11889. }
  11890. }
  11891. }
  11892. /* next try for a partial match, we will accept uri/something */
  11893. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11894. tmp_rh = tmp_rh->next) {
  11895. if (tmp_rh->handler_type == handler_type) {
  11896. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11897. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11898. if (handler_type == WEBSOCKET_HANDLER) {
  11899. *subprotocols = tmp_rh->subprotocols;
  11900. *connect_handler = tmp_rh->connect_handler;
  11901. *ready_handler = tmp_rh->ready_handler;
  11902. *data_handler = tmp_rh->data_handler;
  11903. *close_handler = tmp_rh->close_handler;
  11904. } else if (handler_type == REQUEST_HANDLER) {
  11905. *handler = tmp_rh->handler;
  11906. /* Acquire handler and give it back */
  11907. handler_info_acquire(tmp_rh);
  11908. *handler_info = tmp_rh;
  11909. } else { /* AUTH_HANDLER */
  11910. *auth_handler = tmp_rh->auth_handler;
  11911. }
  11912. *cbdata = tmp_rh->cbdata;
  11913. mg_unlock_context(conn->phys_ctx);
  11914. return 1;
  11915. }
  11916. }
  11917. }
  11918. /* finally try for pattern match */
  11919. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11920. tmp_rh = tmp_rh->next) {
  11921. if (tmp_rh->handler_type == handler_type) {
  11922. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11923. if (handler_type == WEBSOCKET_HANDLER) {
  11924. *subprotocols = tmp_rh->subprotocols;
  11925. *connect_handler = tmp_rh->connect_handler;
  11926. *ready_handler = tmp_rh->ready_handler;
  11927. *data_handler = tmp_rh->data_handler;
  11928. *close_handler = tmp_rh->close_handler;
  11929. } else if (handler_type == REQUEST_HANDLER) {
  11930. *handler = tmp_rh->handler;
  11931. /* Acquire handler and give it back */
  11932. handler_info_acquire(tmp_rh);
  11933. *handler_info = tmp_rh;
  11934. } else { /* AUTH_HANDLER */
  11935. *auth_handler = tmp_rh->auth_handler;
  11936. }
  11937. *cbdata = tmp_rh->cbdata;
  11938. mg_unlock_context(conn->phys_ctx);
  11939. return 1;
  11940. }
  11941. }
  11942. }
  11943. mg_unlock_context(conn->phys_ctx);
  11944. }
  11945. return 0; /* none found */
  11946. }
  11947. /* Check if the script file is in a path, allowed for script files.
  11948. * This can be used if uploading files is possible not only for the server
  11949. * admin, and the upload mechanism does not check the file extension.
  11950. */
  11951. static int
  11952. is_in_script_path(const struct mg_connection *conn, const char *path)
  11953. {
  11954. /* TODO (Feature): Add config value for allowed script path.
  11955. * Default: All allowed. */
  11956. (void)conn;
  11957. (void)path;
  11958. return 1;
  11959. }
  11960. #if defined(USE_WEBSOCKET) \
  11961. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  11962. static int
  11963. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11964. void *cbdata)
  11965. {
  11966. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11967. if (pcallbacks->websocket_connect) {
  11968. return pcallbacks->websocket_connect(conn);
  11969. }
  11970. /* No handler set - assume "OK" */
  11971. return 0;
  11972. }
  11973. static void
  11974. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11975. {
  11976. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11977. if (pcallbacks->websocket_ready) {
  11978. pcallbacks->websocket_ready(conn);
  11979. }
  11980. }
  11981. static int
  11982. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11983. int bits,
  11984. char *data,
  11985. size_t len,
  11986. void *cbdata)
  11987. {
  11988. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11989. if (pcallbacks->websocket_data) {
  11990. return pcallbacks->websocket_data(conn, bits, data, len);
  11991. }
  11992. /* No handler set - assume "OK" */
  11993. return 1;
  11994. }
  11995. static void
  11996. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  11997. void *cbdata)
  11998. {
  11999. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12000. if (pcallbacks->connection_close) {
  12001. pcallbacks->connection_close(conn);
  12002. }
  12003. }
  12004. #endif
  12005. /* This is the heart of the Civetweb's logic.
  12006. * This function is called when the request is read, parsed and validated,
  12007. * and Civetweb must decide what action to take: serve a file, or
  12008. * a directory, or call embedded function, etcetera. */
  12009. static void
  12010. handle_request(struct mg_connection *conn)
  12011. {
  12012. struct mg_request_info *ri = &conn->request_info;
  12013. char path[PATH_MAX];
  12014. int uri_len, ssl_index;
  12015. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12016. is_put_or_delete_request = 0, is_callback_resource = 0;
  12017. int i;
  12018. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12019. mg_request_handler callback_handler = NULL;
  12020. struct mg_handler_info *handler_info = NULL;
  12021. struct mg_websocket_subprotocols *subprotocols;
  12022. mg_websocket_connect_handler ws_connect_handler = NULL;
  12023. mg_websocket_ready_handler ws_ready_handler = NULL;
  12024. mg_websocket_data_handler ws_data_handler = NULL;
  12025. mg_websocket_close_handler ws_close_handler = NULL;
  12026. void *callback_data = NULL;
  12027. mg_authorization_handler auth_handler = NULL;
  12028. void *auth_callback_data = NULL;
  12029. int handler_type;
  12030. time_t curtime = time(NULL);
  12031. char date[64];
  12032. path[0] = 0;
  12033. /* 1. get the request url */
  12034. /* 1.1. split into url and query string */
  12035. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12036. != NULL) {
  12037. *((char *)conn->request_info.query_string++) = '\0';
  12038. }
  12039. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12040. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12041. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12042. if (ssl_index >= 0) {
  12043. redirect_to_https_port(conn, ssl_index);
  12044. } else {
  12045. /* A http to https forward port has been specified,
  12046. * but no https port to forward to. */
  12047. mg_send_http_error(conn,
  12048. 503,
  12049. "%s",
  12050. "Error: SSL forward not configured properly");
  12051. mg_cry_internal(conn,
  12052. "%s",
  12053. "Can not redirect to SSL, no SSL port available");
  12054. }
  12055. return;
  12056. }
  12057. uri_len = (int)strlen(ri->local_uri);
  12058. /* 1.3. decode url (if config says so) */
  12059. if (should_decode_url(conn)) {
  12060. mg_url_decode(
  12061. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12062. }
  12063. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12064. * not possible */
  12065. remove_dot_segments((char *)ri->local_uri);
  12066. /* step 1. completed, the url is known now */
  12067. uri_len = (int)strlen(ri->local_uri);
  12068. DEBUG_TRACE("URL: %s", ri->local_uri);
  12069. /* 2. if this ip has limited speed, set it for this connection */
  12070. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12071. get_remote_ip(conn),
  12072. ri->local_uri);
  12073. /* 3. call a "handle everything" callback, if registered */
  12074. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12075. /* Note that since V1.7 the "begin_request" function is called
  12076. * before an authorization check. If an authorization check is
  12077. * required, use a request_handler instead. */
  12078. i = conn->phys_ctx->callbacks.begin_request(conn);
  12079. if (i > 0) {
  12080. /* callback already processed the request. Store the
  12081. return value as a status code for the access log. */
  12082. conn->status_code = i;
  12083. discard_unread_request_data(conn);
  12084. return;
  12085. } else if (i == 0) {
  12086. /* civetweb should process the request */
  12087. } else {
  12088. /* unspecified - may change with the next version */
  12089. return;
  12090. }
  12091. }
  12092. /* request not yet handled by a handler or redirect, so the request
  12093. * is processed here */
  12094. /* 4. Check for CORS preflight requests and handle them (if configured).
  12095. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12096. */
  12097. if (!strcmp(ri->request_method, "OPTIONS")) {
  12098. /* Send a response to CORS preflights only if
  12099. * access_control_allow_methods is not NULL and not an empty string.
  12100. * In this case, scripts can still handle CORS. */
  12101. const char *cors_meth_cfg =
  12102. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12103. const char *cors_orig_cfg =
  12104. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12105. const char *cors_origin =
  12106. get_header(ri->http_headers, ri->num_headers, "Origin");
  12107. const char *cors_acrm = get_header(ri->http_headers,
  12108. ri->num_headers,
  12109. "Access-Control-Request-Method");
  12110. /* Todo: check if cors_origin is in cors_orig_cfg.
  12111. * Or, let the client check this. */
  12112. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12113. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12114. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12115. /* This is a valid CORS preflight, and the server is configured
  12116. * to
  12117. * handle it automatically. */
  12118. const char *cors_acrh =
  12119. get_header(ri->http_headers,
  12120. ri->num_headers,
  12121. "Access-Control-Request-Headers");
  12122. gmt_time_string(date, sizeof(date), &curtime);
  12123. mg_printf(conn,
  12124. "HTTP/1.1 200 OK\r\n"
  12125. "Date: %s\r\n"
  12126. "Access-Control-Allow-Origin: %s\r\n"
  12127. "Access-Control-Allow-Methods: %s\r\n"
  12128. "Content-Length: 0\r\n"
  12129. "Connection: %s\r\n",
  12130. date,
  12131. cors_orig_cfg,
  12132. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12133. suggest_connection_header(conn));
  12134. if (cors_acrh != NULL) {
  12135. /* CORS request is asking for additional headers */
  12136. const char *cors_hdr_cfg =
  12137. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12138. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12139. /* Allow only if access_control_allow_headers is
  12140. * not NULL and not an empty string. If this
  12141. * configuration is set to *, allow everything.
  12142. * Otherwise this configuration must be a list
  12143. * of allowed HTTP header names. */
  12144. mg_printf(conn,
  12145. "Access-Control-Allow-Headers: %s\r\n",
  12146. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12147. : cors_hdr_cfg));
  12148. }
  12149. }
  12150. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12151. mg_printf(conn, "\r\n");
  12152. return;
  12153. }
  12154. }
  12155. /* 5. interpret the url to find out how the request must be handled
  12156. */
  12157. /* 5.1. first test, if the request targets the regular http(s)://
  12158. * protocol namespace or the websocket ws(s):// protocol namespace.
  12159. */
  12160. is_websocket_request = is_websocket_protocol(conn);
  12161. #if defined(USE_WEBSOCKET)
  12162. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12163. #else
  12164. handler_type = REQUEST_HANDLER;
  12165. #endif /* defined(USE_WEBSOCKET) */
  12166. /* 5.2. check if the request will be handled by a callback */
  12167. if (get_request_handler(conn,
  12168. handler_type,
  12169. &callback_handler,
  12170. &subprotocols,
  12171. &ws_connect_handler,
  12172. &ws_ready_handler,
  12173. &ws_data_handler,
  12174. &ws_close_handler,
  12175. NULL,
  12176. &callback_data,
  12177. &handler_info)) {
  12178. /* 5.2.1. A callback will handle this request. All requests
  12179. * handled
  12180. * by a callback have to be considered as requests to a script
  12181. * resource. */
  12182. is_callback_resource = 1;
  12183. is_script_resource = 1;
  12184. is_put_or_delete_request = is_put_or_delete_method(conn);
  12185. } else {
  12186. no_callback_resource:
  12187. /* 5.2.2. No callback is responsible for this request. The URI
  12188. * addresses a file based resource (static content or Lua/cgi
  12189. * scripts in the file system). */
  12190. is_callback_resource = 0;
  12191. interpret_uri(conn,
  12192. path,
  12193. sizeof(path),
  12194. &file.stat,
  12195. &is_found,
  12196. &is_script_resource,
  12197. &is_websocket_request,
  12198. &is_put_or_delete_request);
  12199. }
  12200. /* 6. authorization check */
  12201. /* 6.1. a custom authorization handler is installed */
  12202. if (get_request_handler(conn,
  12203. AUTH_HANDLER,
  12204. NULL,
  12205. NULL,
  12206. NULL,
  12207. NULL,
  12208. NULL,
  12209. NULL,
  12210. &auth_handler,
  12211. &auth_callback_data,
  12212. NULL)) {
  12213. if (!auth_handler(conn, auth_callback_data)) {
  12214. return;
  12215. }
  12216. } else if (is_put_or_delete_request && !is_script_resource
  12217. && !is_callback_resource) {
  12218. /* 6.2. this request is a PUT/DELETE to a real file */
  12219. /* 6.2.1. thus, the server must have real files */
  12220. #if defined(NO_FILES)
  12221. if (1) {
  12222. #else
  12223. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12224. #endif
  12225. /* This server does not have any real files, thus the
  12226. * PUT/DELETE methods are not valid. */
  12227. mg_send_http_error(conn,
  12228. 405,
  12229. "%s method not allowed",
  12230. conn->request_info.request_method);
  12231. return;
  12232. }
  12233. #if !defined(NO_FILES)
  12234. /* 6.2.2. Check if put authorization for static files is
  12235. * available.
  12236. */
  12237. if (!is_authorized_for_put(conn)) {
  12238. send_authorization_request(conn, NULL);
  12239. return;
  12240. }
  12241. #endif
  12242. } else {
  12243. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12244. * or it is a PUT or DELETE request to a resource that does not
  12245. * correspond to a file. Check authorization. */
  12246. if (!check_authorization(conn, path)) {
  12247. send_authorization_request(conn, NULL);
  12248. return;
  12249. }
  12250. }
  12251. /* request is authorized or does not need authorization */
  12252. /* 7. check if there are request handlers for this uri */
  12253. if (is_callback_resource) {
  12254. if (!is_websocket_request) {
  12255. i = callback_handler(conn, callback_data);
  12256. /* Callback handler will not be used anymore. Release it */
  12257. handler_info_release(handler_info);
  12258. if (i > 0) {
  12259. /* Do nothing, callback has served the request. Store
  12260. * then return value as status code for the log and discard
  12261. * all data from the client not used by the callback. */
  12262. conn->status_code = i;
  12263. discard_unread_request_data(conn);
  12264. } else {
  12265. /* The handler did NOT handle the request. */
  12266. /* Some proper reactions would be:
  12267. * a) close the connections without sending anything
  12268. * b) send a 404 not found
  12269. * c) try if there is a file matching the URI
  12270. * It would be possible to do a, b or c in the callback
  12271. * implementation, and return 1 - we cannot do anything
  12272. * here, that is not possible in the callback.
  12273. *
  12274. * TODO: What would be the best reaction here?
  12275. * (Note: The reaction may change, if there is a better
  12276. *idea.)
  12277. */
  12278. /* For the moment, use option c: We look for a proper file,
  12279. * but since a file request is not always a script resource,
  12280. * the authorization check might be different. */
  12281. interpret_uri(conn,
  12282. path,
  12283. sizeof(path),
  12284. &file.stat,
  12285. &is_found,
  12286. &is_script_resource,
  12287. &is_websocket_request,
  12288. &is_put_or_delete_request);
  12289. callback_handler = NULL;
  12290. /* Here we are at a dead end:
  12291. * According to URI matching, a callback should be
  12292. * responsible for handling the request,
  12293. * we called it, but the callback declared itself
  12294. * not responsible.
  12295. * We use a goto here, to get out of this dead end,
  12296. * and continue with the default handling.
  12297. * A goto here is simpler and better to understand
  12298. * than some curious loop. */
  12299. goto no_callback_resource;
  12300. }
  12301. } else {
  12302. #if defined(USE_WEBSOCKET)
  12303. handle_websocket_request(conn,
  12304. path,
  12305. is_callback_resource,
  12306. subprotocols,
  12307. ws_connect_handler,
  12308. ws_ready_handler,
  12309. ws_data_handler,
  12310. ws_close_handler,
  12311. callback_data);
  12312. #endif
  12313. }
  12314. return;
  12315. }
  12316. /* 8. handle websocket requests */
  12317. #if defined(USE_WEBSOCKET)
  12318. if (is_websocket_request) {
  12319. if (is_script_resource) {
  12320. if (is_in_script_path(conn, path)) {
  12321. /* Websocket Lua script */
  12322. handle_websocket_request(conn,
  12323. path,
  12324. 0 /* Lua Script */,
  12325. NULL,
  12326. NULL,
  12327. NULL,
  12328. NULL,
  12329. NULL,
  12330. conn->phys_ctx->user_data);
  12331. } else {
  12332. /* Script was in an illegal path */
  12333. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12334. }
  12335. } else {
  12336. #if defined(MG_LEGACY_INTERFACE)
  12337. handle_websocket_request(
  12338. conn,
  12339. path,
  12340. !is_script_resource /* could be deprecated global callback */,
  12341. NULL,
  12342. deprecated_websocket_connect_wrapper,
  12343. deprecated_websocket_ready_wrapper,
  12344. deprecated_websocket_data_wrapper,
  12345. NULL,
  12346. conn->phys_ctx->callbacks);
  12347. #else
  12348. mg_send_http_error(conn, 404, "%s", "Not found");
  12349. #endif
  12350. }
  12351. return;
  12352. } else
  12353. #endif
  12354. #if defined(NO_FILES)
  12355. /* 9a. In case the server uses only callbacks, this uri is
  12356. * unknown.
  12357. * Then, all request handling ends here. */
  12358. mg_send_http_error(conn, 404, "%s", "Not Found");
  12359. #else
  12360. /* 9b. This request is either for a static file or resource handled
  12361. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12362. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12363. mg_send_http_error(conn, 404, "%s", "Not Found");
  12364. return;
  12365. }
  12366. /* 10. Request is handled by a script */
  12367. if (is_script_resource) {
  12368. handle_file_based_request(conn, path, &file);
  12369. return;
  12370. }
  12371. /* 11. Handle put/delete/mkcol requests */
  12372. if (is_put_or_delete_request) {
  12373. /* 11.1. PUT method */
  12374. if (!strcmp(ri->request_method, "PUT")) {
  12375. put_file(conn, path);
  12376. return;
  12377. }
  12378. /* 11.2. DELETE method */
  12379. if (!strcmp(ri->request_method, "DELETE")) {
  12380. delete_file(conn, path);
  12381. return;
  12382. }
  12383. /* 11.3. MKCOL method */
  12384. if (!strcmp(ri->request_method, "MKCOL")) {
  12385. mkcol(conn, path);
  12386. return;
  12387. }
  12388. /* 11.4. PATCH method
  12389. * This method is not supported for static resources,
  12390. * only for scripts (Lua, CGI) and callbacks. */
  12391. mg_send_http_error(conn,
  12392. 405,
  12393. "%s method not allowed",
  12394. conn->request_info.request_method);
  12395. return;
  12396. }
  12397. /* 11. File does not exist, or it was configured that it should be
  12398. * hidden */
  12399. if (!is_found || (must_hide_file(conn, path))) {
  12400. mg_send_http_error(conn, 404, "%s", "Not found");
  12401. return;
  12402. }
  12403. /* 12. Directory uris should end with a slash */
  12404. if (file.stat.is_directory && (uri_len > 0)
  12405. && (ri->local_uri[uri_len - 1] != '/')) {
  12406. gmt_time_string(date, sizeof(date), &curtime);
  12407. mg_printf(conn,
  12408. "HTTP/1.1 301 Moved Permanently\r\n"
  12409. "Location: %s/\r\n"
  12410. "Date: %s\r\n"
  12411. /* "Cache-Control: private\r\n" (= default) */
  12412. "Content-Length: 0\r\n"
  12413. "Connection: %s\r\n",
  12414. ri->request_uri,
  12415. date,
  12416. suggest_connection_header(conn));
  12417. send_additional_header(conn);
  12418. mg_printf(conn, "\r\n");
  12419. return;
  12420. }
  12421. /* 13. Handle other methods than GET/HEAD */
  12422. /* 13.1. Handle PROPFIND */
  12423. if (!strcmp(ri->request_method, "PROPFIND")) {
  12424. handle_propfind(conn, path, &file.stat);
  12425. return;
  12426. }
  12427. /* 13.2. Handle OPTIONS for files */
  12428. if (!strcmp(ri->request_method, "OPTIONS")) {
  12429. /* This standard handler is only used for real files.
  12430. * Scripts should support the OPTIONS method themselves, to allow a
  12431. * maximum flexibility.
  12432. * Lua and CGI scripts may fully support CORS this way (including
  12433. * preflights). */
  12434. send_options(conn);
  12435. return;
  12436. }
  12437. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12438. if ((0 != strcmp(ri->request_method, "GET"))
  12439. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12440. mg_send_http_error(conn,
  12441. 405,
  12442. "%s method not allowed",
  12443. conn->request_info.request_method);
  12444. return;
  12445. }
  12446. /* 14. directories */
  12447. if (file.stat.is_directory) {
  12448. /* Substitute files have already been handled above. */
  12449. /* Here we can either generate and send a directory listing,
  12450. * or send an "access denied" error. */
  12451. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12452. "yes")) {
  12453. handle_directory_request(conn, path);
  12454. } else {
  12455. mg_send_http_error(conn,
  12456. 403,
  12457. "%s",
  12458. "Error: Directory listing denied");
  12459. }
  12460. return;
  12461. }
  12462. /* 15. read a normal file with GET or HEAD */
  12463. handle_file_based_request(conn, path, &file);
  12464. #endif /* !defined(NO_FILES) */
  12465. }
  12466. #if !defined(NO_FILESYSTEMS)
  12467. static void
  12468. handle_file_based_request(struct mg_connection *conn,
  12469. const char *path,
  12470. struct mg_file *file)
  12471. {
  12472. if (!conn || !conn->dom_ctx) {
  12473. return;
  12474. }
  12475. if (0) {
  12476. #if defined(USE_LUA)
  12477. } else if (match_prefix(
  12478. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12479. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12480. path)
  12481. > 0) {
  12482. if (is_in_script_path(conn, path)) {
  12483. /* Lua server page: an SSI like page containing mostly plain
  12484. * html
  12485. * code
  12486. * plus some tags with server generated contents. */
  12487. handle_lsp_request(conn, path, file, NULL);
  12488. } else {
  12489. /* Script was in an illegal path */
  12490. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12491. }
  12492. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12493. strlen(
  12494. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12495. path)
  12496. > 0) {
  12497. if (is_in_script_path(conn, path)) {
  12498. /* Lua in-server module script: a CGI like script used to
  12499. * generate
  12500. * the
  12501. * entire reply. */
  12502. mg_exec_lua_script(conn, path, NULL);
  12503. } else {
  12504. /* Script was in an illegal path */
  12505. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12506. }
  12507. #endif
  12508. #if defined(USE_DUKTAPE)
  12509. } else if (match_prefix(
  12510. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12511. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12512. path)
  12513. > 0) {
  12514. if (is_in_script_path(conn, path)) {
  12515. /* Call duktape to generate the page */
  12516. mg_exec_duktape_script(conn, path);
  12517. } else {
  12518. /* Script was in an illegal path */
  12519. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12520. }
  12521. #endif
  12522. #if !defined(NO_CGI)
  12523. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12524. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12525. path)
  12526. > 0) {
  12527. if (is_in_script_path(conn, path)) {
  12528. /* CGI scripts may support all HTTP methods */
  12529. handle_cgi_request(conn, path);
  12530. } else {
  12531. /* Script was in an illegal path */
  12532. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12533. }
  12534. #endif /* !NO_CGI */
  12535. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12536. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12537. path)
  12538. > 0) {
  12539. if (is_in_script_path(conn, path)) {
  12540. handle_ssi_file_request(conn, path, file);
  12541. } else {
  12542. /* Script was in an illegal path */
  12543. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12544. }
  12545. #if !defined(NO_CACHING)
  12546. } else if ((!conn->in_error_handler)
  12547. && is_not_modified(conn, &file->stat)) {
  12548. /* Send 304 "Not Modified" - this must not send any body data */
  12549. handle_not_modified_static_file_request(conn, file);
  12550. #endif /* !NO_CACHING */
  12551. } else {
  12552. handle_static_file_request(conn, path, file, NULL, NULL);
  12553. }
  12554. }
  12555. #endif /* NO_FILESYSTEMS */
  12556. static void
  12557. close_all_listening_sockets(struct mg_context *ctx)
  12558. {
  12559. unsigned int i;
  12560. if (!ctx) {
  12561. return;
  12562. }
  12563. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12564. closesocket(ctx->listening_sockets[i].sock);
  12565. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12566. }
  12567. mg_free(ctx->listening_sockets);
  12568. ctx->listening_sockets = NULL;
  12569. mg_free(ctx->listening_socket_fds);
  12570. ctx->listening_socket_fds = NULL;
  12571. }
  12572. /* Valid listening port specification is: [ip_address:]port[s]
  12573. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12574. * Examples for IPv6: [::]:80, [::1]:80,
  12575. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12576. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12577. * In order to bind to both, IPv4 and IPv6, you can either add
  12578. * both ports using 8080,[::]:8080, or the short form +8080.
  12579. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12580. * one only accepting IPv4 the other only IPv6. +8080 creates
  12581. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12582. * environment, they might work differently, or might not work
  12583. * at all - it must be tested what options work best in the
  12584. * relevant network environment.
  12585. */
  12586. static int
  12587. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12588. {
  12589. unsigned int a, b, c, d, port;
  12590. int ch, len;
  12591. const char *cb;
  12592. char *endptr;
  12593. #if defined(USE_IPV6)
  12594. char buf[100] = {0};
  12595. #endif
  12596. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12597. * Also, all-zeroes in the socket address means binding to all addresses
  12598. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12599. memset(so, 0, sizeof(*so));
  12600. so->lsa.sin.sin_family = AF_INET;
  12601. *ip_version = 0;
  12602. /* Initialize port and len as invalid. */
  12603. port = 0;
  12604. len = 0;
  12605. /* Test for different ways to format this string */
  12606. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12607. == 5) {
  12608. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12609. so->lsa.sin.sin_addr.s_addr =
  12610. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12611. so->lsa.sin.sin_port = htons((uint16_t)port);
  12612. *ip_version = 4;
  12613. #if defined(USE_IPV6)
  12614. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12615. && mg_inet_pton(
  12616. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12617. /* IPv6 address, examples: see above */
  12618. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12619. */
  12620. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12621. *ip_version = 6;
  12622. #endif
  12623. } else if ((vec->ptr[0] == '+')
  12624. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12625. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12626. /* Add 1 to len for the + character we skipped before */
  12627. len++;
  12628. #if defined(USE_IPV6)
  12629. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12630. so->lsa.sin6.sin6_family = AF_INET6;
  12631. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12632. *ip_version = 4 + 6;
  12633. #else
  12634. /* Bind to IPv4 only, since IPv6 is not built in. */
  12635. so->lsa.sin.sin_port = htons((uint16_t)port);
  12636. *ip_version = 4;
  12637. #endif
  12638. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12639. && vec->ptr != endptr) {
  12640. len = endptr - vec->ptr;
  12641. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12642. so->lsa.sin.sin_port = htons((uint16_t)port);
  12643. *ip_version = 4;
  12644. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12645. /* String could be a hostname. This check algotithm
  12646. * will only work for RFC 952 compliant hostnames,
  12647. * starting with a letter, containing only letters,
  12648. * digits and hyphen ('-'). Newer specs may allow
  12649. * more, but this is not guaranteed here, since it
  12650. * may interfere with rules for port option lists. */
  12651. /* According to RFC 1035, hostnames are restricted to 255 characters
  12652. * in total (63 between two dots). */
  12653. char hostname[256];
  12654. size_t hostnlen = (size_t)(cb - vec->ptr);
  12655. if (hostnlen >= sizeof(hostname)) {
  12656. /* This would be invalid in any case */
  12657. *ip_version = 0;
  12658. return 0;
  12659. }
  12660. memcpy(hostname, vec->ptr, hostnlen);
  12661. hostname[hostnlen] = 0;
  12662. if (mg_inet_pton(
  12663. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12664. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12665. *ip_version = 4;
  12666. so->lsa.sin.sin_family = AF_INET;
  12667. so->lsa.sin.sin_port = htons((uint16_t)port);
  12668. len += (int)(hostnlen + 1);
  12669. } else {
  12670. port = 0;
  12671. len = 0;
  12672. }
  12673. #if defined(USE_IPV6)
  12674. } else if (mg_inet_pton(AF_INET6,
  12675. hostname,
  12676. &so->lsa.sin6,
  12677. sizeof(so->lsa.sin6))) {
  12678. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12679. *ip_version = 6;
  12680. so->lsa.sin6.sin6_family = AF_INET6;
  12681. so->lsa.sin.sin_port = htons((uint16_t)port);
  12682. len += (int)(hostnlen + 1);
  12683. } else {
  12684. port = 0;
  12685. len = 0;
  12686. }
  12687. #endif
  12688. }
  12689. } else {
  12690. /* Parsing failure. */
  12691. }
  12692. /* sscanf and the option splitting code ensure the following condition
  12693. */
  12694. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12695. *ip_version = 0;
  12696. return 0;
  12697. }
  12698. ch = vec->ptr[len]; /* Next character after the port number */
  12699. so->is_ssl = (ch == 's');
  12700. so->ssl_redir = (ch == 'r');
  12701. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12702. if (is_valid_port(port)
  12703. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12704. return 1;
  12705. }
  12706. /* Reset ip_version to 0 if there is an error */
  12707. *ip_version = 0;
  12708. return 0;
  12709. }
  12710. /* Is there any SSL port in use? */
  12711. static int
  12712. is_ssl_port_used(const char *ports)
  12713. {
  12714. if (ports) {
  12715. /* There are several different allowed syntax variants:
  12716. * - "80" for a single port using every network interface
  12717. * - "localhost:80" for a single port using only localhost
  12718. * - "80,localhost:8080" for two ports, one bound to localhost
  12719. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12720. * to IPv4 localhost, one to IPv6 localhost
  12721. * - "+80" use port 80 for IPv4 and IPv6
  12722. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12723. * for both: IPv4 and IPv4
  12724. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12725. * additionally port 8080 bound to localhost connections
  12726. *
  12727. * If we just look for 's' anywhere in the string, "localhost:80"
  12728. * will be detected as SSL (false positive).
  12729. * Looking for 's' after a digit may cause false positives in
  12730. * "my24service:8080".
  12731. * Looking from 's' backward if there are only ':' and numbers
  12732. * before will not work for "24service:8080" (non SSL, port 8080)
  12733. * or "24s" (SSL, port 24).
  12734. *
  12735. * Remark: Initially hostnames were not allowed to start with a
  12736. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12737. * Section 2.1).
  12738. *
  12739. * To get this correct, the entire string must be parsed as a whole,
  12740. * reading it as a list element for element and parsing with an
  12741. * algorithm equivalent to parse_port_string.
  12742. *
  12743. * In fact, we use local interface names here, not arbitrary hostnames,
  12744. * so in most cases the only name will be "localhost".
  12745. *
  12746. * So, for now, we use this simple algorithm, that may still return
  12747. * a false positive in bizarre cases.
  12748. */
  12749. int i;
  12750. int portslen = (int)strlen(ports);
  12751. char prevIsNumber = 0;
  12752. for (i = 0; i < portslen; i++) {
  12753. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12754. return 1;
  12755. }
  12756. if (ports[i] >= '0' && ports[i] <= '9') {
  12757. prevIsNumber = 1;
  12758. } else {
  12759. prevIsNumber = 0;
  12760. }
  12761. }
  12762. }
  12763. return 0;
  12764. }
  12765. static int
  12766. set_ports_option(struct mg_context *phys_ctx)
  12767. {
  12768. const char *list;
  12769. int on = 1;
  12770. #if defined(USE_IPV6)
  12771. int off = 0;
  12772. #endif
  12773. struct vec vec;
  12774. struct socket so, *ptr;
  12775. struct mg_pollfd *pfd;
  12776. union usa usa;
  12777. socklen_t len;
  12778. int ip_version;
  12779. int portsTotal = 0;
  12780. int portsOk = 0;
  12781. const char *opt_txt;
  12782. long opt_max_connections;
  12783. if (!phys_ctx) {
  12784. return 0;
  12785. }
  12786. memset(&so, 0, sizeof(so));
  12787. memset(&usa, 0, sizeof(usa));
  12788. len = sizeof(usa);
  12789. list = phys_ctx->dd.config[LISTENING_PORTS];
  12790. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12791. portsTotal++;
  12792. if (!parse_port_string(&vec, &so, &ip_version)) {
  12793. mg_cry_ctx_internal(
  12794. phys_ctx,
  12795. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12796. (int)vec.len,
  12797. vec.ptr,
  12798. portsTotal,
  12799. "[IP_ADDRESS:]PORT[s|r]");
  12800. continue;
  12801. }
  12802. #if !defined(NO_SSL)
  12803. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12804. mg_cry_ctx_internal(phys_ctx,
  12805. "Cannot add SSL socket (entry %i)",
  12806. portsTotal);
  12807. continue;
  12808. }
  12809. #endif
  12810. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12811. == INVALID_SOCKET) {
  12812. mg_cry_ctx_internal(phys_ctx,
  12813. "cannot create socket (entry %i)",
  12814. portsTotal);
  12815. continue;
  12816. }
  12817. #if defined(_WIN32)
  12818. /* Windows SO_REUSEADDR lets many procs binds to a
  12819. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12820. * if someone already has the socket -- DTL */
  12821. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12822. * Windows might need a few seconds before
  12823. * the same port can be used again in the
  12824. * same process, so a short Sleep may be
  12825. * required between mg_stop and mg_start.
  12826. */
  12827. if (setsockopt(so.sock,
  12828. SOL_SOCKET,
  12829. SO_EXCLUSIVEADDRUSE,
  12830. (SOCK_OPT_TYPE)&on,
  12831. sizeof(on))
  12832. != 0) {
  12833. /* Set reuse option, but don't abort on errors. */
  12834. mg_cry_ctx_internal(
  12835. phys_ctx,
  12836. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12837. portsTotal);
  12838. }
  12839. #else
  12840. if (setsockopt(so.sock,
  12841. SOL_SOCKET,
  12842. SO_REUSEADDR,
  12843. (SOCK_OPT_TYPE)&on,
  12844. sizeof(on))
  12845. != 0) {
  12846. /* Set reuse option, but don't abort on errors. */
  12847. mg_cry_ctx_internal(
  12848. phys_ctx,
  12849. "cannot set socket option SO_REUSEADDR (entry %i)",
  12850. portsTotal);
  12851. }
  12852. #endif
  12853. if (ip_version > 4) {
  12854. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12855. #if defined(USE_IPV6)
  12856. if (ip_version > 6) {
  12857. if (so.lsa.sa.sa_family == AF_INET6
  12858. && setsockopt(so.sock,
  12859. IPPROTO_IPV6,
  12860. IPV6_V6ONLY,
  12861. (void *)&off,
  12862. sizeof(off))
  12863. != 0) {
  12864. /* Set IPv6 only option, but don't abort on errors. */
  12865. mg_cry_ctx_internal(
  12866. phys_ctx,
  12867. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12868. portsTotal);
  12869. }
  12870. } else {
  12871. if (so.lsa.sa.sa_family == AF_INET6
  12872. && setsockopt(so.sock,
  12873. IPPROTO_IPV6,
  12874. IPV6_V6ONLY,
  12875. (void *)&on,
  12876. sizeof(on))
  12877. != 0) {
  12878. /* Set IPv6 only option, but don't abort on errors. */
  12879. mg_cry_ctx_internal(
  12880. phys_ctx,
  12881. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12882. portsTotal);
  12883. }
  12884. }
  12885. #else
  12886. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12887. closesocket(so.sock);
  12888. so.sock = INVALID_SOCKET;
  12889. continue;
  12890. #endif
  12891. }
  12892. if (so.lsa.sa.sa_family == AF_INET) {
  12893. len = sizeof(so.lsa.sin);
  12894. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12895. mg_cry_ctx_internal(phys_ctx,
  12896. "cannot bind to %.*s: %d (%s)",
  12897. (int)vec.len,
  12898. vec.ptr,
  12899. (int)ERRNO,
  12900. strerror(errno));
  12901. closesocket(so.sock);
  12902. so.sock = INVALID_SOCKET;
  12903. continue;
  12904. }
  12905. }
  12906. #if defined(USE_IPV6)
  12907. else if (so.lsa.sa.sa_family == AF_INET6) {
  12908. len = sizeof(so.lsa.sin6);
  12909. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12910. mg_cry_ctx_internal(phys_ctx,
  12911. "cannot bind to IPv6 %.*s: %d (%s)",
  12912. (int)vec.len,
  12913. vec.ptr,
  12914. (int)ERRNO,
  12915. strerror(errno));
  12916. closesocket(so.sock);
  12917. so.sock = INVALID_SOCKET;
  12918. continue;
  12919. }
  12920. }
  12921. #endif
  12922. else {
  12923. mg_cry_ctx_internal(
  12924. phys_ctx,
  12925. "cannot bind: address family not supported (entry %i)",
  12926. portsTotal);
  12927. closesocket(so.sock);
  12928. so.sock = INVALID_SOCKET;
  12929. continue;
  12930. }
  12931. opt_txt = phys_ctx->dd.config[MAX_CONNECTIONS];
  12932. opt_max_connections = strtol(opt_txt, NULL, 10);
  12933. if ((opt_max_connections > INT_MAX) || (opt_max_connections < 1)) {
  12934. mg_cry_ctx_internal(phys_ctx,
  12935. "max_connections value \"%s\" is invalid",
  12936. opt_txt);
  12937. continue;
  12938. }
  12939. if (listen(so.sock, (int)opt_max_connections) != 0) {
  12940. mg_cry_ctx_internal(phys_ctx,
  12941. "cannot listen to %.*s: %d (%s)",
  12942. (int)vec.len,
  12943. vec.ptr,
  12944. (int)ERRNO,
  12945. strerror(errno));
  12946. closesocket(so.sock);
  12947. so.sock = INVALID_SOCKET;
  12948. continue;
  12949. }
  12950. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12951. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12952. int err = (int)ERRNO;
  12953. mg_cry_ctx_internal(phys_ctx,
  12954. "call to getsockname failed %.*s: %d (%s)",
  12955. (int)vec.len,
  12956. vec.ptr,
  12957. err,
  12958. strerror(errno));
  12959. closesocket(so.sock);
  12960. so.sock = INVALID_SOCKET;
  12961. continue;
  12962. }
  12963. /* Update lsa port in case of random free ports */
  12964. #if defined(USE_IPV6)
  12965. if (so.lsa.sa.sa_family == AF_INET6) {
  12966. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12967. } else
  12968. #endif
  12969. {
  12970. so.lsa.sin.sin_port = usa.sin.sin_port;
  12971. }
  12972. if ((ptr = (struct socket *)
  12973. mg_realloc_ctx(phys_ctx->listening_sockets,
  12974. (phys_ctx->num_listening_sockets + 1)
  12975. * sizeof(phys_ctx->listening_sockets[0]),
  12976. phys_ctx))
  12977. == NULL) {
  12978. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12979. closesocket(so.sock);
  12980. so.sock = INVALID_SOCKET;
  12981. continue;
  12982. }
  12983. if ((pfd = (struct mg_pollfd *)
  12984. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12985. (phys_ctx->num_listening_sockets + 1)
  12986. * sizeof(phys_ctx->listening_socket_fds[0]),
  12987. phys_ctx))
  12988. == NULL) {
  12989. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12990. closesocket(so.sock);
  12991. so.sock = INVALID_SOCKET;
  12992. mg_free(ptr);
  12993. continue;
  12994. }
  12995. set_close_on_exec(so.sock, NULL, phys_ctx);
  12996. phys_ctx->listening_sockets = ptr;
  12997. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12998. phys_ctx->listening_socket_fds = pfd;
  12999. phys_ctx->num_listening_sockets++;
  13000. portsOk++;
  13001. }
  13002. if (portsOk != portsTotal) {
  13003. close_all_listening_sockets(phys_ctx);
  13004. portsOk = 0;
  13005. }
  13006. return portsOk;
  13007. }
  13008. static const char *
  13009. header_val(const struct mg_connection *conn, const char *header)
  13010. {
  13011. const char *header_value;
  13012. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13013. return "-";
  13014. } else {
  13015. return header_value;
  13016. }
  13017. }
  13018. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13019. static void log_access(const struct mg_connection *conn);
  13020. #include "external_log_access.inl"
  13021. #elif !defined(NO_FILESYSTEMS)
  13022. static void
  13023. log_access(const struct mg_connection *conn)
  13024. {
  13025. const struct mg_request_info *ri;
  13026. struct mg_file fi;
  13027. char date[64], src_addr[IP_ADDR_STR_LEN];
  13028. struct tm *tm;
  13029. const char *referer;
  13030. const char *user_agent;
  13031. char buf[4096];
  13032. if (!conn || !conn->dom_ctx) {
  13033. return;
  13034. }
  13035. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13036. if (mg_fopen(conn,
  13037. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13038. MG_FOPEN_MODE_APPEND,
  13039. &fi)
  13040. == 0) {
  13041. fi.access.fp = NULL;
  13042. }
  13043. } else {
  13044. fi.access.fp = NULL;
  13045. }
  13046. /* Log is written to a file and/or a callback. If both are not set,
  13047. * executing the rest of the function is pointless. */
  13048. if ((fi.access.fp == NULL)
  13049. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13050. return;
  13051. }
  13052. tm = localtime(&conn->conn_birth_time);
  13053. if (tm != NULL) {
  13054. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13055. } else {
  13056. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13057. date[sizeof(date) - 1] = '\0';
  13058. }
  13059. ri = &conn->request_info;
  13060. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13061. referer = header_val(conn, "Referer");
  13062. user_agent = header_val(conn, "User-Agent");
  13063. mg_snprintf(conn,
  13064. NULL, /* Ignore truncation in access log */
  13065. buf,
  13066. sizeof(buf),
  13067. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13068. src_addr,
  13069. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13070. date,
  13071. ri->request_method ? ri->request_method : "-",
  13072. ri->request_uri ? ri->request_uri : "-",
  13073. ri->query_string ? "?" : "",
  13074. ri->query_string ? ri->query_string : "",
  13075. ri->http_version,
  13076. conn->status_code,
  13077. conn->num_bytes_sent,
  13078. referer,
  13079. user_agent);
  13080. if (conn->phys_ctx->callbacks.log_access) {
  13081. conn->phys_ctx->callbacks.log_access(conn, buf);
  13082. }
  13083. if (fi.access.fp) {
  13084. int ok = 1;
  13085. flockfile(fi.access.fp);
  13086. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13087. ok = 0;
  13088. }
  13089. if (fflush(fi.access.fp) != 0) {
  13090. ok = 0;
  13091. }
  13092. funlockfile(fi.access.fp);
  13093. if (mg_fclose(&fi.access) != 0) {
  13094. ok = 0;
  13095. }
  13096. if (!ok) {
  13097. mg_cry_internal(conn,
  13098. "Error writing log file %s",
  13099. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13100. }
  13101. }
  13102. }
  13103. #else
  13104. #error Must either enable filesystems or provide a custom log_access implementation
  13105. #endif /* Externally provided function */
  13106. /* Verify given socket address against the ACL.
  13107. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13108. */
  13109. static int
  13110. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13111. {
  13112. int allowed, flag;
  13113. uint32_t net, mask;
  13114. struct vec vec;
  13115. if (phys_ctx) {
  13116. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13117. /* If any ACL is set, deny by default */
  13118. allowed = (list == NULL) ? '+' : '-';
  13119. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13120. flag = vec.ptr[0];
  13121. if ((flag != '+' && flag != '-')
  13122. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13123. mg_cry_ctx_internal(phys_ctx,
  13124. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13125. __func__);
  13126. return -1;
  13127. }
  13128. if (net == (remote_ip & mask)) {
  13129. allowed = flag;
  13130. }
  13131. }
  13132. return allowed == '+';
  13133. }
  13134. return -1;
  13135. }
  13136. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13137. static int
  13138. set_uid_option(struct mg_context *phys_ctx)
  13139. {
  13140. int success = 0;
  13141. if (phys_ctx) {
  13142. /* We are currently running as curr_uid. */
  13143. const uid_t curr_uid = getuid();
  13144. /* If set, we want to run as run_as_user. */
  13145. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13146. const struct passwd *to_pw = NULL;
  13147. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13148. /* run_as_user does not exist on the system. We can't proceed
  13149. * further. */
  13150. mg_cry_ctx_internal(phys_ctx,
  13151. "%s: unknown user [%s]",
  13152. __func__,
  13153. run_as_user);
  13154. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13155. /* There was either no request to change user, or we're already
  13156. * running as run_as_user. Nothing else to do.
  13157. */
  13158. success = 1;
  13159. } else {
  13160. /* Valid change request. */
  13161. if (setgid(to_pw->pw_gid) == -1) {
  13162. mg_cry_ctx_internal(phys_ctx,
  13163. "%s: setgid(%s): %s",
  13164. __func__,
  13165. run_as_user,
  13166. strerror(errno));
  13167. } else if (setgroups(0, NULL) == -1) {
  13168. mg_cry_ctx_internal(phys_ctx,
  13169. "%s: setgroups(): %s",
  13170. __func__,
  13171. strerror(errno));
  13172. } else if (setuid(to_pw->pw_uid) == -1) {
  13173. mg_cry_ctx_internal(phys_ctx,
  13174. "%s: setuid(%s): %s",
  13175. __func__,
  13176. run_as_user,
  13177. strerror(errno));
  13178. } else {
  13179. success = 1;
  13180. }
  13181. }
  13182. }
  13183. return success;
  13184. }
  13185. #endif /* !_WIN32 */
  13186. static void
  13187. tls_dtor(void *key)
  13188. {
  13189. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13190. /* key == pthread_getspecific(sTlsKey); */
  13191. if (tls) {
  13192. if (tls->is_master == 2) {
  13193. tls->is_master = -3; /* Mark memory as dead */
  13194. mg_free(tls);
  13195. }
  13196. }
  13197. pthread_setspecific(sTlsKey, NULL);
  13198. }
  13199. #if !defined(NO_SSL)
  13200. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13201. struct mg_domain_context *dom_ctx,
  13202. const char *pem,
  13203. const char *chain);
  13204. static const char *ssl_error(void);
  13205. static int
  13206. refresh_trust(struct mg_connection *conn)
  13207. {
  13208. static int reload_lock = 0;
  13209. static long int data_check = 0;
  13210. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  13211. struct stat cert_buf;
  13212. long int t;
  13213. const char *pem;
  13214. const char *chain;
  13215. int should_verify_peer;
  13216. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13217. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13218. * refresh_trust still can not work. */
  13219. return 0;
  13220. }
  13221. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13222. if (chain == NULL) {
  13223. /* pem is not NULL here */
  13224. chain = pem;
  13225. }
  13226. if (*chain == 0) {
  13227. chain = NULL;
  13228. }
  13229. t = data_check;
  13230. if (stat(pem, &cert_buf) != -1) {
  13231. t = (long int)cert_buf.st_mtime;
  13232. }
  13233. if (data_check != t) {
  13234. data_check = t;
  13235. should_verify_peer = 0;
  13236. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13237. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13238. == 0) {
  13239. should_verify_peer = 1;
  13240. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13241. "optional")
  13242. == 0) {
  13243. should_verify_peer = 1;
  13244. }
  13245. }
  13246. if (should_verify_peer) {
  13247. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13248. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13249. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13250. ca_file,
  13251. ca_path)
  13252. != 1) {
  13253. mg_cry_ctx_internal(
  13254. conn->phys_ctx,
  13255. "SSL_CTX_load_verify_locations error: %s "
  13256. "ssl_verify_peer requires setting "
  13257. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13258. "present in "
  13259. "the .conf file?",
  13260. ssl_error());
  13261. return 0;
  13262. }
  13263. }
  13264. if (1 == mg_atomic_inc(p_reload_lock)) {
  13265. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13266. == 0) {
  13267. return 0;
  13268. }
  13269. *p_reload_lock = 0;
  13270. }
  13271. }
  13272. /* lock while cert is reloading */
  13273. while (*p_reload_lock) {
  13274. sleep(1);
  13275. }
  13276. return 1;
  13277. }
  13278. #if defined(OPENSSL_API_1_1)
  13279. #else
  13280. static pthread_mutex_t *ssl_mutexes;
  13281. #endif /* OPENSSL_API_1_1 */
  13282. static int
  13283. sslize(struct mg_connection *conn,
  13284. SSL_CTX *s,
  13285. int (*func)(SSL *),
  13286. volatile int *stop_server,
  13287. const struct mg_client_options *client_options)
  13288. {
  13289. int ret, err;
  13290. int short_trust;
  13291. unsigned timeout = 1024;
  13292. unsigned i;
  13293. if (!conn) {
  13294. return 0;
  13295. }
  13296. short_trust =
  13297. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13298. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13299. if (short_trust) {
  13300. int trust_ret = refresh_trust(conn);
  13301. if (!trust_ret) {
  13302. return trust_ret;
  13303. }
  13304. }
  13305. conn->ssl = SSL_new(s);
  13306. if (conn->ssl == NULL) {
  13307. return 0;
  13308. }
  13309. SSL_set_app_data(conn->ssl, (char *)conn);
  13310. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13311. if (ret != 1) {
  13312. err = SSL_get_error(conn->ssl, ret);
  13313. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13314. SSL_free(conn->ssl);
  13315. conn->ssl = NULL;
  13316. OPENSSL_REMOVE_THREAD_STATE();
  13317. return 0;
  13318. }
  13319. if (client_options) {
  13320. if (client_options->host_name) {
  13321. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13322. }
  13323. }
  13324. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13325. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13326. /* NOTE: The loop below acts as a back-off, so we can end
  13327. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13328. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13329. }
  13330. /* SSL functions may fail and require to be called again:
  13331. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13332. * Here "func" could be SSL_connect or SSL_accept. */
  13333. for (i = 0; i <= timeout; i += 50) {
  13334. ret = func(conn->ssl);
  13335. if (ret != 1) {
  13336. err = SSL_get_error(conn->ssl, ret);
  13337. if ((err == SSL_ERROR_WANT_CONNECT)
  13338. || (err == SSL_ERROR_WANT_ACCEPT)
  13339. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13340. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13341. if (*stop_server) {
  13342. /* Don't wait if the server is going to be stopped. */
  13343. break;
  13344. }
  13345. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13346. /* Simply retry the function call. */
  13347. mg_sleep(50);
  13348. } else {
  13349. /* Need to retry the function call "later".
  13350. * See https://linux.die.net/man/3/ssl_get_error
  13351. * This is typical for non-blocking sockets. */
  13352. struct mg_pollfd pfd;
  13353. int pollres;
  13354. pfd.fd = conn->client.sock;
  13355. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13356. || (err == SSL_ERROR_WANT_WRITE))
  13357. ? POLLOUT
  13358. : POLLIN;
  13359. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13360. if (pollres < 0) {
  13361. /* Break if error occured (-1)
  13362. * or server shutdown (-2) */
  13363. break;
  13364. }
  13365. }
  13366. } else if (err == SSL_ERROR_SYSCALL) {
  13367. /* This is an IO error. Look at errno. */
  13368. err = errno;
  13369. mg_cry_internal(conn, "SSL syscall error %i", err);
  13370. break;
  13371. } else {
  13372. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13373. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13374. break;
  13375. }
  13376. ERR_clear_error();
  13377. } else {
  13378. /* success */
  13379. break;
  13380. }
  13381. }
  13382. if (ret != 1) {
  13383. SSL_free(conn->ssl);
  13384. conn->ssl = NULL;
  13385. OPENSSL_REMOVE_THREAD_STATE();
  13386. return 0;
  13387. }
  13388. return 1;
  13389. }
  13390. /* Return OpenSSL error message (from CRYPTO lib) */
  13391. static const char *
  13392. ssl_error(void)
  13393. {
  13394. unsigned long err;
  13395. err = ERR_get_error();
  13396. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13397. }
  13398. static int
  13399. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13400. {
  13401. int i;
  13402. const char hexdigit[] = "0123456789abcdef";
  13403. if ((memlen <= 0) || (buflen <= 0)) {
  13404. return 0;
  13405. }
  13406. if (buflen < (3 * memlen)) {
  13407. return 0;
  13408. }
  13409. for (i = 0; i < memlen; i++) {
  13410. if (i > 0) {
  13411. buf[3 * i - 1] = ' ';
  13412. }
  13413. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13414. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13415. }
  13416. buf[3 * memlen - 1] = 0;
  13417. return 1;
  13418. }
  13419. static void
  13420. ssl_get_client_cert_info(struct mg_connection *conn)
  13421. {
  13422. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13423. if (cert) {
  13424. char str_subject[1024];
  13425. char str_issuer[1024];
  13426. char str_finger[1024];
  13427. unsigned char buf[256];
  13428. char *str_serial = NULL;
  13429. unsigned int ulen;
  13430. int ilen;
  13431. unsigned char *tmp_buf;
  13432. unsigned char *tmp_p;
  13433. /* Handle to algorithm used for fingerprint */
  13434. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13435. /* Get Subject and issuer */
  13436. X509_NAME *subj = X509_get_subject_name(cert);
  13437. X509_NAME *iss = X509_get_issuer_name(cert);
  13438. /* Get serial number */
  13439. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13440. /* Translate serial number to a hex string */
  13441. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13442. str_serial = BN_bn2hex(serial_bn);
  13443. BN_free(serial_bn);
  13444. /* Translate subject and issuer to a string */
  13445. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13446. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13447. /* Calculate SHA1 fingerprint and store as a hex string */
  13448. ulen = 0;
  13449. /* ASN1_digest is deprecated. Do the calculation manually,
  13450. * using EVP_Digest. */
  13451. ilen = i2d_X509(cert, NULL);
  13452. tmp_buf = (ilen > 0)
  13453. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13454. conn->phys_ctx)
  13455. : NULL;
  13456. if (tmp_buf) {
  13457. tmp_p = tmp_buf;
  13458. (void)i2d_X509(cert, &tmp_p);
  13459. if (!EVP_Digest(
  13460. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13461. ulen = 0;
  13462. }
  13463. mg_free(tmp_buf);
  13464. }
  13465. if (!hexdump2string(
  13466. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13467. *str_finger = 0;
  13468. }
  13469. conn->request_info.client_cert = (struct mg_client_cert *)
  13470. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13471. if (conn->request_info.client_cert) {
  13472. conn->request_info.client_cert->peer_cert = (void *)cert;
  13473. conn->request_info.client_cert->subject =
  13474. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13475. conn->request_info.client_cert->issuer =
  13476. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13477. conn->request_info.client_cert->serial =
  13478. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13479. conn->request_info.client_cert->finger =
  13480. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13481. } else {
  13482. mg_cry_internal(conn,
  13483. "%s",
  13484. "Out of memory: Cannot allocate memory for client "
  13485. "certificate");
  13486. }
  13487. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13488. * see https://linux.die.net/man/3/bn_bn2hex */
  13489. OPENSSL_free(str_serial);
  13490. }
  13491. }
  13492. #if defined(OPENSSL_API_1_1)
  13493. #else
  13494. static void
  13495. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13496. {
  13497. (void)line;
  13498. (void)file;
  13499. if (mode & 1) {
  13500. /* 1 is CRYPTO_LOCK */
  13501. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13502. } else {
  13503. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13504. }
  13505. }
  13506. #endif /* OPENSSL_API_1_1 */
  13507. #if !defined(NO_SSL_DL)
  13508. static void *
  13509. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13510. {
  13511. union {
  13512. void *p;
  13513. void (*fp)(void);
  13514. } u;
  13515. void *dll_handle;
  13516. struct ssl_func *fp;
  13517. int ok;
  13518. int truncated = 0;
  13519. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13520. mg_snprintf(NULL,
  13521. NULL, /* No truncation check for ebuf */
  13522. ebuf,
  13523. ebuf_len,
  13524. "%s: cannot load %s",
  13525. __func__,
  13526. dll_name);
  13527. return NULL;
  13528. }
  13529. ok = 1;
  13530. for (fp = sw; fp->name != NULL; fp++) {
  13531. #if defined(_WIN32)
  13532. /* GetProcAddress() returns pointer to function */
  13533. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13534. #else
  13535. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13536. * pointers to function pointers. We need to use a union to make a
  13537. * cast. */
  13538. u.p = dlsym(dll_handle, fp->name);
  13539. #endif /* _WIN32 */
  13540. if (u.fp == NULL) {
  13541. if (ok) {
  13542. mg_snprintf(NULL,
  13543. &truncated,
  13544. ebuf,
  13545. ebuf_len,
  13546. "%s: %s: cannot find %s",
  13547. __func__,
  13548. dll_name,
  13549. fp->name);
  13550. ok = 0;
  13551. } else {
  13552. size_t cur_len = strlen(ebuf);
  13553. if (!truncated) {
  13554. mg_snprintf(NULL,
  13555. &truncated,
  13556. ebuf + cur_len,
  13557. ebuf_len - cur_len - 3,
  13558. ", %s",
  13559. fp->name);
  13560. if (truncated) {
  13561. /* If truncated, add "..." */
  13562. strcat(ebuf, "...");
  13563. }
  13564. }
  13565. }
  13566. /* Debug:
  13567. * printf("Missing function: %s\n", fp->name); */
  13568. } else {
  13569. fp->ptr = u.fp;
  13570. }
  13571. }
  13572. if (!ok) {
  13573. (void)dlclose(dll_handle);
  13574. return NULL;
  13575. }
  13576. return dll_handle;
  13577. }
  13578. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13579. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13580. #endif /* NO_SSL_DL */
  13581. #if defined(SSL_ALREADY_INITIALIZED)
  13582. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13583. #else
  13584. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13585. #endif
  13586. static int
  13587. initialize_ssl(char *ebuf, size_t ebuf_len)
  13588. {
  13589. #if defined(OPENSSL_API_1_1)
  13590. if (ebuf_len > 0) {
  13591. ebuf[0] = 0;
  13592. }
  13593. #if !defined(NO_SSL_DL)
  13594. if (!cryptolib_dll_handle) {
  13595. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13596. if (!cryptolib_dll_handle) {
  13597. mg_snprintf(NULL,
  13598. NULL, /* No truncation check for ebuf */
  13599. ebuf,
  13600. ebuf_len,
  13601. "%s: error loading library %s",
  13602. __func__,
  13603. CRYPTO_LIB);
  13604. DEBUG_TRACE("%s", ebuf);
  13605. return 0;
  13606. }
  13607. }
  13608. #endif /* NO_SSL_DL */
  13609. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13610. return 1;
  13611. }
  13612. #else /* not OPENSSL_API_1_1 */
  13613. int i, num_locks;
  13614. size_t size;
  13615. if (ebuf_len > 0) {
  13616. ebuf[0] = 0;
  13617. }
  13618. #if !defined(NO_SSL_DL)
  13619. if (!cryptolib_dll_handle) {
  13620. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13621. if (!cryptolib_dll_handle) {
  13622. mg_snprintf(NULL,
  13623. NULL, /* No truncation check for ebuf */
  13624. ebuf,
  13625. ebuf_len,
  13626. "%s: error loading library %s",
  13627. __func__,
  13628. CRYPTO_LIB);
  13629. DEBUG_TRACE("%s", ebuf);
  13630. return 0;
  13631. }
  13632. }
  13633. #endif /* NO_SSL_DL */
  13634. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13635. return 1;
  13636. }
  13637. /* Initialize locking callbacks, needed for thread safety.
  13638. * http://www.openssl.org/support/faq.html#PROG1
  13639. */
  13640. num_locks = CRYPTO_num_locks();
  13641. if (num_locks < 0) {
  13642. num_locks = 0;
  13643. }
  13644. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13645. /* allocate mutex array, if required */
  13646. if (num_locks == 0) {
  13647. /* No mutex array required */
  13648. ssl_mutexes = NULL;
  13649. } else {
  13650. /* Mutex array required - allocate it */
  13651. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13652. /* Check OOM */
  13653. if (ssl_mutexes == NULL) {
  13654. mg_snprintf(NULL,
  13655. NULL, /* No truncation check for ebuf */
  13656. ebuf,
  13657. ebuf_len,
  13658. "%s: cannot allocate mutexes: %s",
  13659. __func__,
  13660. ssl_error());
  13661. DEBUG_TRACE("%s", ebuf);
  13662. return 0;
  13663. }
  13664. /* initialize mutex array */
  13665. for (i = 0; i < num_locks; i++) {
  13666. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13667. mg_snprintf(NULL,
  13668. NULL, /* No truncation check for ebuf */
  13669. ebuf,
  13670. ebuf_len,
  13671. "%s: error initializing mutex %i of %i",
  13672. __func__,
  13673. i,
  13674. num_locks);
  13675. DEBUG_TRACE("%s", ebuf);
  13676. mg_free(ssl_mutexes);
  13677. return 0;
  13678. }
  13679. }
  13680. }
  13681. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13682. CRYPTO_set_id_callback(&mg_current_thread_id);
  13683. #endif /* OPENSSL_API_1_1 */
  13684. #if !defined(NO_SSL_DL)
  13685. if (!ssllib_dll_handle) {
  13686. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13687. if (!ssllib_dll_handle) {
  13688. #if !defined(OPENSSL_API_1_1)
  13689. mg_free(ssl_mutexes);
  13690. #endif
  13691. DEBUG_TRACE("%s", ebuf);
  13692. return 0;
  13693. }
  13694. }
  13695. #endif /* NO_SSL_DL */
  13696. #if defined(OPENSSL_API_1_1)
  13697. /* Initialize SSL library */
  13698. OPENSSL_init_ssl(0, NULL);
  13699. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13700. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13701. NULL);
  13702. #else
  13703. /* Initialize SSL library */
  13704. SSL_library_init();
  13705. SSL_load_error_strings();
  13706. #endif
  13707. return 1;
  13708. }
  13709. static int
  13710. ssl_use_pem_file(struct mg_context *phys_ctx,
  13711. struct mg_domain_context *dom_ctx,
  13712. const char *pem,
  13713. const char *chain)
  13714. {
  13715. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13716. mg_cry_ctx_internal(phys_ctx,
  13717. "%s: cannot open certificate file %s: %s",
  13718. __func__,
  13719. pem,
  13720. ssl_error());
  13721. return 0;
  13722. }
  13723. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13724. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13725. mg_cry_ctx_internal(phys_ctx,
  13726. "%s: cannot open private key file %s: %s",
  13727. __func__,
  13728. pem,
  13729. ssl_error());
  13730. return 0;
  13731. }
  13732. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13733. mg_cry_ctx_internal(phys_ctx,
  13734. "%s: certificate and private key do not match: %s",
  13735. __func__,
  13736. pem);
  13737. return 0;
  13738. }
  13739. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13740. * chain files that contain private keys and certificates in
  13741. * SSL_CTX_use_certificate_chain_file.
  13742. * The CivetWeb-Server used pem-Files that contained both information.
  13743. * In order to make wolfSSL work, it is split in two files.
  13744. * One file that contains key and certificate used by the server and
  13745. * an optional chain file for the ssl stack.
  13746. */
  13747. if (chain) {
  13748. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13749. mg_cry_ctx_internal(phys_ctx,
  13750. "%s: cannot use certificate chain file %s: %s",
  13751. __func__,
  13752. chain,
  13753. ssl_error());
  13754. return 0;
  13755. }
  13756. }
  13757. return 1;
  13758. }
  13759. #if defined(OPENSSL_API_1_1)
  13760. static unsigned long
  13761. ssl_get_protocol(int version_id)
  13762. {
  13763. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13764. if (version_id > 0)
  13765. ret |= SSL_OP_NO_SSLv2;
  13766. if (version_id > 1)
  13767. ret |= SSL_OP_NO_SSLv3;
  13768. if (version_id > 2)
  13769. ret |= SSL_OP_NO_TLSv1;
  13770. if (version_id > 3)
  13771. ret |= SSL_OP_NO_TLSv1_1;
  13772. if (version_id > 4)
  13773. ret |= SSL_OP_NO_TLSv1_2;
  13774. #if defined(SSL_OP_NO_TLSv1_3)
  13775. if (version_id > 5)
  13776. ret |= SSL_OP_NO_TLSv1_3;
  13777. #endif
  13778. return ret;
  13779. }
  13780. #else
  13781. static long
  13782. ssl_get_protocol(int version_id)
  13783. {
  13784. long ret = (long)SSL_OP_ALL;
  13785. if (version_id > 0)
  13786. ret |= SSL_OP_NO_SSLv2;
  13787. if (version_id > 1)
  13788. ret |= SSL_OP_NO_SSLv3;
  13789. if (version_id > 2)
  13790. ret |= SSL_OP_NO_TLSv1;
  13791. if (version_id > 3)
  13792. ret |= SSL_OP_NO_TLSv1_1;
  13793. if (version_id > 4)
  13794. ret |= SSL_OP_NO_TLSv1_2;
  13795. #if defined(SSL_OP_NO_TLSv1_3)
  13796. if (version_id > 5)
  13797. ret |= SSL_OP_NO_TLSv1_3;
  13798. #endif
  13799. return ret;
  13800. }
  13801. #endif /* OPENSSL_API_1_1 */
  13802. /* SSL callback documentation:
  13803. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13804. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13805. * https://linux.die.net/man/3/ssl_set_info_callback */
  13806. /* Note: There is no "const" for the first argument in the documentation
  13807. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13808. * / OpenSSL compatibility layers have it. Having a different definition will
  13809. * cause a warning in C and an error in C++. Use "const SSL *", while
  13810. * automatical conversion from "SSL *" works for all compilers, but not other
  13811. * way around */
  13812. static void
  13813. ssl_info_callback(const SSL *ssl, int what, int ret)
  13814. {
  13815. (void)ret;
  13816. if (what & SSL_CB_HANDSHAKE_START) {
  13817. SSL_get_app_data(ssl);
  13818. }
  13819. if (what & SSL_CB_HANDSHAKE_DONE) {
  13820. /* TODO: check for openSSL 1.1 */
  13821. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13822. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13823. }
  13824. }
  13825. static int
  13826. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13827. {
  13828. struct mg_context *ctx = (struct mg_context *)arg;
  13829. struct mg_domain_context *dom =
  13830. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13831. #if defined(GCC_DIAGNOSTIC)
  13832. #pragma GCC diagnostic push
  13833. #pragma GCC diagnostic ignored "-Wcast-align"
  13834. #endif /* defined(GCC_DIAGNOSTIC) */
  13835. /* We used an aligned pointer in SSL_set_app_data */
  13836. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13837. #if defined(GCC_DIAGNOSTIC)
  13838. #pragma GCC diagnostic pop
  13839. #endif /* defined(GCC_DIAGNOSTIC) */
  13840. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13841. (void)ad;
  13842. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13843. DEBUG_TRACE("%s", "internal error - assertion failed");
  13844. return SSL_TLSEXT_ERR_NOACK;
  13845. }
  13846. /* Old clients (Win XP) will not support SNI. Then, there
  13847. * is no server name available in the request - we can
  13848. * only work with the default certificate.
  13849. * Multiple HTTPS hosts on one IP+port are only possible
  13850. * with a certificate containing all alternative names.
  13851. */
  13852. if ((servername == NULL) || (*servername == 0)) {
  13853. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13854. conn->dom_ctx = &(ctx->dd);
  13855. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13856. return SSL_TLSEXT_ERR_NOACK;
  13857. }
  13858. DEBUG_TRACE("TLS connection to host %s", servername);
  13859. while (dom) {
  13860. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13861. /* Found matching domain */
  13862. DEBUG_TRACE("TLS domain %s found",
  13863. dom->config[AUTHENTICATION_DOMAIN]);
  13864. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13865. conn->dom_ctx = dom;
  13866. return SSL_TLSEXT_ERR_OK;
  13867. }
  13868. dom = dom->next;
  13869. }
  13870. /* Default domain */
  13871. DEBUG_TRACE("TLS default domain %s used",
  13872. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13873. conn->dom_ctx = &(ctx->dd);
  13874. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13875. return SSL_TLSEXT_ERR_OK;
  13876. }
  13877. /* Setup SSL CTX as required by CivetWeb */
  13878. static int
  13879. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13880. struct mg_domain_context *dom_ctx,
  13881. const char *pem,
  13882. const char *chain)
  13883. {
  13884. int callback_ret;
  13885. int should_verify_peer;
  13886. int peer_certificate_optional;
  13887. const char *ca_path;
  13888. const char *ca_file;
  13889. int use_default_verify_paths;
  13890. int verify_depth;
  13891. struct timespec now_mt;
  13892. md5_byte_t ssl_context_id[16];
  13893. md5_state_t md5state;
  13894. int protocol_ver;
  13895. #if defined(OPENSSL_API_1_1)
  13896. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13897. mg_cry_ctx_internal(phys_ctx,
  13898. "SSL_CTX_new (server) error: %s",
  13899. ssl_error());
  13900. return 0;
  13901. }
  13902. #else
  13903. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13904. mg_cry_ctx_internal(phys_ctx,
  13905. "SSL_CTX_new (server) error: %s",
  13906. ssl_error());
  13907. return 0;
  13908. }
  13909. #endif /* OPENSSL_API_1_1 */
  13910. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13911. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13912. | SSL_OP_NO_TLSv1_1);
  13913. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13914. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13915. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13916. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13917. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13918. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13919. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13920. #if defined(SSL_OP_NO_RENEGOTIATION)
  13921. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13922. #endif
  13923. #if !defined(NO_SSL_DL)
  13924. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13925. #endif /* NO_SSL_DL */
  13926. /* In SSL documentation examples callback defined without const specifier
  13927. * 'void (*)(SSL *, int, int)' See:
  13928. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13929. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13930. * But in the source code const SSL is used:
  13931. * 'void (*)(const SSL *, int, int)' See:
  13932. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13933. * Problem about wrong documentation described, but not resolved:
  13934. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13935. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13936. * But when compiled with modern C++ compiler, correct const should be
  13937. * provided
  13938. */
  13939. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13940. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13941. ssl_servername_callback);
  13942. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13943. /* If a callback has been specified, call it. */
  13944. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13945. ? 0
  13946. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13947. phys_ctx->user_data));
  13948. /* If callback returns 0, civetweb sets up the SSL certificate.
  13949. * If it returns 1, civetweb assumes the calback already did this.
  13950. * If it returns -1, initializing ssl fails. */
  13951. if (callback_ret < 0) {
  13952. mg_cry_ctx_internal(phys_ctx,
  13953. "SSL callback returned error: %i",
  13954. callback_ret);
  13955. return 0;
  13956. }
  13957. if (callback_ret > 0) {
  13958. /* Callback did everything. */
  13959. return 1;
  13960. }
  13961. /* If a domain callback has been specified, call it. */
  13962. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  13963. ? 0
  13964. : (phys_ctx->callbacks.init_ssl_domain(
  13965. dom_ctx->config[AUTHENTICATION_DOMAIN],
  13966. dom_ctx->ssl_ctx,
  13967. phys_ctx->user_data));
  13968. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  13969. * If it returns 1, civetweb assumes the calback already did this.
  13970. * If it returns -1, initializing ssl fails. */
  13971. if (callback_ret < 0) {
  13972. mg_cry_ctx_internal(phys_ctx,
  13973. "Domain SSL callback returned error: %i",
  13974. callback_ret);
  13975. return 0;
  13976. }
  13977. if (callback_ret > 0) {
  13978. /* Domain callback did everything. */
  13979. return 1;
  13980. }
  13981. /* Use some combination of start time, domain and port as a SSL
  13982. * context ID. This should be unique on the current machine. */
  13983. md5_init(&md5state);
  13984. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13985. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13986. md5_append(&md5state,
  13987. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13988. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13989. md5_append(&md5state,
  13990. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13991. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13992. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13993. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13994. md5_finish(&md5state, ssl_context_id);
  13995. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13996. (unsigned char *)ssl_context_id,
  13997. sizeof(ssl_context_id));
  13998. if (pem != NULL) {
  13999. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14000. return 0;
  14001. }
  14002. }
  14003. /* Should we support client certificates? */
  14004. /* Default is "no". */
  14005. should_verify_peer = 0;
  14006. peer_certificate_optional = 0;
  14007. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14008. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14009. /* Yes, they are mandatory */
  14010. should_verify_peer = 1;
  14011. peer_certificate_optional = 0;
  14012. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14013. "optional")
  14014. == 0) {
  14015. /* Yes, they are optional */
  14016. should_verify_peer = 1;
  14017. peer_certificate_optional = 1;
  14018. }
  14019. }
  14020. use_default_verify_paths =
  14021. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14022. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14023. == 0);
  14024. if (should_verify_peer) {
  14025. ca_path = dom_ctx->config[SSL_CA_PATH];
  14026. ca_file = dom_ctx->config[SSL_CA_FILE];
  14027. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14028. != 1) {
  14029. mg_cry_ctx_internal(phys_ctx,
  14030. "SSL_CTX_load_verify_locations error: %s "
  14031. "ssl_verify_peer requires setting "
  14032. "either ssl_ca_path or ssl_ca_file. "
  14033. "Is any of them present in the "
  14034. ".conf file?",
  14035. ssl_error());
  14036. return 0;
  14037. }
  14038. if (peer_certificate_optional) {
  14039. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14040. } else {
  14041. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14042. SSL_VERIFY_PEER
  14043. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14044. NULL);
  14045. }
  14046. if (use_default_verify_paths
  14047. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14048. mg_cry_ctx_internal(phys_ctx,
  14049. "SSL_CTX_set_default_verify_paths error: %s",
  14050. ssl_error());
  14051. return 0;
  14052. }
  14053. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14054. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14055. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14056. }
  14057. }
  14058. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14059. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14060. dom_ctx->config[SSL_CIPHER_LIST])
  14061. != 1) {
  14062. mg_cry_ctx_internal(phys_ctx,
  14063. "SSL_CTX_set_cipher_list error: %s",
  14064. ssl_error());
  14065. }
  14066. }
  14067. return 1;
  14068. }
  14069. /* Check if SSL is required.
  14070. * If so, dynamically load SSL library
  14071. * and set up ctx->ssl_ctx pointer. */
  14072. static int
  14073. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14074. {
  14075. void *ssl_ctx = 0;
  14076. int callback_ret;
  14077. const char *pem;
  14078. const char *chain;
  14079. char ebuf[128];
  14080. if (!phys_ctx) {
  14081. return 0;
  14082. }
  14083. if (!dom_ctx) {
  14084. dom_ctx = &(phys_ctx->dd);
  14085. }
  14086. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14087. /* No SSL port is set. No need to setup SSL. */
  14088. return 1;
  14089. }
  14090. /* Check for external SSL_CTX */
  14091. callback_ret =
  14092. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14093. ? 0
  14094. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14095. phys_ctx->user_data));
  14096. if (callback_ret < 0) {
  14097. mg_cry_ctx_internal(phys_ctx,
  14098. "external_ssl_ctx callback returned error: %i",
  14099. callback_ret);
  14100. return 0;
  14101. } else if (callback_ret > 0) {
  14102. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14103. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14104. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14105. return 0;
  14106. }
  14107. return 1;
  14108. }
  14109. /* Check for external domain SSL_CTX */
  14110. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14111. ? 0
  14112. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14113. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14114. &ssl_ctx,
  14115. phys_ctx->user_data));
  14116. if (callback_ret < 0) {
  14117. mg_cry_ctx_internal(
  14118. phys_ctx,
  14119. "external_ssl_ctx_domain callback returned error: %i",
  14120. callback_ret);
  14121. return 0;
  14122. } else if (callback_ret > 0) {
  14123. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14124. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14125. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14126. return 0;
  14127. }
  14128. return 1;
  14129. }
  14130. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return 0,
  14131. * CivetWeb should continue initializing SSL */
  14132. /* If PEM file is not specified and the init_ssl callbacks
  14133. * are not specified, setup will fail. */
  14134. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14135. && (phys_ctx->callbacks.init_ssl == NULL)
  14136. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14137. /* No certificate and no init_ssl callbacks:
  14138. * Essential data to set up TLS is missing.
  14139. */
  14140. mg_cry_ctx_internal(phys_ctx,
  14141. "Initializing SSL failed: -%s is not set",
  14142. config_options[SSL_CERTIFICATE].name);
  14143. return 0;
  14144. }
  14145. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14146. if (chain == NULL) {
  14147. chain = pem;
  14148. }
  14149. if ((chain != NULL) && (*chain == 0)) {
  14150. chain = NULL;
  14151. }
  14152. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14153. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14154. return 0;
  14155. }
  14156. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14157. }
  14158. static void
  14159. uninitialize_ssl(void)
  14160. {
  14161. #if defined(OPENSSL_API_1_1)
  14162. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14163. /* Shutdown according to
  14164. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14165. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14166. */
  14167. CONF_modules_unload(1);
  14168. #else
  14169. int i;
  14170. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14171. /* Shutdown according to
  14172. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14173. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14174. */
  14175. CRYPTO_set_locking_callback(NULL);
  14176. CRYPTO_set_id_callback(NULL);
  14177. ENGINE_cleanup();
  14178. CONF_modules_unload(1);
  14179. ERR_free_strings();
  14180. EVP_cleanup();
  14181. CRYPTO_cleanup_all_ex_data();
  14182. OPENSSL_REMOVE_THREAD_STATE();
  14183. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14184. pthread_mutex_destroy(&ssl_mutexes[i]);
  14185. }
  14186. mg_free(ssl_mutexes);
  14187. ssl_mutexes = NULL;
  14188. #endif /* OPENSSL_API_1_1 */
  14189. }
  14190. }
  14191. #endif /* !NO_SSL */
  14192. #if !defined(NO_FILESYSTEMS)
  14193. static int
  14194. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14195. {
  14196. if (phys_ctx) {
  14197. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14198. const char *path;
  14199. struct mg_connection fc;
  14200. if (!dom_ctx) {
  14201. dom_ctx = &(phys_ctx->dd);
  14202. }
  14203. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14204. if ((path != NULL)
  14205. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14206. mg_cry_ctx_internal(phys_ctx,
  14207. "Cannot open %s: %s",
  14208. path,
  14209. strerror(ERRNO));
  14210. return 0;
  14211. }
  14212. return 1;
  14213. }
  14214. return 0;
  14215. }
  14216. #endif /* NO_FILESYSTEMS */
  14217. static int
  14218. set_acl_option(struct mg_context *phys_ctx)
  14219. {
  14220. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14221. }
  14222. static void
  14223. reset_per_request_attributes(struct mg_connection *conn)
  14224. {
  14225. if (!conn) {
  14226. return;
  14227. }
  14228. conn->connection_type =
  14229. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14230. conn->num_bytes_sent = conn->consumed_content = 0;
  14231. conn->path_info = NULL;
  14232. conn->status_code = -1;
  14233. conn->content_len = -1;
  14234. conn->is_chunked = 0;
  14235. conn->must_close = 0;
  14236. conn->request_len = 0;
  14237. conn->throttle = 0;
  14238. conn->accept_gzip = 0;
  14239. conn->response_info.content_length = conn->request_info.content_length = -1;
  14240. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14241. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14242. conn->response_info.status_text = NULL;
  14243. conn->response_info.status_code = 0;
  14244. conn->request_info.remote_user = NULL;
  14245. conn->request_info.request_method = NULL;
  14246. conn->request_info.request_uri = NULL;
  14247. conn->request_info.local_uri = NULL;
  14248. #if defined(MG_LEGACY_INTERFACE)
  14249. /* Legacy before split into local_uri and request_uri */
  14250. conn->request_info.uri = NULL;
  14251. #endif
  14252. }
  14253. static int
  14254. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14255. {
  14256. if (setsockopt(sock,
  14257. IPPROTO_TCP,
  14258. TCP_NODELAY,
  14259. (SOCK_OPT_TYPE)&nodelay_on,
  14260. sizeof(nodelay_on))
  14261. != 0) {
  14262. /* Error */
  14263. return 1;
  14264. }
  14265. /* OK */
  14266. return 0;
  14267. }
  14268. #if !defined(__ZEPHYR__)
  14269. static void
  14270. close_socket_gracefully(struct mg_connection *conn)
  14271. {
  14272. #if defined(_WIN32)
  14273. char buf[MG_BUF_LEN];
  14274. int n;
  14275. #endif
  14276. struct linger linger;
  14277. int error_code = 0;
  14278. int linger_timeout = -2;
  14279. socklen_t opt_len = sizeof(error_code);
  14280. if (!conn) {
  14281. return;
  14282. }
  14283. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14284. * "Note that enabling a nonzero timeout on a nonblocking socket
  14285. * is not recommended.", so set it to blocking now */
  14286. set_blocking_mode(conn->client.sock);
  14287. /* Send FIN to the client */
  14288. shutdown(conn->client.sock, SHUTDOWN_WR);
  14289. #if defined(_WIN32)
  14290. /* Read and discard pending incoming data. If we do not do that and
  14291. * close
  14292. * the socket, the data in the send buffer may be discarded. This
  14293. * behaviour is seen on Windows, when client keeps sending data
  14294. * when server decides to close the connection; then when client
  14295. * does recv() it gets no data back. */
  14296. do {
  14297. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14298. } while (n > 0);
  14299. #endif
  14300. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14301. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14302. }
  14303. /* Set linger option according to configuration */
  14304. if (linger_timeout >= 0) {
  14305. /* Set linger option to avoid socket hanging out after close. This
  14306. * prevent ephemeral port exhaust problem under high QPS. */
  14307. linger.l_onoff = 1;
  14308. #if defined(_MSC_VER)
  14309. #pragma warning(push)
  14310. #pragma warning(disable : 4244)
  14311. #endif
  14312. #if defined(GCC_DIAGNOSTIC)
  14313. #pragma GCC diagnostic push
  14314. #pragma GCC diagnostic ignored "-Wconversion"
  14315. #endif
  14316. /* Data type of linger structure elements may differ,
  14317. * so we don't know what cast we need here.
  14318. * Disable type conversion warnings. */
  14319. linger.l_linger = (linger_timeout + 999) / 1000;
  14320. #if defined(GCC_DIAGNOSTIC)
  14321. #pragma GCC diagnostic pop
  14322. #endif
  14323. #if defined(_MSC_VER)
  14324. #pragma warning(pop)
  14325. #endif
  14326. } else {
  14327. linger.l_onoff = 0;
  14328. linger.l_linger = 0;
  14329. }
  14330. if (linger_timeout < -1) {
  14331. /* Default: don't configure any linger */
  14332. } else if (getsockopt(conn->client.sock,
  14333. SOL_SOCKET,
  14334. SO_ERROR,
  14335. #if defined(_WIN32) /* WinSock uses different data type here */
  14336. (char *)&error_code,
  14337. #else
  14338. &error_code,
  14339. #endif
  14340. &opt_len)
  14341. != 0) {
  14342. /* Cannot determine if socket is already closed. This should
  14343. * not occur and never did in a test. Log an error message
  14344. * and continue. */
  14345. mg_cry_internal(conn,
  14346. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14347. __func__,
  14348. strerror(ERRNO));
  14349. #if defined(_WIN32)
  14350. } else if (error_code == WSAECONNRESET) {
  14351. #else
  14352. } else if (error_code == ECONNRESET) {
  14353. #endif
  14354. /* Socket already closed by client/peer, close socket without linger
  14355. */
  14356. } else {
  14357. /* Set linger timeout */
  14358. if (setsockopt(conn->client.sock,
  14359. SOL_SOCKET,
  14360. SO_LINGER,
  14361. (char *)&linger,
  14362. sizeof(linger))
  14363. != 0) {
  14364. mg_cry_internal(
  14365. conn,
  14366. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14367. __func__,
  14368. linger.l_onoff,
  14369. linger.l_linger,
  14370. strerror(ERRNO));
  14371. }
  14372. }
  14373. /* Now we know that our FIN is ACK-ed, safe to close */
  14374. closesocket(conn->client.sock);
  14375. conn->client.sock = INVALID_SOCKET;
  14376. }
  14377. #endif
  14378. static void
  14379. close_connection(struct mg_connection *conn)
  14380. {
  14381. #if defined(USE_SERVER_STATS)
  14382. conn->conn_state = 6; /* to close */
  14383. #endif
  14384. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14385. if (conn->lua_websocket_state) {
  14386. lua_websocket_close(conn, conn->lua_websocket_state);
  14387. conn->lua_websocket_state = NULL;
  14388. }
  14389. #endif
  14390. mg_lock_connection(conn);
  14391. /* Set close flag, so keep-alive loops will stop */
  14392. conn->must_close = 1;
  14393. /* call the connection_close callback if assigned */
  14394. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14395. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14396. conn->phys_ctx->callbacks.connection_close(conn);
  14397. }
  14398. }
  14399. /* Reset user data, after close callback is called.
  14400. * Do not reuse it. If the user needs a destructor,
  14401. * it must be done in the connection_close callback. */
  14402. mg_set_user_connection_data(conn, NULL);
  14403. #if defined(USE_SERVER_STATS)
  14404. conn->conn_state = 7; /* closing */
  14405. #endif
  14406. #if !defined(NO_SSL)
  14407. if (conn->ssl != NULL) {
  14408. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14409. */
  14410. SSL_shutdown(conn->ssl);
  14411. SSL_free(conn->ssl);
  14412. OPENSSL_REMOVE_THREAD_STATE();
  14413. conn->ssl = NULL;
  14414. }
  14415. #endif
  14416. if (conn->client.sock != INVALID_SOCKET) {
  14417. #if defined(__ZEPHYR__)
  14418. closesocket(conn->client.sock);
  14419. #else
  14420. close_socket_gracefully(conn);
  14421. #endif
  14422. conn->client.sock = INVALID_SOCKET;
  14423. }
  14424. if (conn->host) {
  14425. mg_free((void *)conn->host);
  14426. conn->host = NULL;
  14427. }
  14428. mg_unlock_connection(conn);
  14429. #if defined(USE_SERVER_STATS)
  14430. conn->conn_state = 8; /* closed */
  14431. #endif
  14432. }
  14433. void
  14434. mg_close_connection(struct mg_connection *conn)
  14435. {
  14436. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14437. return;
  14438. }
  14439. #if defined(USE_WEBSOCKET)
  14440. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14441. if (conn->in_websocket_handling) {
  14442. /* Set close flag, so the server thread can exit. */
  14443. conn->must_close = 1;
  14444. return;
  14445. }
  14446. }
  14447. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14448. unsigned int i;
  14449. /* client context: loops must end */
  14450. conn->phys_ctx->stop_flag = 1;
  14451. conn->must_close = 1;
  14452. /* We need to get the client thread out of the select/recv call
  14453. * here. */
  14454. /* Since we use a sleep quantum of some seconds to check for recv
  14455. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14456. /* join worker thread */
  14457. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14458. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14459. }
  14460. }
  14461. #endif /* defined(USE_WEBSOCKET) */
  14462. close_connection(conn);
  14463. #if !defined(NO_SSL)
  14464. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14465. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14466. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14467. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14468. }
  14469. #endif
  14470. #if defined(USE_WEBSOCKET)
  14471. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14472. mg_free(conn->phys_ctx->worker_threadids);
  14473. (void)pthread_mutex_destroy(&conn->mutex);
  14474. mg_free(conn);
  14475. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14476. mg_free(conn);
  14477. }
  14478. #else
  14479. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14480. mg_free(conn);
  14481. }
  14482. #endif /* defined(USE_WEBSOCKET) */
  14483. }
  14484. static struct mg_connection *
  14485. mg_connect_client_impl(const struct mg_client_options *client_options,
  14486. int use_ssl,
  14487. char *ebuf,
  14488. size_t ebuf_len)
  14489. {
  14490. struct mg_connection *conn = NULL;
  14491. SOCKET sock;
  14492. union usa sa;
  14493. struct sockaddr *psa;
  14494. socklen_t len;
  14495. unsigned max_req_size =
  14496. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14497. /* Size of structures, aligned to 8 bytes */
  14498. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14499. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14500. conn =
  14501. (struct mg_connection *)mg_calloc(1,
  14502. conn_size + ctx_size + max_req_size);
  14503. if (conn == NULL) {
  14504. mg_snprintf(NULL,
  14505. NULL, /* No truncation check for ebuf */
  14506. ebuf,
  14507. ebuf_len,
  14508. "calloc(): %s",
  14509. strerror(ERRNO));
  14510. return NULL;
  14511. }
  14512. #if defined(GCC_DIAGNOSTIC)
  14513. #pragma GCC diagnostic push
  14514. #pragma GCC diagnostic ignored "-Wcast-align"
  14515. #endif /* defined(GCC_DIAGNOSTIC) */
  14516. /* conn_size is aligned to 8 bytes */
  14517. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14518. #if defined(GCC_DIAGNOSTIC)
  14519. #pragma GCC diagnostic pop
  14520. #endif /* defined(GCC_DIAGNOSTIC) */
  14521. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14522. conn->buf_size = (int)max_req_size;
  14523. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14524. conn->dom_ctx = &(conn->phys_ctx->dd);
  14525. if (!connect_socket(conn->phys_ctx,
  14526. client_options->host,
  14527. client_options->port,
  14528. use_ssl,
  14529. ebuf,
  14530. ebuf_len,
  14531. &sock,
  14532. &sa)) {
  14533. /* ebuf is set by connect_socket,
  14534. * free all memory and return NULL; */
  14535. mg_free(conn);
  14536. return NULL;
  14537. }
  14538. #if !defined(NO_SSL)
  14539. #if defined(OPENSSL_API_1_1)
  14540. if (use_ssl
  14541. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14542. == NULL) {
  14543. mg_snprintf(NULL,
  14544. NULL, /* No truncation check for ebuf */
  14545. ebuf,
  14546. ebuf_len,
  14547. "SSL_CTX_new error: %s",
  14548. ssl_error());
  14549. closesocket(sock);
  14550. mg_free(conn);
  14551. return NULL;
  14552. }
  14553. #else
  14554. if (use_ssl
  14555. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14556. == NULL) {
  14557. mg_snprintf(NULL,
  14558. NULL, /* No truncation check for ebuf */
  14559. ebuf,
  14560. ebuf_len,
  14561. "SSL_CTX_new error: %s",
  14562. ssl_error());
  14563. closesocket(sock);
  14564. mg_free(conn);
  14565. return NULL;
  14566. }
  14567. #endif /* OPENSSL_API_1_1 */
  14568. #endif /* NO_SSL */
  14569. #if defined(USE_IPV6)
  14570. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14571. : sizeof(conn->client.rsa.sin6);
  14572. psa = (sa.sa.sa_family == AF_INET)
  14573. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14574. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14575. #else
  14576. len = sizeof(conn->client.rsa.sin);
  14577. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14578. #endif
  14579. conn->client.sock = sock;
  14580. conn->client.lsa = sa;
  14581. if (getsockname(sock, psa, &len) != 0) {
  14582. mg_cry_internal(conn,
  14583. "%s: getsockname() failed: %s",
  14584. __func__,
  14585. strerror(ERRNO));
  14586. }
  14587. conn->client.is_ssl = use_ssl ? 1 : 0;
  14588. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14589. mg_snprintf(NULL,
  14590. NULL, /* No truncation check for ebuf */
  14591. ebuf,
  14592. ebuf_len,
  14593. "Can not create mutex");
  14594. #if !defined(NO_SSL)
  14595. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14596. #endif
  14597. closesocket(sock);
  14598. mg_free(conn);
  14599. return NULL;
  14600. }
  14601. #if !defined(NO_SSL)
  14602. if (use_ssl) {
  14603. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14604. * SSL_CTX_set_verify call is needed to switch off server
  14605. * certificate checking, which is off by default in OpenSSL and
  14606. * on in yaSSL. */
  14607. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14608. * SSL_VERIFY_PEER, verify_ssl_server); */
  14609. if (client_options->client_cert) {
  14610. if (!ssl_use_pem_file(conn->phys_ctx,
  14611. conn->dom_ctx,
  14612. client_options->client_cert,
  14613. NULL)) {
  14614. mg_snprintf(NULL,
  14615. NULL, /* No truncation check for ebuf */
  14616. ebuf,
  14617. ebuf_len,
  14618. "Can not use SSL client certificate");
  14619. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14620. closesocket(sock);
  14621. mg_free(conn);
  14622. return NULL;
  14623. }
  14624. }
  14625. if (client_options->server_cert) {
  14626. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14627. client_options->server_cert,
  14628. NULL)
  14629. != 1) {
  14630. mg_cry_internal(conn,
  14631. "SSL_CTX_load_verify_locations error: %s ",
  14632. ssl_error());
  14633. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14634. closesocket(sock);
  14635. mg_free(conn);
  14636. return NULL;
  14637. }
  14638. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14639. } else {
  14640. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14641. }
  14642. if (!sslize(conn,
  14643. conn->dom_ctx->ssl_ctx,
  14644. SSL_connect,
  14645. &(conn->phys_ctx->stop_flag),
  14646. client_options)) {
  14647. mg_snprintf(NULL,
  14648. NULL, /* No truncation check for ebuf */
  14649. ebuf,
  14650. ebuf_len,
  14651. "SSL connection error");
  14652. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14653. closesocket(sock);
  14654. mg_free(conn);
  14655. return NULL;
  14656. }
  14657. }
  14658. #endif
  14659. return conn;
  14660. }
  14661. CIVETWEB_API struct mg_connection *
  14662. mg_connect_client_secure(const struct mg_client_options *client_options,
  14663. char *error_buffer,
  14664. size_t error_buffer_size)
  14665. {
  14666. return mg_connect_client_impl(client_options,
  14667. 1,
  14668. error_buffer,
  14669. error_buffer_size);
  14670. }
  14671. struct mg_connection *
  14672. mg_connect_client(const char *host,
  14673. int port,
  14674. int use_ssl,
  14675. char *error_buffer,
  14676. size_t error_buffer_size)
  14677. {
  14678. struct mg_client_options opts;
  14679. memset(&opts, 0, sizeof(opts));
  14680. opts.host = host;
  14681. opts.port = port;
  14682. return mg_connect_client_impl(&opts,
  14683. use_ssl,
  14684. error_buffer,
  14685. error_buffer_size);
  14686. }
  14687. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14688. struct mg_connection *
  14689. mg_connect_client2(const char *host,
  14690. const char *protocol,
  14691. int port,
  14692. const char *path,
  14693. struct mg_init_data *init,
  14694. struct mg_error_data *error)
  14695. {
  14696. int is_ssl, is_ws;
  14697. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14698. if (error != NULL) {
  14699. error->code = 0;
  14700. if (error->text_buffer_size > 0) {
  14701. *error->text = 0;
  14702. }
  14703. }
  14704. if ((host == NULL) || (protocol == NULL)) {
  14705. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14706. mg_snprintf(NULL,
  14707. NULL, /* No truncation check for error buffers */
  14708. error->text,
  14709. error->text_buffer_size,
  14710. "%s",
  14711. "Invalid parameters");
  14712. }
  14713. return NULL;
  14714. }
  14715. /* check all known protocolls */
  14716. if (!mg_strcasecmp(protocol, "http")) {
  14717. is_ssl = 0;
  14718. is_ws = 0;
  14719. } else if (!mg_strcasecmp(protocol, "https")) {
  14720. is_ssl = 1;
  14721. is_ws = 0;
  14722. #if defined(USE_WEBSOCKET)
  14723. } else if (!mg_strcasecmp(protocol, "ws")) {
  14724. is_ssl = 0;
  14725. is_ws = 1;
  14726. } else if (!mg_strcasecmp(protocol, "wss")) {
  14727. is_ssl = 1;
  14728. is_ws = 1;
  14729. #endif
  14730. } else {
  14731. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14732. mg_snprintf(NULL,
  14733. NULL, /* No truncation check for error buffers */
  14734. error->text,
  14735. error->text_buffer_size,
  14736. "Protocol %s not supported",
  14737. protocol);
  14738. }
  14739. return NULL;
  14740. }
  14741. /* TODO: The current implementation here just calls the old implementations,
  14742. * without using any new options. This is just a first step to test the new
  14743. * interfaces. */
  14744. #if defined(USE_WEBSOCKET)
  14745. if (is_ws) {
  14746. /* TODO: implement all options */
  14747. return mg_connect_websocket_client(host,
  14748. port,
  14749. is_ssl,
  14750. error->text,
  14751. error->text_buffer_size,
  14752. (path ? path : ""),
  14753. NULL /* TODO: origin */,
  14754. deprecated_websocket_data_wrapper,
  14755. deprecated_websocket_close_wrapper,
  14756. (void *)init->callbacks);
  14757. }
  14758. #endif
  14759. /* TODO: all additional options */
  14760. struct mg_client_options opts;
  14761. memset(&opts, 0, sizeof(opts));
  14762. opts.host = host;
  14763. opts.port = port;
  14764. return mg_connect_client_impl(&opts,
  14765. is_ssl,
  14766. error->text,
  14767. error->text_buffer_size);
  14768. }
  14769. #endif
  14770. static const struct {
  14771. const char *proto;
  14772. size_t proto_len;
  14773. unsigned default_port;
  14774. } abs_uri_protocols[] = {{"http://", 7, 80},
  14775. {"https://", 8, 443},
  14776. {"ws://", 5, 80},
  14777. {"wss://", 6, 443},
  14778. {NULL, 0, 0}};
  14779. /* Check if the uri is valid.
  14780. * return 0 for invalid uri,
  14781. * return 1 for *,
  14782. * return 2 for relative uri,
  14783. * return 3 for absolute uri without port,
  14784. * return 4 for absolute uri with port */
  14785. static int
  14786. get_uri_type(const char *uri)
  14787. {
  14788. int i;
  14789. const char *hostend, *portbegin;
  14790. char *portend;
  14791. unsigned long port;
  14792. /* According to the HTTP standard
  14793. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14794. * URI can be an asterisk (*) or should start with slash (relative uri),
  14795. * or it should start with the protocol (absolute uri). */
  14796. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14797. /* asterisk */
  14798. return 1;
  14799. }
  14800. /* Valid URIs according to RFC 3986
  14801. * (https://www.ietf.org/rfc/rfc3986.txt)
  14802. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14803. * and unreserved characters A-Z a-z 0-9 and -._~
  14804. * and % encoded symbols.
  14805. */
  14806. for (i = 0; uri[i] != 0; i++) {
  14807. if (uri[i] < 33) {
  14808. /* control characters and spaces are invalid */
  14809. return 0;
  14810. }
  14811. if (uri[i] > 126) {
  14812. /* non-ascii characters must be % encoded */
  14813. return 0;
  14814. } else {
  14815. switch (uri[i]) {
  14816. case '"': /* 34 */
  14817. case '<': /* 60 */
  14818. case '>': /* 62 */
  14819. case '\\': /* 92 */
  14820. case '^': /* 94 */
  14821. case '`': /* 96 */
  14822. case '{': /* 123 */
  14823. case '|': /* 124 */
  14824. case '}': /* 125 */
  14825. return 0;
  14826. default:
  14827. /* character is ok */
  14828. break;
  14829. }
  14830. }
  14831. }
  14832. /* A relative uri starts with a / character */
  14833. if (uri[0] == '/') {
  14834. /* relative uri */
  14835. return 2;
  14836. }
  14837. /* It could be an absolute uri: */
  14838. /* This function only checks if the uri is valid, not if it is
  14839. * addressing the current server. So civetweb can also be used
  14840. * as a proxy server. */
  14841. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14842. if (mg_strncasecmp(uri,
  14843. abs_uri_protocols[i].proto,
  14844. abs_uri_protocols[i].proto_len)
  14845. == 0) {
  14846. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14847. if (!hostend) {
  14848. return 0;
  14849. }
  14850. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14851. if (!portbegin) {
  14852. return 3;
  14853. }
  14854. port = strtoul(portbegin + 1, &portend, 10);
  14855. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14856. return 0;
  14857. }
  14858. return 4;
  14859. }
  14860. }
  14861. return 0;
  14862. }
  14863. /* Return NULL or the relative uri at the current server */
  14864. static const char *
  14865. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14866. {
  14867. const char *server_domain;
  14868. size_t server_domain_len;
  14869. size_t request_domain_len = 0;
  14870. unsigned long port = 0;
  14871. int i, auth_domain_check_enabled;
  14872. const char *hostbegin = NULL;
  14873. const char *hostend = NULL;
  14874. const char *portbegin;
  14875. char *portend;
  14876. auth_domain_check_enabled =
  14877. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14878. /* DNS is case insensitive, so use case insensitive string compare here
  14879. */
  14880. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14881. if (mg_strncasecmp(uri,
  14882. abs_uri_protocols[i].proto,
  14883. abs_uri_protocols[i].proto_len)
  14884. == 0) {
  14885. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14886. hostend = strchr(hostbegin, '/');
  14887. if (!hostend) {
  14888. return 0;
  14889. }
  14890. portbegin = strchr(hostbegin, ':');
  14891. if ((!portbegin) || (portbegin > hostend)) {
  14892. port = abs_uri_protocols[i].default_port;
  14893. request_domain_len = (size_t)(hostend - hostbegin);
  14894. } else {
  14895. port = strtoul(portbegin + 1, &portend, 10);
  14896. if ((portend != hostend) || (port <= 0)
  14897. || !is_valid_port(port)) {
  14898. return 0;
  14899. }
  14900. request_domain_len = (size_t)(portbegin - hostbegin);
  14901. }
  14902. /* protocol found, port set */
  14903. break;
  14904. }
  14905. }
  14906. if (!port) {
  14907. /* port remains 0 if the protocol is not found */
  14908. return 0;
  14909. }
  14910. /* Check if the request is directed to a different server. */
  14911. /* First check if the port is the same (IPv4 and IPv6). */
  14912. #if defined(USE_IPV6)
  14913. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14914. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14915. /* Request is directed to a different port */
  14916. return 0;
  14917. }
  14918. } else
  14919. #endif
  14920. {
  14921. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14922. /* Request is directed to a different port */
  14923. return 0;
  14924. }
  14925. }
  14926. /* Finally check if the server corresponds to the authentication
  14927. * domain of the server (the server domain).
  14928. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14929. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14930. * but do not allow substrings (like
  14931. * http://notmydomain.com/path/file.ext
  14932. * or http://mydomain.com.fake/path/file.ext).
  14933. */
  14934. if (auth_domain_check_enabled) {
  14935. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14936. server_domain_len = strlen(server_domain);
  14937. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14938. return 0;
  14939. }
  14940. if ((request_domain_len == server_domain_len)
  14941. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14942. /* Request is directed to this server - full name match. */
  14943. } else {
  14944. if (request_domain_len < (server_domain_len + 2)) {
  14945. /* Request is directed to another server: The server name
  14946. * is longer than the request name.
  14947. * Drop this case here to avoid overflows in the
  14948. * following checks. */
  14949. return 0;
  14950. }
  14951. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14952. /* Request is directed to another server: It could be a
  14953. * substring
  14954. * like notmyserver.com */
  14955. return 0;
  14956. }
  14957. if (0
  14958. != memcmp(server_domain,
  14959. hostbegin + request_domain_len - server_domain_len,
  14960. server_domain_len)) {
  14961. /* Request is directed to another server:
  14962. * The server name is different. */
  14963. return 0;
  14964. }
  14965. }
  14966. }
  14967. return hostend;
  14968. }
  14969. static int
  14970. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14971. {
  14972. if (ebuf_len > 0) {
  14973. ebuf[0] = '\0';
  14974. }
  14975. *err = 0;
  14976. reset_per_request_attributes(conn);
  14977. if (!conn) {
  14978. mg_snprintf(conn,
  14979. NULL, /* No truncation check for ebuf */
  14980. ebuf,
  14981. ebuf_len,
  14982. "%s",
  14983. "Internal error");
  14984. *err = 500;
  14985. return 0;
  14986. }
  14987. /* Set the time the request was received. This value should be used for
  14988. * timeouts. */
  14989. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14990. conn->request_len =
  14991. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14992. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14993. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14994. mg_snprintf(conn,
  14995. NULL, /* No truncation check for ebuf */
  14996. ebuf,
  14997. ebuf_len,
  14998. "%s",
  14999. "Invalid message size");
  15000. *err = 500;
  15001. return 0;
  15002. }
  15003. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15004. mg_snprintf(conn,
  15005. NULL, /* No truncation check for ebuf */
  15006. ebuf,
  15007. ebuf_len,
  15008. "%s",
  15009. "Message too large");
  15010. *err = 413;
  15011. return 0;
  15012. }
  15013. if (conn->request_len <= 0) {
  15014. if (conn->data_len > 0) {
  15015. mg_snprintf(conn,
  15016. NULL, /* No truncation check for ebuf */
  15017. ebuf,
  15018. ebuf_len,
  15019. "%s",
  15020. "Malformed message");
  15021. *err = 400;
  15022. } else {
  15023. /* Server did not recv anything -> just close the connection */
  15024. conn->must_close = 1;
  15025. mg_snprintf(conn,
  15026. NULL, /* No truncation check for ebuf */
  15027. ebuf,
  15028. ebuf_len,
  15029. "%s",
  15030. "No data received");
  15031. *err = 0;
  15032. }
  15033. return 0;
  15034. }
  15035. return 1;
  15036. }
  15037. static int
  15038. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15039. {
  15040. const char *cl;
  15041. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15042. return 0;
  15043. }
  15044. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15045. <= 0) {
  15046. mg_snprintf(conn,
  15047. NULL, /* No truncation check for ebuf */
  15048. ebuf,
  15049. ebuf_len,
  15050. "%s",
  15051. "Bad request");
  15052. *err = 400;
  15053. return 0;
  15054. }
  15055. /* Message is a valid request */
  15056. /* Is there a "host" ? */
  15057. if (conn->host != NULL) {
  15058. mg_free((void *)conn->host);
  15059. }
  15060. conn->host = alloc_get_host(conn);
  15061. if (!conn->host) {
  15062. mg_snprintf(conn,
  15063. NULL, /* No truncation check for ebuf */
  15064. ebuf,
  15065. ebuf_len,
  15066. "%s",
  15067. "Bad request: Host mismatch");
  15068. *err = 400;
  15069. return 0;
  15070. }
  15071. if (((cl = get_header(conn->request_info.http_headers,
  15072. conn->request_info.num_headers,
  15073. "Transfer-Encoding"))
  15074. != NULL)
  15075. && mg_strcasecmp(cl, "identity")) {
  15076. if (mg_strcasecmp(cl, "chunked")) {
  15077. mg_snprintf(conn,
  15078. NULL, /* No truncation check for ebuf */
  15079. ebuf,
  15080. ebuf_len,
  15081. "%s",
  15082. "Bad request");
  15083. *err = 400;
  15084. return 0;
  15085. }
  15086. conn->is_chunked = 1;
  15087. conn->content_len = 0; /* not yet read */
  15088. } else if ((cl = get_header(conn->request_info.http_headers,
  15089. conn->request_info.num_headers,
  15090. "Content-Length"))
  15091. != NULL) {
  15092. /* Request has content length set */
  15093. char *endptr = NULL;
  15094. conn->content_len = strtoll(cl, &endptr, 10);
  15095. if ((endptr == cl) || (conn->content_len < 0)) {
  15096. mg_snprintf(conn,
  15097. NULL, /* No truncation check for ebuf */
  15098. ebuf,
  15099. ebuf_len,
  15100. "%s",
  15101. "Bad request");
  15102. *err = 411;
  15103. return 0;
  15104. }
  15105. /* Publish the content length back to the request info. */
  15106. conn->request_info.content_length = conn->content_len;
  15107. } else {
  15108. /* There is no exception, see RFC7230. */
  15109. conn->content_len = 0;
  15110. }
  15111. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15112. return 1;
  15113. }
  15114. /* conn is assumed to be valid in this internal function */
  15115. static int
  15116. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15117. {
  15118. const char *cl;
  15119. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15120. return 0;
  15121. }
  15122. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15123. <= 0) {
  15124. mg_snprintf(conn,
  15125. NULL, /* No truncation check for ebuf */
  15126. ebuf,
  15127. ebuf_len,
  15128. "%s",
  15129. "Bad response");
  15130. *err = 400;
  15131. return 0;
  15132. }
  15133. /* Message is a valid response */
  15134. if (((cl = get_header(conn->response_info.http_headers,
  15135. conn->response_info.num_headers,
  15136. "Transfer-Encoding"))
  15137. != NULL)
  15138. && mg_strcasecmp(cl, "identity")) {
  15139. if (mg_strcasecmp(cl, "chunked")) {
  15140. mg_snprintf(conn,
  15141. NULL, /* No truncation check for ebuf */
  15142. ebuf,
  15143. ebuf_len,
  15144. "%s",
  15145. "Bad request");
  15146. *err = 400;
  15147. return 0;
  15148. }
  15149. conn->is_chunked = 1;
  15150. conn->content_len = 0; /* not yet read */
  15151. } else if ((cl = get_header(conn->response_info.http_headers,
  15152. conn->response_info.num_headers,
  15153. "Content-Length"))
  15154. != NULL) {
  15155. char *endptr = NULL;
  15156. conn->content_len = strtoll(cl, &endptr, 10);
  15157. if ((endptr == cl) || (conn->content_len < 0)) {
  15158. mg_snprintf(conn,
  15159. NULL, /* No truncation check for ebuf */
  15160. ebuf,
  15161. ebuf_len,
  15162. "%s",
  15163. "Bad request");
  15164. *err = 411;
  15165. return 0;
  15166. }
  15167. /* Publish the content length back to the response info. */
  15168. conn->response_info.content_length = conn->content_len;
  15169. /* TODO: check if it is still used in response_info */
  15170. conn->request_info.content_length = conn->content_len;
  15171. /* TODO: we should also consider HEAD method */
  15172. if (conn->response_info.status_code == 304) {
  15173. conn->content_len = 0;
  15174. }
  15175. } else {
  15176. /* TODO: we should also consider HEAD method */
  15177. if (((conn->response_info.status_code >= 100)
  15178. && (conn->response_info.status_code <= 199))
  15179. || (conn->response_info.status_code == 204)
  15180. || (conn->response_info.status_code == 304)) {
  15181. conn->content_len = 0;
  15182. } else {
  15183. conn->content_len = -1; /* unknown content length */
  15184. }
  15185. }
  15186. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15187. return 1;
  15188. }
  15189. int
  15190. mg_get_response(struct mg_connection *conn,
  15191. char *ebuf,
  15192. size_t ebuf_len,
  15193. int timeout)
  15194. {
  15195. int err, ret;
  15196. char txt[32]; /* will not overflow */
  15197. char *save_timeout;
  15198. char *new_timeout;
  15199. if (ebuf_len > 0) {
  15200. ebuf[0] = '\0';
  15201. }
  15202. if (!conn) {
  15203. mg_snprintf(conn,
  15204. NULL, /* No truncation check for ebuf */
  15205. ebuf,
  15206. ebuf_len,
  15207. "%s",
  15208. "Parameter error");
  15209. return -1;
  15210. }
  15211. /* Reset the previous responses */
  15212. conn->data_len = 0;
  15213. /* Implementation of API function for HTTP clients */
  15214. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15215. if (timeout >= 0) {
  15216. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15217. new_timeout = txt;
  15218. } else {
  15219. new_timeout = NULL;
  15220. }
  15221. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15222. ret = get_response(conn, ebuf, ebuf_len, &err);
  15223. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15224. #if defined(MG_LEGACY_INTERFACE)
  15225. /* TODO: 1) uri is deprecated;
  15226. * 2) here, ri.uri is the http response code */
  15227. conn->request_info.uri = conn->request_info.request_uri;
  15228. #endif
  15229. conn->request_info.local_uri = conn->request_info.request_uri;
  15230. /* TODO (mid): Define proper return values - maybe return length?
  15231. * For the first test use <0 for error and >0 for OK */
  15232. return (ret == 0) ? -1 : +1;
  15233. }
  15234. struct mg_connection *
  15235. mg_download(const char *host,
  15236. int port,
  15237. int use_ssl,
  15238. char *ebuf,
  15239. size_t ebuf_len,
  15240. const char *fmt,
  15241. ...)
  15242. {
  15243. struct mg_connection *conn;
  15244. va_list ap;
  15245. int i;
  15246. int reqerr;
  15247. if (ebuf_len > 0) {
  15248. ebuf[0] = '\0';
  15249. }
  15250. va_start(ap, fmt);
  15251. /* open a connection */
  15252. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15253. if (conn != NULL) {
  15254. i = mg_vprintf(conn, fmt, ap);
  15255. if (i <= 0) {
  15256. mg_snprintf(conn,
  15257. NULL, /* No truncation check for ebuf */
  15258. ebuf,
  15259. ebuf_len,
  15260. "%s",
  15261. "Error sending request");
  15262. } else {
  15263. /* make sure the buffer is clear */
  15264. conn->data_len = 0;
  15265. get_response(conn, ebuf, ebuf_len, &reqerr);
  15266. #if defined(MG_LEGACY_INTERFACE)
  15267. /* TODO: 1) uri is deprecated;
  15268. * 2) here, ri.uri is the http response code */
  15269. conn->request_info.uri = conn->request_info.request_uri;
  15270. #endif
  15271. conn->request_info.local_uri = conn->request_info.request_uri;
  15272. }
  15273. }
  15274. /* if an error occurred, close the connection */
  15275. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15276. mg_close_connection(conn);
  15277. conn = NULL;
  15278. }
  15279. va_end(ap);
  15280. return conn;
  15281. }
  15282. struct websocket_client_thread_data {
  15283. struct mg_connection *conn;
  15284. mg_websocket_data_handler data_handler;
  15285. mg_websocket_close_handler close_handler;
  15286. void *callback_data;
  15287. };
  15288. #if defined(USE_WEBSOCKET)
  15289. #if defined(_WIN32)
  15290. static unsigned __stdcall websocket_client_thread(void *data)
  15291. #else
  15292. static void *
  15293. websocket_client_thread(void *data)
  15294. #endif
  15295. {
  15296. struct websocket_client_thread_data *cdata =
  15297. (struct websocket_client_thread_data *)data;
  15298. void *user_thread_ptr = NULL;
  15299. #if !defined(_WIN32)
  15300. struct sigaction sa;
  15301. /* Ignore SIGPIPE */
  15302. memset(&sa, 0, sizeof(sa));
  15303. sa.sa_handler = SIG_IGN;
  15304. sigaction(SIGPIPE, &sa, NULL);
  15305. #endif
  15306. mg_set_thread_name("ws-clnt");
  15307. if (cdata->conn->phys_ctx) {
  15308. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15309. /* 3 indicates a websocket client thread */
  15310. /* TODO: check if conn->phys_ctx can be set */
  15311. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15312. cdata->conn->phys_ctx, 3);
  15313. }
  15314. }
  15315. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15316. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15317. if (cdata->close_handler != NULL) {
  15318. cdata->close_handler(cdata->conn, cdata->callback_data);
  15319. }
  15320. /* The websocket_client context has only this thread. If it runs out,
  15321. set the stop_flag to 2 (= "stopped"). */
  15322. cdata->conn->phys_ctx->stop_flag = 2;
  15323. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15324. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15325. 3,
  15326. user_thread_ptr);
  15327. }
  15328. mg_free((void *)cdata);
  15329. #if defined(_WIN32)
  15330. return 0;
  15331. #else
  15332. return NULL;
  15333. #endif
  15334. }
  15335. #endif
  15336. struct mg_connection *
  15337. mg_connect_websocket_client(const char *host,
  15338. int port,
  15339. int use_ssl,
  15340. char *error_buffer,
  15341. size_t error_buffer_size,
  15342. const char *path,
  15343. const char *origin,
  15344. mg_websocket_data_handler data_func,
  15345. mg_websocket_close_handler close_func,
  15346. void *user_data)
  15347. {
  15348. struct mg_connection *conn = NULL;
  15349. #if defined(USE_WEBSOCKET)
  15350. struct websocket_client_thread_data *thread_data;
  15351. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15352. static const char *handshake_req;
  15353. if (origin != NULL) {
  15354. handshake_req = "GET %s HTTP/1.1\r\n"
  15355. "Host: %s\r\n"
  15356. "Upgrade: websocket\r\n"
  15357. "Connection: Upgrade\r\n"
  15358. "Sec-WebSocket-Key: %s\r\n"
  15359. "Sec-WebSocket-Version: 13\r\n"
  15360. "Origin: %s\r\n"
  15361. "\r\n";
  15362. } else {
  15363. handshake_req = "GET %s HTTP/1.1\r\n"
  15364. "Host: %s\r\n"
  15365. "Upgrade: websocket\r\n"
  15366. "Connection: Upgrade\r\n"
  15367. "Sec-WebSocket-Key: %s\r\n"
  15368. "Sec-WebSocket-Version: 13\r\n"
  15369. "\r\n";
  15370. }
  15371. #if defined(__clang__)
  15372. #pragma clang diagnostic push
  15373. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15374. #endif
  15375. /* Establish the client connection and request upgrade */
  15376. conn = mg_download(host,
  15377. port,
  15378. use_ssl,
  15379. error_buffer,
  15380. error_buffer_size,
  15381. handshake_req,
  15382. path,
  15383. host,
  15384. magic,
  15385. origin);
  15386. #if defined(__clang__)
  15387. #pragma clang diagnostic pop
  15388. #endif
  15389. /* Connection object will be null if something goes wrong */
  15390. if (conn == NULL) {
  15391. if (!*error_buffer) {
  15392. /* There should be already an error message */
  15393. mg_snprintf(conn,
  15394. NULL, /* No truncation check for ebuf */
  15395. error_buffer,
  15396. error_buffer_size,
  15397. "Unexpected error");
  15398. }
  15399. return NULL;
  15400. }
  15401. if (conn->response_info.status_code != 101) {
  15402. /* We sent an "upgrade" request. For a correct websocket
  15403. * protocol handshake, we expect a "101 Continue" response.
  15404. * Otherwise it is a protocol violation. Maybe the HTTP
  15405. * Server does not know websockets. */
  15406. if (!*error_buffer) {
  15407. /* set an error, if not yet set */
  15408. mg_snprintf(conn,
  15409. NULL, /* No truncation check for ebuf */
  15410. error_buffer,
  15411. error_buffer_size,
  15412. "Unexpected server reply");
  15413. }
  15414. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15415. mg_close_connection(conn);
  15416. return NULL;
  15417. }
  15418. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15419. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15420. if (!thread_data) {
  15421. DEBUG_TRACE("%s\r\n", "Out of memory");
  15422. mg_close_connection(conn);
  15423. return NULL;
  15424. }
  15425. thread_data->conn = conn;
  15426. thread_data->data_handler = data_func;
  15427. thread_data->close_handler = close_func;
  15428. thread_data->callback_data = user_data;
  15429. conn->phys_ctx->worker_threadids =
  15430. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15431. if (!conn->phys_ctx->worker_threadids) {
  15432. DEBUG_TRACE("%s\r\n", "Out of memory");
  15433. mg_free(thread_data);
  15434. mg_close_connection(conn);
  15435. return NULL;
  15436. }
  15437. /* Now upgrade to ws/wss client context */
  15438. conn->phys_ctx->user_data = user_data;
  15439. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15440. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15441. /* Start a thread to read the websocket client connection
  15442. * This thread will automatically stop when mg_disconnect is
  15443. * called on the client connection */
  15444. if (mg_start_thread_with_id(websocket_client_thread,
  15445. thread_data,
  15446. conn->phys_ctx->worker_threadids)
  15447. != 0) {
  15448. conn->phys_ctx->cfg_worker_threads = 0;
  15449. mg_free(thread_data);
  15450. mg_close_connection(conn);
  15451. conn = NULL;
  15452. DEBUG_TRACE("%s",
  15453. "Websocket client connect thread could not be started\r\n");
  15454. }
  15455. #else
  15456. /* Appease "unused parameter" warnings */
  15457. (void)host;
  15458. (void)port;
  15459. (void)use_ssl;
  15460. (void)error_buffer;
  15461. (void)error_buffer_size;
  15462. (void)path;
  15463. (void)origin;
  15464. (void)user_data;
  15465. (void)data_func;
  15466. (void)close_func;
  15467. #endif
  15468. return conn;
  15469. }
  15470. /* Prepare connection data structure */
  15471. static void
  15472. init_connection(struct mg_connection *conn)
  15473. {
  15474. /* Is keep alive allowed by the server */
  15475. int keep_alive_enabled =
  15476. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15477. if (!keep_alive_enabled) {
  15478. conn->must_close = 1;
  15479. }
  15480. /* Important: on new connection, reset the receiving buffer. Credit
  15481. * goes to crule42. */
  15482. conn->data_len = 0;
  15483. conn->handled_requests = 0;
  15484. mg_set_user_connection_data(conn, NULL);
  15485. #if defined(USE_SERVER_STATS)
  15486. conn->conn_state = 2; /* init */
  15487. #endif
  15488. /* call the init_connection callback if assigned */
  15489. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15490. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15491. void *conn_data = NULL;
  15492. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15493. mg_set_user_connection_data(conn, conn_data);
  15494. }
  15495. }
  15496. }
  15497. /* Process a connection - may handle multiple requests
  15498. * using the same connection.
  15499. * Must be called with a valid connection (conn and
  15500. * conn->phys_ctx must be valid).
  15501. */
  15502. static void
  15503. process_new_connection(struct mg_connection *conn)
  15504. {
  15505. struct mg_request_info *ri = &conn->request_info;
  15506. int keep_alive, discard_len;
  15507. char ebuf[100];
  15508. const char *hostend;
  15509. int reqerr, uri_type;
  15510. #if defined(USE_SERVER_STATS)
  15511. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15512. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15513. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15514. /* could use atomic compare exchange, but this
  15515. * seems overkill for statistics data */
  15516. conn->phys_ctx->max_active_connections = mcon;
  15517. }
  15518. #endif
  15519. init_connection(conn);
  15520. DEBUG_TRACE("Start processing connection from %s",
  15521. conn->request_info.remote_addr);
  15522. /* Loop over multiple requests sent using the same connection
  15523. * (while "keep alive"). */
  15524. do {
  15525. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15526. conn->handled_requests + 1);
  15527. #if defined(USE_SERVER_STATS)
  15528. conn->conn_state = 3; /* ready */
  15529. #endif
  15530. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15531. /* The request sent by the client could not be understood by
  15532. * the server, or it was incomplete or a timeout. Send an
  15533. * error message and close the connection. */
  15534. if (reqerr > 0) {
  15535. DEBUG_ASSERT(ebuf[0] != '\0');
  15536. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15537. }
  15538. } else if (strcmp(ri->http_version, "1.0")
  15539. && strcmp(ri->http_version, "1.1")) {
  15540. mg_snprintf(conn,
  15541. NULL, /* No truncation check for ebuf */
  15542. ebuf,
  15543. sizeof(ebuf),
  15544. "Bad HTTP version: [%s]",
  15545. ri->http_version);
  15546. mg_send_http_error(conn, 505, "%s", ebuf);
  15547. }
  15548. if (ebuf[0] == '\0') {
  15549. uri_type = get_uri_type(conn->request_info.request_uri);
  15550. switch (uri_type) {
  15551. case 1:
  15552. /* Asterisk */
  15553. conn->request_info.local_uri = NULL;
  15554. break;
  15555. case 2:
  15556. /* relative uri */
  15557. conn->request_info.local_uri = conn->request_info.request_uri;
  15558. break;
  15559. case 3:
  15560. case 4:
  15561. /* absolute uri (with/without port) */
  15562. hostend = get_rel_url_at_current_server(
  15563. conn->request_info.request_uri, conn);
  15564. if (hostend) {
  15565. conn->request_info.local_uri = hostend;
  15566. } else {
  15567. conn->request_info.local_uri = NULL;
  15568. }
  15569. break;
  15570. default:
  15571. mg_snprintf(conn,
  15572. NULL, /* No truncation check for ebuf */
  15573. ebuf,
  15574. sizeof(ebuf),
  15575. "Invalid URI");
  15576. mg_send_http_error(conn, 400, "%s", ebuf);
  15577. conn->request_info.local_uri = NULL;
  15578. break;
  15579. }
  15580. #if defined(MG_LEGACY_INTERFACE)
  15581. /* Legacy before split into local_uri and request_uri */
  15582. conn->request_info.uri = conn->request_info.local_uri;
  15583. #endif
  15584. }
  15585. DEBUG_TRACE("http: %s, error: %s",
  15586. (ri->http_version ? ri->http_version : "none"),
  15587. (ebuf[0] ? ebuf : "none"));
  15588. if (ebuf[0] == '\0') {
  15589. if (conn->request_info.local_uri) {
  15590. /* handle request to local server */
  15591. #if defined(USE_SERVER_STATS)
  15592. conn->conn_state = 4; /* processing */
  15593. #endif
  15594. handle_request(conn);
  15595. #if defined(USE_SERVER_STATS)
  15596. conn->conn_state = 5; /* processed */
  15597. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15598. conn->consumed_content);
  15599. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15600. conn->num_bytes_sent);
  15601. #endif
  15602. DEBUG_TRACE("%s", "handle_request done");
  15603. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15604. conn->phys_ctx->callbacks.end_request(conn,
  15605. conn->status_code);
  15606. DEBUG_TRACE("%s", "end_request callback done");
  15607. }
  15608. log_access(conn);
  15609. } else {
  15610. /* TODO: handle non-local request (PROXY) */
  15611. conn->must_close = 1;
  15612. }
  15613. } else {
  15614. conn->must_close = 1;
  15615. }
  15616. if (ri->remote_user != NULL) {
  15617. mg_free((void *)ri->remote_user);
  15618. /* Important! When having connections with and without auth
  15619. * would cause double free and then crash */
  15620. ri->remote_user = NULL;
  15621. }
  15622. /* NOTE(lsm): order is important here. should_keep_alive() call
  15623. * is using parsed request, which will be invalid after
  15624. * memmove's below.
  15625. * Therefore, memorize should_keep_alive() result now for later
  15626. * use in loop exit condition. */
  15627. /* Enable it only if this request is completely discardable. */
  15628. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15629. && (conn->content_len >= 0) && (conn->request_len > 0)
  15630. && ((conn->is_chunked == 4)
  15631. || (!conn->is_chunked
  15632. && ((conn->consumed_content == conn->content_len)
  15633. || ((conn->request_len + conn->content_len)
  15634. <= conn->data_len))));
  15635. if (keep_alive) {
  15636. /* Discard all buffered data for this request */
  15637. discard_len =
  15638. ((conn->request_len + conn->content_len) < conn->data_len)
  15639. ? (int)(conn->request_len + conn->content_len)
  15640. : conn->data_len;
  15641. conn->data_len -= discard_len;
  15642. if (conn->data_len > 0) {
  15643. DEBUG_TRACE("discard_len = %d", discard_len);
  15644. memmove(conn->buf,
  15645. conn->buf + discard_len,
  15646. (size_t)conn->data_len);
  15647. }
  15648. }
  15649. DEBUG_ASSERT(conn->data_len >= 0);
  15650. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15651. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15652. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15653. (long int)conn->data_len,
  15654. (long int)conn->buf_size);
  15655. break;
  15656. }
  15657. conn->handled_requests++;
  15658. } while (keep_alive);
  15659. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15660. conn->request_info.remote_addr,
  15661. difftime(time(NULL), conn->conn_birth_time));
  15662. close_connection(conn);
  15663. #if defined(USE_SERVER_STATS)
  15664. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15665. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15666. #endif
  15667. }
  15668. #if defined(ALTERNATIVE_QUEUE)
  15669. static void
  15670. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15671. {
  15672. unsigned int i;
  15673. while (!ctx->stop_flag) {
  15674. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15675. /* find a free worker slot and signal it */
  15676. if (ctx->client_socks[i].in_use == 2) {
  15677. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15678. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15679. ctx->client_socks[i] = *sp;
  15680. ctx->client_socks[i].in_use = 1;
  15681. /* socket has been moved to the consumer */
  15682. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15683. (void)event_signal(ctx->client_wait_events[i]);
  15684. return;
  15685. }
  15686. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15687. }
  15688. }
  15689. /* queue is full */
  15690. mg_sleep(1);
  15691. }
  15692. /* must consume */
  15693. set_blocking_mode(sp->sock);
  15694. closesocket(sp->sock);
  15695. }
  15696. static int
  15697. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15698. {
  15699. DEBUG_TRACE("%s", "going idle");
  15700. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15701. ctx->client_socks[thread_index].in_use = 2;
  15702. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15703. event_wait(ctx->client_wait_events[thread_index]);
  15704. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15705. *sp = ctx->client_socks[thread_index];
  15706. if (ctx->stop_flag) {
  15707. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15708. if (sp->in_use == 1) {
  15709. /* must consume */
  15710. set_blocking_mode(sp->sock);
  15711. closesocket(sp->sock);
  15712. }
  15713. return 0;
  15714. }
  15715. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15716. if (sp->in_use == 1) {
  15717. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15718. return 1;
  15719. }
  15720. /* must not reach here */
  15721. DEBUG_ASSERT(0);
  15722. return 0;
  15723. }
  15724. #else /* ALTERNATIVE_QUEUE */
  15725. /* Worker threads take accepted socket from the queue */
  15726. static int
  15727. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15728. {
  15729. (void)thread_index;
  15730. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15731. DEBUG_TRACE("%s", "going idle");
  15732. /* If the queue is empty, wait. We're idle at this point. */
  15733. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15734. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15735. }
  15736. /* If we're stopping, sq_head may be equal to sq_tail. */
  15737. if (ctx->sq_head > ctx->sq_tail) {
  15738. /* Copy socket from the queue and increment tail */
  15739. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  15740. ctx->sq_tail++;
  15741. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15742. /* Wrap pointers if needed */
  15743. while (ctx->sq_tail > ctx->sq_size) {
  15744. ctx->sq_tail -= ctx->sq_size;
  15745. ctx->sq_head -= ctx->sq_size;
  15746. }
  15747. }
  15748. (void)pthread_cond_signal(&ctx->sq_empty);
  15749. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15750. return !ctx->stop_flag;
  15751. }
  15752. /* Master thread adds accepted socket to a queue */
  15753. static void
  15754. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15755. {
  15756. int queue_filled;
  15757. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15758. queue_filled = ctx->sq_head - ctx->sq_tail;
  15759. /* If the queue is full, wait */
  15760. while ((ctx->stop_flag == 0) && (queue_filled >= ctx->sq_size)) {
  15761. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  15762. #if defined(USE_SERVER_STATS)
  15763. if (queue_filled > ctx->sq_max_fill) {
  15764. ctx->sq_max_fill = queue_filled;
  15765. }
  15766. #endif
  15767. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15768. ctx->sq_blocked = 0; /* Not blocked now */
  15769. queue_filled = ctx->sq_head - ctx->sq_tail;
  15770. }
  15771. if (queue_filled < ctx->sq_size) {
  15772. /* Copy socket to the queue and increment head */
  15773. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  15774. ctx->sq_head++;
  15775. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15776. }
  15777. queue_filled = ctx->sq_head - ctx->sq_tail;
  15778. #if defined(USE_SERVER_STATS)
  15779. if (queue_filled > ctx->sq_max_fill) {
  15780. ctx->sq_max_fill = queue_filled;
  15781. }
  15782. #endif
  15783. (void)pthread_cond_signal(&ctx->sq_full);
  15784. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15785. }
  15786. #endif /* ALTERNATIVE_QUEUE */
  15787. static void
  15788. worker_thread_run(struct mg_connection *conn)
  15789. {
  15790. struct mg_context *ctx = conn->phys_ctx;
  15791. int thread_index;
  15792. struct mg_workerTLS tls;
  15793. #if defined(MG_LEGACY_INTERFACE)
  15794. uint32_t addr;
  15795. #endif
  15796. mg_set_thread_name("worker");
  15797. tls.is_master = 0;
  15798. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15799. #if defined(_WIN32)
  15800. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15801. #endif
  15802. /* Initialize thread local storage before calling any callback */
  15803. pthread_setspecific(sTlsKey, &tls);
  15804. /* Check if there is a user callback */
  15805. if (ctx->callbacks.init_thread) {
  15806. /* call init_thread for a worker thread (type 1), and store the return
  15807. * value */
  15808. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15809. } else {
  15810. /* No callback: set user pointer to NULL */
  15811. tls.user_ptr = NULL;
  15812. }
  15813. /* Connection structure has been pre-allocated */
  15814. thread_index = (int)(conn - ctx->worker_connections);
  15815. if ((thread_index < 0)
  15816. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15817. mg_cry_ctx_internal(ctx,
  15818. "Internal error: Invalid worker index %i",
  15819. thread_index);
  15820. return;
  15821. }
  15822. /* Request buffers are not pre-allocated. They are private to the
  15823. * request and do not contain any state information that might be
  15824. * of interest to anyone observing a server status. */
  15825. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15826. if (conn->buf == NULL) {
  15827. mg_cry_ctx_internal(
  15828. ctx,
  15829. "Out of memory: Cannot allocate buffer for worker %i",
  15830. thread_index);
  15831. return;
  15832. }
  15833. conn->buf_size = (int)ctx->max_request_size;
  15834. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15835. conn->host = NULL; /* until we have more information. */
  15836. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15837. conn->request_info.user_data = ctx->user_data;
  15838. /* Allocate a mutex for this connection to allow communication both
  15839. * within the request handler and from elsewhere in the application
  15840. */
  15841. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15842. mg_free(conn->buf);
  15843. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15844. return;
  15845. }
  15846. #if defined(USE_SERVER_STATS)
  15847. conn->conn_state = 1; /* not consumed */
  15848. #endif
  15849. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15850. * signal sq_empty condvar to wake up the master waiting in
  15851. * produce_socket() */
  15852. while (consume_socket(ctx, &conn->client, thread_index)) {
  15853. #if defined(USE_SERVER_STATS)
  15854. conn->conn_close_time = 0;
  15855. #endif
  15856. conn->conn_birth_time = time(NULL);
  15857. /* Fill in IP, port info early so even if SSL setup below fails,
  15858. * error handler would have the corresponding info.
  15859. * Thanks to Johannes Winkelmann for the patch.
  15860. */
  15861. #if defined(USE_IPV6)
  15862. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15863. conn->request_info.remote_port =
  15864. ntohs(conn->client.rsa.sin6.sin6_port);
  15865. } else
  15866. #endif
  15867. {
  15868. conn->request_info.remote_port =
  15869. ntohs(conn->client.rsa.sin.sin_port);
  15870. }
  15871. sockaddr_to_string(conn->request_info.remote_addr,
  15872. sizeof(conn->request_info.remote_addr),
  15873. &conn->client.rsa);
  15874. DEBUG_TRACE("Start processing connection from %s",
  15875. conn->request_info.remote_addr);
  15876. conn->request_info.is_ssl = conn->client.is_ssl;
  15877. if (conn->client.is_ssl) {
  15878. #if !defined(NO_SSL)
  15879. /* HTTPS connection */
  15880. if (sslize(conn,
  15881. conn->dom_ctx->ssl_ctx,
  15882. SSL_accept,
  15883. &(conn->phys_ctx->stop_flag),
  15884. NULL)) {
  15885. /* conn->dom_ctx is set in get_request */
  15886. /* Get SSL client certificate information (if set) */
  15887. ssl_get_client_cert_info(conn);
  15888. /* process HTTPS connection */
  15889. process_new_connection(conn);
  15890. /* Free client certificate info */
  15891. if (conn->request_info.client_cert) {
  15892. mg_free((void *)(conn->request_info.client_cert->subject));
  15893. mg_free((void *)(conn->request_info.client_cert->issuer));
  15894. mg_free((void *)(conn->request_info.client_cert->serial));
  15895. mg_free((void *)(conn->request_info.client_cert->finger));
  15896. /* Free certificate memory */
  15897. X509_free(
  15898. (X509 *)conn->request_info.client_cert->peer_cert);
  15899. conn->request_info.client_cert->peer_cert = 0;
  15900. conn->request_info.client_cert->subject = 0;
  15901. conn->request_info.client_cert->issuer = 0;
  15902. conn->request_info.client_cert->serial = 0;
  15903. conn->request_info.client_cert->finger = 0;
  15904. mg_free(conn->request_info.client_cert);
  15905. conn->request_info.client_cert = 0;
  15906. }
  15907. } else {
  15908. /* make sure the connection is cleaned up on SSL failure */
  15909. close_connection(conn);
  15910. }
  15911. #endif
  15912. } else {
  15913. /* process HTTP connection */
  15914. process_new_connection(conn);
  15915. }
  15916. DEBUG_TRACE("%s", "Connection closed");
  15917. #if defined(USE_SERVER_STATS)
  15918. conn->conn_close_time = time(NULL);
  15919. #endif
  15920. }
  15921. /* Call exit thread user callback */
  15922. if (ctx->callbacks.exit_thread) {
  15923. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15924. }
  15925. /* delete thread local storage objects */
  15926. pthread_setspecific(sTlsKey, NULL);
  15927. #if defined(_WIN32)
  15928. CloseHandle(tls.pthread_cond_helper_mutex);
  15929. #endif
  15930. pthread_mutex_destroy(&conn->mutex);
  15931. /* Free the request buffer. */
  15932. conn->buf_size = 0;
  15933. mg_free(conn->buf);
  15934. conn->buf = NULL;
  15935. #if defined(USE_SERVER_STATS)
  15936. conn->conn_state = 9; /* done */
  15937. #endif
  15938. DEBUG_TRACE("%s", "exiting");
  15939. }
  15940. /* Threads have different return types on Windows and Unix. */
  15941. #if defined(_WIN32)
  15942. static unsigned __stdcall worker_thread(void *thread_func_param)
  15943. {
  15944. worker_thread_run((struct mg_connection *)thread_func_param);
  15945. return 0;
  15946. }
  15947. #else
  15948. static void *
  15949. worker_thread(void *thread_func_param)
  15950. {
  15951. #if !defined(__ZEPHYR__)
  15952. struct sigaction sa;
  15953. /* Ignore SIGPIPE */
  15954. memset(&sa, 0, sizeof(sa));
  15955. sa.sa_handler = SIG_IGN;
  15956. sigaction(SIGPIPE, &sa, NULL);
  15957. #endif
  15958. worker_thread_run((struct mg_connection *)thread_func_param);
  15959. return NULL;
  15960. }
  15961. #endif /* _WIN32 */
  15962. /* This is an internal function, thus all arguments are expected to be
  15963. * valid - a NULL check is not required. */
  15964. static void
  15965. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15966. {
  15967. struct socket so;
  15968. char src_addr[IP_ADDR_STR_LEN];
  15969. socklen_t len = sizeof(so.rsa);
  15970. #if !defined(__ZEPHYR__)
  15971. int on = 1;
  15972. #endif
  15973. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15974. == INVALID_SOCKET) {
  15975. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15976. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15977. mg_cry_ctx_internal(ctx,
  15978. "%s: %s is not allowed to connect",
  15979. __func__,
  15980. src_addr);
  15981. closesocket(so.sock);
  15982. } else {
  15983. /* Put so socket structure into the queue */
  15984. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15985. set_close_on_exec(so.sock, NULL, ctx);
  15986. so.is_ssl = listener->is_ssl;
  15987. so.ssl_redir = listener->ssl_redir;
  15988. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15989. mg_cry_ctx_internal(ctx,
  15990. "%s: getsockname() failed: %s",
  15991. __func__,
  15992. strerror(ERRNO));
  15993. }
  15994. #if !defined(__ZEPHYR__)
  15995. /* Set TCP keep-alive. This is needed because if HTTP-level
  15996. * keep-alive
  15997. * is enabled, and client resets the connection, server won't get
  15998. * TCP FIN or RST and will keep the connection open forever. With
  15999. * TCP keep-alive, next keep-alive handshake will figure out that
  16000. * the client is down and will close the server end.
  16001. * Thanks to Igor Klopov who suggested the patch. */
  16002. if (setsockopt(so.sock,
  16003. SOL_SOCKET,
  16004. SO_KEEPALIVE,
  16005. (SOCK_OPT_TYPE)&on,
  16006. sizeof(on))
  16007. != 0) {
  16008. mg_cry_ctx_internal(
  16009. ctx,
  16010. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16011. __func__,
  16012. strerror(ERRNO));
  16013. }
  16014. #endif
  16015. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16016. * to effectively fill up the underlying IP packet payload and
  16017. * reduce the overhead of sending lots of small buffers. However
  16018. * this hurts the server's throughput (ie. operations per second)
  16019. * when HTTP 1.1 persistent connections are used and the responses
  16020. * are relatively small (eg. less than 1400 bytes).
  16021. */
  16022. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16023. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16024. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16025. mg_cry_ctx_internal(
  16026. ctx,
  16027. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16028. __func__,
  16029. strerror(ERRNO));
  16030. }
  16031. }
  16032. /* The "non blocking" property should already be
  16033. * inherited from the parent socket. Set it for
  16034. * non-compliant socket implementations. */
  16035. set_non_blocking_mode(so.sock);
  16036. so.in_use = 0;
  16037. produce_socket(ctx, &so);
  16038. }
  16039. }
  16040. static void
  16041. master_thread_run(struct mg_context *ctx)
  16042. {
  16043. struct mg_workerTLS tls;
  16044. struct mg_pollfd *pfd;
  16045. unsigned int i;
  16046. unsigned int workerthreadcount;
  16047. if (!ctx) {
  16048. return;
  16049. }
  16050. mg_set_thread_name("master");
  16051. /* Increase priority of the master thread */
  16052. #if defined(_WIN32)
  16053. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16054. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16055. int min_prio = sched_get_priority_min(SCHED_RR);
  16056. int max_prio = sched_get_priority_max(SCHED_RR);
  16057. if ((min_prio >= 0) && (max_prio >= 0)
  16058. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16059. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16060. struct sched_param sched_param = {0};
  16061. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16062. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16063. }
  16064. #endif
  16065. /* Initialize thread local storage */
  16066. #if defined(_WIN32)
  16067. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16068. #endif
  16069. tls.is_master = 1;
  16070. pthread_setspecific(sTlsKey, &tls);
  16071. if (ctx->callbacks.init_thread) {
  16072. /* Callback for the master thread (type 0) */
  16073. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16074. } else {
  16075. tls.user_ptr = NULL;
  16076. }
  16077. /* Server starts *now* */
  16078. ctx->start_time = time(NULL);
  16079. /* Start the server */
  16080. pfd = ctx->listening_socket_fds;
  16081. while (ctx->stop_flag == 0) {
  16082. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16083. pfd[i].fd = ctx->listening_sockets[i].sock;
  16084. pfd[i].events = POLLIN;
  16085. }
  16086. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16087. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16088. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16089. * successful poll, and POLLIN is defined as
  16090. * (POLLRDNORM | POLLRDBAND)
  16091. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16092. * pfd[i].revents == POLLIN. */
  16093. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  16094. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16095. }
  16096. }
  16097. }
  16098. }
  16099. /* Here stop_flag is 1 - Initiate shutdown. */
  16100. DEBUG_TRACE("%s", "stopping workers");
  16101. /* Stop signal received: somebody called mg_stop. Quit. */
  16102. close_all_listening_sockets(ctx);
  16103. /* Wakeup workers that are waiting for connections to handle. */
  16104. #if defined(ALTERNATIVE_QUEUE)
  16105. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16106. event_signal(ctx->client_wait_events[i]);
  16107. }
  16108. #else
  16109. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16110. pthread_cond_broadcast(&ctx->sq_full);
  16111. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16112. #endif
  16113. /* Join all worker threads to avoid leaking threads. */
  16114. workerthreadcount = ctx->cfg_worker_threads;
  16115. for (i = 0; i < workerthreadcount; i++) {
  16116. if (ctx->worker_threadids[i] != 0) {
  16117. mg_join_thread(ctx->worker_threadids[i]);
  16118. }
  16119. }
  16120. #if defined(USE_LUA)
  16121. /* Free Lua state of lua background task */
  16122. if (ctx->lua_background_state) {
  16123. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16124. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16125. if (lua_istable(lstate, -1)) {
  16126. reg_boolean(lstate, "shutdown", 1);
  16127. lua_pop(lstate, 1);
  16128. mg_sleep(2);
  16129. }
  16130. lua_close(lstate);
  16131. ctx->lua_background_state = 0;
  16132. }
  16133. #endif
  16134. DEBUG_TRACE("%s", "exiting");
  16135. /* call exit thread callback */
  16136. if (ctx->callbacks.exit_thread) {
  16137. /* Callback for the master thread (type 0) */
  16138. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16139. }
  16140. #if defined(_WIN32)
  16141. CloseHandle(tls.pthread_cond_helper_mutex);
  16142. #endif
  16143. pthread_setspecific(sTlsKey, NULL);
  16144. /* Signal mg_stop() that we're done.
  16145. * WARNING: This must be the very last thing this
  16146. * thread does, as ctx becomes invalid after this line. */
  16147. ctx->stop_flag = 2;
  16148. }
  16149. /* Threads have different return types on Windows and Unix. */
  16150. #if defined(_WIN32)
  16151. static unsigned __stdcall master_thread(void *thread_func_param)
  16152. {
  16153. master_thread_run((struct mg_context *)thread_func_param);
  16154. return 0;
  16155. }
  16156. #else
  16157. static void *
  16158. master_thread(void *thread_func_param)
  16159. {
  16160. #if !defined(__ZEPHYR__)
  16161. struct sigaction sa;
  16162. /* Ignore SIGPIPE */
  16163. memset(&sa, 0, sizeof(sa));
  16164. sa.sa_handler = SIG_IGN;
  16165. sigaction(SIGPIPE, &sa, NULL);
  16166. #endif
  16167. master_thread_run((struct mg_context *)thread_func_param);
  16168. return NULL;
  16169. }
  16170. #endif /* _WIN32 */
  16171. static void
  16172. free_context(struct mg_context *ctx)
  16173. {
  16174. int i;
  16175. struct mg_handler_info *tmp_rh;
  16176. if (ctx == NULL) {
  16177. return;
  16178. }
  16179. if (ctx->callbacks.exit_context) {
  16180. ctx->callbacks.exit_context(ctx);
  16181. }
  16182. /* All threads exited, no sync is needed. Destroy thread mutex and
  16183. * condvars
  16184. */
  16185. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16186. #if defined(ALTERNATIVE_QUEUE)
  16187. mg_free(ctx->client_socks);
  16188. if (ctx->client_wait_events != NULL) {
  16189. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16190. event_destroy(ctx->client_wait_events[i]);
  16191. }
  16192. mg_free(ctx->client_wait_events);
  16193. }
  16194. #else
  16195. (void)pthread_cond_destroy(&ctx->sq_empty);
  16196. (void)pthread_cond_destroy(&ctx->sq_full);
  16197. mg_free(ctx->squeue);
  16198. #endif
  16199. /* Destroy other context global data structures mutex */
  16200. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16201. #if defined(USE_TIMERS)
  16202. timers_exit(ctx);
  16203. #endif
  16204. /* Deallocate config parameters */
  16205. for (i = 0; i < NUM_OPTIONS; i++) {
  16206. if (ctx->dd.config[i] != NULL) {
  16207. #if defined(_MSC_VER)
  16208. #pragma warning(suppress : 6001)
  16209. #endif
  16210. mg_free(ctx->dd.config[i]);
  16211. }
  16212. }
  16213. /* Deallocate request handlers */
  16214. while (ctx->dd.handlers) {
  16215. tmp_rh = ctx->dd.handlers;
  16216. ctx->dd.handlers = tmp_rh->next;
  16217. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  16218. pthread_cond_destroy(&tmp_rh->refcount_cond);
  16219. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  16220. }
  16221. mg_free(tmp_rh->uri);
  16222. mg_free(tmp_rh);
  16223. }
  16224. #if !defined(NO_SSL)
  16225. /* Deallocate SSL context */
  16226. if (ctx->dd.ssl_ctx != NULL) {
  16227. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16228. int callback_ret =
  16229. (ctx->callbacks.external_ssl_ctx == NULL)
  16230. ? 0
  16231. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16232. if (callback_ret == 0) {
  16233. SSL_CTX_free(ctx->dd.ssl_ctx);
  16234. }
  16235. /* else: ignore error and ommit SSL_CTX_free in case
  16236. * callback_ret is 1 */
  16237. }
  16238. #endif /* !NO_SSL */
  16239. /* Deallocate worker thread ID array */
  16240. mg_free(ctx->worker_threadids);
  16241. /* Deallocate worker thread ID array */
  16242. mg_free(ctx->worker_connections);
  16243. /* deallocate system name string */
  16244. mg_free(ctx->systemName);
  16245. /* Deallocate context itself */
  16246. mg_free(ctx);
  16247. }
  16248. void
  16249. mg_stop(struct mg_context *ctx)
  16250. {
  16251. pthread_t mt;
  16252. if (!ctx) {
  16253. return;
  16254. }
  16255. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16256. * two threads is not allowed. */
  16257. mt = ctx->masterthreadid;
  16258. if (mt == 0) {
  16259. return;
  16260. }
  16261. ctx->masterthreadid = 0;
  16262. /* Set stop flag, so all threads know they have to exit. */
  16263. ctx->stop_flag = 1;
  16264. /* Wait until everything has stopped. */
  16265. while (ctx->stop_flag != 2) {
  16266. (void)mg_sleep(10);
  16267. }
  16268. mg_join_thread(mt);
  16269. free_context(ctx);
  16270. #if defined(_WIN32)
  16271. (void)WSACleanup();
  16272. #endif /* _WIN32 */
  16273. }
  16274. static void
  16275. get_system_name(char **sysName)
  16276. {
  16277. #if defined(_WIN32)
  16278. #if defined(_WIN32_WCE)
  16279. *sysName = mg_strdup("WinCE");
  16280. #else
  16281. char name[128];
  16282. DWORD dwVersion = 0;
  16283. DWORD dwMajorVersion = 0;
  16284. DWORD dwMinorVersion = 0;
  16285. DWORD dwBuild = 0;
  16286. BOOL wowRet, isWoW = FALSE;
  16287. #if defined(_MSC_VER)
  16288. #pragma warning(push)
  16289. /* GetVersion was declared deprecated */
  16290. #pragma warning(disable : 4996)
  16291. #endif
  16292. dwVersion = GetVersion();
  16293. #if defined(_MSC_VER)
  16294. #pragma warning(pop)
  16295. #endif
  16296. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16297. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16298. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16299. (void)dwBuild;
  16300. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16301. sprintf(name,
  16302. "Windows %u.%u%s",
  16303. (unsigned)dwMajorVersion,
  16304. (unsigned)dwMinorVersion,
  16305. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16306. *sysName = mg_strdup(name);
  16307. #endif
  16308. #elif defined(__ZEPHYR__)
  16309. *sysName = mg_strdup("Zephyr OS");
  16310. #else
  16311. struct utsname name;
  16312. memset(&name, 0, sizeof(name));
  16313. uname(&name);
  16314. *sysName = mg_strdup(name.sysname);
  16315. #endif
  16316. }
  16317. static void
  16318. legacy_init(const char **options)
  16319. {
  16320. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16321. if (options) {
  16322. const char **run_options = options;
  16323. const char *optname = config_options[LISTENING_PORTS].name;
  16324. /* Try to find the "listening_ports" option */
  16325. while (*run_options) {
  16326. if (!strcmp(*run_options, optname)) {
  16327. ports_option = run_options[1];
  16328. }
  16329. run_options += 2;
  16330. }
  16331. }
  16332. if (is_ssl_port_used(ports_option)) {
  16333. /* Initialize with SSL support */
  16334. mg_init_library(MG_FEATURES_TLS);
  16335. } else {
  16336. /* Initialize without SSL support */
  16337. mg_init_library(MG_FEATURES_DEFAULT);
  16338. }
  16339. }
  16340. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16341. static
  16342. #endif
  16343. struct mg_context *
  16344. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16345. {
  16346. struct mg_context *ctx;
  16347. const char *name, *value, *default_value;
  16348. int idx, ok, workerthreadcount;
  16349. unsigned int i;
  16350. int itmp;
  16351. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16352. const char **options =
  16353. ((init != NULL) ? (init->configuration_options) : (NULL));
  16354. struct mg_workerTLS tls;
  16355. #if defined(_WIN32)
  16356. WSADATA data;
  16357. WSAStartup(MAKEWORD(2, 2), &data);
  16358. #endif /* _WIN32 */
  16359. if (error != NULL) {
  16360. error->code = 0;
  16361. if (error->text_buffer_size > 0) {
  16362. *error->text = 0;
  16363. }
  16364. }
  16365. if (mg_init_library_called == 0) {
  16366. /* Legacy INIT, if mg_start is called without mg_init_library.
  16367. * Note: This will cause a memory leak when unloading the library. */
  16368. legacy_init(options);
  16369. }
  16370. /* Allocate context and initialize reasonable general case defaults. */
  16371. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16372. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16373. mg_snprintf(NULL,
  16374. NULL, /* No truncation check for error buffers */
  16375. error->text,
  16376. error->text_buffer_size,
  16377. "%s",
  16378. "Out of memory");
  16379. }
  16380. return NULL;
  16381. }
  16382. /* Random number generator will initialize at the first call */
  16383. ctx->dd.auth_nonce_mask =
  16384. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16385. /* Save started thread index to reuse in other external API calls
  16386. * For the sake of thread synchronization all non-civetweb threads
  16387. * can be considered as single external thread */
  16388. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16389. tls.is_master = -1; /* Thread calling mg_start */
  16390. tls.thread_idx = ctx->starter_thread_idx;
  16391. #if defined(_WIN32)
  16392. tls.pthread_cond_helper_mutex = NULL;
  16393. #endif
  16394. pthread_setspecific(sTlsKey, &tls);
  16395. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16396. #if !defined(ALTERNATIVE_QUEUE)
  16397. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16398. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16399. ctx->sq_blocked = 0;
  16400. #endif
  16401. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16402. if (!ok) {
  16403. const char *err_msg =
  16404. "Cannot initialize thread synchronization objects";
  16405. /* Fatal error - abort start. However, this situation should never
  16406. * occur in practice. */
  16407. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16408. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16409. mg_snprintf(NULL,
  16410. NULL, /* No truncation check for error buffers */
  16411. error->text,
  16412. error->text_buffer_size,
  16413. "%s",
  16414. err_msg);
  16415. }
  16416. mg_free(ctx);
  16417. pthread_setspecific(sTlsKey, NULL);
  16418. return NULL;
  16419. }
  16420. if ((init != NULL) && (init->callbacks != NULL)) {
  16421. /* Set all callbacks except exit_context. */
  16422. ctx->callbacks = *init->callbacks;
  16423. exit_callback = init->callbacks->exit_context;
  16424. /* The exit callback is activated once the context is successfully
  16425. * created. It should not be called, if an incomplete context object is
  16426. * deleted during a failed initialization. */
  16427. ctx->callbacks.exit_context = 0;
  16428. }
  16429. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16430. ctx->dd.handlers = NULL;
  16431. ctx->dd.next = NULL;
  16432. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16433. ctx->dd.shared_lua_websockets = NULL;
  16434. #endif
  16435. /* Store options */
  16436. while (options && (name = *options++) != NULL) {
  16437. if ((idx = get_option_index(name)) == -1) {
  16438. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16439. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16440. mg_snprintf(NULL,
  16441. NULL, /* No truncation check for error buffers */
  16442. error->text,
  16443. error->text_buffer_size,
  16444. "Invalid configuration option: %s",
  16445. name);
  16446. }
  16447. free_context(ctx);
  16448. pthread_setspecific(sTlsKey, NULL);
  16449. return NULL;
  16450. } else if ((value = *options++) == NULL) {
  16451. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16452. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16453. mg_snprintf(NULL,
  16454. NULL, /* No truncation check for error buffers */
  16455. error->text,
  16456. error->text_buffer_size,
  16457. "Invalid configuration option value: %s",
  16458. name);
  16459. }
  16460. free_context(ctx);
  16461. pthread_setspecific(sTlsKey, NULL);
  16462. return NULL;
  16463. }
  16464. if (ctx->dd.config[idx] != NULL) {
  16465. /* A duplicate configuration option is not an error - the last
  16466. * option value will be used. */
  16467. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16468. mg_free(ctx->dd.config[idx]);
  16469. }
  16470. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16471. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16472. }
  16473. /* Set default value if needed */
  16474. for (i = 0; config_options[i].name != NULL; i++) {
  16475. default_value = config_options[i].default_value;
  16476. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16477. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16478. }
  16479. }
  16480. /* Request size option */
  16481. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16482. if (itmp < 1024) {
  16483. mg_cry_ctx_internal(ctx,
  16484. "%s too small",
  16485. config_options[MAX_REQUEST_SIZE].name);
  16486. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16487. mg_snprintf(NULL,
  16488. NULL, /* No truncation check for error buffers */
  16489. error->text,
  16490. error->text_buffer_size,
  16491. "Invalid configuration option value: %s",
  16492. config_options[MAX_REQUEST_SIZE].name);
  16493. }
  16494. free_context(ctx);
  16495. pthread_setspecific(sTlsKey, NULL);
  16496. return NULL;
  16497. }
  16498. ctx->max_request_size = (unsigned)itmp;
  16499. /* Queue length */
  16500. #if !defined(ALTERNATIVE_QUEUE)
  16501. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16502. if (itmp < 1) {
  16503. mg_cry_ctx_internal(ctx,
  16504. "%s too small",
  16505. config_options[CONNECTION_QUEUE_SIZE].name);
  16506. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16507. mg_snprintf(NULL,
  16508. NULL, /* No truncation check for error buffers */
  16509. error->text,
  16510. error->text_buffer_size,
  16511. "Invalid configuration option value: %s",
  16512. config_options[CONNECTION_QUEUE_SIZE].name);
  16513. }
  16514. free_context(ctx);
  16515. pthread_setspecific(sTlsKey, NULL);
  16516. return NULL;
  16517. }
  16518. ctx->squeue = (struct socket *)mg_calloc(itmp, sizeof(struct socket));
  16519. if (ctx->squeue == NULL) {
  16520. mg_cry_ctx_internal(ctx,
  16521. "Out of memory: Cannot allocate %s",
  16522. config_options[CONNECTION_QUEUE_SIZE].name);
  16523. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16524. mg_snprintf(NULL,
  16525. NULL, /* No truncation check for error buffers */
  16526. error->text,
  16527. error->text_buffer_size,
  16528. "Out of memory: Cannot allocate %s",
  16529. config_options[CONNECTION_QUEUE_SIZE].name);
  16530. }
  16531. free_context(ctx);
  16532. pthread_setspecific(sTlsKey, NULL);
  16533. return NULL;
  16534. }
  16535. ctx->sq_size = itmp;
  16536. #endif
  16537. /* Worker thread count option */
  16538. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16539. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16540. if (workerthreadcount <= 0) {
  16541. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16542. } else {
  16543. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16544. }
  16545. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16546. mg_snprintf(NULL,
  16547. NULL, /* No truncation check for error buffers */
  16548. error->text,
  16549. error->text_buffer_size,
  16550. "Invalid configuration option value: %s",
  16551. config_options[NUM_THREADS].name);
  16552. }
  16553. free_context(ctx);
  16554. pthread_setspecific(sTlsKey, NULL);
  16555. return NULL;
  16556. }
  16557. /* Document root */
  16558. #if defined(NO_FILES)
  16559. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16560. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16561. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16562. mg_snprintf(NULL,
  16563. NULL, /* No truncation check for error buffers */
  16564. error->text,
  16565. error->text_buffer_size,
  16566. "Invalid configuration option value: %s",
  16567. config_options[DOCUMENT_ROOT].name);
  16568. }
  16569. free_context(ctx);
  16570. pthread_setspecific(sTlsKey, NULL);
  16571. return NULL;
  16572. }
  16573. #endif
  16574. get_system_name(&ctx->systemName);
  16575. #if defined(USE_LUA)
  16576. /* If a Lua background script has been configured, start it. */
  16577. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16578. char ebuf[256];
  16579. struct vec opt_vec;
  16580. struct vec eq_vec;
  16581. const char *sparams;
  16582. lua_State *state = mg_prepare_lua_context_script(
  16583. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16584. if (!state) {
  16585. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16586. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16587. mg_snprintf(NULL,
  16588. NULL, /* No truncation check for error buffers */
  16589. error->text,
  16590. error->text_buffer_size,
  16591. "Error in script %s: %s",
  16592. config_options[DOCUMENT_ROOT].name,
  16593. ebuf);
  16594. }
  16595. free_context(ctx);
  16596. pthread_setspecific(sTlsKey, NULL);
  16597. return NULL;
  16598. }
  16599. ctx->lua_background_state = (void *)state;
  16600. lua_newtable(state);
  16601. reg_boolean(state, "shutdown", 0);
  16602. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16603. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16604. reg_llstring(
  16605. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16606. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16607. break;
  16608. }
  16609. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16610. } else {
  16611. ctx->lua_background_state = 0;
  16612. }
  16613. #endif
  16614. /* Step by step initialization of ctx - depending on build options */
  16615. #if !defined(NO_FILESYSTEMS)
  16616. if (!set_gpass_option(ctx, NULL)) {
  16617. const char *err_msg = "Invalid global password file";
  16618. /* Fatal error - abort start. */
  16619. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16620. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16621. mg_snprintf(NULL,
  16622. NULL, /* No truncation check for error buffers */
  16623. error->text,
  16624. error->text_buffer_size,
  16625. "%s",
  16626. err_msg);
  16627. }
  16628. free_context(ctx);
  16629. pthread_setspecific(sTlsKey, NULL);
  16630. return NULL;
  16631. }
  16632. #endif
  16633. #if !defined(NO_SSL)
  16634. if (!init_ssl_ctx(ctx, NULL)) {
  16635. const char *err_msg = "Error initializing SSL context";
  16636. /* Fatal error - abort start. */
  16637. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16638. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16639. mg_snprintf(NULL,
  16640. NULL, /* No truncation check for error buffers */
  16641. error->text,
  16642. error->text_buffer_size,
  16643. "%s",
  16644. err_msg);
  16645. }
  16646. free_context(ctx);
  16647. pthread_setspecific(sTlsKey, NULL);
  16648. return NULL;
  16649. }
  16650. #endif
  16651. if (!set_ports_option(ctx)) {
  16652. const char *err_msg = "Failed to setup server ports";
  16653. /* Fatal error - abort start. */
  16654. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16655. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16656. mg_snprintf(NULL,
  16657. NULL, /* No truncation check for error buffers */
  16658. error->text,
  16659. error->text_buffer_size,
  16660. "%s",
  16661. err_msg);
  16662. }
  16663. free_context(ctx);
  16664. pthread_setspecific(sTlsKey, NULL);
  16665. return NULL;
  16666. }
  16667. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16668. if (!set_uid_option(ctx)) {
  16669. const char *err_msg = "Failed to run as configured user";
  16670. /* Fatal error - abort start. */
  16671. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16672. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16673. mg_snprintf(NULL,
  16674. NULL, /* No truncation check for error buffers */
  16675. error->text,
  16676. error->text_buffer_size,
  16677. "%s",
  16678. err_msg);
  16679. }
  16680. free_context(ctx);
  16681. pthread_setspecific(sTlsKey, NULL);
  16682. return NULL;
  16683. }
  16684. #endif
  16685. if (!set_acl_option(ctx)) {
  16686. const char *err_msg = "Failed to setup access control list";
  16687. /* Fatal error - abort start. */
  16688. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16689. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16690. mg_snprintf(NULL,
  16691. NULL, /* No truncation check for error buffers */
  16692. error->text,
  16693. error->text_buffer_size,
  16694. "%s",
  16695. err_msg);
  16696. }
  16697. free_context(ctx);
  16698. pthread_setspecific(sTlsKey, NULL);
  16699. return NULL;
  16700. }
  16701. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16702. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16703. sizeof(pthread_t),
  16704. ctx);
  16705. if (ctx->worker_threadids == NULL) {
  16706. const char *err_msg = "Not enough memory for worker thread ID array";
  16707. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16708. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16709. mg_snprintf(NULL,
  16710. NULL, /* No truncation check for error buffers */
  16711. error->text,
  16712. error->text_buffer_size,
  16713. "%s",
  16714. err_msg);
  16715. }
  16716. free_context(ctx);
  16717. pthread_setspecific(sTlsKey, NULL);
  16718. return NULL;
  16719. }
  16720. ctx->worker_connections =
  16721. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16722. sizeof(struct mg_connection),
  16723. ctx);
  16724. if (ctx->worker_connections == NULL) {
  16725. const char *err_msg =
  16726. "Not enough memory for worker thread connection array";
  16727. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16728. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16729. mg_snprintf(NULL,
  16730. NULL, /* No truncation check for error buffers */
  16731. error->text,
  16732. error->text_buffer_size,
  16733. "%s",
  16734. err_msg);
  16735. }
  16736. free_context(ctx);
  16737. pthread_setspecific(sTlsKey, NULL);
  16738. return NULL;
  16739. }
  16740. #if defined(ALTERNATIVE_QUEUE)
  16741. ctx->client_wait_events =
  16742. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16743. sizeof(ctx->client_wait_events[0]),
  16744. ctx);
  16745. if (ctx->client_wait_events == NULL) {
  16746. const char *err_msg = "Not enough memory for worker event array";
  16747. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16748. mg_free(ctx->worker_threadids);
  16749. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16750. mg_snprintf(NULL,
  16751. NULL, /* No truncation check for error buffers */
  16752. error->text,
  16753. error->text_buffer_size,
  16754. "%s",
  16755. err_msg);
  16756. }
  16757. free_context(ctx);
  16758. pthread_setspecific(sTlsKey, NULL);
  16759. return NULL;
  16760. }
  16761. ctx->client_socks =
  16762. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16763. sizeof(ctx->client_socks[0]),
  16764. ctx);
  16765. if (ctx->client_socks == NULL) {
  16766. const char *err_msg = "Not enough memory for worker socket array";
  16767. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16768. mg_free(ctx->client_wait_events);
  16769. mg_free(ctx->worker_threadids);
  16770. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16771. mg_snprintf(NULL,
  16772. NULL, /* No truncation check for error buffers */
  16773. error->text,
  16774. error->text_buffer_size,
  16775. "%s",
  16776. err_msg);
  16777. }
  16778. free_context(ctx);
  16779. pthread_setspecific(sTlsKey, NULL);
  16780. return NULL;
  16781. }
  16782. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16783. ctx->client_wait_events[i] = event_create();
  16784. if (ctx->client_wait_events[i] == 0) {
  16785. const char *err_msg = "Error creating worker event %i";
  16786. mg_cry_ctx_internal(ctx, err_msg, i);
  16787. while (i > 0) {
  16788. i--;
  16789. event_destroy(ctx->client_wait_events[i]);
  16790. }
  16791. mg_free(ctx->client_socks);
  16792. mg_free(ctx->client_wait_events);
  16793. mg_free(ctx->worker_threadids);
  16794. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16795. mg_snprintf(NULL,
  16796. NULL, /* No truncation check for error buffers */
  16797. error->text,
  16798. error->text_buffer_size,
  16799. err_msg,
  16800. i);
  16801. }
  16802. free_context(ctx);
  16803. pthread_setspecific(sTlsKey, NULL);
  16804. return NULL;
  16805. }
  16806. }
  16807. #endif
  16808. #if defined(USE_TIMERS)
  16809. if (timers_init(ctx) != 0) {
  16810. const char *err_msg = "Error creating timers";
  16811. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16812. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16813. mg_snprintf(NULL,
  16814. NULL, /* No truncation check for error buffers */
  16815. error->text,
  16816. error->text_buffer_size,
  16817. "%s",
  16818. err_msg);
  16819. }
  16820. free_context(ctx);
  16821. pthread_setspecific(sTlsKey, NULL);
  16822. return NULL;
  16823. }
  16824. #endif
  16825. /* Context has been created - init user libraries */
  16826. if (ctx->callbacks.init_context) {
  16827. ctx->callbacks.init_context(ctx);
  16828. }
  16829. /* From now, the context is successfully created.
  16830. * When it is destroyed, the exit callback should be called. */
  16831. ctx->callbacks.exit_context = exit_callback;
  16832. ctx->context_type = CONTEXT_SERVER; /* server context */
  16833. /* Start master (listening) thread */
  16834. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16835. /* Start worker threads */
  16836. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16837. /* worker_thread sets up the other fields */
  16838. ctx->worker_connections[i].phys_ctx = ctx;
  16839. if (mg_start_thread_with_id(worker_thread,
  16840. &ctx->worker_connections[i],
  16841. &ctx->worker_threadids[i])
  16842. != 0) {
  16843. long error_no = (long)ERRNO;
  16844. /* thread was not created */
  16845. if (i > 0) {
  16846. /* If the second, third, ... thread cannot be created, set a
  16847. * warning, but keep running. */
  16848. mg_cry_ctx_internal(ctx,
  16849. "Cannot start worker thread %i: error %ld",
  16850. i + 1,
  16851. error_no);
  16852. /* If the server initialization should stop here, all threads
  16853. * that have already been created must be stopped first, before
  16854. * any free_context(ctx) call.
  16855. */
  16856. } else {
  16857. /* If the first worker thread cannot be created, stop
  16858. * initialization and free the entire server context. */
  16859. mg_cry_ctx_internal(ctx,
  16860. "Cannot create threads: error %ld",
  16861. error_no);
  16862. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16863. mg_snprintf(
  16864. NULL,
  16865. NULL, /* No truncation check for error buffers */
  16866. error->text,
  16867. error->text_buffer_size,
  16868. "Cannot create first worker thread: error %ld",
  16869. error_no);
  16870. }
  16871. free_context(ctx);
  16872. pthread_setspecific(sTlsKey, NULL);
  16873. return NULL;
  16874. }
  16875. break;
  16876. }
  16877. }
  16878. pthread_setspecific(sTlsKey, NULL);
  16879. return ctx;
  16880. }
  16881. struct mg_context *
  16882. mg_start(const struct mg_callbacks *callbacks,
  16883. void *user_data,
  16884. const char **options)
  16885. {
  16886. struct mg_init_data init = {0};
  16887. init.callbacks = callbacks;
  16888. init.user_data = user_data;
  16889. init.configuration_options = options;
  16890. return mg_start2(&init, NULL);
  16891. }
  16892. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16893. /* Add an additional domain to an already running web server. */
  16894. int
  16895. mg_start_domain2(struct mg_context *ctx,
  16896. const char **options,
  16897. struct mg_error_data *error)
  16898. {
  16899. const char *name;
  16900. const char *value;
  16901. const char *default_value;
  16902. struct mg_domain_context *new_dom;
  16903. struct mg_domain_context *dom;
  16904. int idx, i;
  16905. if (error != NULL) {
  16906. error->code = 0;
  16907. if (error->text_buffer_size > 0) {
  16908. *error->text = 0;
  16909. }
  16910. }
  16911. if ((ctx == NULL) || (options == NULL)) {
  16912. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16913. mg_snprintf(NULL,
  16914. NULL, /* No truncation check for error buffers */
  16915. error->text,
  16916. error->text_buffer_size,
  16917. "%s",
  16918. "Invalid parameters");
  16919. }
  16920. return -1;
  16921. }
  16922. if (ctx->stop_flag != 0) {
  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. "%s",
  16929. "Server already stopped");
  16930. }
  16931. return -1;
  16932. }
  16933. new_dom = (struct mg_domain_context *)
  16934. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16935. if (!new_dom) {
  16936. /* Out of memory */
  16937. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16938. mg_snprintf(NULL,
  16939. NULL, /* No truncation check for error buffers */
  16940. error->text,
  16941. error->text_buffer_size,
  16942. "%s",
  16943. "Out or memory");
  16944. }
  16945. return -6;
  16946. }
  16947. /* Store options - TODO: unite duplicate code */
  16948. while (options && (name = *options++) != NULL) {
  16949. if ((idx = get_option_index(name)) == -1) {
  16950. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16951. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16952. mg_snprintf(NULL,
  16953. NULL, /* No truncation check for error buffers */
  16954. error->text,
  16955. error->text_buffer_size,
  16956. "Invalid option: %s",
  16957. name);
  16958. }
  16959. mg_free(new_dom);
  16960. return -2;
  16961. } else if ((value = *options++) == NULL) {
  16962. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  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 option value: %s",
  16969. name);
  16970. }
  16971. mg_free(new_dom);
  16972. return -2;
  16973. }
  16974. if (new_dom->config[idx] != NULL) {
  16975. /* Duplicate option: Later values overwrite earlier ones. */
  16976. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16977. mg_free(new_dom->config[idx]);
  16978. }
  16979. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16980. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16981. }
  16982. /* Authentication domain is mandatory */
  16983. /* TODO: Maybe use a new option hostname? */
  16984. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16985. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16986. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16987. mg_snprintf(NULL,
  16988. NULL, /* No truncation check for error buffers */
  16989. error->text,
  16990. error->text_buffer_size,
  16991. "Mandatory option %s missing",
  16992. config_options[AUTHENTICATION_DOMAIN].name);
  16993. }
  16994. mg_free(new_dom);
  16995. return -4;
  16996. }
  16997. /* Set default value if needed. Take the config value from
  16998. * ctx as a default value. */
  16999. for (i = 0; config_options[i].name != NULL; i++) {
  17000. default_value = ctx->dd.config[i];
  17001. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17002. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17003. }
  17004. }
  17005. new_dom->handlers = NULL;
  17006. new_dom->next = NULL;
  17007. new_dom->nonce_count = 0;
  17008. new_dom->auth_nonce_mask =
  17009. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17010. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17011. new_dom->shared_lua_websockets = NULL;
  17012. #endif
  17013. if (!init_ssl_ctx(ctx, new_dom)) {
  17014. /* Init SSL failed */
  17015. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17016. mg_snprintf(NULL,
  17017. NULL, /* No truncation check for error buffers */
  17018. error->text,
  17019. error->text_buffer_size,
  17020. "%s",
  17021. "Initializing SSL context failed");
  17022. }
  17023. mg_free(new_dom);
  17024. return -3;
  17025. }
  17026. /* Add element to linked list. */
  17027. mg_lock_context(ctx);
  17028. idx = 0;
  17029. dom = &(ctx->dd);
  17030. for (;;) {
  17031. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17032. dom->config[AUTHENTICATION_DOMAIN])) {
  17033. /* Domain collision */
  17034. mg_cry_ctx_internal(ctx,
  17035. "domain %s already in use",
  17036. new_dom->config[AUTHENTICATION_DOMAIN]);
  17037. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17038. mg_snprintf(NULL,
  17039. NULL, /* No truncation check for error buffers */
  17040. error->text,
  17041. error->text_buffer_size,
  17042. "Domain %s specified by %s is already in use",
  17043. new_dom->config[AUTHENTICATION_DOMAIN],
  17044. config_options[AUTHENTICATION_DOMAIN].name);
  17045. }
  17046. mg_free(new_dom);
  17047. return -5;
  17048. }
  17049. /* Count number of domains */
  17050. idx++;
  17051. if (dom->next == NULL) {
  17052. dom->next = new_dom;
  17053. break;
  17054. }
  17055. dom = dom->next;
  17056. }
  17057. mg_unlock_context(ctx);
  17058. /* Return domain number */
  17059. return idx;
  17060. }
  17061. int
  17062. mg_start_domain(struct mg_context *ctx, const char **options)
  17063. {
  17064. return mg_start_domain2(ctx, options, NULL);
  17065. }
  17066. #endif
  17067. /* Feature check API function */
  17068. unsigned
  17069. mg_check_feature(unsigned feature)
  17070. {
  17071. static const unsigned feature_set = 0
  17072. /* Set bits for available features according to API documentation.
  17073. * This bit mask is created at compile time, according to the active
  17074. * preprocessor defines. It is a single const value at runtime. */
  17075. #if !defined(NO_FILES)
  17076. | MG_FEATURES_FILES
  17077. #endif
  17078. #if !defined(NO_SSL)
  17079. | MG_FEATURES_SSL
  17080. #endif
  17081. #if !defined(NO_CGI)
  17082. | MG_FEATURES_CGI
  17083. #endif
  17084. #if defined(USE_IPV6)
  17085. | MG_FEATURES_IPV6
  17086. #endif
  17087. #if defined(USE_WEBSOCKET)
  17088. | MG_FEATURES_WEBSOCKET
  17089. #endif
  17090. #if defined(USE_LUA)
  17091. | MG_FEATURES_LUA
  17092. #endif
  17093. #if defined(USE_DUKTAPE)
  17094. | MG_FEATURES_SSJS
  17095. #endif
  17096. #if !defined(NO_CACHING)
  17097. | MG_FEATURES_CACHE
  17098. #endif
  17099. #if defined(USE_SERVER_STATS)
  17100. | MG_FEATURES_STATS
  17101. #endif
  17102. #if defined(USE_ZLIB)
  17103. | MG_FEATURES_COMPRESSION
  17104. #endif
  17105. /* Set some extra bits not defined in the API documentation.
  17106. * These bits may change without further notice. */
  17107. #if defined(MG_LEGACY_INTERFACE)
  17108. | 0x00008000u
  17109. #endif
  17110. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17111. | 0x00004000u
  17112. #endif
  17113. #if defined(MEMORY_DEBUGGING)
  17114. | 0x00001000u
  17115. #endif
  17116. #if defined(USE_TIMERS)
  17117. | 0x00020000u
  17118. #endif
  17119. #if !defined(NO_NONCE_CHECK)
  17120. | 0x00040000u
  17121. #endif
  17122. #if !defined(NO_POPEN)
  17123. | 0x00080000u
  17124. #endif
  17125. ;
  17126. return (feature & feature_set);
  17127. }
  17128. static size_t
  17129. mg_str_append(char **dst, char *end, const char *src)
  17130. {
  17131. size_t len = strlen(src);
  17132. if (*dst != end) {
  17133. /* Append src if enough space, or close dst. */
  17134. if ((size_t)(end - *dst) > len) {
  17135. strcpy(*dst, src);
  17136. *dst += len;
  17137. } else {
  17138. *dst = end;
  17139. }
  17140. }
  17141. return len;
  17142. }
  17143. /* Get system information. It can be printed or stored by the caller.
  17144. * Return the size of available information. */
  17145. int
  17146. mg_get_system_info(char *buffer, int buflen)
  17147. {
  17148. char *end, *append_eoobj = NULL, block[256];
  17149. size_t system_info_length = 0;
  17150. #if defined(_WIN32)
  17151. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17152. #else
  17153. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17154. #endif
  17155. if ((buffer == NULL) || (buflen < 1)) {
  17156. buflen = 0;
  17157. end = buffer;
  17158. } else {
  17159. *buffer = 0;
  17160. end = buffer + buflen;
  17161. }
  17162. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17163. /* has enough space to append eoobj */
  17164. append_eoobj = buffer;
  17165. end -= sizeof(eoobj) - 1;
  17166. }
  17167. system_info_length += mg_str_append(&buffer, end, "{");
  17168. /* Server version */
  17169. {
  17170. const char *version = mg_version();
  17171. mg_snprintf(NULL,
  17172. NULL,
  17173. block,
  17174. sizeof(block),
  17175. "%s\"version\" : \"%s\"",
  17176. eol,
  17177. version);
  17178. system_info_length += mg_str_append(&buffer, end, block);
  17179. }
  17180. /* System info */
  17181. {
  17182. #if defined(_WIN32)
  17183. DWORD dwVersion = 0;
  17184. DWORD dwMajorVersion = 0;
  17185. DWORD dwMinorVersion = 0;
  17186. SYSTEM_INFO si;
  17187. GetSystemInfo(&si);
  17188. #if defined(_MSC_VER)
  17189. #pragma warning(push)
  17190. /* GetVersion was declared deprecated */
  17191. #pragma warning(disable : 4996)
  17192. #endif
  17193. dwVersion = GetVersion();
  17194. #if defined(_MSC_VER)
  17195. #pragma warning(pop)
  17196. #endif
  17197. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17198. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17199. mg_snprintf(NULL,
  17200. NULL,
  17201. block,
  17202. sizeof(block),
  17203. ",%s\"os\" : \"Windows %u.%u\"",
  17204. eol,
  17205. (unsigned)dwMajorVersion,
  17206. (unsigned)dwMinorVersion);
  17207. system_info_length += mg_str_append(&buffer, end, block);
  17208. mg_snprintf(NULL,
  17209. NULL,
  17210. block,
  17211. sizeof(block),
  17212. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17213. eol,
  17214. (unsigned)si.wProcessorArchitecture,
  17215. (unsigned)si.dwNumberOfProcessors,
  17216. (unsigned)si.dwActiveProcessorMask);
  17217. system_info_length += mg_str_append(&buffer, end, block);
  17218. #elif defined(__ZEPHYR__)
  17219. mg_snprintf(NULL,
  17220. NULL,
  17221. block,
  17222. sizeof(block),
  17223. ",%s\"os\" : \"%s %s\"",
  17224. eol,
  17225. "Zephyr OS",
  17226. ZEPHYR_VERSION);
  17227. system_info_length += mg_str_append(&buffer, end, block);
  17228. #else
  17229. struct utsname name;
  17230. memset(&name, 0, sizeof(name));
  17231. uname(&name);
  17232. mg_snprintf(NULL,
  17233. NULL,
  17234. block,
  17235. sizeof(block),
  17236. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17237. eol,
  17238. name.sysname,
  17239. name.version,
  17240. name.release,
  17241. name.machine);
  17242. system_info_length += mg_str_append(&buffer, end, block);
  17243. #endif
  17244. }
  17245. /* Features */
  17246. {
  17247. mg_snprintf(NULL,
  17248. NULL,
  17249. block,
  17250. sizeof(block),
  17251. ",%s\"features\" : %lu"
  17252. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17253. eol,
  17254. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17255. eol,
  17256. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17257. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17258. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17259. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17260. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17261. : "",
  17262. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17263. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17264. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17265. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17266. system_info_length += mg_str_append(&buffer, end, block);
  17267. #if defined(USE_LUA)
  17268. mg_snprintf(NULL,
  17269. NULL,
  17270. block,
  17271. sizeof(block),
  17272. ",%s\"lua_version\" : \"%u (%s)\"",
  17273. eol,
  17274. (unsigned)LUA_VERSION_NUM,
  17275. LUA_RELEASE);
  17276. system_info_length += mg_str_append(&buffer, end, block);
  17277. #endif
  17278. #if defined(USE_DUKTAPE)
  17279. mg_snprintf(NULL,
  17280. NULL,
  17281. block,
  17282. sizeof(block),
  17283. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17284. eol,
  17285. (unsigned)DUK_VERSION / 10000,
  17286. ((unsigned)DUK_VERSION / 100) % 100,
  17287. (unsigned)DUK_VERSION % 100);
  17288. system_info_length += mg_str_append(&buffer, end, block);
  17289. #endif
  17290. }
  17291. /* Build date */
  17292. {
  17293. #if defined(GCC_DIAGNOSTIC)
  17294. #if GCC_VERSION >= 40900
  17295. #pragma GCC diagnostic push
  17296. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17297. #pragma GCC diagnostic ignored "-Wdate-time"
  17298. #endif
  17299. #endif
  17300. mg_snprintf(NULL,
  17301. NULL,
  17302. block,
  17303. sizeof(block),
  17304. ",%s\"build\" : \"%s\"",
  17305. eol,
  17306. __DATE__);
  17307. #if defined(GCC_DIAGNOSTIC)
  17308. #if GCC_VERSION >= 40900
  17309. #pragma GCC diagnostic pop
  17310. #endif
  17311. #endif
  17312. system_info_length += mg_str_append(&buffer, end, block);
  17313. }
  17314. /* Compiler information */
  17315. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17316. {
  17317. #if defined(_MSC_VER)
  17318. mg_snprintf(NULL,
  17319. NULL,
  17320. block,
  17321. sizeof(block),
  17322. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17323. eol,
  17324. (unsigned)_MSC_VER,
  17325. (unsigned)_MSC_FULL_VER);
  17326. system_info_length += mg_str_append(&buffer, end, block);
  17327. #elif defined(__MINGW64__)
  17328. mg_snprintf(NULL,
  17329. NULL,
  17330. block,
  17331. sizeof(block),
  17332. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17333. eol,
  17334. (unsigned)__MINGW64_VERSION_MAJOR,
  17335. (unsigned)__MINGW64_VERSION_MINOR);
  17336. system_info_length += mg_str_append(&buffer, end, block);
  17337. mg_snprintf(NULL,
  17338. NULL,
  17339. block,
  17340. sizeof(block),
  17341. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17342. eol,
  17343. (unsigned)__MINGW32_MAJOR_VERSION,
  17344. (unsigned)__MINGW32_MINOR_VERSION);
  17345. system_info_length += mg_str_append(&buffer, end, block);
  17346. #elif defined(__MINGW32__)
  17347. mg_snprintf(NULL,
  17348. NULL,
  17349. block,
  17350. sizeof(block),
  17351. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17352. eol,
  17353. (unsigned)__MINGW32_MAJOR_VERSION,
  17354. (unsigned)__MINGW32_MINOR_VERSION);
  17355. system_info_length += mg_str_append(&buffer, end, block);
  17356. #elif defined(__clang__)
  17357. mg_snprintf(NULL,
  17358. NULL,
  17359. block,
  17360. sizeof(block),
  17361. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17362. eol,
  17363. __clang_major__,
  17364. __clang_minor__,
  17365. __clang_patchlevel__,
  17366. __clang_version__);
  17367. system_info_length += mg_str_append(&buffer, end, block);
  17368. #elif defined(__GNUC__)
  17369. mg_snprintf(NULL,
  17370. NULL,
  17371. block,
  17372. sizeof(block),
  17373. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17374. eol,
  17375. (unsigned)__GNUC__,
  17376. (unsigned)__GNUC_MINOR__,
  17377. (unsigned)__GNUC_PATCHLEVEL__);
  17378. system_info_length += mg_str_append(&buffer, end, block);
  17379. #elif defined(__INTEL_COMPILER)
  17380. mg_snprintf(NULL,
  17381. NULL,
  17382. block,
  17383. sizeof(block),
  17384. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17385. eol,
  17386. (unsigned)__INTEL_COMPILER);
  17387. system_info_length += mg_str_append(&buffer, end, block);
  17388. #elif defined(__BORLANDC__)
  17389. mg_snprintf(NULL,
  17390. NULL,
  17391. block,
  17392. sizeof(block),
  17393. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17394. eol,
  17395. (unsigned)__BORLANDC__);
  17396. system_info_length += mg_str_append(&buffer, end, block);
  17397. #elif defined(__SUNPRO_C)
  17398. mg_snprintf(NULL,
  17399. NULL,
  17400. block,
  17401. sizeof(block),
  17402. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17403. eol,
  17404. (unsigned)__SUNPRO_C);
  17405. system_info_length += mg_str_append(&buffer, end, block);
  17406. #else
  17407. mg_snprintf(NULL,
  17408. NULL,
  17409. block,
  17410. sizeof(block),
  17411. ",%s\"compiler\" : \"other\"",
  17412. eol);
  17413. system_info_length += mg_str_append(&buffer, end, block);
  17414. #endif
  17415. }
  17416. /* Determine 32/64 bit data mode.
  17417. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17418. {
  17419. mg_snprintf(NULL,
  17420. NULL,
  17421. block,
  17422. sizeof(block),
  17423. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17424. "char:%u/%u, "
  17425. "ptr:%u, size:%u, time:%u\"",
  17426. eol,
  17427. (unsigned)sizeof(short),
  17428. (unsigned)sizeof(int),
  17429. (unsigned)sizeof(long),
  17430. (unsigned)sizeof(long long),
  17431. (unsigned)sizeof(float),
  17432. (unsigned)sizeof(double),
  17433. (unsigned)sizeof(long double),
  17434. (unsigned)sizeof(char),
  17435. (unsigned)sizeof(wchar_t),
  17436. (unsigned)sizeof(void *),
  17437. (unsigned)sizeof(size_t),
  17438. (unsigned)sizeof(time_t));
  17439. system_info_length += mg_str_append(&buffer, end, block);
  17440. }
  17441. /* Terminate string */
  17442. if (append_eoobj) {
  17443. strcat(append_eoobj, eoobj);
  17444. }
  17445. system_info_length += sizeof(eoobj) - 1;
  17446. return (int)system_info_length;
  17447. }
  17448. /* Get context information. It can be printed or stored by the caller.
  17449. * Return the size of available information. */
  17450. int
  17451. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17452. {
  17453. #if defined(USE_SERVER_STATS)
  17454. char *end, *append_eoobj = NULL, block[256];
  17455. size_t context_info_length = 0;
  17456. #if defined(_WIN32)
  17457. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17458. #else
  17459. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17460. #endif
  17461. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17462. if ((buffer == NULL) || (buflen < 1)) {
  17463. buflen = 0;
  17464. end = buffer;
  17465. } else {
  17466. *buffer = 0;
  17467. end = buffer + buflen;
  17468. }
  17469. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17470. /* has enough space to append eoobj */
  17471. append_eoobj = buffer;
  17472. end -= sizeof(eoobj) - 1;
  17473. }
  17474. context_info_length += mg_str_append(&buffer, end, "{");
  17475. if (ms) { /* <-- should be always true */
  17476. /* Memory information */
  17477. mg_snprintf(NULL,
  17478. NULL,
  17479. block,
  17480. sizeof(block),
  17481. "%s\"memory\" : {%s"
  17482. "\"blocks\" : %i,%s"
  17483. "\"used\" : %" INT64_FMT ",%s"
  17484. "\"maxUsed\" : %" INT64_FMT "%s"
  17485. "}",
  17486. eol,
  17487. eol,
  17488. ms->blockCount,
  17489. eol,
  17490. ms->totalMemUsed,
  17491. eol,
  17492. ms->maxMemUsed,
  17493. eol);
  17494. context_info_length += mg_str_append(&buffer, end, block);
  17495. }
  17496. if (ctx) {
  17497. /* Declare all variables at begin of the block, to comply
  17498. * with old C standards. */
  17499. char start_time_str[64] = {0};
  17500. char now_str[64] = {0};
  17501. time_t start_time = ctx->start_time;
  17502. time_t now = time(NULL);
  17503. /* Connections information */
  17504. mg_snprintf(NULL,
  17505. NULL,
  17506. block,
  17507. sizeof(block),
  17508. ",%s\"connections\" : {%s"
  17509. "\"active\" : %i,%s"
  17510. "\"maxActive\" : %i,%s"
  17511. "\"total\" : %" INT64_FMT "%s"
  17512. "}",
  17513. eol,
  17514. eol,
  17515. ctx->active_connections,
  17516. eol,
  17517. ctx->max_active_connections,
  17518. eol,
  17519. ctx->total_connections,
  17520. eol);
  17521. context_info_length += mg_str_append(&buffer, end, block);
  17522. /* Queue information */
  17523. #if !defined(ALTERNATIVE_QUEUE)
  17524. mg_snprintf(NULL,
  17525. NULL,
  17526. block,
  17527. sizeof(block),
  17528. ",%s\"queue\" : {%s"
  17529. "\"length\" : %i,%s"
  17530. "\"filled\" : %i,%s"
  17531. "\"maxFilled\" : %i,%s"
  17532. "\"full\" : %s%s"
  17533. "}",
  17534. eol,
  17535. eol,
  17536. ctx->sq_size,
  17537. eol,
  17538. ctx->sq_head - ctx->sq_tail,
  17539. eol,
  17540. ctx->sq_max_fill,
  17541. eol,
  17542. (ctx->sq_blocked ? "true" : "false"),
  17543. eol);
  17544. context_info_length += mg_str_append(&buffer, end, block);
  17545. #endif
  17546. /* Requests information */
  17547. mg_snprintf(NULL,
  17548. NULL,
  17549. block,
  17550. sizeof(block),
  17551. ",%s\"requests\" : {%s"
  17552. "\"total\" : %" INT64_FMT "%s"
  17553. "}",
  17554. eol,
  17555. eol,
  17556. ctx->total_requests,
  17557. eol);
  17558. context_info_length += mg_str_append(&buffer, end, block);
  17559. /* Data information */
  17560. mg_snprintf(NULL,
  17561. NULL,
  17562. block,
  17563. sizeof(block),
  17564. ",%s\"data\" : {%s"
  17565. "\"read\" : %" INT64_FMT ",%s"
  17566. "\"written\" : %" INT64_FMT "%s"
  17567. "}",
  17568. eol,
  17569. eol,
  17570. ctx->total_data_read,
  17571. eol,
  17572. ctx->total_data_written,
  17573. eol);
  17574. context_info_length += mg_str_append(&buffer, end, block);
  17575. /* Execution time information */
  17576. gmt_time_string(start_time_str,
  17577. sizeof(start_time_str) - 1,
  17578. &start_time);
  17579. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17580. mg_snprintf(NULL,
  17581. NULL,
  17582. block,
  17583. sizeof(block),
  17584. ",%s\"time\" : {%s"
  17585. "\"uptime\" : %.0f,%s"
  17586. "\"start\" : \"%s\",%s"
  17587. "\"now\" : \"%s\"%s"
  17588. "}",
  17589. eol,
  17590. eol,
  17591. difftime(now, start_time),
  17592. eol,
  17593. start_time_str,
  17594. eol,
  17595. now_str,
  17596. eol);
  17597. context_info_length += mg_str_append(&buffer, end, block);
  17598. }
  17599. /* Terminate string */
  17600. if (append_eoobj) {
  17601. strcat(append_eoobj, eoobj);
  17602. }
  17603. context_info_length += sizeof(eoobj) - 1;
  17604. return (int)context_info_length;
  17605. #else
  17606. (void)ctx;
  17607. if ((buffer != NULL) && (buflen > 0)) {
  17608. *buffer = 0;
  17609. }
  17610. return 0;
  17611. #endif
  17612. }
  17613. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17614. /* Get connection information. It can be printed or stored by the caller.
  17615. * Return the size of available information. */
  17616. int
  17617. mg_get_connection_info(const struct mg_context *ctx,
  17618. int idx,
  17619. char *buffer,
  17620. int buflen)
  17621. {
  17622. const struct mg_connection *conn;
  17623. const struct mg_request_info *ri;
  17624. char *end, *append_eoobj = NULL, block[256];
  17625. size_t connection_info_length = 0;
  17626. int state = 0;
  17627. const char *state_str = "unknown";
  17628. #if defined(_WIN32)
  17629. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17630. #else
  17631. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17632. #endif
  17633. if ((buffer == NULL) || (buflen < 1)) {
  17634. buflen = 0;
  17635. end = buffer;
  17636. } else {
  17637. *buffer = 0;
  17638. end = buffer + buflen;
  17639. }
  17640. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17641. /* has enough space to append eoobj */
  17642. append_eoobj = buffer;
  17643. end -= sizeof(eoobj) - 1;
  17644. }
  17645. if ((ctx == NULL) || (idx < 0)) {
  17646. /* Parameter error */
  17647. return 0;
  17648. }
  17649. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  17650. /* Out of range */
  17651. return 0;
  17652. }
  17653. /* Take connection [idx]. This connection is not locked in
  17654. * any way, so some other thread might use it. */
  17655. conn = (ctx->worker_connections) + idx;
  17656. /* Initialize output string */
  17657. connection_info_length += mg_str_append(&buffer, end, "{");
  17658. /* Init variables */
  17659. ri = &(conn->request_info);
  17660. #if defined(USE_SERVER_STATS)
  17661. state = conn->conn_state;
  17662. /* State as string */
  17663. switch (state) {
  17664. case 0:
  17665. state_str = "undefined";
  17666. break;
  17667. case 1:
  17668. state_str = "not used";
  17669. break;
  17670. case 2:
  17671. state_str = "init";
  17672. break;
  17673. case 3:
  17674. state_str = "ready";
  17675. break;
  17676. case 4:
  17677. state_str = "processing";
  17678. break;
  17679. case 5:
  17680. state_str = "processed";
  17681. break;
  17682. case 6:
  17683. state_str = "to close";
  17684. break;
  17685. case 7:
  17686. state_str = "closing";
  17687. break;
  17688. case 8:
  17689. state_str = "closed";
  17690. break;
  17691. case 9:
  17692. state_str = "done";
  17693. break;
  17694. }
  17695. #endif
  17696. /* Connection info */
  17697. if ((state >= 3) && (state < 9)) {
  17698. mg_snprintf(NULL,
  17699. NULL,
  17700. block,
  17701. sizeof(block),
  17702. "%s\"connection\" : {%s"
  17703. "\"remote\" : {%s"
  17704. "\"protocol\" : \"%s\",%s"
  17705. "\"addr\" : \"%s\",%s"
  17706. "\"port\" : %u%s"
  17707. "},%s"
  17708. "\"handled_requests\" : %u%s"
  17709. "}",
  17710. eol,
  17711. eol,
  17712. eol,
  17713. get_proto_name(conn),
  17714. eol,
  17715. ri->remote_addr,
  17716. eol,
  17717. ri->remote_port,
  17718. eol,
  17719. eol,
  17720. conn->handled_requests,
  17721. eol);
  17722. connection_info_length += mg_str_append(&buffer, end, block);
  17723. }
  17724. /* Request info */
  17725. if ((state >= 4) && (state < 6)) {
  17726. mg_snprintf(NULL,
  17727. NULL,
  17728. block,
  17729. sizeof(block),
  17730. "%s%s\"request_info\" : {%s"
  17731. "\"method\" : \"%s\",%s"
  17732. "\"uri\" : \"%s\",%s"
  17733. "\"query\" : %s%s%s%s"
  17734. "}",
  17735. (connection_info_length > 1 ? "," : ""),
  17736. eol,
  17737. eol,
  17738. ri->request_method,
  17739. eol,
  17740. ri->request_uri,
  17741. eol,
  17742. ri->query_string ? "\"" : "",
  17743. ri->query_string ? ri->query_string : "null",
  17744. ri->query_string ? "\"" : "",
  17745. eol);
  17746. connection_info_length += mg_str_append(&buffer, end, block);
  17747. }
  17748. /* Execution time information */
  17749. if ((state >= 2) && (state < 9)) {
  17750. char start_time_str[64] = {0};
  17751. char close_time_str[64] = {0};
  17752. time_t start_time = conn->conn_birth_time;
  17753. time_t close_time = conn->conn_close_time;
  17754. double time_diff;
  17755. gmt_time_string(start_time_str,
  17756. sizeof(start_time_str) - 1,
  17757. &start_time);
  17758. if (close_time != 0) {
  17759. time_diff = difftime(close_time, start_time);
  17760. gmt_time_string(close_time_str,
  17761. sizeof(close_time_str) - 1,
  17762. &close_time);
  17763. } else {
  17764. time_t now = time(NULL);
  17765. time_diff = difftime(now, start_time);
  17766. close_time_str[0] = 0; /* or use "now" ? */
  17767. }
  17768. mg_snprintf(NULL,
  17769. NULL,
  17770. block,
  17771. sizeof(block),
  17772. "%s%s\"time\" : {%s"
  17773. "\"uptime\" : %.0f,%s"
  17774. "\"start\" : \"%s\",%s"
  17775. "\"closed\" : \"%s\"%s"
  17776. "}",
  17777. (connection_info_length > 1 ? "," : ""),
  17778. eol,
  17779. eol,
  17780. time_diff,
  17781. eol,
  17782. start_time_str,
  17783. eol,
  17784. close_time_str,
  17785. eol);
  17786. connection_info_length += mg_str_append(&buffer, end, block);
  17787. }
  17788. /* Remote user name */
  17789. if ((ri->remote_user) && (state < 9)) {
  17790. mg_snprintf(NULL,
  17791. NULL,
  17792. block,
  17793. sizeof(block),
  17794. "%s%s\"user\" : {%s"
  17795. "\"name\" : \"%s\",%s"
  17796. "}",
  17797. (connection_info_length > 1 ? "," : ""),
  17798. eol,
  17799. eol,
  17800. ri->remote_user,
  17801. eol);
  17802. connection_info_length += mg_str_append(&buffer, end, block);
  17803. }
  17804. /* Data block */
  17805. if (state >= 3) {
  17806. mg_snprintf(NULL,
  17807. NULL,
  17808. block,
  17809. sizeof(block),
  17810. "%s%s\"data\" : {%s"
  17811. "\"read\" : %" INT64_FMT ",%s"
  17812. "\"written\" : %" INT64_FMT "%s"
  17813. "}",
  17814. (connection_info_length > 1 ? "," : ""),
  17815. eol,
  17816. eol,
  17817. conn->consumed_content,
  17818. eol,
  17819. conn->num_bytes_sent,
  17820. eol);
  17821. connection_info_length += mg_str_append(&buffer, end, block);
  17822. }
  17823. /* State */
  17824. mg_snprintf(NULL,
  17825. NULL,
  17826. block,
  17827. sizeof(block),
  17828. "%s%s\"state\" : \"%s\"",
  17829. (connection_info_length > 1 ? "," : ""),
  17830. eol,
  17831. state_str);
  17832. connection_info_length += mg_str_append(&buffer, end, block);
  17833. /* Terminate string */
  17834. if (append_eoobj) {
  17835. strcat(append_eoobj, eoobj);
  17836. }
  17837. connection_info_length += sizeof(eoobj) - 1;
  17838. return (int)connection_info_length;
  17839. }
  17840. #endif
  17841. /* Initialize this library. This function does not need to be thread safe.
  17842. */
  17843. unsigned
  17844. mg_init_library(unsigned features)
  17845. {
  17846. #if !defined(NO_SSL)
  17847. char ebuf[128];
  17848. #endif
  17849. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17850. unsigned features_inited = features_to_init;
  17851. if (mg_init_library_called <= 0) {
  17852. /* Not initialized yet */
  17853. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17854. return 0;
  17855. }
  17856. }
  17857. mg_global_lock();
  17858. if (mg_init_library_called <= 0) {
  17859. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17860. /* Fatal error - abort start. However, this situation should
  17861. * never occur in practice. */
  17862. mg_global_unlock();
  17863. return 0;
  17864. }
  17865. #if defined(_WIN32)
  17866. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17867. #else
  17868. pthread_mutexattr_init(&pthread_mutex_attr);
  17869. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17870. #endif
  17871. #if defined(USE_LUA)
  17872. lua_init_optional_libraries();
  17873. #endif
  17874. }
  17875. mg_global_unlock();
  17876. #if !defined(NO_SSL)
  17877. if (features_to_init & MG_FEATURES_SSL) {
  17878. if (!mg_ssl_initialized) {
  17879. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17880. mg_ssl_initialized = 1;
  17881. } else {
  17882. (void)ebuf;
  17883. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17884. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17885. }
  17886. } else {
  17887. /* ssl already initialized */
  17888. }
  17889. }
  17890. #endif
  17891. /* Start WinSock for Windows */
  17892. mg_global_lock();
  17893. if (mg_init_library_called <= 0) {
  17894. #if defined(_WIN32)
  17895. WSADATA data;
  17896. WSAStartup(MAKEWORD(2, 2), &data);
  17897. #endif /* _WIN32 */
  17898. mg_init_library_called = 1;
  17899. } else {
  17900. mg_init_library_called++;
  17901. }
  17902. mg_global_unlock();
  17903. return features_inited;
  17904. }
  17905. /* Un-initialize this library. */
  17906. unsigned
  17907. mg_exit_library(void)
  17908. {
  17909. if (mg_init_library_called <= 0) {
  17910. return 0;
  17911. }
  17912. mg_global_lock();
  17913. mg_init_library_called--;
  17914. if (mg_init_library_called == 0) {
  17915. #if defined(_WIN32)
  17916. (void)WSACleanup();
  17917. #endif /* _WIN32 */
  17918. #if !defined(NO_SSL)
  17919. if (mg_ssl_initialized) {
  17920. uninitialize_ssl();
  17921. mg_ssl_initialized = 0;
  17922. }
  17923. #endif
  17924. #if defined(_WIN32)
  17925. (void)pthread_mutex_destroy(&global_log_file_lock);
  17926. #else
  17927. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17928. #endif
  17929. (void)pthread_key_delete(sTlsKey);
  17930. #if defined(USE_LUA)
  17931. lua_exit_optional_libraries();
  17932. #endif
  17933. mg_global_unlock();
  17934. (void)pthread_mutex_destroy(&global_lock_mutex);
  17935. return 1;
  17936. }
  17937. mg_global_unlock();
  17938. return 1;
  17939. }
  17940. /* End of civetweb.c */