civetweb.c 554 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676
  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. is_tls_set = 1;
  11628. tls.is_master = -1;
  11629. tls.thread_idx = phys_ctx->starter_thread_idx;
  11630. #if defined(_WIN32)
  11631. tls.pthread_cond_helper_mutex = NULL;
  11632. #endif
  11633. pthread_setspecific(sTlsKey, &tls);
  11634. }
  11635. mg_lock_context(phys_ctx);
  11636. /* first try to find an existing handler */
  11637. lastref = &(dom_ctx->handlers);
  11638. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11639. if (tmp_rh->handler_type == handler_type) {
  11640. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11641. if (!is_delete_request) {
  11642. /* update existing handler */
  11643. if (handler_type == REQUEST_HANDLER) {
  11644. /* Wait for end of use before updating */
  11645. handler_info_wait_unused(tmp_rh);
  11646. /* Ok, the handler is no more use -> Update it */
  11647. tmp_rh->handler = handler;
  11648. } else if (handler_type == WEBSOCKET_HANDLER) {
  11649. tmp_rh->subprotocols = subprotocols;
  11650. tmp_rh->connect_handler = connect_handler;
  11651. tmp_rh->ready_handler = ready_handler;
  11652. tmp_rh->data_handler = data_handler;
  11653. tmp_rh->close_handler = close_handler;
  11654. } else { /* AUTH_HANDLER */
  11655. tmp_rh->auth_handler = auth_handler;
  11656. }
  11657. tmp_rh->cbdata = cbdata;
  11658. } else {
  11659. /* remove existing handler */
  11660. if (handler_type == REQUEST_HANDLER) {
  11661. /* Wait for end of use before removing */
  11662. handler_info_wait_unused(tmp_rh);
  11663. /* Ok, the handler is no more used -> Destroy resources
  11664. */
  11665. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11666. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11667. }
  11668. *lastref = tmp_rh->next;
  11669. mg_free(tmp_rh->uri);
  11670. mg_free(tmp_rh);
  11671. }
  11672. mg_unlock_context(phys_ctx);
  11673. if (is_tls_set) {
  11674. pthread_setspecific(sTlsKey, NULL);
  11675. }
  11676. return;
  11677. }
  11678. }
  11679. lastref = &(tmp_rh->next);
  11680. }
  11681. if (is_delete_request) {
  11682. /* no handler to set, this was a remove request to a non-existing
  11683. * handler */
  11684. mg_unlock_context(phys_ctx);
  11685. if (is_tls_set) {
  11686. pthread_setspecific(sTlsKey, NULL);
  11687. }
  11688. return;
  11689. }
  11690. tmp_rh =
  11691. (struct mg_handler_info *)mg_calloc_ctx(1,
  11692. sizeof(struct mg_handler_info),
  11693. phys_ctx);
  11694. if (tmp_rh == NULL) {
  11695. mg_unlock_context(phys_ctx);
  11696. mg_cry_ctx_internal(phys_ctx,
  11697. "%s",
  11698. "Cannot create new request handler struct, OOM");
  11699. if (is_tls_set) {
  11700. pthread_setspecific(sTlsKey, NULL);
  11701. }
  11702. return;
  11703. }
  11704. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11705. if (!tmp_rh->uri) {
  11706. mg_unlock_context(phys_ctx);
  11707. mg_free(tmp_rh);
  11708. mg_cry_ctx_internal(phys_ctx,
  11709. "%s",
  11710. "Cannot create new request handler struct, OOM");
  11711. if (is_tls_set) {
  11712. pthread_setspecific(sTlsKey, NULL);
  11713. }
  11714. return;
  11715. }
  11716. tmp_rh->uri_len = urilen;
  11717. if (handler_type == REQUEST_HANDLER) {
  11718. /* Init refcount mutex and condition */
  11719. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11720. mg_unlock_context(phys_ctx);
  11721. mg_free(tmp_rh);
  11722. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11723. if (is_tls_set) {
  11724. pthread_setspecific(sTlsKey, NULL);
  11725. }
  11726. return;
  11727. }
  11728. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11729. mg_unlock_context(phys_ctx);
  11730. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11731. mg_free(tmp_rh);
  11732. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11733. if (is_tls_set) {
  11734. pthread_setspecific(sTlsKey, NULL);
  11735. }
  11736. return;
  11737. }
  11738. tmp_rh->refcount = 0;
  11739. tmp_rh->handler = handler;
  11740. } else if (handler_type == WEBSOCKET_HANDLER) {
  11741. tmp_rh->subprotocols = subprotocols;
  11742. tmp_rh->connect_handler = connect_handler;
  11743. tmp_rh->ready_handler = ready_handler;
  11744. tmp_rh->data_handler = data_handler;
  11745. tmp_rh->close_handler = close_handler;
  11746. } else { /* AUTH_HANDLER */
  11747. tmp_rh->auth_handler = auth_handler;
  11748. }
  11749. tmp_rh->cbdata = cbdata;
  11750. tmp_rh->handler_type = handler_type;
  11751. tmp_rh->next = NULL;
  11752. *lastref = tmp_rh;
  11753. mg_unlock_context(phys_ctx);
  11754. if (is_tls_set) {
  11755. pthread_setspecific(sTlsKey, NULL);
  11756. }
  11757. }
  11758. void
  11759. mg_set_request_handler(struct mg_context *ctx,
  11760. const char *uri,
  11761. mg_request_handler handler,
  11762. void *cbdata)
  11763. {
  11764. mg_set_handler_type(ctx,
  11765. &(ctx->dd),
  11766. uri,
  11767. REQUEST_HANDLER,
  11768. handler == NULL,
  11769. handler,
  11770. NULL,
  11771. NULL,
  11772. NULL,
  11773. NULL,
  11774. NULL,
  11775. NULL,
  11776. cbdata);
  11777. }
  11778. void
  11779. mg_set_websocket_handler(struct mg_context *ctx,
  11780. const char *uri,
  11781. mg_websocket_connect_handler connect_handler,
  11782. mg_websocket_ready_handler ready_handler,
  11783. mg_websocket_data_handler data_handler,
  11784. mg_websocket_close_handler close_handler,
  11785. void *cbdata)
  11786. {
  11787. mg_set_websocket_handler_with_subprotocols(ctx,
  11788. uri,
  11789. NULL,
  11790. connect_handler,
  11791. ready_handler,
  11792. data_handler,
  11793. close_handler,
  11794. cbdata);
  11795. }
  11796. void
  11797. mg_set_websocket_handler_with_subprotocols(
  11798. struct mg_context *ctx,
  11799. const char *uri,
  11800. struct mg_websocket_subprotocols *subprotocols,
  11801. mg_websocket_connect_handler connect_handler,
  11802. mg_websocket_ready_handler ready_handler,
  11803. mg_websocket_data_handler data_handler,
  11804. mg_websocket_close_handler close_handler,
  11805. void *cbdata)
  11806. {
  11807. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11808. && (data_handler == NULL)
  11809. && (close_handler == NULL);
  11810. mg_set_handler_type(ctx,
  11811. &(ctx->dd),
  11812. uri,
  11813. WEBSOCKET_HANDLER,
  11814. is_delete_request,
  11815. NULL,
  11816. subprotocols,
  11817. connect_handler,
  11818. ready_handler,
  11819. data_handler,
  11820. close_handler,
  11821. NULL,
  11822. cbdata);
  11823. }
  11824. void
  11825. mg_set_auth_handler(struct mg_context *ctx,
  11826. const char *uri,
  11827. mg_authorization_handler handler,
  11828. void *cbdata)
  11829. {
  11830. mg_set_handler_type(ctx,
  11831. &(ctx->dd),
  11832. uri,
  11833. AUTH_HANDLER,
  11834. handler == NULL,
  11835. NULL,
  11836. NULL,
  11837. NULL,
  11838. NULL,
  11839. NULL,
  11840. NULL,
  11841. handler,
  11842. cbdata);
  11843. }
  11844. static int
  11845. get_request_handler(struct mg_connection *conn,
  11846. int handler_type,
  11847. mg_request_handler *handler,
  11848. struct mg_websocket_subprotocols **subprotocols,
  11849. mg_websocket_connect_handler *connect_handler,
  11850. mg_websocket_ready_handler *ready_handler,
  11851. mg_websocket_data_handler *data_handler,
  11852. mg_websocket_close_handler *close_handler,
  11853. mg_authorization_handler *auth_handler,
  11854. void **cbdata,
  11855. struct mg_handler_info **handler_info)
  11856. {
  11857. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11858. if (request_info) {
  11859. const char *uri = request_info->local_uri;
  11860. size_t urilen = strlen(uri);
  11861. struct mg_handler_info *tmp_rh;
  11862. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11863. return 0;
  11864. }
  11865. mg_lock_context(conn->phys_ctx);
  11866. /* first try for an exact match */
  11867. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11868. tmp_rh = tmp_rh->next) {
  11869. if (tmp_rh->handler_type == handler_type) {
  11870. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11871. if (handler_type == WEBSOCKET_HANDLER) {
  11872. *subprotocols = tmp_rh->subprotocols;
  11873. *connect_handler = tmp_rh->connect_handler;
  11874. *ready_handler = tmp_rh->ready_handler;
  11875. *data_handler = tmp_rh->data_handler;
  11876. *close_handler = tmp_rh->close_handler;
  11877. } else if (handler_type == REQUEST_HANDLER) {
  11878. *handler = tmp_rh->handler;
  11879. /* Acquire handler and give it back */
  11880. handler_info_acquire(tmp_rh);
  11881. *handler_info = tmp_rh;
  11882. } else { /* AUTH_HANDLER */
  11883. *auth_handler = tmp_rh->auth_handler;
  11884. }
  11885. *cbdata = tmp_rh->cbdata;
  11886. mg_unlock_context(conn->phys_ctx);
  11887. return 1;
  11888. }
  11889. }
  11890. }
  11891. /* next try for a partial match, we will accept uri/something */
  11892. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11893. tmp_rh = tmp_rh->next) {
  11894. if (tmp_rh->handler_type == handler_type) {
  11895. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11896. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11897. if (handler_type == WEBSOCKET_HANDLER) {
  11898. *subprotocols = tmp_rh->subprotocols;
  11899. *connect_handler = tmp_rh->connect_handler;
  11900. *ready_handler = tmp_rh->ready_handler;
  11901. *data_handler = tmp_rh->data_handler;
  11902. *close_handler = tmp_rh->close_handler;
  11903. } else if (handler_type == REQUEST_HANDLER) {
  11904. *handler = tmp_rh->handler;
  11905. /* Acquire handler and give it back */
  11906. handler_info_acquire(tmp_rh);
  11907. *handler_info = tmp_rh;
  11908. } else { /* AUTH_HANDLER */
  11909. *auth_handler = tmp_rh->auth_handler;
  11910. }
  11911. *cbdata = tmp_rh->cbdata;
  11912. mg_unlock_context(conn->phys_ctx);
  11913. return 1;
  11914. }
  11915. }
  11916. }
  11917. /* finally try for pattern match */
  11918. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11919. tmp_rh = tmp_rh->next) {
  11920. if (tmp_rh->handler_type == handler_type) {
  11921. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11922. if (handler_type == WEBSOCKET_HANDLER) {
  11923. *subprotocols = tmp_rh->subprotocols;
  11924. *connect_handler = tmp_rh->connect_handler;
  11925. *ready_handler = tmp_rh->ready_handler;
  11926. *data_handler = tmp_rh->data_handler;
  11927. *close_handler = tmp_rh->close_handler;
  11928. } else if (handler_type == REQUEST_HANDLER) {
  11929. *handler = tmp_rh->handler;
  11930. /* Acquire handler and give it back */
  11931. handler_info_acquire(tmp_rh);
  11932. *handler_info = tmp_rh;
  11933. } else { /* AUTH_HANDLER */
  11934. *auth_handler = tmp_rh->auth_handler;
  11935. }
  11936. *cbdata = tmp_rh->cbdata;
  11937. mg_unlock_context(conn->phys_ctx);
  11938. return 1;
  11939. }
  11940. }
  11941. }
  11942. mg_unlock_context(conn->phys_ctx);
  11943. }
  11944. return 0; /* none found */
  11945. }
  11946. /* Check if the script file is in a path, allowed for script files.
  11947. * This can be used if uploading files is possible not only for the server
  11948. * admin, and the upload mechanism does not check the file extension.
  11949. */
  11950. static int
  11951. is_in_script_path(const struct mg_connection *conn, const char *path)
  11952. {
  11953. /* TODO (Feature): Add config value for allowed script path.
  11954. * Default: All allowed. */
  11955. (void)conn;
  11956. (void)path;
  11957. return 1;
  11958. }
  11959. #if defined(USE_WEBSOCKET) \
  11960. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  11961. static int
  11962. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11963. void *cbdata)
  11964. {
  11965. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11966. if (pcallbacks->websocket_connect) {
  11967. return pcallbacks->websocket_connect(conn);
  11968. }
  11969. /* No handler set - assume "OK" */
  11970. return 0;
  11971. }
  11972. static void
  11973. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11974. {
  11975. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11976. if (pcallbacks->websocket_ready) {
  11977. pcallbacks->websocket_ready(conn);
  11978. }
  11979. }
  11980. static int
  11981. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11982. int bits,
  11983. char *data,
  11984. size_t len,
  11985. void *cbdata)
  11986. {
  11987. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11988. if (pcallbacks->websocket_data) {
  11989. return pcallbacks->websocket_data(conn, bits, data, len);
  11990. }
  11991. /* No handler set - assume "OK" */
  11992. return 1;
  11993. }
  11994. static void
  11995. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  11996. void *cbdata)
  11997. {
  11998. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11999. if (pcallbacks->connection_close) {
  12000. pcallbacks->connection_close(conn);
  12001. }
  12002. }
  12003. #endif
  12004. /* This is the heart of the Civetweb's logic.
  12005. * This function is called when the request is read, parsed and validated,
  12006. * and Civetweb must decide what action to take: serve a file, or
  12007. * a directory, or call embedded function, etcetera. */
  12008. static void
  12009. handle_request(struct mg_connection *conn)
  12010. {
  12011. struct mg_request_info *ri = &conn->request_info;
  12012. char path[PATH_MAX];
  12013. int uri_len, ssl_index;
  12014. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12015. is_put_or_delete_request = 0, is_callback_resource = 0;
  12016. int i;
  12017. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12018. mg_request_handler callback_handler = NULL;
  12019. struct mg_handler_info *handler_info = NULL;
  12020. struct mg_websocket_subprotocols *subprotocols;
  12021. mg_websocket_connect_handler ws_connect_handler = NULL;
  12022. mg_websocket_ready_handler ws_ready_handler = NULL;
  12023. mg_websocket_data_handler ws_data_handler = NULL;
  12024. mg_websocket_close_handler ws_close_handler = NULL;
  12025. void *callback_data = NULL;
  12026. mg_authorization_handler auth_handler = NULL;
  12027. void *auth_callback_data = NULL;
  12028. int handler_type;
  12029. time_t curtime = time(NULL);
  12030. char date[64];
  12031. path[0] = 0;
  12032. /* 1. get the request url */
  12033. /* 1.1. split into url and query string */
  12034. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12035. != NULL) {
  12036. *((char *)conn->request_info.query_string++) = '\0';
  12037. }
  12038. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12039. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12040. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12041. if (ssl_index >= 0) {
  12042. redirect_to_https_port(conn, ssl_index);
  12043. } else {
  12044. /* A http to https forward port has been specified,
  12045. * but no https port to forward to. */
  12046. mg_send_http_error(conn,
  12047. 503,
  12048. "%s",
  12049. "Error: SSL forward not configured properly");
  12050. mg_cry_internal(conn,
  12051. "%s",
  12052. "Can not redirect to SSL, no SSL port available");
  12053. }
  12054. return;
  12055. }
  12056. uri_len = (int)strlen(ri->local_uri);
  12057. /* 1.3. decode url (if config says so) */
  12058. if (should_decode_url(conn)) {
  12059. mg_url_decode(
  12060. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12061. }
  12062. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12063. * not possible */
  12064. remove_dot_segments((char *)ri->local_uri);
  12065. /* step 1. completed, the url is known now */
  12066. uri_len = (int)strlen(ri->local_uri);
  12067. DEBUG_TRACE("URL: %s", ri->local_uri);
  12068. /* 2. if this ip has limited speed, set it for this connection */
  12069. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12070. get_remote_ip(conn),
  12071. ri->local_uri);
  12072. /* 3. call a "handle everything" callback, if registered */
  12073. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12074. /* Note that since V1.7 the "begin_request" function is called
  12075. * before an authorization check. If an authorization check is
  12076. * required, use a request_handler instead. */
  12077. i = conn->phys_ctx->callbacks.begin_request(conn);
  12078. if (i > 0) {
  12079. /* callback already processed the request. Store the
  12080. return value as a status code for the access log. */
  12081. conn->status_code = i;
  12082. discard_unread_request_data(conn);
  12083. return;
  12084. } else if (i == 0) {
  12085. /* civetweb should process the request */
  12086. } else {
  12087. /* unspecified - may change with the next version */
  12088. return;
  12089. }
  12090. }
  12091. /* request not yet handled by a handler or redirect, so the request
  12092. * is processed here */
  12093. /* 4. Check for CORS preflight requests and handle them (if configured).
  12094. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12095. */
  12096. if (!strcmp(ri->request_method, "OPTIONS")) {
  12097. /* Send a response to CORS preflights only if
  12098. * access_control_allow_methods is not NULL and not an empty string.
  12099. * In this case, scripts can still handle CORS. */
  12100. const char *cors_meth_cfg =
  12101. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12102. const char *cors_orig_cfg =
  12103. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12104. const char *cors_origin =
  12105. get_header(ri->http_headers, ri->num_headers, "Origin");
  12106. const char *cors_acrm = get_header(ri->http_headers,
  12107. ri->num_headers,
  12108. "Access-Control-Request-Method");
  12109. /* Todo: check if cors_origin is in cors_orig_cfg.
  12110. * Or, let the client check this. */
  12111. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12112. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12113. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12114. /* This is a valid CORS preflight, and the server is configured
  12115. * to
  12116. * handle it automatically. */
  12117. const char *cors_acrh =
  12118. get_header(ri->http_headers,
  12119. ri->num_headers,
  12120. "Access-Control-Request-Headers");
  12121. gmt_time_string(date, sizeof(date), &curtime);
  12122. mg_printf(conn,
  12123. "HTTP/1.1 200 OK\r\n"
  12124. "Date: %s\r\n"
  12125. "Access-Control-Allow-Origin: %s\r\n"
  12126. "Access-Control-Allow-Methods: %s\r\n"
  12127. "Content-Length: 0\r\n"
  12128. "Connection: %s\r\n",
  12129. date,
  12130. cors_orig_cfg,
  12131. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12132. suggest_connection_header(conn));
  12133. if (cors_acrh != NULL) {
  12134. /* CORS request is asking for additional headers */
  12135. const char *cors_hdr_cfg =
  12136. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12137. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12138. /* Allow only if access_control_allow_headers is
  12139. * not NULL and not an empty string. If this
  12140. * configuration is set to *, allow everything.
  12141. * Otherwise this configuration must be a list
  12142. * of allowed HTTP header names. */
  12143. mg_printf(conn,
  12144. "Access-Control-Allow-Headers: %s\r\n",
  12145. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12146. : cors_hdr_cfg));
  12147. }
  12148. }
  12149. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12150. mg_printf(conn, "\r\n");
  12151. return;
  12152. }
  12153. }
  12154. /* 5. interpret the url to find out how the request must be handled
  12155. */
  12156. /* 5.1. first test, if the request targets the regular http(s)://
  12157. * protocol namespace or the websocket ws(s):// protocol namespace.
  12158. */
  12159. is_websocket_request = is_websocket_protocol(conn);
  12160. #if defined(USE_WEBSOCKET)
  12161. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12162. #else
  12163. handler_type = REQUEST_HANDLER;
  12164. #endif /* defined(USE_WEBSOCKET) */
  12165. /* 5.2. check if the request will be handled by a callback */
  12166. if (get_request_handler(conn,
  12167. handler_type,
  12168. &callback_handler,
  12169. &subprotocols,
  12170. &ws_connect_handler,
  12171. &ws_ready_handler,
  12172. &ws_data_handler,
  12173. &ws_close_handler,
  12174. NULL,
  12175. &callback_data,
  12176. &handler_info)) {
  12177. /* 5.2.1. A callback will handle this request. All requests
  12178. * handled
  12179. * by a callback have to be considered as requests to a script
  12180. * resource. */
  12181. is_callback_resource = 1;
  12182. is_script_resource = 1;
  12183. is_put_or_delete_request = is_put_or_delete_method(conn);
  12184. } else {
  12185. no_callback_resource:
  12186. /* 5.2.2. No callback is responsible for this request. The URI
  12187. * addresses a file based resource (static content or Lua/cgi
  12188. * scripts in the file system). */
  12189. is_callback_resource = 0;
  12190. interpret_uri(conn,
  12191. path,
  12192. sizeof(path),
  12193. &file.stat,
  12194. &is_found,
  12195. &is_script_resource,
  12196. &is_websocket_request,
  12197. &is_put_or_delete_request);
  12198. }
  12199. /* 6. authorization check */
  12200. /* 6.1. a custom authorization handler is installed */
  12201. if (get_request_handler(conn,
  12202. AUTH_HANDLER,
  12203. NULL,
  12204. NULL,
  12205. NULL,
  12206. NULL,
  12207. NULL,
  12208. NULL,
  12209. &auth_handler,
  12210. &auth_callback_data,
  12211. NULL)) {
  12212. if (!auth_handler(conn, auth_callback_data)) {
  12213. return;
  12214. }
  12215. } else if (is_put_or_delete_request && !is_script_resource
  12216. && !is_callback_resource) {
  12217. /* 6.2. this request is a PUT/DELETE to a real file */
  12218. /* 6.2.1. thus, the server must have real files */
  12219. #if defined(NO_FILES)
  12220. if (1) {
  12221. #else
  12222. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12223. #endif
  12224. /* This server does not have any real files, thus the
  12225. * PUT/DELETE methods are not valid. */
  12226. mg_send_http_error(conn,
  12227. 405,
  12228. "%s method not allowed",
  12229. conn->request_info.request_method);
  12230. return;
  12231. }
  12232. #if !defined(NO_FILES)
  12233. /* 6.2.2. Check if put authorization for static files is
  12234. * available.
  12235. */
  12236. if (!is_authorized_for_put(conn)) {
  12237. send_authorization_request(conn, NULL);
  12238. return;
  12239. }
  12240. #endif
  12241. } else {
  12242. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12243. * or it is a PUT or DELETE request to a resource that does not
  12244. * correspond to a file. Check authorization. */
  12245. if (!check_authorization(conn, path)) {
  12246. send_authorization_request(conn, NULL);
  12247. return;
  12248. }
  12249. }
  12250. /* request is authorized or does not need authorization */
  12251. /* 7. check if there are request handlers for this uri */
  12252. if (is_callback_resource) {
  12253. if (!is_websocket_request) {
  12254. i = callback_handler(conn, callback_data);
  12255. /* Callback handler will not be used anymore. Release it */
  12256. handler_info_release(handler_info);
  12257. if (i > 0) {
  12258. /* Do nothing, callback has served the request. Store
  12259. * then return value as status code for the log and discard
  12260. * all data from the client not used by the callback. */
  12261. conn->status_code = i;
  12262. discard_unread_request_data(conn);
  12263. } else {
  12264. /* The handler did NOT handle the request. */
  12265. /* Some proper reactions would be:
  12266. * a) close the connections without sending anything
  12267. * b) send a 404 not found
  12268. * c) try if there is a file matching the URI
  12269. * It would be possible to do a, b or c in the callback
  12270. * implementation, and return 1 - we cannot do anything
  12271. * here, that is not possible in the callback.
  12272. *
  12273. * TODO: What would be the best reaction here?
  12274. * (Note: The reaction may change, if there is a better
  12275. *idea.)
  12276. */
  12277. /* For the moment, use option c: We look for a proper file,
  12278. * but since a file request is not always a script resource,
  12279. * the authorization check might be different. */
  12280. interpret_uri(conn,
  12281. path,
  12282. sizeof(path),
  12283. &file.stat,
  12284. &is_found,
  12285. &is_script_resource,
  12286. &is_websocket_request,
  12287. &is_put_or_delete_request);
  12288. callback_handler = NULL;
  12289. /* Here we are at a dead end:
  12290. * According to URI matching, a callback should be
  12291. * responsible for handling the request,
  12292. * we called it, but the callback declared itself
  12293. * not responsible.
  12294. * We use a goto here, to get out of this dead end,
  12295. * and continue with the default handling.
  12296. * A goto here is simpler and better to understand
  12297. * than some curious loop. */
  12298. goto no_callback_resource;
  12299. }
  12300. } else {
  12301. #if defined(USE_WEBSOCKET)
  12302. handle_websocket_request(conn,
  12303. path,
  12304. is_callback_resource,
  12305. subprotocols,
  12306. ws_connect_handler,
  12307. ws_ready_handler,
  12308. ws_data_handler,
  12309. ws_close_handler,
  12310. callback_data);
  12311. #endif
  12312. }
  12313. return;
  12314. }
  12315. /* 8. handle websocket requests */
  12316. #if defined(USE_WEBSOCKET)
  12317. if (is_websocket_request) {
  12318. if (is_script_resource) {
  12319. if (is_in_script_path(conn, path)) {
  12320. /* Websocket Lua script */
  12321. handle_websocket_request(conn,
  12322. path,
  12323. 0 /* Lua Script */,
  12324. NULL,
  12325. NULL,
  12326. NULL,
  12327. NULL,
  12328. NULL,
  12329. conn->phys_ctx->user_data);
  12330. } else {
  12331. /* Script was in an illegal path */
  12332. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12333. }
  12334. } else {
  12335. #if defined(MG_LEGACY_INTERFACE)
  12336. handle_websocket_request(
  12337. conn,
  12338. path,
  12339. !is_script_resource /* could be deprecated global callback */,
  12340. NULL,
  12341. deprecated_websocket_connect_wrapper,
  12342. deprecated_websocket_ready_wrapper,
  12343. deprecated_websocket_data_wrapper,
  12344. NULL,
  12345. conn->phys_ctx->callbacks);
  12346. #else
  12347. mg_send_http_error(conn, 404, "%s", "Not found");
  12348. #endif
  12349. }
  12350. return;
  12351. } else
  12352. #endif
  12353. #if defined(NO_FILES)
  12354. /* 9a. In case the server uses only callbacks, this uri is
  12355. * unknown.
  12356. * Then, all request handling ends here. */
  12357. mg_send_http_error(conn, 404, "%s", "Not Found");
  12358. #else
  12359. /* 9b. This request is either for a static file or resource handled
  12360. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12361. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12362. mg_send_http_error(conn, 404, "%s", "Not Found");
  12363. return;
  12364. }
  12365. /* 10. Request is handled by a script */
  12366. if (is_script_resource) {
  12367. handle_file_based_request(conn, path, &file);
  12368. return;
  12369. }
  12370. /* 11. Handle put/delete/mkcol requests */
  12371. if (is_put_or_delete_request) {
  12372. /* 11.1. PUT method */
  12373. if (!strcmp(ri->request_method, "PUT")) {
  12374. put_file(conn, path);
  12375. return;
  12376. }
  12377. /* 11.2. DELETE method */
  12378. if (!strcmp(ri->request_method, "DELETE")) {
  12379. delete_file(conn, path);
  12380. return;
  12381. }
  12382. /* 11.3. MKCOL method */
  12383. if (!strcmp(ri->request_method, "MKCOL")) {
  12384. mkcol(conn, path);
  12385. return;
  12386. }
  12387. /* 11.4. PATCH method
  12388. * This method is not supported for static resources,
  12389. * only for scripts (Lua, CGI) and callbacks. */
  12390. mg_send_http_error(conn,
  12391. 405,
  12392. "%s method not allowed",
  12393. conn->request_info.request_method);
  12394. return;
  12395. }
  12396. /* 11. File does not exist, or it was configured that it should be
  12397. * hidden */
  12398. if (!is_found || (must_hide_file(conn, path))) {
  12399. mg_send_http_error(conn, 404, "%s", "Not found");
  12400. return;
  12401. }
  12402. /* 12. Directory uris should end with a slash */
  12403. if (file.stat.is_directory && (uri_len > 0)
  12404. && (ri->local_uri[uri_len - 1] != '/')) {
  12405. gmt_time_string(date, sizeof(date), &curtime);
  12406. mg_printf(conn,
  12407. "HTTP/1.1 301 Moved Permanently\r\n"
  12408. "Location: %s/\r\n"
  12409. "Date: %s\r\n"
  12410. /* "Cache-Control: private\r\n" (= default) */
  12411. "Content-Length: 0\r\n"
  12412. "Connection: %s\r\n",
  12413. ri->request_uri,
  12414. date,
  12415. suggest_connection_header(conn));
  12416. send_additional_header(conn);
  12417. mg_printf(conn, "\r\n");
  12418. return;
  12419. }
  12420. /* 13. Handle other methods than GET/HEAD */
  12421. /* 13.1. Handle PROPFIND */
  12422. if (!strcmp(ri->request_method, "PROPFIND")) {
  12423. handle_propfind(conn, path, &file.stat);
  12424. return;
  12425. }
  12426. /* 13.2. Handle OPTIONS for files */
  12427. if (!strcmp(ri->request_method, "OPTIONS")) {
  12428. /* This standard handler is only used for real files.
  12429. * Scripts should support the OPTIONS method themselves, to allow a
  12430. * maximum flexibility.
  12431. * Lua and CGI scripts may fully support CORS this way (including
  12432. * preflights). */
  12433. send_options(conn);
  12434. return;
  12435. }
  12436. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12437. if ((0 != strcmp(ri->request_method, "GET"))
  12438. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12439. mg_send_http_error(conn,
  12440. 405,
  12441. "%s method not allowed",
  12442. conn->request_info.request_method);
  12443. return;
  12444. }
  12445. /* 14. directories */
  12446. if (file.stat.is_directory) {
  12447. /* Substitute files have already been handled above. */
  12448. /* Here we can either generate and send a directory listing,
  12449. * or send an "access denied" error. */
  12450. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12451. "yes")) {
  12452. handle_directory_request(conn, path);
  12453. } else {
  12454. mg_send_http_error(conn,
  12455. 403,
  12456. "%s",
  12457. "Error: Directory listing denied");
  12458. }
  12459. return;
  12460. }
  12461. /* 15. read a normal file with GET or HEAD */
  12462. handle_file_based_request(conn, path, &file);
  12463. #endif /* !defined(NO_FILES) */
  12464. }
  12465. #if !defined(NO_FILESYSTEMS)
  12466. static void
  12467. handle_file_based_request(struct mg_connection *conn,
  12468. const char *path,
  12469. struct mg_file *file)
  12470. {
  12471. if (!conn || !conn->dom_ctx) {
  12472. return;
  12473. }
  12474. if (0) {
  12475. #if defined(USE_LUA)
  12476. } else if (match_prefix(
  12477. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12478. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12479. path)
  12480. > 0) {
  12481. if (is_in_script_path(conn, path)) {
  12482. /* Lua server page: an SSI like page containing mostly plain
  12483. * html
  12484. * code
  12485. * plus some tags with server generated contents. */
  12486. handle_lsp_request(conn, path, file, NULL);
  12487. } else {
  12488. /* Script was in an illegal path */
  12489. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12490. }
  12491. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12492. strlen(
  12493. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12494. path)
  12495. > 0) {
  12496. if (is_in_script_path(conn, path)) {
  12497. /* Lua in-server module script: a CGI like script used to
  12498. * generate
  12499. * the
  12500. * entire reply. */
  12501. mg_exec_lua_script(conn, path, NULL);
  12502. } else {
  12503. /* Script was in an illegal path */
  12504. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12505. }
  12506. #endif
  12507. #if defined(USE_DUKTAPE)
  12508. } else if (match_prefix(
  12509. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12510. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12511. path)
  12512. > 0) {
  12513. if (is_in_script_path(conn, path)) {
  12514. /* Call duktape to generate the page */
  12515. mg_exec_duktape_script(conn, path);
  12516. } else {
  12517. /* Script was in an illegal path */
  12518. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12519. }
  12520. #endif
  12521. #if !defined(NO_CGI)
  12522. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12523. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12524. path)
  12525. > 0) {
  12526. if (is_in_script_path(conn, path)) {
  12527. /* CGI scripts may support all HTTP methods */
  12528. handle_cgi_request(conn, path);
  12529. } else {
  12530. /* Script was in an illegal path */
  12531. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12532. }
  12533. #endif /* !NO_CGI */
  12534. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12535. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12536. path)
  12537. > 0) {
  12538. if (is_in_script_path(conn, path)) {
  12539. handle_ssi_file_request(conn, path, file);
  12540. } else {
  12541. /* Script was in an illegal path */
  12542. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12543. }
  12544. #if !defined(NO_CACHING)
  12545. } else if ((!conn->in_error_handler)
  12546. && is_not_modified(conn, &file->stat)) {
  12547. /* Send 304 "Not Modified" - this must not send any body data */
  12548. handle_not_modified_static_file_request(conn, file);
  12549. #endif /* !NO_CACHING */
  12550. } else {
  12551. handle_static_file_request(conn, path, file, NULL, NULL);
  12552. }
  12553. }
  12554. #endif /* NO_FILESYSTEMS */
  12555. static void
  12556. close_all_listening_sockets(struct mg_context *ctx)
  12557. {
  12558. unsigned int i;
  12559. if (!ctx) {
  12560. return;
  12561. }
  12562. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12563. closesocket(ctx->listening_sockets[i].sock);
  12564. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12565. }
  12566. mg_free(ctx->listening_sockets);
  12567. ctx->listening_sockets = NULL;
  12568. mg_free(ctx->listening_socket_fds);
  12569. ctx->listening_socket_fds = NULL;
  12570. }
  12571. /* Valid listening port specification is: [ip_address:]port[s]
  12572. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12573. * Examples for IPv6: [::]:80, [::1]:80,
  12574. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12575. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12576. * In order to bind to both, IPv4 and IPv6, you can either add
  12577. * both ports using 8080,[::]:8080, or the short form +8080.
  12578. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12579. * one only accepting IPv4 the other only IPv6. +8080 creates
  12580. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12581. * environment, they might work differently, or might not work
  12582. * at all - it must be tested what options work best in the
  12583. * relevant network environment.
  12584. */
  12585. static int
  12586. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12587. {
  12588. unsigned int a, b, c, d, port;
  12589. int ch, len;
  12590. const char *cb;
  12591. char *endptr;
  12592. #if defined(USE_IPV6)
  12593. char buf[100] = {0};
  12594. #endif
  12595. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12596. * Also, all-zeroes in the socket address means binding to all addresses
  12597. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12598. memset(so, 0, sizeof(*so));
  12599. so->lsa.sin.sin_family = AF_INET;
  12600. *ip_version = 0;
  12601. /* Initialize port and len as invalid. */
  12602. port = 0;
  12603. len = 0;
  12604. /* Test for different ways to format this string */
  12605. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12606. == 5) {
  12607. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12608. so->lsa.sin.sin_addr.s_addr =
  12609. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12610. so->lsa.sin.sin_port = htons((uint16_t)port);
  12611. *ip_version = 4;
  12612. #if defined(USE_IPV6)
  12613. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12614. && mg_inet_pton(
  12615. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12616. /* IPv6 address, examples: see above */
  12617. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12618. */
  12619. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12620. *ip_version = 6;
  12621. #endif
  12622. } else if ((vec->ptr[0] == '+')
  12623. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12624. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12625. /* Add 1 to len for the + character we skipped before */
  12626. len++;
  12627. #if defined(USE_IPV6)
  12628. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12629. so->lsa.sin6.sin6_family = AF_INET6;
  12630. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12631. *ip_version = 4 + 6;
  12632. #else
  12633. /* Bind to IPv4 only, since IPv6 is not built in. */
  12634. so->lsa.sin.sin_port = htons((uint16_t)port);
  12635. *ip_version = 4;
  12636. #endif
  12637. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12638. && vec->ptr != endptr) {
  12639. len = endptr - vec->ptr;
  12640. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12641. so->lsa.sin.sin_port = htons((uint16_t)port);
  12642. *ip_version = 4;
  12643. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12644. /* String could be a hostname. This check algotithm
  12645. * will only work for RFC 952 compliant hostnames,
  12646. * starting with a letter, containing only letters,
  12647. * digits and hyphen ('-'). Newer specs may allow
  12648. * more, but this is not guaranteed here, since it
  12649. * may interfere with rules for port option lists. */
  12650. /* According to RFC 1035, hostnames are restricted to 255 characters
  12651. * in total (63 between two dots). */
  12652. char hostname[256];
  12653. size_t hostnlen = (size_t)(cb - vec->ptr);
  12654. if (hostnlen >= sizeof(hostname)) {
  12655. /* This would be invalid in any case */
  12656. *ip_version = 0;
  12657. return 0;
  12658. }
  12659. memcpy(hostname, vec->ptr, hostnlen);
  12660. hostname[hostnlen] = 0;
  12661. if (mg_inet_pton(
  12662. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12663. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12664. *ip_version = 4;
  12665. so->lsa.sin.sin_family = AF_INET;
  12666. so->lsa.sin.sin_port = htons((uint16_t)port);
  12667. len += (int)(hostnlen + 1);
  12668. } else {
  12669. port = 0;
  12670. len = 0;
  12671. }
  12672. #if defined(USE_IPV6)
  12673. } else if (mg_inet_pton(AF_INET6,
  12674. hostname,
  12675. &so->lsa.sin6,
  12676. sizeof(so->lsa.sin6))) {
  12677. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12678. *ip_version = 6;
  12679. so->lsa.sin6.sin6_family = AF_INET6;
  12680. so->lsa.sin.sin_port = htons((uint16_t)port);
  12681. len += (int)(hostnlen + 1);
  12682. } else {
  12683. port = 0;
  12684. len = 0;
  12685. }
  12686. #endif
  12687. }
  12688. } else {
  12689. /* Parsing failure. */
  12690. }
  12691. /* sscanf and the option splitting code ensure the following condition
  12692. */
  12693. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12694. *ip_version = 0;
  12695. return 0;
  12696. }
  12697. ch = vec->ptr[len]; /* Next character after the port number */
  12698. so->is_ssl = (ch == 's');
  12699. so->ssl_redir = (ch == 'r');
  12700. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12701. if (is_valid_port(port)
  12702. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12703. return 1;
  12704. }
  12705. /* Reset ip_version to 0 if there is an error */
  12706. *ip_version = 0;
  12707. return 0;
  12708. }
  12709. /* Is there any SSL port in use? */
  12710. static int
  12711. is_ssl_port_used(const char *ports)
  12712. {
  12713. if (ports) {
  12714. /* There are several different allowed syntax variants:
  12715. * - "80" for a single port using every network interface
  12716. * - "localhost:80" for a single port using only localhost
  12717. * - "80,localhost:8080" for two ports, one bound to localhost
  12718. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12719. * to IPv4 localhost, one to IPv6 localhost
  12720. * - "+80" use port 80 for IPv4 and IPv6
  12721. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12722. * for both: IPv4 and IPv4
  12723. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12724. * additionally port 8080 bound to localhost connections
  12725. *
  12726. * If we just look for 's' anywhere in the string, "localhost:80"
  12727. * will be detected as SSL (false positive).
  12728. * Looking for 's' after a digit may cause false positives in
  12729. * "my24service:8080".
  12730. * Looking from 's' backward if there are only ':' and numbers
  12731. * before will not work for "24service:8080" (non SSL, port 8080)
  12732. * or "24s" (SSL, port 24).
  12733. *
  12734. * Remark: Initially hostnames were not allowed to start with a
  12735. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12736. * Section 2.1).
  12737. *
  12738. * To get this correct, the entire string must be parsed as a whole,
  12739. * reading it as a list element for element and parsing with an
  12740. * algorithm equivalent to parse_port_string.
  12741. *
  12742. * In fact, we use local interface names here, not arbitrary hostnames,
  12743. * so in most cases the only name will be "localhost".
  12744. *
  12745. * So, for now, we use this simple algorithm, that may still return
  12746. * a false positive in bizarre cases.
  12747. */
  12748. int i;
  12749. int portslen = (int)strlen(ports);
  12750. char prevIsNumber = 0;
  12751. for (i = 0; i < portslen; i++) {
  12752. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12753. return 1;
  12754. }
  12755. if (ports[i] >= '0' && ports[i] <= '9') {
  12756. prevIsNumber = 1;
  12757. } else {
  12758. prevIsNumber = 0;
  12759. }
  12760. }
  12761. }
  12762. return 0;
  12763. }
  12764. static int
  12765. set_ports_option(struct mg_context *phys_ctx)
  12766. {
  12767. const char *list;
  12768. int on = 1;
  12769. #if defined(USE_IPV6)
  12770. int off = 0;
  12771. #endif
  12772. struct vec vec;
  12773. struct socket so, *ptr;
  12774. struct mg_pollfd *pfd;
  12775. union usa usa;
  12776. socklen_t len;
  12777. int ip_version;
  12778. int portsTotal = 0;
  12779. int portsOk = 0;
  12780. const char *opt_txt;
  12781. long opt_max_connections;
  12782. if (!phys_ctx) {
  12783. return 0;
  12784. }
  12785. memset(&so, 0, sizeof(so));
  12786. memset(&usa, 0, sizeof(usa));
  12787. len = sizeof(usa);
  12788. list = phys_ctx->dd.config[LISTENING_PORTS];
  12789. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12790. portsTotal++;
  12791. if (!parse_port_string(&vec, &so, &ip_version)) {
  12792. mg_cry_ctx_internal(
  12793. phys_ctx,
  12794. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12795. (int)vec.len,
  12796. vec.ptr,
  12797. portsTotal,
  12798. "[IP_ADDRESS:]PORT[s|r]");
  12799. continue;
  12800. }
  12801. #if !defined(NO_SSL)
  12802. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12803. mg_cry_ctx_internal(phys_ctx,
  12804. "Cannot add SSL socket (entry %i)",
  12805. portsTotal);
  12806. continue;
  12807. }
  12808. #endif
  12809. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12810. == INVALID_SOCKET) {
  12811. mg_cry_ctx_internal(phys_ctx,
  12812. "cannot create socket (entry %i)",
  12813. portsTotal);
  12814. continue;
  12815. }
  12816. #if defined(_WIN32)
  12817. /* Windows SO_REUSEADDR lets many procs binds to a
  12818. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12819. * if someone already has the socket -- DTL */
  12820. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12821. * Windows might need a few seconds before
  12822. * the same port can be used again in the
  12823. * same process, so a short Sleep may be
  12824. * required between mg_stop and mg_start.
  12825. */
  12826. if (setsockopt(so.sock,
  12827. SOL_SOCKET,
  12828. SO_EXCLUSIVEADDRUSE,
  12829. (SOCK_OPT_TYPE)&on,
  12830. sizeof(on))
  12831. != 0) {
  12832. /* Set reuse option, but don't abort on errors. */
  12833. mg_cry_ctx_internal(
  12834. phys_ctx,
  12835. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12836. portsTotal);
  12837. }
  12838. #else
  12839. if (setsockopt(so.sock,
  12840. SOL_SOCKET,
  12841. SO_REUSEADDR,
  12842. (SOCK_OPT_TYPE)&on,
  12843. sizeof(on))
  12844. != 0) {
  12845. /* Set reuse option, but don't abort on errors. */
  12846. mg_cry_ctx_internal(
  12847. phys_ctx,
  12848. "cannot set socket option SO_REUSEADDR (entry %i)",
  12849. portsTotal);
  12850. }
  12851. #endif
  12852. if (ip_version > 4) {
  12853. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12854. #if defined(USE_IPV6)
  12855. if (ip_version > 6) {
  12856. if (so.lsa.sa.sa_family == AF_INET6
  12857. && setsockopt(so.sock,
  12858. IPPROTO_IPV6,
  12859. IPV6_V6ONLY,
  12860. (void *)&off,
  12861. sizeof(off))
  12862. != 0) {
  12863. /* Set IPv6 only option, but don't abort on errors. */
  12864. mg_cry_ctx_internal(
  12865. phys_ctx,
  12866. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12867. portsTotal);
  12868. }
  12869. } else {
  12870. if (so.lsa.sa.sa_family == AF_INET6
  12871. && setsockopt(so.sock,
  12872. IPPROTO_IPV6,
  12873. IPV6_V6ONLY,
  12874. (void *)&on,
  12875. sizeof(on))
  12876. != 0) {
  12877. /* Set IPv6 only option, but don't abort on errors. */
  12878. mg_cry_ctx_internal(
  12879. phys_ctx,
  12880. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12881. portsTotal);
  12882. }
  12883. }
  12884. #else
  12885. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12886. closesocket(so.sock);
  12887. so.sock = INVALID_SOCKET;
  12888. continue;
  12889. #endif
  12890. }
  12891. if (so.lsa.sa.sa_family == AF_INET) {
  12892. len = sizeof(so.lsa.sin);
  12893. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12894. mg_cry_ctx_internal(phys_ctx,
  12895. "cannot bind to %.*s: %d (%s)",
  12896. (int)vec.len,
  12897. vec.ptr,
  12898. (int)ERRNO,
  12899. strerror(errno));
  12900. closesocket(so.sock);
  12901. so.sock = INVALID_SOCKET;
  12902. continue;
  12903. }
  12904. }
  12905. #if defined(USE_IPV6)
  12906. else if (so.lsa.sa.sa_family == AF_INET6) {
  12907. len = sizeof(so.lsa.sin6);
  12908. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12909. mg_cry_ctx_internal(phys_ctx,
  12910. "cannot bind to IPv6 %.*s: %d (%s)",
  12911. (int)vec.len,
  12912. vec.ptr,
  12913. (int)ERRNO,
  12914. strerror(errno));
  12915. closesocket(so.sock);
  12916. so.sock = INVALID_SOCKET;
  12917. continue;
  12918. }
  12919. }
  12920. #endif
  12921. else {
  12922. mg_cry_ctx_internal(
  12923. phys_ctx,
  12924. "cannot bind: address family not supported (entry %i)",
  12925. portsTotal);
  12926. closesocket(so.sock);
  12927. so.sock = INVALID_SOCKET;
  12928. continue;
  12929. }
  12930. opt_txt = phys_ctx->dd.config[MAX_CONNECTIONS];
  12931. opt_max_connections = strtol(opt_txt, NULL, 10);
  12932. if ((opt_max_connections > INT_MAX) || (opt_max_connections < 1)) {
  12933. mg_cry_ctx_internal(phys_ctx,
  12934. "max_connections value \"%s\" is invalid",
  12935. opt_txt);
  12936. continue;
  12937. }
  12938. if (listen(so.sock, (int)opt_max_connections) != 0) {
  12939. mg_cry_ctx_internal(phys_ctx,
  12940. "cannot listen to %.*s: %d (%s)",
  12941. (int)vec.len,
  12942. vec.ptr,
  12943. (int)ERRNO,
  12944. strerror(errno));
  12945. closesocket(so.sock);
  12946. so.sock = INVALID_SOCKET;
  12947. continue;
  12948. }
  12949. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12950. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12951. int err = (int)ERRNO;
  12952. mg_cry_ctx_internal(phys_ctx,
  12953. "call to getsockname failed %.*s: %d (%s)",
  12954. (int)vec.len,
  12955. vec.ptr,
  12956. err,
  12957. strerror(errno));
  12958. closesocket(so.sock);
  12959. so.sock = INVALID_SOCKET;
  12960. continue;
  12961. }
  12962. /* Update lsa port in case of random free ports */
  12963. #if defined(USE_IPV6)
  12964. if (so.lsa.sa.sa_family == AF_INET6) {
  12965. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12966. } else
  12967. #endif
  12968. {
  12969. so.lsa.sin.sin_port = usa.sin.sin_port;
  12970. }
  12971. if ((ptr = (struct socket *)
  12972. mg_realloc_ctx(phys_ctx->listening_sockets,
  12973. (phys_ctx->num_listening_sockets + 1)
  12974. * sizeof(phys_ctx->listening_sockets[0]),
  12975. phys_ctx))
  12976. == NULL) {
  12977. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12978. closesocket(so.sock);
  12979. so.sock = INVALID_SOCKET;
  12980. continue;
  12981. }
  12982. if ((pfd = (struct mg_pollfd *)
  12983. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12984. (phys_ctx->num_listening_sockets + 1)
  12985. * sizeof(phys_ctx->listening_socket_fds[0]),
  12986. phys_ctx))
  12987. == NULL) {
  12988. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12989. closesocket(so.sock);
  12990. so.sock = INVALID_SOCKET;
  12991. mg_free(ptr);
  12992. continue;
  12993. }
  12994. set_close_on_exec(so.sock, NULL, phys_ctx);
  12995. phys_ctx->listening_sockets = ptr;
  12996. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12997. phys_ctx->listening_socket_fds = pfd;
  12998. phys_ctx->num_listening_sockets++;
  12999. portsOk++;
  13000. }
  13001. if (portsOk != portsTotal) {
  13002. close_all_listening_sockets(phys_ctx);
  13003. portsOk = 0;
  13004. }
  13005. return portsOk;
  13006. }
  13007. static const char *
  13008. header_val(const struct mg_connection *conn, const char *header)
  13009. {
  13010. const char *header_value;
  13011. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13012. return "-";
  13013. } else {
  13014. return header_value;
  13015. }
  13016. }
  13017. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13018. static void log_access(const struct mg_connection *conn);
  13019. #include "external_log_access.inl"
  13020. #elif !defined(NO_FILESYSTEMS)
  13021. static void
  13022. log_access(const struct mg_connection *conn)
  13023. {
  13024. const struct mg_request_info *ri;
  13025. struct mg_file fi;
  13026. char date[64], src_addr[IP_ADDR_STR_LEN];
  13027. struct tm *tm;
  13028. const char *referer;
  13029. const char *user_agent;
  13030. char buf[4096];
  13031. if (!conn || !conn->dom_ctx) {
  13032. return;
  13033. }
  13034. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13035. if (mg_fopen(conn,
  13036. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13037. MG_FOPEN_MODE_APPEND,
  13038. &fi)
  13039. == 0) {
  13040. fi.access.fp = NULL;
  13041. }
  13042. } else {
  13043. fi.access.fp = NULL;
  13044. }
  13045. /* Log is written to a file and/or a callback. If both are not set,
  13046. * executing the rest of the function is pointless. */
  13047. if ((fi.access.fp == NULL)
  13048. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13049. return;
  13050. }
  13051. tm = localtime(&conn->conn_birth_time);
  13052. if (tm != NULL) {
  13053. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13054. } else {
  13055. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13056. date[sizeof(date) - 1] = '\0';
  13057. }
  13058. ri = &conn->request_info;
  13059. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13060. referer = header_val(conn, "Referer");
  13061. user_agent = header_val(conn, "User-Agent");
  13062. mg_snprintf(conn,
  13063. NULL, /* Ignore truncation in access log */
  13064. buf,
  13065. sizeof(buf),
  13066. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13067. src_addr,
  13068. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13069. date,
  13070. ri->request_method ? ri->request_method : "-",
  13071. ri->request_uri ? ri->request_uri : "-",
  13072. ri->query_string ? "?" : "",
  13073. ri->query_string ? ri->query_string : "",
  13074. ri->http_version,
  13075. conn->status_code,
  13076. conn->num_bytes_sent,
  13077. referer,
  13078. user_agent);
  13079. if (conn->phys_ctx->callbacks.log_access) {
  13080. conn->phys_ctx->callbacks.log_access(conn, buf);
  13081. }
  13082. if (fi.access.fp) {
  13083. int ok = 1;
  13084. flockfile(fi.access.fp);
  13085. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13086. ok = 0;
  13087. }
  13088. if (fflush(fi.access.fp) != 0) {
  13089. ok = 0;
  13090. }
  13091. funlockfile(fi.access.fp);
  13092. if (mg_fclose(&fi.access) != 0) {
  13093. ok = 0;
  13094. }
  13095. if (!ok) {
  13096. mg_cry_internal(conn,
  13097. "Error writing log file %s",
  13098. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13099. }
  13100. }
  13101. }
  13102. #else
  13103. #error Must either enable filesystems or provide a custom log_access implementation
  13104. #endif /* Externally provided function */
  13105. /* Verify given socket address against the ACL.
  13106. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13107. */
  13108. static int
  13109. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13110. {
  13111. int allowed, flag;
  13112. uint32_t net, mask;
  13113. struct vec vec;
  13114. if (phys_ctx) {
  13115. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13116. /* If any ACL is set, deny by default */
  13117. allowed = (list == NULL) ? '+' : '-';
  13118. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13119. flag = vec.ptr[0];
  13120. if ((flag != '+' && flag != '-')
  13121. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13122. mg_cry_ctx_internal(phys_ctx,
  13123. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13124. __func__);
  13125. return -1;
  13126. }
  13127. if (net == (remote_ip & mask)) {
  13128. allowed = flag;
  13129. }
  13130. }
  13131. return allowed == '+';
  13132. }
  13133. return -1;
  13134. }
  13135. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13136. static int
  13137. set_uid_option(struct mg_context *phys_ctx)
  13138. {
  13139. int success = 0;
  13140. if (phys_ctx) {
  13141. /* We are currently running as curr_uid. */
  13142. const uid_t curr_uid = getuid();
  13143. /* If set, we want to run as run_as_user. */
  13144. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13145. const struct passwd *to_pw = NULL;
  13146. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13147. /* run_as_user does not exist on the system. We can't proceed
  13148. * further. */
  13149. mg_cry_ctx_internal(phys_ctx,
  13150. "%s: unknown user [%s]",
  13151. __func__,
  13152. run_as_user);
  13153. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13154. /* There was either no request to change user, or we're already
  13155. * running as run_as_user. Nothing else to do.
  13156. */
  13157. success = 1;
  13158. } else {
  13159. /* Valid change request. */
  13160. if (setgid(to_pw->pw_gid) == -1) {
  13161. mg_cry_ctx_internal(phys_ctx,
  13162. "%s: setgid(%s): %s",
  13163. __func__,
  13164. run_as_user,
  13165. strerror(errno));
  13166. } else if (setgroups(0, NULL) == -1) {
  13167. mg_cry_ctx_internal(phys_ctx,
  13168. "%s: setgroups(): %s",
  13169. __func__,
  13170. strerror(errno));
  13171. } else if (setuid(to_pw->pw_uid) == -1) {
  13172. mg_cry_ctx_internal(phys_ctx,
  13173. "%s: setuid(%s): %s",
  13174. __func__,
  13175. run_as_user,
  13176. strerror(errno));
  13177. } else {
  13178. success = 1;
  13179. }
  13180. }
  13181. }
  13182. return success;
  13183. }
  13184. #endif /* !_WIN32 */
  13185. static void
  13186. tls_dtor(void *key)
  13187. {
  13188. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13189. /* key == pthread_getspecific(sTlsKey); */
  13190. if (tls) {
  13191. if (tls->is_master == 2) {
  13192. tls->is_master = -3; /* Mark memory as dead */
  13193. mg_free(tls);
  13194. }
  13195. }
  13196. pthread_setspecific(sTlsKey, NULL);
  13197. }
  13198. #if !defined(NO_SSL)
  13199. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13200. struct mg_domain_context *dom_ctx,
  13201. const char *pem,
  13202. const char *chain);
  13203. static const char *ssl_error(void);
  13204. static int
  13205. refresh_trust(struct mg_connection *conn)
  13206. {
  13207. static int reload_lock = 0;
  13208. static long int data_check = 0;
  13209. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  13210. struct stat cert_buf;
  13211. long int t;
  13212. const char *pem;
  13213. const char *chain;
  13214. int should_verify_peer;
  13215. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13216. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13217. * refresh_trust still can not work. */
  13218. return 0;
  13219. }
  13220. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13221. if (chain == NULL) {
  13222. /* pem is not NULL here */
  13223. chain = pem;
  13224. }
  13225. if (*chain == 0) {
  13226. chain = NULL;
  13227. }
  13228. t = data_check;
  13229. if (stat(pem, &cert_buf) != -1) {
  13230. t = (long int)cert_buf.st_mtime;
  13231. }
  13232. if (data_check != t) {
  13233. data_check = t;
  13234. should_verify_peer = 0;
  13235. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13236. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13237. == 0) {
  13238. should_verify_peer = 1;
  13239. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13240. "optional")
  13241. == 0) {
  13242. should_verify_peer = 1;
  13243. }
  13244. }
  13245. if (should_verify_peer) {
  13246. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13247. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13248. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13249. ca_file,
  13250. ca_path)
  13251. != 1) {
  13252. mg_cry_ctx_internal(
  13253. conn->phys_ctx,
  13254. "SSL_CTX_load_verify_locations error: %s "
  13255. "ssl_verify_peer requires setting "
  13256. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13257. "present in "
  13258. "the .conf file?",
  13259. ssl_error());
  13260. return 0;
  13261. }
  13262. }
  13263. if (1 == mg_atomic_inc(p_reload_lock)) {
  13264. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13265. == 0) {
  13266. return 0;
  13267. }
  13268. *p_reload_lock = 0;
  13269. }
  13270. }
  13271. /* lock while cert is reloading */
  13272. while (*p_reload_lock) {
  13273. sleep(1);
  13274. }
  13275. return 1;
  13276. }
  13277. #if defined(OPENSSL_API_1_1)
  13278. #else
  13279. static pthread_mutex_t *ssl_mutexes;
  13280. #endif /* OPENSSL_API_1_1 */
  13281. static int
  13282. sslize(struct mg_connection *conn,
  13283. SSL_CTX *s,
  13284. int (*func)(SSL *),
  13285. volatile int *stop_server,
  13286. const struct mg_client_options *client_options)
  13287. {
  13288. int ret, err;
  13289. int short_trust;
  13290. unsigned timeout = 1024;
  13291. unsigned i;
  13292. if (!conn) {
  13293. return 0;
  13294. }
  13295. short_trust =
  13296. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13297. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13298. if (short_trust) {
  13299. int trust_ret = refresh_trust(conn);
  13300. if (!trust_ret) {
  13301. return trust_ret;
  13302. }
  13303. }
  13304. conn->ssl = SSL_new(s);
  13305. if (conn->ssl == NULL) {
  13306. return 0;
  13307. }
  13308. SSL_set_app_data(conn->ssl, (char *)conn);
  13309. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13310. if (ret != 1) {
  13311. err = SSL_get_error(conn->ssl, ret);
  13312. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13313. SSL_free(conn->ssl);
  13314. conn->ssl = NULL;
  13315. OPENSSL_REMOVE_THREAD_STATE();
  13316. return 0;
  13317. }
  13318. if (client_options) {
  13319. if (client_options->host_name) {
  13320. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13321. }
  13322. }
  13323. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13324. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13325. /* NOTE: The loop below acts as a back-off, so we can end
  13326. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13327. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13328. }
  13329. /* SSL functions may fail and require to be called again:
  13330. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13331. * Here "func" could be SSL_connect or SSL_accept. */
  13332. for (i = 0; i <= timeout; i += 50) {
  13333. ret = func(conn->ssl);
  13334. if (ret != 1) {
  13335. err = SSL_get_error(conn->ssl, ret);
  13336. if ((err == SSL_ERROR_WANT_CONNECT)
  13337. || (err == SSL_ERROR_WANT_ACCEPT)
  13338. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13339. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13340. if (*stop_server) {
  13341. /* Don't wait if the server is going to be stopped. */
  13342. break;
  13343. }
  13344. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13345. /* Simply retry the function call. */
  13346. mg_sleep(50);
  13347. } else {
  13348. /* Need to retry the function call "later".
  13349. * See https://linux.die.net/man/3/ssl_get_error
  13350. * This is typical for non-blocking sockets. */
  13351. struct mg_pollfd pfd;
  13352. int pollres;
  13353. pfd.fd = conn->client.sock;
  13354. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13355. || (err == SSL_ERROR_WANT_WRITE))
  13356. ? POLLOUT
  13357. : POLLIN;
  13358. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13359. if (pollres < 0) {
  13360. /* Break if error occured (-1)
  13361. * or server shutdown (-2) */
  13362. break;
  13363. }
  13364. }
  13365. } else if (err == SSL_ERROR_SYSCALL) {
  13366. /* This is an IO error. Look at errno. */
  13367. err = errno;
  13368. mg_cry_internal(conn, "SSL syscall error %i", err);
  13369. break;
  13370. } else {
  13371. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13372. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13373. break;
  13374. }
  13375. ERR_clear_error();
  13376. } else {
  13377. /* success */
  13378. break;
  13379. }
  13380. }
  13381. if (ret != 1) {
  13382. SSL_free(conn->ssl);
  13383. conn->ssl = NULL;
  13384. OPENSSL_REMOVE_THREAD_STATE();
  13385. return 0;
  13386. }
  13387. return 1;
  13388. }
  13389. /* Return OpenSSL error message (from CRYPTO lib) */
  13390. static const char *
  13391. ssl_error(void)
  13392. {
  13393. unsigned long err;
  13394. err = ERR_get_error();
  13395. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13396. }
  13397. static int
  13398. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13399. {
  13400. int i;
  13401. const char hexdigit[] = "0123456789abcdef";
  13402. if ((memlen <= 0) || (buflen <= 0)) {
  13403. return 0;
  13404. }
  13405. if (buflen < (3 * memlen)) {
  13406. return 0;
  13407. }
  13408. for (i = 0; i < memlen; i++) {
  13409. if (i > 0) {
  13410. buf[3 * i - 1] = ' ';
  13411. }
  13412. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13413. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13414. }
  13415. buf[3 * memlen - 1] = 0;
  13416. return 1;
  13417. }
  13418. static void
  13419. ssl_get_client_cert_info(struct mg_connection *conn)
  13420. {
  13421. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13422. if (cert) {
  13423. char str_subject[1024];
  13424. char str_issuer[1024];
  13425. char str_finger[1024];
  13426. unsigned char buf[256];
  13427. char *str_serial = NULL;
  13428. unsigned int ulen;
  13429. int ilen;
  13430. unsigned char *tmp_buf;
  13431. unsigned char *tmp_p;
  13432. /* Handle to algorithm used for fingerprint */
  13433. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13434. /* Get Subject and issuer */
  13435. X509_NAME *subj = X509_get_subject_name(cert);
  13436. X509_NAME *iss = X509_get_issuer_name(cert);
  13437. /* Get serial number */
  13438. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13439. /* Translate serial number to a hex string */
  13440. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13441. str_serial = BN_bn2hex(serial_bn);
  13442. BN_free(serial_bn);
  13443. /* Translate subject and issuer to a string */
  13444. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13445. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13446. /* Calculate SHA1 fingerprint and store as a hex string */
  13447. ulen = 0;
  13448. /* ASN1_digest is deprecated. Do the calculation manually,
  13449. * using EVP_Digest. */
  13450. ilen = i2d_X509(cert, NULL);
  13451. tmp_buf = (ilen > 0)
  13452. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13453. conn->phys_ctx)
  13454. : NULL;
  13455. if (tmp_buf) {
  13456. tmp_p = tmp_buf;
  13457. (void)i2d_X509(cert, &tmp_p);
  13458. if (!EVP_Digest(
  13459. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13460. ulen = 0;
  13461. }
  13462. mg_free(tmp_buf);
  13463. }
  13464. if (!hexdump2string(
  13465. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13466. *str_finger = 0;
  13467. }
  13468. conn->request_info.client_cert = (struct mg_client_cert *)
  13469. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13470. if (conn->request_info.client_cert) {
  13471. conn->request_info.client_cert->peer_cert = (void *)cert;
  13472. conn->request_info.client_cert->subject =
  13473. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13474. conn->request_info.client_cert->issuer =
  13475. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13476. conn->request_info.client_cert->serial =
  13477. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13478. conn->request_info.client_cert->finger =
  13479. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13480. } else {
  13481. mg_cry_internal(conn,
  13482. "%s",
  13483. "Out of memory: Cannot allocate memory for client "
  13484. "certificate");
  13485. }
  13486. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13487. * see https://linux.die.net/man/3/bn_bn2hex */
  13488. OPENSSL_free(str_serial);
  13489. }
  13490. }
  13491. #if defined(OPENSSL_API_1_1)
  13492. #else
  13493. static void
  13494. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13495. {
  13496. (void)line;
  13497. (void)file;
  13498. if (mode & 1) {
  13499. /* 1 is CRYPTO_LOCK */
  13500. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13501. } else {
  13502. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13503. }
  13504. }
  13505. #endif /* OPENSSL_API_1_1 */
  13506. #if !defined(NO_SSL_DL)
  13507. static void *
  13508. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13509. {
  13510. union {
  13511. void *p;
  13512. void (*fp)(void);
  13513. } u;
  13514. void *dll_handle;
  13515. struct ssl_func *fp;
  13516. int ok;
  13517. int truncated = 0;
  13518. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13519. mg_snprintf(NULL,
  13520. NULL, /* No truncation check for ebuf */
  13521. ebuf,
  13522. ebuf_len,
  13523. "%s: cannot load %s",
  13524. __func__,
  13525. dll_name);
  13526. return NULL;
  13527. }
  13528. ok = 1;
  13529. for (fp = sw; fp->name != NULL; fp++) {
  13530. #if defined(_WIN32)
  13531. /* GetProcAddress() returns pointer to function */
  13532. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13533. #else
  13534. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13535. * pointers to function pointers. We need to use a union to make a
  13536. * cast. */
  13537. u.p = dlsym(dll_handle, fp->name);
  13538. #endif /* _WIN32 */
  13539. if (u.fp == NULL) {
  13540. if (ok) {
  13541. mg_snprintf(NULL,
  13542. &truncated,
  13543. ebuf,
  13544. ebuf_len,
  13545. "%s: %s: cannot find %s",
  13546. __func__,
  13547. dll_name,
  13548. fp->name);
  13549. ok = 0;
  13550. } else {
  13551. size_t cur_len = strlen(ebuf);
  13552. if (!truncated) {
  13553. mg_snprintf(NULL,
  13554. &truncated,
  13555. ebuf + cur_len,
  13556. ebuf_len - cur_len - 3,
  13557. ", %s",
  13558. fp->name);
  13559. if (truncated) {
  13560. /* If truncated, add "..." */
  13561. strcat(ebuf, "...");
  13562. }
  13563. }
  13564. }
  13565. /* Debug:
  13566. * printf("Missing function: %s\n", fp->name); */
  13567. } else {
  13568. fp->ptr = u.fp;
  13569. }
  13570. }
  13571. if (!ok) {
  13572. (void)dlclose(dll_handle);
  13573. return NULL;
  13574. }
  13575. return dll_handle;
  13576. }
  13577. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13578. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13579. #endif /* NO_SSL_DL */
  13580. #if defined(SSL_ALREADY_INITIALIZED)
  13581. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13582. #else
  13583. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13584. #endif
  13585. static int
  13586. initialize_ssl(char *ebuf, size_t ebuf_len)
  13587. {
  13588. #if defined(OPENSSL_API_1_1)
  13589. if (ebuf_len > 0) {
  13590. ebuf[0] = 0;
  13591. }
  13592. #if !defined(NO_SSL_DL)
  13593. if (!cryptolib_dll_handle) {
  13594. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13595. if (!cryptolib_dll_handle) {
  13596. mg_snprintf(NULL,
  13597. NULL, /* No truncation check for ebuf */
  13598. ebuf,
  13599. ebuf_len,
  13600. "%s: error loading library %s",
  13601. __func__,
  13602. CRYPTO_LIB);
  13603. DEBUG_TRACE("%s", ebuf);
  13604. return 0;
  13605. }
  13606. }
  13607. #endif /* NO_SSL_DL */
  13608. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13609. return 1;
  13610. }
  13611. #else /* not OPENSSL_API_1_1 */
  13612. int i, num_locks;
  13613. size_t size;
  13614. if (ebuf_len > 0) {
  13615. ebuf[0] = 0;
  13616. }
  13617. #if !defined(NO_SSL_DL)
  13618. if (!cryptolib_dll_handle) {
  13619. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13620. if (!cryptolib_dll_handle) {
  13621. mg_snprintf(NULL,
  13622. NULL, /* No truncation check for ebuf */
  13623. ebuf,
  13624. ebuf_len,
  13625. "%s: error loading library %s",
  13626. __func__,
  13627. CRYPTO_LIB);
  13628. DEBUG_TRACE("%s", ebuf);
  13629. return 0;
  13630. }
  13631. }
  13632. #endif /* NO_SSL_DL */
  13633. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13634. return 1;
  13635. }
  13636. /* Initialize locking callbacks, needed for thread safety.
  13637. * http://www.openssl.org/support/faq.html#PROG1
  13638. */
  13639. num_locks = CRYPTO_num_locks();
  13640. if (num_locks < 0) {
  13641. num_locks = 0;
  13642. }
  13643. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13644. /* allocate mutex array, if required */
  13645. if (num_locks == 0) {
  13646. /* No mutex array required */
  13647. ssl_mutexes = NULL;
  13648. } else {
  13649. /* Mutex array required - allocate it */
  13650. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13651. /* Check OOM */
  13652. if (ssl_mutexes == NULL) {
  13653. mg_snprintf(NULL,
  13654. NULL, /* No truncation check for ebuf */
  13655. ebuf,
  13656. ebuf_len,
  13657. "%s: cannot allocate mutexes: %s",
  13658. __func__,
  13659. ssl_error());
  13660. DEBUG_TRACE("%s", ebuf);
  13661. return 0;
  13662. }
  13663. /* initialize mutex array */
  13664. for (i = 0; i < num_locks; i++) {
  13665. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13666. mg_snprintf(NULL,
  13667. NULL, /* No truncation check for ebuf */
  13668. ebuf,
  13669. ebuf_len,
  13670. "%s: error initializing mutex %i of %i",
  13671. __func__,
  13672. i,
  13673. num_locks);
  13674. DEBUG_TRACE("%s", ebuf);
  13675. mg_free(ssl_mutexes);
  13676. return 0;
  13677. }
  13678. }
  13679. }
  13680. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13681. CRYPTO_set_id_callback(&mg_current_thread_id);
  13682. #endif /* OPENSSL_API_1_1 */
  13683. #if !defined(NO_SSL_DL)
  13684. if (!ssllib_dll_handle) {
  13685. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13686. if (!ssllib_dll_handle) {
  13687. #if !defined(OPENSSL_API_1_1)
  13688. mg_free(ssl_mutexes);
  13689. #endif
  13690. DEBUG_TRACE("%s", ebuf);
  13691. return 0;
  13692. }
  13693. }
  13694. #endif /* NO_SSL_DL */
  13695. #if defined(OPENSSL_API_1_1)
  13696. /* Initialize SSL library */
  13697. OPENSSL_init_ssl(0, NULL);
  13698. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13699. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13700. NULL);
  13701. #else
  13702. /* Initialize SSL library */
  13703. SSL_library_init();
  13704. SSL_load_error_strings();
  13705. #endif
  13706. return 1;
  13707. }
  13708. static int
  13709. ssl_use_pem_file(struct mg_context *phys_ctx,
  13710. struct mg_domain_context *dom_ctx,
  13711. const char *pem,
  13712. const char *chain)
  13713. {
  13714. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13715. mg_cry_ctx_internal(phys_ctx,
  13716. "%s: cannot open certificate file %s: %s",
  13717. __func__,
  13718. pem,
  13719. ssl_error());
  13720. return 0;
  13721. }
  13722. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13723. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13724. mg_cry_ctx_internal(phys_ctx,
  13725. "%s: cannot open private key file %s: %s",
  13726. __func__,
  13727. pem,
  13728. ssl_error());
  13729. return 0;
  13730. }
  13731. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13732. mg_cry_ctx_internal(phys_ctx,
  13733. "%s: certificate and private key do not match: %s",
  13734. __func__,
  13735. pem);
  13736. return 0;
  13737. }
  13738. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13739. * chain files that contain private keys and certificates in
  13740. * SSL_CTX_use_certificate_chain_file.
  13741. * The CivetWeb-Server used pem-Files that contained both information.
  13742. * In order to make wolfSSL work, it is split in two files.
  13743. * One file that contains key and certificate used by the server and
  13744. * an optional chain file for the ssl stack.
  13745. */
  13746. if (chain) {
  13747. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13748. mg_cry_ctx_internal(phys_ctx,
  13749. "%s: cannot use certificate chain file %s: %s",
  13750. __func__,
  13751. chain,
  13752. ssl_error());
  13753. return 0;
  13754. }
  13755. }
  13756. return 1;
  13757. }
  13758. #if defined(OPENSSL_API_1_1)
  13759. static unsigned long
  13760. ssl_get_protocol(int version_id)
  13761. {
  13762. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13763. if (version_id > 0)
  13764. ret |= SSL_OP_NO_SSLv2;
  13765. if (version_id > 1)
  13766. ret |= SSL_OP_NO_SSLv3;
  13767. if (version_id > 2)
  13768. ret |= SSL_OP_NO_TLSv1;
  13769. if (version_id > 3)
  13770. ret |= SSL_OP_NO_TLSv1_1;
  13771. if (version_id > 4)
  13772. ret |= SSL_OP_NO_TLSv1_2;
  13773. #if defined(SSL_OP_NO_TLSv1_3)
  13774. if (version_id > 5)
  13775. ret |= SSL_OP_NO_TLSv1_3;
  13776. #endif
  13777. return ret;
  13778. }
  13779. #else
  13780. static long
  13781. ssl_get_protocol(int version_id)
  13782. {
  13783. long ret = (long)SSL_OP_ALL;
  13784. if (version_id > 0)
  13785. ret |= SSL_OP_NO_SSLv2;
  13786. if (version_id > 1)
  13787. ret |= SSL_OP_NO_SSLv3;
  13788. if (version_id > 2)
  13789. ret |= SSL_OP_NO_TLSv1;
  13790. if (version_id > 3)
  13791. ret |= SSL_OP_NO_TLSv1_1;
  13792. if (version_id > 4)
  13793. ret |= SSL_OP_NO_TLSv1_2;
  13794. #if defined(SSL_OP_NO_TLSv1_3)
  13795. if (version_id > 5)
  13796. ret |= SSL_OP_NO_TLSv1_3;
  13797. #endif
  13798. return ret;
  13799. }
  13800. #endif /* OPENSSL_API_1_1 */
  13801. /* SSL callback documentation:
  13802. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13803. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13804. * https://linux.die.net/man/3/ssl_set_info_callback */
  13805. /* Note: There is no "const" for the first argument in the documentation
  13806. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13807. * / OpenSSL compatibility layers have it. Having a different definition will
  13808. * cause a warning in C and an error in C++. Use "const SSL *", while
  13809. * automatical conversion from "SSL *" works for all compilers, but not other
  13810. * way around */
  13811. static void
  13812. ssl_info_callback(const SSL *ssl, int what, int ret)
  13813. {
  13814. (void)ret;
  13815. if (what & SSL_CB_HANDSHAKE_START) {
  13816. SSL_get_app_data(ssl);
  13817. }
  13818. if (what & SSL_CB_HANDSHAKE_DONE) {
  13819. /* TODO: check for openSSL 1.1 */
  13820. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13821. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13822. }
  13823. }
  13824. static int
  13825. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13826. {
  13827. struct mg_context *ctx = (struct mg_context *)arg;
  13828. struct mg_domain_context *dom =
  13829. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13830. #if defined(GCC_DIAGNOSTIC)
  13831. #pragma GCC diagnostic push
  13832. #pragma GCC diagnostic ignored "-Wcast-align"
  13833. #endif /* defined(GCC_DIAGNOSTIC) */
  13834. /* We used an aligned pointer in SSL_set_app_data */
  13835. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13836. #if defined(GCC_DIAGNOSTIC)
  13837. #pragma GCC diagnostic pop
  13838. #endif /* defined(GCC_DIAGNOSTIC) */
  13839. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13840. (void)ad;
  13841. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13842. DEBUG_TRACE("%s", "internal error - assertion failed");
  13843. return SSL_TLSEXT_ERR_NOACK;
  13844. }
  13845. /* Old clients (Win XP) will not support SNI. Then, there
  13846. * is no server name available in the request - we can
  13847. * only work with the default certificate.
  13848. * Multiple HTTPS hosts on one IP+port are only possible
  13849. * with a certificate containing all alternative names.
  13850. */
  13851. if ((servername == NULL) || (*servername == 0)) {
  13852. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13853. conn->dom_ctx = &(ctx->dd);
  13854. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13855. return SSL_TLSEXT_ERR_NOACK;
  13856. }
  13857. DEBUG_TRACE("TLS connection to host %s", servername);
  13858. while (dom) {
  13859. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13860. /* Found matching domain */
  13861. DEBUG_TRACE("TLS domain %s found",
  13862. dom->config[AUTHENTICATION_DOMAIN]);
  13863. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13864. conn->dom_ctx = dom;
  13865. return SSL_TLSEXT_ERR_OK;
  13866. }
  13867. dom = dom->next;
  13868. }
  13869. /* Default domain */
  13870. DEBUG_TRACE("TLS default domain %s used",
  13871. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13872. conn->dom_ctx = &(ctx->dd);
  13873. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13874. return SSL_TLSEXT_ERR_OK;
  13875. }
  13876. /* Setup SSL CTX as required by CivetWeb */
  13877. static int
  13878. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13879. struct mg_domain_context *dom_ctx,
  13880. const char *pem,
  13881. const char *chain)
  13882. {
  13883. int callback_ret;
  13884. int should_verify_peer;
  13885. int peer_certificate_optional;
  13886. const char *ca_path;
  13887. const char *ca_file;
  13888. int use_default_verify_paths;
  13889. int verify_depth;
  13890. struct timespec now_mt;
  13891. md5_byte_t ssl_context_id[16];
  13892. md5_state_t md5state;
  13893. int protocol_ver;
  13894. #if defined(OPENSSL_API_1_1)
  13895. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13896. mg_cry_ctx_internal(phys_ctx,
  13897. "SSL_CTX_new (server) error: %s",
  13898. ssl_error());
  13899. return 0;
  13900. }
  13901. #else
  13902. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13903. mg_cry_ctx_internal(phys_ctx,
  13904. "SSL_CTX_new (server) error: %s",
  13905. ssl_error());
  13906. return 0;
  13907. }
  13908. #endif /* OPENSSL_API_1_1 */
  13909. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13910. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13911. | SSL_OP_NO_TLSv1_1);
  13912. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13913. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13914. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13915. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13916. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13917. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13918. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13919. #if defined(SSL_OP_NO_RENEGOTIATION)
  13920. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13921. #endif
  13922. #if !defined(NO_SSL_DL)
  13923. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13924. #endif /* NO_SSL_DL */
  13925. /* In SSL documentation examples callback defined without const specifier
  13926. * 'void (*)(SSL *, int, int)' See:
  13927. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13928. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13929. * But in the source code const SSL is used:
  13930. * 'void (*)(const SSL *, int, int)' See:
  13931. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13932. * Problem about wrong documentation described, but not resolved:
  13933. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13934. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13935. * But when compiled with modern C++ compiler, correct const should be
  13936. * provided
  13937. */
  13938. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13939. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13940. ssl_servername_callback);
  13941. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13942. /* If a callback has been specified, call it. */
  13943. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13944. ? 0
  13945. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13946. phys_ctx->user_data));
  13947. /* If callback returns 0, civetweb sets up the SSL certificate.
  13948. * If it returns 1, civetweb assumes the calback already did this.
  13949. * If it returns -1, initializing ssl fails. */
  13950. if (callback_ret < 0) {
  13951. mg_cry_ctx_internal(phys_ctx,
  13952. "SSL callback returned error: %i",
  13953. callback_ret);
  13954. return 0;
  13955. }
  13956. if (callback_ret > 0) {
  13957. /* Callback did everything. */
  13958. return 1;
  13959. }
  13960. /* If a domain callback has been specified, call it. */
  13961. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  13962. ? 0
  13963. : (phys_ctx->callbacks.init_ssl_domain(
  13964. dom_ctx->config[AUTHENTICATION_DOMAIN],
  13965. dom_ctx->ssl_ctx,
  13966. phys_ctx->user_data));
  13967. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  13968. * If it returns 1, civetweb assumes the calback already did this.
  13969. * If it returns -1, initializing ssl fails. */
  13970. if (callback_ret < 0) {
  13971. mg_cry_ctx_internal(phys_ctx,
  13972. "Domain SSL callback returned error: %i",
  13973. callback_ret);
  13974. return 0;
  13975. }
  13976. if (callback_ret > 0) {
  13977. /* Domain callback did everything. */
  13978. return 1;
  13979. }
  13980. /* Use some combination of start time, domain and port as a SSL
  13981. * context ID. This should be unique on the current machine. */
  13982. md5_init(&md5state);
  13983. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13984. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13985. md5_append(&md5state,
  13986. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13987. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13988. md5_append(&md5state,
  13989. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13990. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13991. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13992. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13993. md5_finish(&md5state, ssl_context_id);
  13994. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13995. (unsigned char *)ssl_context_id,
  13996. sizeof(ssl_context_id));
  13997. if (pem != NULL) {
  13998. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13999. return 0;
  14000. }
  14001. }
  14002. /* Should we support client certificates? */
  14003. /* Default is "no". */
  14004. should_verify_peer = 0;
  14005. peer_certificate_optional = 0;
  14006. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14007. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14008. /* Yes, they are mandatory */
  14009. should_verify_peer = 1;
  14010. peer_certificate_optional = 0;
  14011. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14012. "optional")
  14013. == 0) {
  14014. /* Yes, they are optional */
  14015. should_verify_peer = 1;
  14016. peer_certificate_optional = 1;
  14017. }
  14018. }
  14019. use_default_verify_paths =
  14020. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14021. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14022. == 0);
  14023. if (should_verify_peer) {
  14024. ca_path = dom_ctx->config[SSL_CA_PATH];
  14025. ca_file = dom_ctx->config[SSL_CA_FILE];
  14026. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14027. != 1) {
  14028. mg_cry_ctx_internal(phys_ctx,
  14029. "SSL_CTX_load_verify_locations error: %s "
  14030. "ssl_verify_peer requires setting "
  14031. "either ssl_ca_path or ssl_ca_file. "
  14032. "Is any of them present in the "
  14033. ".conf file?",
  14034. ssl_error());
  14035. return 0;
  14036. }
  14037. if (peer_certificate_optional) {
  14038. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14039. } else {
  14040. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14041. SSL_VERIFY_PEER
  14042. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14043. NULL);
  14044. }
  14045. if (use_default_verify_paths
  14046. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14047. mg_cry_ctx_internal(phys_ctx,
  14048. "SSL_CTX_set_default_verify_paths error: %s",
  14049. ssl_error());
  14050. return 0;
  14051. }
  14052. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14053. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14054. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14055. }
  14056. }
  14057. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14058. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14059. dom_ctx->config[SSL_CIPHER_LIST])
  14060. != 1) {
  14061. mg_cry_ctx_internal(phys_ctx,
  14062. "SSL_CTX_set_cipher_list error: %s",
  14063. ssl_error());
  14064. }
  14065. }
  14066. return 1;
  14067. }
  14068. /* Check if SSL is required.
  14069. * If so, dynamically load SSL library
  14070. * and set up ctx->ssl_ctx pointer. */
  14071. static int
  14072. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14073. {
  14074. void *ssl_ctx = 0;
  14075. int callback_ret;
  14076. const char *pem;
  14077. const char *chain;
  14078. char ebuf[128];
  14079. if (!phys_ctx) {
  14080. return 0;
  14081. }
  14082. if (!dom_ctx) {
  14083. dom_ctx = &(phys_ctx->dd);
  14084. }
  14085. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14086. /* No SSL port is set. No need to setup SSL. */
  14087. return 1;
  14088. }
  14089. /* Check for external SSL_CTX */
  14090. callback_ret =
  14091. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14092. ? 0
  14093. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14094. phys_ctx->user_data));
  14095. if (callback_ret < 0) {
  14096. mg_cry_ctx_internal(phys_ctx,
  14097. "external_ssl_ctx callback returned error: %i",
  14098. callback_ret);
  14099. return 0;
  14100. } else if (callback_ret > 0) {
  14101. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14102. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14103. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14104. return 0;
  14105. }
  14106. return 1;
  14107. }
  14108. /* Check for external domain SSL_CTX */
  14109. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14110. ? 0
  14111. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14112. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14113. &ssl_ctx,
  14114. phys_ctx->user_data));
  14115. if (callback_ret < 0) {
  14116. mg_cry_ctx_internal(
  14117. phys_ctx,
  14118. "external_ssl_ctx_domain callback returned error: %i",
  14119. callback_ret);
  14120. return 0;
  14121. } else if (callback_ret > 0) {
  14122. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14123. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14124. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14125. return 0;
  14126. }
  14127. return 1;
  14128. }
  14129. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return 0,
  14130. * CivetWeb should continue initializing SSL */
  14131. /* If PEM file is not specified and the init_ssl callbacks
  14132. * are not specified, setup will fail. */
  14133. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14134. && (phys_ctx->callbacks.init_ssl == NULL)
  14135. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14136. /* No certificate and no init_ssl callbacks:
  14137. * Essential data to set up TLS is missing.
  14138. */
  14139. mg_cry_ctx_internal(phys_ctx,
  14140. "Initializing SSL failed: -%s is not set",
  14141. config_options[SSL_CERTIFICATE].name);
  14142. return 0;
  14143. }
  14144. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14145. if (chain == NULL) {
  14146. chain = pem;
  14147. }
  14148. if ((chain != NULL) && (*chain == 0)) {
  14149. chain = NULL;
  14150. }
  14151. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14152. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14153. return 0;
  14154. }
  14155. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14156. }
  14157. static void
  14158. uninitialize_ssl(void)
  14159. {
  14160. #if defined(OPENSSL_API_1_1)
  14161. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14162. /* Shutdown according to
  14163. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14164. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14165. */
  14166. CONF_modules_unload(1);
  14167. #else
  14168. int i;
  14169. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14170. /* Shutdown according to
  14171. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14172. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14173. */
  14174. CRYPTO_set_locking_callback(NULL);
  14175. CRYPTO_set_id_callback(NULL);
  14176. ENGINE_cleanup();
  14177. CONF_modules_unload(1);
  14178. ERR_free_strings();
  14179. EVP_cleanup();
  14180. CRYPTO_cleanup_all_ex_data();
  14181. OPENSSL_REMOVE_THREAD_STATE();
  14182. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14183. pthread_mutex_destroy(&ssl_mutexes[i]);
  14184. }
  14185. mg_free(ssl_mutexes);
  14186. ssl_mutexes = NULL;
  14187. #endif /* OPENSSL_API_1_1 */
  14188. }
  14189. }
  14190. #endif /* !NO_SSL */
  14191. #if !defined(NO_FILESYSTEMS)
  14192. static int
  14193. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14194. {
  14195. if (phys_ctx) {
  14196. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14197. const char *path;
  14198. struct mg_connection fc;
  14199. if (!dom_ctx) {
  14200. dom_ctx = &(phys_ctx->dd);
  14201. }
  14202. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14203. if ((path != NULL)
  14204. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14205. mg_cry_ctx_internal(phys_ctx,
  14206. "Cannot open %s: %s",
  14207. path,
  14208. strerror(ERRNO));
  14209. return 0;
  14210. }
  14211. return 1;
  14212. }
  14213. return 0;
  14214. }
  14215. #endif /* NO_FILESYSTEMS */
  14216. static int
  14217. set_acl_option(struct mg_context *phys_ctx)
  14218. {
  14219. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14220. }
  14221. static void
  14222. reset_per_request_attributes(struct mg_connection *conn)
  14223. {
  14224. if (!conn) {
  14225. return;
  14226. }
  14227. conn->connection_type =
  14228. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14229. conn->num_bytes_sent = conn->consumed_content = 0;
  14230. conn->path_info = NULL;
  14231. conn->status_code = -1;
  14232. conn->content_len = -1;
  14233. conn->is_chunked = 0;
  14234. conn->must_close = 0;
  14235. conn->request_len = 0;
  14236. conn->throttle = 0;
  14237. conn->accept_gzip = 0;
  14238. conn->response_info.content_length = conn->request_info.content_length = -1;
  14239. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14240. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14241. conn->response_info.status_text = NULL;
  14242. conn->response_info.status_code = 0;
  14243. conn->request_info.remote_user = NULL;
  14244. conn->request_info.request_method = NULL;
  14245. conn->request_info.request_uri = NULL;
  14246. conn->request_info.local_uri = NULL;
  14247. #if defined(MG_LEGACY_INTERFACE)
  14248. /* Legacy before split into local_uri and request_uri */
  14249. conn->request_info.uri = NULL;
  14250. #endif
  14251. }
  14252. static int
  14253. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14254. {
  14255. if (setsockopt(sock,
  14256. IPPROTO_TCP,
  14257. TCP_NODELAY,
  14258. (SOCK_OPT_TYPE)&nodelay_on,
  14259. sizeof(nodelay_on))
  14260. != 0) {
  14261. /* Error */
  14262. return 1;
  14263. }
  14264. /* OK */
  14265. return 0;
  14266. }
  14267. #if !defined(__ZEPHYR__)
  14268. static void
  14269. close_socket_gracefully(struct mg_connection *conn)
  14270. {
  14271. #if defined(_WIN32)
  14272. char buf[MG_BUF_LEN];
  14273. int n;
  14274. #endif
  14275. struct linger linger;
  14276. int error_code = 0;
  14277. int linger_timeout = -2;
  14278. socklen_t opt_len = sizeof(error_code);
  14279. if (!conn) {
  14280. return;
  14281. }
  14282. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14283. * "Note that enabling a nonzero timeout on a nonblocking socket
  14284. * is not recommended.", so set it to blocking now */
  14285. set_blocking_mode(conn->client.sock);
  14286. /* Send FIN to the client */
  14287. shutdown(conn->client.sock, SHUTDOWN_WR);
  14288. #if defined(_WIN32)
  14289. /* Read and discard pending incoming data. If we do not do that and
  14290. * close
  14291. * the socket, the data in the send buffer may be discarded. This
  14292. * behaviour is seen on Windows, when client keeps sending data
  14293. * when server decides to close the connection; then when client
  14294. * does recv() it gets no data back. */
  14295. do {
  14296. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14297. } while (n > 0);
  14298. #endif
  14299. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14300. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14301. }
  14302. /* Set linger option according to configuration */
  14303. if (linger_timeout >= 0) {
  14304. /* Set linger option to avoid socket hanging out after close. This
  14305. * prevent ephemeral port exhaust problem under high QPS. */
  14306. linger.l_onoff = 1;
  14307. #if defined(_MSC_VER)
  14308. #pragma warning(push)
  14309. #pragma warning(disable : 4244)
  14310. #endif
  14311. #if defined(GCC_DIAGNOSTIC)
  14312. #pragma GCC diagnostic push
  14313. #pragma GCC diagnostic ignored "-Wconversion"
  14314. #endif
  14315. /* Data type of linger structure elements may differ,
  14316. * so we don't know what cast we need here.
  14317. * Disable type conversion warnings. */
  14318. linger.l_linger = (linger_timeout + 999) / 1000;
  14319. #if defined(GCC_DIAGNOSTIC)
  14320. #pragma GCC diagnostic pop
  14321. #endif
  14322. #if defined(_MSC_VER)
  14323. #pragma warning(pop)
  14324. #endif
  14325. } else {
  14326. linger.l_onoff = 0;
  14327. linger.l_linger = 0;
  14328. }
  14329. if (linger_timeout < -1) {
  14330. /* Default: don't configure any linger */
  14331. } else if (getsockopt(conn->client.sock,
  14332. SOL_SOCKET,
  14333. SO_ERROR,
  14334. #if defined(_WIN32) /* WinSock uses different data type here */
  14335. (char *)&error_code,
  14336. #else
  14337. &error_code,
  14338. #endif
  14339. &opt_len)
  14340. != 0) {
  14341. /* Cannot determine if socket is already closed. This should
  14342. * not occur and never did in a test. Log an error message
  14343. * and continue. */
  14344. mg_cry_internal(conn,
  14345. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14346. __func__,
  14347. strerror(ERRNO));
  14348. #if defined(_WIN32)
  14349. } else if (error_code == WSAECONNRESET) {
  14350. #else
  14351. } else if (error_code == ECONNRESET) {
  14352. #endif
  14353. /* Socket already closed by client/peer, close socket without linger
  14354. */
  14355. } else {
  14356. /* Set linger timeout */
  14357. if (setsockopt(conn->client.sock,
  14358. SOL_SOCKET,
  14359. SO_LINGER,
  14360. (char *)&linger,
  14361. sizeof(linger))
  14362. != 0) {
  14363. mg_cry_internal(
  14364. conn,
  14365. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14366. __func__,
  14367. linger.l_onoff,
  14368. linger.l_linger,
  14369. strerror(ERRNO));
  14370. }
  14371. }
  14372. /* Now we know that our FIN is ACK-ed, safe to close */
  14373. closesocket(conn->client.sock);
  14374. conn->client.sock = INVALID_SOCKET;
  14375. }
  14376. #endif
  14377. static void
  14378. close_connection(struct mg_connection *conn)
  14379. {
  14380. #if defined(USE_SERVER_STATS)
  14381. conn->conn_state = 6; /* to close */
  14382. #endif
  14383. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14384. if (conn->lua_websocket_state) {
  14385. lua_websocket_close(conn, conn->lua_websocket_state);
  14386. conn->lua_websocket_state = NULL;
  14387. }
  14388. #endif
  14389. mg_lock_connection(conn);
  14390. /* Set close flag, so keep-alive loops will stop */
  14391. conn->must_close = 1;
  14392. /* call the connection_close callback if assigned */
  14393. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14394. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14395. conn->phys_ctx->callbacks.connection_close(conn);
  14396. }
  14397. }
  14398. /* Reset user data, after close callback is called.
  14399. * Do not reuse it. If the user needs a destructor,
  14400. * it must be done in the connection_close callback. */
  14401. mg_set_user_connection_data(conn, NULL);
  14402. #if defined(USE_SERVER_STATS)
  14403. conn->conn_state = 7; /* closing */
  14404. #endif
  14405. #if !defined(NO_SSL)
  14406. if (conn->ssl != NULL) {
  14407. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14408. */
  14409. SSL_shutdown(conn->ssl);
  14410. SSL_free(conn->ssl);
  14411. OPENSSL_REMOVE_THREAD_STATE();
  14412. conn->ssl = NULL;
  14413. }
  14414. #endif
  14415. if (conn->client.sock != INVALID_SOCKET) {
  14416. #if defined(__ZEPHYR__)
  14417. closesocket(conn->client.sock);
  14418. #else
  14419. close_socket_gracefully(conn);
  14420. #endif
  14421. conn->client.sock = INVALID_SOCKET;
  14422. }
  14423. if (conn->host) {
  14424. mg_free((void *)conn->host);
  14425. conn->host = NULL;
  14426. }
  14427. mg_unlock_connection(conn);
  14428. #if defined(USE_SERVER_STATS)
  14429. conn->conn_state = 8; /* closed */
  14430. #endif
  14431. }
  14432. void
  14433. mg_close_connection(struct mg_connection *conn)
  14434. {
  14435. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14436. return;
  14437. }
  14438. #if defined(USE_WEBSOCKET)
  14439. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14440. if (conn->in_websocket_handling) {
  14441. /* Set close flag, so the server thread can exit. */
  14442. conn->must_close = 1;
  14443. return;
  14444. }
  14445. }
  14446. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14447. unsigned int i;
  14448. /* client context: loops must end */
  14449. conn->phys_ctx->stop_flag = 1;
  14450. conn->must_close = 1;
  14451. /* We need to get the client thread out of the select/recv call
  14452. * here. */
  14453. /* Since we use a sleep quantum of some seconds to check for recv
  14454. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14455. /* join worker thread */
  14456. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14457. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14458. }
  14459. }
  14460. #endif /* defined(USE_WEBSOCKET) */
  14461. close_connection(conn);
  14462. #if !defined(NO_SSL)
  14463. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14464. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14465. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14466. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14467. }
  14468. #endif
  14469. #if defined(USE_WEBSOCKET)
  14470. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14471. mg_free(conn->phys_ctx->worker_threadids);
  14472. (void)pthread_mutex_destroy(&conn->mutex);
  14473. mg_free(conn);
  14474. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14475. mg_free(conn);
  14476. }
  14477. #else
  14478. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14479. mg_free(conn);
  14480. }
  14481. #endif /* defined(USE_WEBSOCKET) */
  14482. }
  14483. static struct mg_connection *
  14484. mg_connect_client_impl(const struct mg_client_options *client_options,
  14485. int use_ssl,
  14486. char *ebuf,
  14487. size_t ebuf_len)
  14488. {
  14489. struct mg_connection *conn = NULL;
  14490. SOCKET sock;
  14491. union usa sa;
  14492. struct sockaddr *psa;
  14493. socklen_t len;
  14494. unsigned max_req_size =
  14495. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14496. /* Size of structures, aligned to 8 bytes */
  14497. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14498. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14499. conn =
  14500. (struct mg_connection *)mg_calloc(1,
  14501. conn_size + ctx_size + max_req_size);
  14502. if (conn == NULL) {
  14503. mg_snprintf(NULL,
  14504. NULL, /* No truncation check for ebuf */
  14505. ebuf,
  14506. ebuf_len,
  14507. "calloc(): %s",
  14508. strerror(ERRNO));
  14509. return NULL;
  14510. }
  14511. #if defined(GCC_DIAGNOSTIC)
  14512. #pragma GCC diagnostic push
  14513. #pragma GCC diagnostic ignored "-Wcast-align"
  14514. #endif /* defined(GCC_DIAGNOSTIC) */
  14515. /* conn_size is aligned to 8 bytes */
  14516. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14517. #if defined(GCC_DIAGNOSTIC)
  14518. #pragma GCC diagnostic pop
  14519. #endif /* defined(GCC_DIAGNOSTIC) */
  14520. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14521. conn->buf_size = (int)max_req_size;
  14522. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14523. conn->dom_ctx = &(conn->phys_ctx->dd);
  14524. if (!connect_socket(conn->phys_ctx,
  14525. client_options->host,
  14526. client_options->port,
  14527. use_ssl,
  14528. ebuf,
  14529. ebuf_len,
  14530. &sock,
  14531. &sa)) {
  14532. /* ebuf is set by connect_socket,
  14533. * free all memory and return NULL; */
  14534. mg_free(conn);
  14535. return NULL;
  14536. }
  14537. #if !defined(NO_SSL)
  14538. #if defined(OPENSSL_API_1_1)
  14539. if (use_ssl
  14540. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14541. == NULL) {
  14542. mg_snprintf(NULL,
  14543. NULL, /* No truncation check for ebuf */
  14544. ebuf,
  14545. ebuf_len,
  14546. "SSL_CTX_new error: %s",
  14547. ssl_error());
  14548. closesocket(sock);
  14549. mg_free(conn);
  14550. return NULL;
  14551. }
  14552. #else
  14553. if (use_ssl
  14554. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14555. == NULL) {
  14556. mg_snprintf(NULL,
  14557. NULL, /* No truncation check for ebuf */
  14558. ebuf,
  14559. ebuf_len,
  14560. "SSL_CTX_new error: %s",
  14561. ssl_error());
  14562. closesocket(sock);
  14563. mg_free(conn);
  14564. return NULL;
  14565. }
  14566. #endif /* OPENSSL_API_1_1 */
  14567. #endif /* NO_SSL */
  14568. #if defined(USE_IPV6)
  14569. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14570. : sizeof(conn->client.rsa.sin6);
  14571. psa = (sa.sa.sa_family == AF_INET)
  14572. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14573. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14574. #else
  14575. len = sizeof(conn->client.rsa.sin);
  14576. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14577. #endif
  14578. conn->client.sock = sock;
  14579. conn->client.lsa = sa;
  14580. if (getsockname(sock, psa, &len) != 0) {
  14581. mg_cry_internal(conn,
  14582. "%s: getsockname() failed: %s",
  14583. __func__,
  14584. strerror(ERRNO));
  14585. }
  14586. conn->client.is_ssl = use_ssl ? 1 : 0;
  14587. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14588. mg_snprintf(NULL,
  14589. NULL, /* No truncation check for ebuf */
  14590. ebuf,
  14591. ebuf_len,
  14592. "Can not create mutex");
  14593. #if !defined(NO_SSL)
  14594. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14595. #endif
  14596. closesocket(sock);
  14597. mg_free(conn);
  14598. return NULL;
  14599. }
  14600. #if !defined(NO_SSL)
  14601. if (use_ssl) {
  14602. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14603. * SSL_CTX_set_verify call is needed to switch off server
  14604. * certificate checking, which is off by default in OpenSSL and
  14605. * on in yaSSL. */
  14606. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14607. * SSL_VERIFY_PEER, verify_ssl_server); */
  14608. if (client_options->client_cert) {
  14609. if (!ssl_use_pem_file(conn->phys_ctx,
  14610. conn->dom_ctx,
  14611. client_options->client_cert,
  14612. NULL)) {
  14613. mg_snprintf(NULL,
  14614. NULL, /* No truncation check for ebuf */
  14615. ebuf,
  14616. ebuf_len,
  14617. "Can not use SSL client certificate");
  14618. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14619. closesocket(sock);
  14620. mg_free(conn);
  14621. return NULL;
  14622. }
  14623. }
  14624. if (client_options->server_cert) {
  14625. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14626. client_options->server_cert,
  14627. NULL)
  14628. != 1) {
  14629. mg_cry_internal(conn,
  14630. "SSL_CTX_load_verify_locations error: %s ",
  14631. ssl_error());
  14632. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14633. closesocket(sock);
  14634. mg_free(conn);
  14635. return NULL;
  14636. }
  14637. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14638. } else {
  14639. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14640. }
  14641. if (!sslize(conn,
  14642. conn->dom_ctx->ssl_ctx,
  14643. SSL_connect,
  14644. &(conn->phys_ctx->stop_flag),
  14645. client_options)) {
  14646. mg_snprintf(NULL,
  14647. NULL, /* No truncation check for ebuf */
  14648. ebuf,
  14649. ebuf_len,
  14650. "SSL connection error");
  14651. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14652. closesocket(sock);
  14653. mg_free(conn);
  14654. return NULL;
  14655. }
  14656. }
  14657. #endif
  14658. return conn;
  14659. }
  14660. CIVETWEB_API struct mg_connection *
  14661. mg_connect_client_secure(const struct mg_client_options *client_options,
  14662. char *error_buffer,
  14663. size_t error_buffer_size)
  14664. {
  14665. return mg_connect_client_impl(client_options,
  14666. 1,
  14667. error_buffer,
  14668. error_buffer_size);
  14669. }
  14670. struct mg_connection *
  14671. mg_connect_client(const char *host,
  14672. int port,
  14673. int use_ssl,
  14674. char *error_buffer,
  14675. size_t error_buffer_size)
  14676. {
  14677. struct mg_client_options opts;
  14678. memset(&opts, 0, sizeof(opts));
  14679. opts.host = host;
  14680. opts.port = port;
  14681. return mg_connect_client_impl(&opts,
  14682. use_ssl,
  14683. error_buffer,
  14684. error_buffer_size);
  14685. }
  14686. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14687. struct mg_connection *
  14688. mg_connect_client2(const char *host,
  14689. const char *protocol,
  14690. int port,
  14691. const char *path,
  14692. struct mg_init_data *init,
  14693. struct mg_error_data *error)
  14694. {
  14695. int is_ssl, is_ws;
  14696. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14697. if (error != NULL) {
  14698. error->code = 0;
  14699. if (error->text_buffer_size > 0) {
  14700. *error->text = 0;
  14701. }
  14702. }
  14703. if ((host == NULL) || (protocol == NULL)) {
  14704. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14705. mg_snprintf(NULL,
  14706. NULL, /* No truncation check for error buffers */
  14707. error->text,
  14708. error->text_buffer_size,
  14709. "%s",
  14710. "Invalid parameters");
  14711. }
  14712. return NULL;
  14713. }
  14714. /* check all known protocolls */
  14715. if (!mg_strcasecmp(protocol, "http")) {
  14716. is_ssl = 0;
  14717. is_ws = 0;
  14718. } else if (!mg_strcasecmp(protocol, "https")) {
  14719. is_ssl = 1;
  14720. is_ws = 0;
  14721. #if defined(USE_WEBSOCKET)
  14722. } else if (!mg_strcasecmp(protocol, "ws")) {
  14723. is_ssl = 0;
  14724. is_ws = 1;
  14725. } else if (!mg_strcasecmp(protocol, "wss")) {
  14726. is_ssl = 1;
  14727. is_ws = 1;
  14728. #endif
  14729. } else {
  14730. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14731. mg_snprintf(NULL,
  14732. NULL, /* No truncation check for error buffers */
  14733. error->text,
  14734. error->text_buffer_size,
  14735. "Protocol %s not supported",
  14736. protocol);
  14737. }
  14738. return NULL;
  14739. }
  14740. /* TODO: The current implementation here just calls the old implementations,
  14741. * without using any new options. This is just a first step to test the new
  14742. * interfaces. */
  14743. #if defined(USE_WEBSOCKET)
  14744. if (is_ws) {
  14745. /* TODO: implement all options */
  14746. return mg_connect_websocket_client(host,
  14747. port,
  14748. is_ssl,
  14749. error->text,
  14750. error->text_buffer_size,
  14751. (path ? path : ""),
  14752. NULL /* TODO: origin */,
  14753. deprecated_websocket_data_wrapper,
  14754. deprecated_websocket_close_wrapper,
  14755. (void *)init->callbacks);
  14756. }
  14757. #endif
  14758. /* TODO: all additional options */
  14759. struct mg_client_options opts;
  14760. memset(&opts, 0, sizeof(opts));
  14761. opts.host = host;
  14762. opts.port = port;
  14763. return mg_connect_client_impl(&opts,
  14764. is_ssl,
  14765. error->text,
  14766. error->text_buffer_size);
  14767. }
  14768. #endif
  14769. static const struct {
  14770. const char *proto;
  14771. size_t proto_len;
  14772. unsigned default_port;
  14773. } abs_uri_protocols[] = {{"http://", 7, 80},
  14774. {"https://", 8, 443},
  14775. {"ws://", 5, 80},
  14776. {"wss://", 6, 443},
  14777. {NULL, 0, 0}};
  14778. /* Check if the uri is valid.
  14779. * return 0 for invalid uri,
  14780. * return 1 for *,
  14781. * return 2 for relative uri,
  14782. * return 3 for absolute uri without port,
  14783. * return 4 for absolute uri with port */
  14784. static int
  14785. get_uri_type(const char *uri)
  14786. {
  14787. int i;
  14788. const char *hostend, *portbegin;
  14789. char *portend;
  14790. unsigned long port;
  14791. /* According to the HTTP standard
  14792. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14793. * URI can be an asterisk (*) or should start with slash (relative uri),
  14794. * or it should start with the protocol (absolute uri). */
  14795. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14796. /* asterisk */
  14797. return 1;
  14798. }
  14799. /* Valid URIs according to RFC 3986
  14800. * (https://www.ietf.org/rfc/rfc3986.txt)
  14801. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14802. * and unreserved characters A-Z a-z 0-9 and -._~
  14803. * and % encoded symbols.
  14804. */
  14805. for (i = 0; uri[i] != 0; i++) {
  14806. if (uri[i] < 33) {
  14807. /* control characters and spaces are invalid */
  14808. return 0;
  14809. }
  14810. if (uri[i] > 126) {
  14811. /* non-ascii characters must be % encoded */
  14812. return 0;
  14813. } else {
  14814. switch (uri[i]) {
  14815. case '"': /* 34 */
  14816. case '<': /* 60 */
  14817. case '>': /* 62 */
  14818. case '\\': /* 92 */
  14819. case '^': /* 94 */
  14820. case '`': /* 96 */
  14821. case '{': /* 123 */
  14822. case '|': /* 124 */
  14823. case '}': /* 125 */
  14824. return 0;
  14825. default:
  14826. /* character is ok */
  14827. break;
  14828. }
  14829. }
  14830. }
  14831. /* A relative uri starts with a / character */
  14832. if (uri[0] == '/') {
  14833. /* relative uri */
  14834. return 2;
  14835. }
  14836. /* It could be an absolute uri: */
  14837. /* This function only checks if the uri is valid, not if it is
  14838. * addressing the current server. So civetweb can also be used
  14839. * as a proxy server. */
  14840. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14841. if (mg_strncasecmp(uri,
  14842. abs_uri_protocols[i].proto,
  14843. abs_uri_protocols[i].proto_len)
  14844. == 0) {
  14845. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14846. if (!hostend) {
  14847. return 0;
  14848. }
  14849. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14850. if (!portbegin) {
  14851. return 3;
  14852. }
  14853. port = strtoul(portbegin + 1, &portend, 10);
  14854. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14855. return 0;
  14856. }
  14857. return 4;
  14858. }
  14859. }
  14860. return 0;
  14861. }
  14862. /* Return NULL or the relative uri at the current server */
  14863. static const char *
  14864. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14865. {
  14866. const char *server_domain;
  14867. size_t server_domain_len;
  14868. size_t request_domain_len = 0;
  14869. unsigned long port = 0;
  14870. int i, auth_domain_check_enabled;
  14871. const char *hostbegin = NULL;
  14872. const char *hostend = NULL;
  14873. const char *portbegin;
  14874. char *portend;
  14875. auth_domain_check_enabled =
  14876. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14877. /* DNS is case insensitive, so use case insensitive string compare here
  14878. */
  14879. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14880. if (mg_strncasecmp(uri,
  14881. abs_uri_protocols[i].proto,
  14882. abs_uri_protocols[i].proto_len)
  14883. == 0) {
  14884. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14885. hostend = strchr(hostbegin, '/');
  14886. if (!hostend) {
  14887. return 0;
  14888. }
  14889. portbegin = strchr(hostbegin, ':');
  14890. if ((!portbegin) || (portbegin > hostend)) {
  14891. port = abs_uri_protocols[i].default_port;
  14892. request_domain_len = (size_t)(hostend - hostbegin);
  14893. } else {
  14894. port = strtoul(portbegin + 1, &portend, 10);
  14895. if ((portend != hostend) || (port <= 0)
  14896. || !is_valid_port(port)) {
  14897. return 0;
  14898. }
  14899. request_domain_len = (size_t)(portbegin - hostbegin);
  14900. }
  14901. /* protocol found, port set */
  14902. break;
  14903. }
  14904. }
  14905. if (!port) {
  14906. /* port remains 0 if the protocol is not found */
  14907. return 0;
  14908. }
  14909. /* Check if the request is directed to a different server. */
  14910. /* First check if the port is the same (IPv4 and IPv6). */
  14911. #if defined(USE_IPV6)
  14912. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14913. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14914. /* Request is directed to a different port */
  14915. return 0;
  14916. }
  14917. } else
  14918. #endif
  14919. {
  14920. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14921. /* Request is directed to a different port */
  14922. return 0;
  14923. }
  14924. }
  14925. /* Finally check if the server corresponds to the authentication
  14926. * domain of the server (the server domain).
  14927. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14928. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14929. * but do not allow substrings (like
  14930. * http://notmydomain.com/path/file.ext
  14931. * or http://mydomain.com.fake/path/file.ext).
  14932. */
  14933. if (auth_domain_check_enabled) {
  14934. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14935. server_domain_len = strlen(server_domain);
  14936. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14937. return 0;
  14938. }
  14939. if ((request_domain_len == server_domain_len)
  14940. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14941. /* Request is directed to this server - full name match. */
  14942. } else {
  14943. if (request_domain_len < (server_domain_len + 2)) {
  14944. /* Request is directed to another server: The server name
  14945. * is longer than the request name.
  14946. * Drop this case here to avoid overflows in the
  14947. * following checks. */
  14948. return 0;
  14949. }
  14950. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14951. /* Request is directed to another server: It could be a
  14952. * substring
  14953. * like notmyserver.com */
  14954. return 0;
  14955. }
  14956. if (0
  14957. != memcmp(server_domain,
  14958. hostbegin + request_domain_len - server_domain_len,
  14959. server_domain_len)) {
  14960. /* Request is directed to another server:
  14961. * The server name is different. */
  14962. return 0;
  14963. }
  14964. }
  14965. }
  14966. return hostend;
  14967. }
  14968. static int
  14969. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14970. {
  14971. if (ebuf_len > 0) {
  14972. ebuf[0] = '\0';
  14973. }
  14974. *err = 0;
  14975. reset_per_request_attributes(conn);
  14976. if (!conn) {
  14977. mg_snprintf(conn,
  14978. NULL, /* No truncation check for ebuf */
  14979. ebuf,
  14980. ebuf_len,
  14981. "%s",
  14982. "Internal error");
  14983. *err = 500;
  14984. return 0;
  14985. }
  14986. /* Set the time the request was received. This value should be used for
  14987. * timeouts. */
  14988. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14989. conn->request_len =
  14990. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14991. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14992. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14993. mg_snprintf(conn,
  14994. NULL, /* No truncation check for ebuf */
  14995. ebuf,
  14996. ebuf_len,
  14997. "%s",
  14998. "Invalid message size");
  14999. *err = 500;
  15000. return 0;
  15001. }
  15002. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15003. mg_snprintf(conn,
  15004. NULL, /* No truncation check for ebuf */
  15005. ebuf,
  15006. ebuf_len,
  15007. "%s",
  15008. "Message too large");
  15009. *err = 413;
  15010. return 0;
  15011. }
  15012. if (conn->request_len <= 0) {
  15013. if (conn->data_len > 0) {
  15014. mg_snprintf(conn,
  15015. NULL, /* No truncation check for ebuf */
  15016. ebuf,
  15017. ebuf_len,
  15018. "%s",
  15019. "Malformed message");
  15020. *err = 400;
  15021. } else {
  15022. /* Server did not recv anything -> just close the connection */
  15023. conn->must_close = 1;
  15024. mg_snprintf(conn,
  15025. NULL, /* No truncation check for ebuf */
  15026. ebuf,
  15027. ebuf_len,
  15028. "%s",
  15029. "No data received");
  15030. *err = 0;
  15031. }
  15032. return 0;
  15033. }
  15034. return 1;
  15035. }
  15036. static int
  15037. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15038. {
  15039. const char *cl;
  15040. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15041. return 0;
  15042. }
  15043. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15044. <= 0) {
  15045. mg_snprintf(conn,
  15046. NULL, /* No truncation check for ebuf */
  15047. ebuf,
  15048. ebuf_len,
  15049. "%s",
  15050. "Bad request");
  15051. *err = 400;
  15052. return 0;
  15053. }
  15054. /* Message is a valid request */
  15055. /* Is there a "host" ? */
  15056. if (conn->host != NULL) {
  15057. mg_free((void *)conn->host);
  15058. }
  15059. conn->host = alloc_get_host(conn);
  15060. if (!conn->host) {
  15061. mg_snprintf(conn,
  15062. NULL, /* No truncation check for ebuf */
  15063. ebuf,
  15064. ebuf_len,
  15065. "%s",
  15066. "Bad request: Host mismatch");
  15067. *err = 400;
  15068. return 0;
  15069. }
  15070. if (((cl = get_header(conn->request_info.http_headers,
  15071. conn->request_info.num_headers,
  15072. "Transfer-Encoding"))
  15073. != NULL)
  15074. && mg_strcasecmp(cl, "identity")) {
  15075. if (mg_strcasecmp(cl, "chunked")) {
  15076. mg_snprintf(conn,
  15077. NULL, /* No truncation check for ebuf */
  15078. ebuf,
  15079. ebuf_len,
  15080. "%s",
  15081. "Bad request");
  15082. *err = 400;
  15083. return 0;
  15084. }
  15085. conn->is_chunked = 1;
  15086. conn->content_len = 0; /* not yet read */
  15087. } else if ((cl = get_header(conn->request_info.http_headers,
  15088. conn->request_info.num_headers,
  15089. "Content-Length"))
  15090. != NULL) {
  15091. /* Request has content length set */
  15092. char *endptr = NULL;
  15093. conn->content_len = strtoll(cl, &endptr, 10);
  15094. if ((endptr == cl) || (conn->content_len < 0)) {
  15095. mg_snprintf(conn,
  15096. NULL, /* No truncation check for ebuf */
  15097. ebuf,
  15098. ebuf_len,
  15099. "%s",
  15100. "Bad request");
  15101. *err = 411;
  15102. return 0;
  15103. }
  15104. /* Publish the content length back to the request info. */
  15105. conn->request_info.content_length = conn->content_len;
  15106. } else {
  15107. /* There is no exception, see RFC7230. */
  15108. conn->content_len = 0;
  15109. }
  15110. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15111. return 1;
  15112. }
  15113. /* conn is assumed to be valid in this internal function */
  15114. static int
  15115. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15116. {
  15117. const char *cl;
  15118. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15119. return 0;
  15120. }
  15121. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15122. <= 0) {
  15123. mg_snprintf(conn,
  15124. NULL, /* No truncation check for ebuf */
  15125. ebuf,
  15126. ebuf_len,
  15127. "%s",
  15128. "Bad response");
  15129. *err = 400;
  15130. return 0;
  15131. }
  15132. /* Message is a valid response */
  15133. if (((cl = get_header(conn->response_info.http_headers,
  15134. conn->response_info.num_headers,
  15135. "Transfer-Encoding"))
  15136. != NULL)
  15137. && mg_strcasecmp(cl, "identity")) {
  15138. if (mg_strcasecmp(cl, "chunked")) {
  15139. mg_snprintf(conn,
  15140. NULL, /* No truncation check for ebuf */
  15141. ebuf,
  15142. ebuf_len,
  15143. "%s",
  15144. "Bad request");
  15145. *err = 400;
  15146. return 0;
  15147. }
  15148. conn->is_chunked = 1;
  15149. conn->content_len = 0; /* not yet read */
  15150. } else if ((cl = get_header(conn->response_info.http_headers,
  15151. conn->response_info.num_headers,
  15152. "Content-Length"))
  15153. != NULL) {
  15154. char *endptr = NULL;
  15155. conn->content_len = strtoll(cl, &endptr, 10);
  15156. if ((endptr == cl) || (conn->content_len < 0)) {
  15157. mg_snprintf(conn,
  15158. NULL, /* No truncation check for ebuf */
  15159. ebuf,
  15160. ebuf_len,
  15161. "%s",
  15162. "Bad request");
  15163. *err = 411;
  15164. return 0;
  15165. }
  15166. /* Publish the content length back to the response info. */
  15167. conn->response_info.content_length = conn->content_len;
  15168. /* TODO: check if it is still used in response_info */
  15169. conn->request_info.content_length = conn->content_len;
  15170. /* TODO: we should also consider HEAD method */
  15171. if (conn->response_info.status_code == 304) {
  15172. conn->content_len = 0;
  15173. }
  15174. } else {
  15175. /* TODO: we should also consider HEAD method */
  15176. if (((conn->response_info.status_code >= 100)
  15177. && (conn->response_info.status_code <= 199))
  15178. || (conn->response_info.status_code == 204)
  15179. || (conn->response_info.status_code == 304)) {
  15180. conn->content_len = 0;
  15181. } else {
  15182. conn->content_len = -1; /* unknown content length */
  15183. }
  15184. }
  15185. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15186. return 1;
  15187. }
  15188. int
  15189. mg_get_response(struct mg_connection *conn,
  15190. char *ebuf,
  15191. size_t ebuf_len,
  15192. int timeout)
  15193. {
  15194. int err, ret;
  15195. char txt[32]; /* will not overflow */
  15196. char *save_timeout;
  15197. char *new_timeout;
  15198. if (ebuf_len > 0) {
  15199. ebuf[0] = '\0';
  15200. }
  15201. if (!conn) {
  15202. mg_snprintf(conn,
  15203. NULL, /* No truncation check for ebuf */
  15204. ebuf,
  15205. ebuf_len,
  15206. "%s",
  15207. "Parameter error");
  15208. return -1;
  15209. }
  15210. /* Reset the previous responses */
  15211. conn->data_len = 0;
  15212. /* Implementation of API function for HTTP clients */
  15213. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15214. if (timeout >= 0) {
  15215. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15216. new_timeout = txt;
  15217. } else {
  15218. new_timeout = NULL;
  15219. }
  15220. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15221. ret = get_response(conn, ebuf, ebuf_len, &err);
  15222. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15223. #if defined(MG_LEGACY_INTERFACE)
  15224. /* TODO: 1) uri is deprecated;
  15225. * 2) here, ri.uri is the http response code */
  15226. conn->request_info.uri = conn->request_info.request_uri;
  15227. #endif
  15228. conn->request_info.local_uri = conn->request_info.request_uri;
  15229. /* TODO (mid): Define proper return values - maybe return length?
  15230. * For the first test use <0 for error and >0 for OK */
  15231. return (ret == 0) ? -1 : +1;
  15232. }
  15233. struct mg_connection *
  15234. mg_download(const char *host,
  15235. int port,
  15236. int use_ssl,
  15237. char *ebuf,
  15238. size_t ebuf_len,
  15239. const char *fmt,
  15240. ...)
  15241. {
  15242. struct mg_connection *conn;
  15243. va_list ap;
  15244. int i;
  15245. int reqerr;
  15246. if (ebuf_len > 0) {
  15247. ebuf[0] = '\0';
  15248. }
  15249. va_start(ap, fmt);
  15250. /* open a connection */
  15251. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15252. if (conn != NULL) {
  15253. i = mg_vprintf(conn, fmt, ap);
  15254. if (i <= 0) {
  15255. mg_snprintf(conn,
  15256. NULL, /* No truncation check for ebuf */
  15257. ebuf,
  15258. ebuf_len,
  15259. "%s",
  15260. "Error sending request");
  15261. } else {
  15262. /* make sure the buffer is clear */
  15263. conn->data_len = 0;
  15264. get_response(conn, ebuf, ebuf_len, &reqerr);
  15265. #if defined(MG_LEGACY_INTERFACE)
  15266. /* TODO: 1) uri is deprecated;
  15267. * 2) here, ri.uri is the http response code */
  15268. conn->request_info.uri = conn->request_info.request_uri;
  15269. #endif
  15270. conn->request_info.local_uri = conn->request_info.request_uri;
  15271. }
  15272. }
  15273. /* if an error occurred, close the connection */
  15274. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15275. mg_close_connection(conn);
  15276. conn = NULL;
  15277. }
  15278. va_end(ap);
  15279. return conn;
  15280. }
  15281. struct websocket_client_thread_data {
  15282. struct mg_connection *conn;
  15283. mg_websocket_data_handler data_handler;
  15284. mg_websocket_close_handler close_handler;
  15285. void *callback_data;
  15286. };
  15287. #if defined(USE_WEBSOCKET)
  15288. #if defined(_WIN32)
  15289. static unsigned __stdcall websocket_client_thread(void *data)
  15290. #else
  15291. static void *
  15292. websocket_client_thread(void *data)
  15293. #endif
  15294. {
  15295. struct websocket_client_thread_data *cdata =
  15296. (struct websocket_client_thread_data *)data;
  15297. void *user_thread_ptr = NULL;
  15298. #if !defined(_WIN32)
  15299. struct sigaction sa;
  15300. /* Ignore SIGPIPE */
  15301. memset(&sa, 0, sizeof(sa));
  15302. sa.sa_handler = SIG_IGN;
  15303. sigaction(SIGPIPE, &sa, NULL);
  15304. #endif
  15305. mg_set_thread_name("ws-clnt");
  15306. if (cdata->conn->phys_ctx) {
  15307. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15308. /* 3 indicates a websocket client thread */
  15309. /* TODO: check if conn->phys_ctx can be set */
  15310. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15311. cdata->conn->phys_ctx, 3);
  15312. }
  15313. }
  15314. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15315. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15316. if (cdata->close_handler != NULL) {
  15317. cdata->close_handler(cdata->conn, cdata->callback_data);
  15318. }
  15319. /* The websocket_client context has only this thread. If it runs out,
  15320. set the stop_flag to 2 (= "stopped"). */
  15321. cdata->conn->phys_ctx->stop_flag = 2;
  15322. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15323. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15324. 3,
  15325. user_thread_ptr);
  15326. }
  15327. mg_free((void *)cdata);
  15328. #if defined(_WIN32)
  15329. return 0;
  15330. #else
  15331. return NULL;
  15332. #endif
  15333. }
  15334. #endif
  15335. struct mg_connection *
  15336. mg_connect_websocket_client(const char *host,
  15337. int port,
  15338. int use_ssl,
  15339. char *error_buffer,
  15340. size_t error_buffer_size,
  15341. const char *path,
  15342. const char *origin,
  15343. mg_websocket_data_handler data_func,
  15344. mg_websocket_close_handler close_func,
  15345. void *user_data)
  15346. {
  15347. struct mg_connection *conn = NULL;
  15348. #if defined(USE_WEBSOCKET)
  15349. struct websocket_client_thread_data *thread_data;
  15350. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15351. static const char *handshake_req;
  15352. if (origin != NULL) {
  15353. handshake_req = "GET %s HTTP/1.1\r\n"
  15354. "Host: %s\r\n"
  15355. "Upgrade: websocket\r\n"
  15356. "Connection: Upgrade\r\n"
  15357. "Sec-WebSocket-Key: %s\r\n"
  15358. "Sec-WebSocket-Version: 13\r\n"
  15359. "Origin: %s\r\n"
  15360. "\r\n";
  15361. } else {
  15362. handshake_req = "GET %s HTTP/1.1\r\n"
  15363. "Host: %s\r\n"
  15364. "Upgrade: websocket\r\n"
  15365. "Connection: Upgrade\r\n"
  15366. "Sec-WebSocket-Key: %s\r\n"
  15367. "Sec-WebSocket-Version: 13\r\n"
  15368. "\r\n";
  15369. }
  15370. #if defined(__clang__)
  15371. #pragma clang diagnostic push
  15372. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15373. #endif
  15374. /* Establish the client connection and request upgrade */
  15375. conn = mg_download(host,
  15376. port,
  15377. use_ssl,
  15378. error_buffer,
  15379. error_buffer_size,
  15380. handshake_req,
  15381. path,
  15382. host,
  15383. magic,
  15384. origin);
  15385. #if defined(__clang__)
  15386. #pragma clang diagnostic pop
  15387. #endif
  15388. /* Connection object will be null if something goes wrong */
  15389. if (conn == NULL) {
  15390. if (!*error_buffer) {
  15391. /* There should be already an error message */
  15392. mg_snprintf(conn,
  15393. NULL, /* No truncation check for ebuf */
  15394. error_buffer,
  15395. error_buffer_size,
  15396. "Unexpected error");
  15397. }
  15398. return NULL;
  15399. }
  15400. if (conn->response_info.status_code != 101) {
  15401. /* We sent an "upgrade" request. For a correct websocket
  15402. * protocol handshake, we expect a "101 Continue" response.
  15403. * Otherwise it is a protocol violation. Maybe the HTTP
  15404. * Server does not know websockets. */
  15405. if (!*error_buffer) {
  15406. /* set an error, if not yet set */
  15407. mg_snprintf(conn,
  15408. NULL, /* No truncation check for ebuf */
  15409. error_buffer,
  15410. error_buffer_size,
  15411. "Unexpected server reply");
  15412. }
  15413. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15414. mg_close_connection(conn);
  15415. return NULL;
  15416. }
  15417. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15418. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15419. if (!thread_data) {
  15420. DEBUG_TRACE("%s\r\n", "Out of memory");
  15421. mg_close_connection(conn);
  15422. return NULL;
  15423. }
  15424. thread_data->conn = conn;
  15425. thread_data->data_handler = data_func;
  15426. thread_data->close_handler = close_func;
  15427. thread_data->callback_data = user_data;
  15428. conn->phys_ctx->worker_threadids =
  15429. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15430. if (!conn->phys_ctx->worker_threadids) {
  15431. DEBUG_TRACE("%s\r\n", "Out of memory");
  15432. mg_free(thread_data);
  15433. mg_close_connection(conn);
  15434. return NULL;
  15435. }
  15436. /* Now upgrade to ws/wss client context */
  15437. conn->phys_ctx->user_data = user_data;
  15438. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15439. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15440. /* Start a thread to read the websocket client connection
  15441. * This thread will automatically stop when mg_disconnect is
  15442. * called on the client connection */
  15443. if (mg_start_thread_with_id(websocket_client_thread,
  15444. thread_data,
  15445. conn->phys_ctx->worker_threadids)
  15446. != 0) {
  15447. conn->phys_ctx->cfg_worker_threads = 0;
  15448. mg_free(thread_data);
  15449. mg_close_connection(conn);
  15450. conn = NULL;
  15451. DEBUG_TRACE("%s",
  15452. "Websocket client connect thread could not be started\r\n");
  15453. }
  15454. #else
  15455. /* Appease "unused parameter" warnings */
  15456. (void)host;
  15457. (void)port;
  15458. (void)use_ssl;
  15459. (void)error_buffer;
  15460. (void)error_buffer_size;
  15461. (void)path;
  15462. (void)origin;
  15463. (void)user_data;
  15464. (void)data_func;
  15465. (void)close_func;
  15466. #endif
  15467. return conn;
  15468. }
  15469. /* Prepare connection data structure */
  15470. static void
  15471. init_connection(struct mg_connection *conn)
  15472. {
  15473. /* Is keep alive allowed by the server */
  15474. int keep_alive_enabled =
  15475. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15476. if (!keep_alive_enabled) {
  15477. conn->must_close = 1;
  15478. }
  15479. /* Important: on new connection, reset the receiving buffer. Credit
  15480. * goes to crule42. */
  15481. conn->data_len = 0;
  15482. conn->handled_requests = 0;
  15483. mg_set_user_connection_data(conn, NULL);
  15484. #if defined(USE_SERVER_STATS)
  15485. conn->conn_state = 2; /* init */
  15486. #endif
  15487. /* call the init_connection callback if assigned */
  15488. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15489. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15490. void *conn_data = NULL;
  15491. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15492. mg_set_user_connection_data(conn, conn_data);
  15493. }
  15494. }
  15495. }
  15496. /* Process a connection - may handle multiple requests
  15497. * using the same connection.
  15498. * Must be called with a valid connection (conn and
  15499. * conn->phys_ctx must be valid).
  15500. */
  15501. static void
  15502. process_new_connection(struct mg_connection *conn)
  15503. {
  15504. struct mg_request_info *ri = &conn->request_info;
  15505. int keep_alive, discard_len;
  15506. char ebuf[100];
  15507. const char *hostend;
  15508. int reqerr, uri_type;
  15509. #if defined(USE_SERVER_STATS)
  15510. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15511. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15512. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15513. /* could use atomic compare exchange, but this
  15514. * seems overkill for statistics data */
  15515. conn->phys_ctx->max_active_connections = mcon;
  15516. }
  15517. #endif
  15518. init_connection(conn);
  15519. DEBUG_TRACE("Start processing connection from %s",
  15520. conn->request_info.remote_addr);
  15521. /* Loop over multiple requests sent using the same connection
  15522. * (while "keep alive"). */
  15523. do {
  15524. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15525. conn->handled_requests + 1);
  15526. #if defined(USE_SERVER_STATS)
  15527. conn->conn_state = 3; /* ready */
  15528. #endif
  15529. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15530. /* The request sent by the client could not be understood by
  15531. * the server, or it was incomplete or a timeout. Send an
  15532. * error message and close the connection. */
  15533. if (reqerr > 0) {
  15534. DEBUG_ASSERT(ebuf[0] != '\0');
  15535. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15536. }
  15537. } else if (strcmp(ri->http_version, "1.0")
  15538. && strcmp(ri->http_version, "1.1")) {
  15539. mg_snprintf(conn,
  15540. NULL, /* No truncation check for ebuf */
  15541. ebuf,
  15542. sizeof(ebuf),
  15543. "Bad HTTP version: [%s]",
  15544. ri->http_version);
  15545. mg_send_http_error(conn, 505, "%s", ebuf);
  15546. }
  15547. if (ebuf[0] == '\0') {
  15548. uri_type = get_uri_type(conn->request_info.request_uri);
  15549. switch (uri_type) {
  15550. case 1:
  15551. /* Asterisk */
  15552. conn->request_info.local_uri = NULL;
  15553. break;
  15554. case 2:
  15555. /* relative uri */
  15556. conn->request_info.local_uri = conn->request_info.request_uri;
  15557. break;
  15558. case 3:
  15559. case 4:
  15560. /* absolute uri (with/without port) */
  15561. hostend = get_rel_url_at_current_server(
  15562. conn->request_info.request_uri, conn);
  15563. if (hostend) {
  15564. conn->request_info.local_uri = hostend;
  15565. } else {
  15566. conn->request_info.local_uri = NULL;
  15567. }
  15568. break;
  15569. default:
  15570. mg_snprintf(conn,
  15571. NULL, /* No truncation check for ebuf */
  15572. ebuf,
  15573. sizeof(ebuf),
  15574. "Invalid URI");
  15575. mg_send_http_error(conn, 400, "%s", ebuf);
  15576. conn->request_info.local_uri = NULL;
  15577. break;
  15578. }
  15579. #if defined(MG_LEGACY_INTERFACE)
  15580. /* Legacy before split into local_uri and request_uri */
  15581. conn->request_info.uri = conn->request_info.local_uri;
  15582. #endif
  15583. }
  15584. DEBUG_TRACE("http: %s, error: %s",
  15585. (ri->http_version ? ri->http_version : "none"),
  15586. (ebuf[0] ? ebuf : "none"));
  15587. if (ebuf[0] == '\0') {
  15588. if (conn->request_info.local_uri) {
  15589. /* handle request to local server */
  15590. #if defined(USE_SERVER_STATS)
  15591. conn->conn_state = 4; /* processing */
  15592. #endif
  15593. handle_request(conn);
  15594. #if defined(USE_SERVER_STATS)
  15595. conn->conn_state = 5; /* processed */
  15596. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15597. conn->consumed_content);
  15598. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15599. conn->num_bytes_sent);
  15600. #endif
  15601. DEBUG_TRACE("%s", "handle_request done");
  15602. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15603. conn->phys_ctx->callbacks.end_request(conn,
  15604. conn->status_code);
  15605. DEBUG_TRACE("%s", "end_request callback done");
  15606. }
  15607. log_access(conn);
  15608. } else {
  15609. /* TODO: handle non-local request (PROXY) */
  15610. conn->must_close = 1;
  15611. }
  15612. } else {
  15613. conn->must_close = 1;
  15614. }
  15615. if (ri->remote_user != NULL) {
  15616. mg_free((void *)ri->remote_user);
  15617. /* Important! When having connections with and without auth
  15618. * would cause double free and then crash */
  15619. ri->remote_user = NULL;
  15620. }
  15621. /* NOTE(lsm): order is important here. should_keep_alive() call
  15622. * is using parsed request, which will be invalid after
  15623. * memmove's below.
  15624. * Therefore, memorize should_keep_alive() result now for later
  15625. * use in loop exit condition. */
  15626. /* Enable it only if this request is completely discardable. */
  15627. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15628. && (conn->content_len >= 0) && (conn->request_len > 0)
  15629. && ((conn->is_chunked == 4)
  15630. || (!conn->is_chunked
  15631. && ((conn->consumed_content == conn->content_len)
  15632. || ((conn->request_len + conn->content_len)
  15633. <= conn->data_len))));
  15634. if (keep_alive) {
  15635. /* Discard all buffered data for this request */
  15636. discard_len =
  15637. ((conn->request_len + conn->content_len) < conn->data_len)
  15638. ? (int)(conn->request_len + conn->content_len)
  15639. : conn->data_len;
  15640. conn->data_len -= discard_len;
  15641. if (conn->data_len > 0) {
  15642. DEBUG_TRACE("discard_len = %d", discard_len);
  15643. memmove(conn->buf,
  15644. conn->buf + discard_len,
  15645. (size_t)conn->data_len);
  15646. }
  15647. }
  15648. DEBUG_ASSERT(conn->data_len >= 0);
  15649. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15650. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15651. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15652. (long int)conn->data_len,
  15653. (long int)conn->buf_size);
  15654. break;
  15655. }
  15656. conn->handled_requests++;
  15657. } while (keep_alive);
  15658. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15659. conn->request_info.remote_addr,
  15660. difftime(time(NULL), conn->conn_birth_time));
  15661. close_connection(conn);
  15662. #if defined(USE_SERVER_STATS)
  15663. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15664. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15665. #endif
  15666. }
  15667. #if defined(ALTERNATIVE_QUEUE)
  15668. static void
  15669. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15670. {
  15671. unsigned int i;
  15672. while (!ctx->stop_flag) {
  15673. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15674. /* find a free worker slot and signal it */
  15675. if (ctx->client_socks[i].in_use == 2) {
  15676. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15677. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15678. ctx->client_socks[i] = *sp;
  15679. ctx->client_socks[i].in_use = 1;
  15680. /* socket has been moved to the consumer */
  15681. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15682. (void)event_signal(ctx->client_wait_events[i]);
  15683. return;
  15684. }
  15685. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15686. }
  15687. }
  15688. /* queue is full */
  15689. mg_sleep(1);
  15690. }
  15691. /* must consume */
  15692. set_blocking_mode(sp->sock);
  15693. closesocket(sp->sock);
  15694. }
  15695. static int
  15696. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15697. {
  15698. DEBUG_TRACE("%s", "going idle");
  15699. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15700. ctx->client_socks[thread_index].in_use = 2;
  15701. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15702. event_wait(ctx->client_wait_events[thread_index]);
  15703. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15704. *sp = ctx->client_socks[thread_index];
  15705. if (ctx->stop_flag) {
  15706. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15707. if (sp->in_use == 1) {
  15708. /* must consume */
  15709. set_blocking_mode(sp->sock);
  15710. closesocket(sp->sock);
  15711. }
  15712. return 0;
  15713. }
  15714. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15715. if (sp->in_use == 1) {
  15716. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15717. return 1;
  15718. }
  15719. /* must not reach here */
  15720. DEBUG_ASSERT(0);
  15721. return 0;
  15722. }
  15723. #else /* ALTERNATIVE_QUEUE */
  15724. /* Worker threads take accepted socket from the queue */
  15725. static int
  15726. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15727. {
  15728. (void)thread_index;
  15729. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15730. DEBUG_TRACE("%s", "going idle");
  15731. /* If the queue is empty, wait. We're idle at this point. */
  15732. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15733. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15734. }
  15735. /* If we're stopping, sq_head may be equal to sq_tail. */
  15736. if (ctx->sq_head > ctx->sq_tail) {
  15737. /* Copy socket from the queue and increment tail */
  15738. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  15739. ctx->sq_tail++;
  15740. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15741. /* Wrap pointers if needed */
  15742. while (ctx->sq_tail > ctx->sq_size) {
  15743. ctx->sq_tail -= ctx->sq_size;
  15744. ctx->sq_head -= ctx->sq_size;
  15745. }
  15746. }
  15747. (void)pthread_cond_signal(&ctx->sq_empty);
  15748. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15749. return !ctx->stop_flag;
  15750. }
  15751. /* Master thread adds accepted socket to a queue */
  15752. static void
  15753. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15754. {
  15755. int queue_filled;
  15756. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15757. queue_filled = ctx->sq_head - ctx->sq_tail;
  15758. /* If the queue is full, wait */
  15759. while ((ctx->stop_flag == 0) && (queue_filled >= ctx->sq_size)) {
  15760. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  15761. #if defined(USE_SERVER_STATS)
  15762. if (queue_filled > ctx->sq_max_fill) {
  15763. ctx->sq_max_fill = queue_filled;
  15764. }
  15765. #endif
  15766. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15767. ctx->sq_blocked = 0; /* Not blocked now */
  15768. queue_filled = ctx->sq_head - ctx->sq_tail;
  15769. }
  15770. if (queue_filled < ctx->sq_size) {
  15771. /* Copy socket to the queue and increment head */
  15772. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  15773. ctx->sq_head++;
  15774. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15775. }
  15776. queue_filled = ctx->sq_head - ctx->sq_tail;
  15777. #if defined(USE_SERVER_STATS)
  15778. if (queue_filled > ctx->sq_max_fill) {
  15779. ctx->sq_max_fill = queue_filled;
  15780. }
  15781. #endif
  15782. (void)pthread_cond_signal(&ctx->sq_full);
  15783. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15784. }
  15785. #endif /* ALTERNATIVE_QUEUE */
  15786. static void
  15787. worker_thread_run(struct mg_connection *conn)
  15788. {
  15789. struct mg_context *ctx = conn->phys_ctx;
  15790. int thread_index;
  15791. struct mg_workerTLS tls;
  15792. #if defined(MG_LEGACY_INTERFACE)
  15793. uint32_t addr;
  15794. #endif
  15795. mg_set_thread_name("worker");
  15796. tls.is_master = 0;
  15797. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15798. #if defined(_WIN32)
  15799. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15800. #endif
  15801. /* Initialize thread local storage before calling any callback */
  15802. pthread_setspecific(sTlsKey, &tls);
  15803. /* Check if there is a user callback */
  15804. if (ctx->callbacks.init_thread) {
  15805. /* call init_thread for a worker thread (type 1), and store the return
  15806. * value */
  15807. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15808. } else {
  15809. /* No callback: set user pointer to NULL */
  15810. tls.user_ptr = NULL;
  15811. }
  15812. /* Connection structure has been pre-allocated */
  15813. thread_index = (int)(conn - ctx->worker_connections);
  15814. if ((thread_index < 0)
  15815. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15816. mg_cry_ctx_internal(ctx,
  15817. "Internal error: Invalid worker index %i",
  15818. thread_index);
  15819. return;
  15820. }
  15821. /* Request buffers are not pre-allocated. They are private to the
  15822. * request and do not contain any state information that might be
  15823. * of interest to anyone observing a server status. */
  15824. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15825. if (conn->buf == NULL) {
  15826. mg_cry_ctx_internal(
  15827. ctx,
  15828. "Out of memory: Cannot allocate buffer for worker %i",
  15829. thread_index);
  15830. return;
  15831. }
  15832. conn->buf_size = (int)ctx->max_request_size;
  15833. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15834. conn->host = NULL; /* until we have more information. */
  15835. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15836. conn->request_info.user_data = ctx->user_data;
  15837. /* Allocate a mutex for this connection to allow communication both
  15838. * within the request handler and from elsewhere in the application
  15839. */
  15840. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15841. mg_free(conn->buf);
  15842. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15843. return;
  15844. }
  15845. #if defined(USE_SERVER_STATS)
  15846. conn->conn_state = 1; /* not consumed */
  15847. #endif
  15848. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15849. * signal sq_empty condvar to wake up the master waiting in
  15850. * produce_socket() */
  15851. while (consume_socket(ctx, &conn->client, thread_index)) {
  15852. #if defined(USE_SERVER_STATS)
  15853. conn->conn_close_time = 0;
  15854. #endif
  15855. conn->conn_birth_time = time(NULL);
  15856. /* Fill in IP, port info early so even if SSL setup below fails,
  15857. * error handler would have the corresponding info.
  15858. * Thanks to Johannes Winkelmann for the patch.
  15859. */
  15860. #if defined(USE_IPV6)
  15861. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15862. conn->request_info.remote_port =
  15863. ntohs(conn->client.rsa.sin6.sin6_port);
  15864. } else
  15865. #endif
  15866. {
  15867. conn->request_info.remote_port =
  15868. ntohs(conn->client.rsa.sin.sin_port);
  15869. }
  15870. sockaddr_to_string(conn->request_info.remote_addr,
  15871. sizeof(conn->request_info.remote_addr),
  15872. &conn->client.rsa);
  15873. DEBUG_TRACE("Start processing connection from %s",
  15874. conn->request_info.remote_addr);
  15875. conn->request_info.is_ssl = conn->client.is_ssl;
  15876. if (conn->client.is_ssl) {
  15877. #if !defined(NO_SSL)
  15878. /* HTTPS connection */
  15879. if (sslize(conn,
  15880. conn->dom_ctx->ssl_ctx,
  15881. SSL_accept,
  15882. &(conn->phys_ctx->stop_flag),
  15883. NULL)) {
  15884. /* conn->dom_ctx is set in get_request */
  15885. /* Get SSL client certificate information (if set) */
  15886. ssl_get_client_cert_info(conn);
  15887. /* process HTTPS connection */
  15888. process_new_connection(conn);
  15889. /* Free client certificate info */
  15890. if (conn->request_info.client_cert) {
  15891. mg_free((void *)(conn->request_info.client_cert->subject));
  15892. mg_free((void *)(conn->request_info.client_cert->issuer));
  15893. mg_free((void *)(conn->request_info.client_cert->serial));
  15894. mg_free((void *)(conn->request_info.client_cert->finger));
  15895. /* Free certificate memory */
  15896. X509_free(
  15897. (X509 *)conn->request_info.client_cert->peer_cert);
  15898. conn->request_info.client_cert->peer_cert = 0;
  15899. conn->request_info.client_cert->subject = 0;
  15900. conn->request_info.client_cert->issuer = 0;
  15901. conn->request_info.client_cert->serial = 0;
  15902. conn->request_info.client_cert->finger = 0;
  15903. mg_free(conn->request_info.client_cert);
  15904. conn->request_info.client_cert = 0;
  15905. }
  15906. } else {
  15907. /* make sure the connection is cleaned up on SSL failure */
  15908. close_connection(conn);
  15909. }
  15910. #endif
  15911. } else {
  15912. /* process HTTP connection */
  15913. process_new_connection(conn);
  15914. }
  15915. DEBUG_TRACE("%s", "Connection closed");
  15916. #if defined(USE_SERVER_STATS)
  15917. conn->conn_close_time = time(NULL);
  15918. #endif
  15919. }
  15920. /* Call exit thread user callback */
  15921. if (ctx->callbacks.exit_thread) {
  15922. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15923. }
  15924. /* delete thread local storage objects */
  15925. pthread_setspecific(sTlsKey, NULL);
  15926. #if defined(_WIN32)
  15927. CloseHandle(tls.pthread_cond_helper_mutex);
  15928. #endif
  15929. pthread_mutex_destroy(&conn->mutex);
  15930. /* Free the request buffer. */
  15931. conn->buf_size = 0;
  15932. mg_free(conn->buf);
  15933. conn->buf = NULL;
  15934. #if defined(USE_SERVER_STATS)
  15935. conn->conn_state = 9; /* done */
  15936. #endif
  15937. DEBUG_TRACE("%s", "exiting");
  15938. }
  15939. /* Threads have different return types on Windows and Unix. */
  15940. #if defined(_WIN32)
  15941. static unsigned __stdcall worker_thread(void *thread_func_param)
  15942. {
  15943. worker_thread_run((struct mg_connection *)thread_func_param);
  15944. return 0;
  15945. }
  15946. #else
  15947. static void *
  15948. worker_thread(void *thread_func_param)
  15949. {
  15950. #if !defined(__ZEPHYR__)
  15951. struct sigaction sa;
  15952. /* Ignore SIGPIPE */
  15953. memset(&sa, 0, sizeof(sa));
  15954. sa.sa_handler = SIG_IGN;
  15955. sigaction(SIGPIPE, &sa, NULL);
  15956. #endif
  15957. worker_thread_run((struct mg_connection *)thread_func_param);
  15958. return NULL;
  15959. }
  15960. #endif /* _WIN32 */
  15961. /* This is an internal function, thus all arguments are expected to be
  15962. * valid - a NULL check is not required. */
  15963. static void
  15964. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15965. {
  15966. struct socket so;
  15967. char src_addr[IP_ADDR_STR_LEN];
  15968. socklen_t len = sizeof(so.rsa);
  15969. #if !defined(__ZEPHYR__)
  15970. int on = 1;
  15971. #endif
  15972. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15973. == INVALID_SOCKET) {
  15974. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15975. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15976. mg_cry_ctx_internal(ctx,
  15977. "%s: %s is not allowed to connect",
  15978. __func__,
  15979. src_addr);
  15980. closesocket(so.sock);
  15981. } else {
  15982. /* Put so socket structure into the queue */
  15983. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15984. set_close_on_exec(so.sock, NULL, ctx);
  15985. so.is_ssl = listener->is_ssl;
  15986. so.ssl_redir = listener->ssl_redir;
  15987. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15988. mg_cry_ctx_internal(ctx,
  15989. "%s: getsockname() failed: %s",
  15990. __func__,
  15991. strerror(ERRNO));
  15992. }
  15993. #if !defined(__ZEPHYR__)
  15994. /* Set TCP keep-alive. This is needed because if HTTP-level
  15995. * keep-alive
  15996. * is enabled, and client resets the connection, server won't get
  15997. * TCP FIN or RST and will keep the connection open forever. With
  15998. * TCP keep-alive, next keep-alive handshake will figure out that
  15999. * the client is down and will close the server end.
  16000. * Thanks to Igor Klopov who suggested the patch. */
  16001. if (setsockopt(so.sock,
  16002. SOL_SOCKET,
  16003. SO_KEEPALIVE,
  16004. (SOCK_OPT_TYPE)&on,
  16005. sizeof(on))
  16006. != 0) {
  16007. mg_cry_ctx_internal(
  16008. ctx,
  16009. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16010. __func__,
  16011. strerror(ERRNO));
  16012. }
  16013. #endif
  16014. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16015. * to effectively fill up the underlying IP packet payload and
  16016. * reduce the overhead of sending lots of small buffers. However
  16017. * this hurts the server's throughput (ie. operations per second)
  16018. * when HTTP 1.1 persistent connections are used and the responses
  16019. * are relatively small (eg. less than 1400 bytes).
  16020. */
  16021. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16022. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16023. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16024. mg_cry_ctx_internal(
  16025. ctx,
  16026. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16027. __func__,
  16028. strerror(ERRNO));
  16029. }
  16030. }
  16031. /* The "non blocking" property should already be
  16032. * inherited from the parent socket. Set it for
  16033. * non-compliant socket implementations. */
  16034. set_non_blocking_mode(so.sock);
  16035. so.in_use = 0;
  16036. produce_socket(ctx, &so);
  16037. }
  16038. }
  16039. static void
  16040. master_thread_run(struct mg_context *ctx)
  16041. {
  16042. struct mg_workerTLS tls;
  16043. struct mg_pollfd *pfd;
  16044. unsigned int i;
  16045. unsigned int workerthreadcount;
  16046. if (!ctx) {
  16047. return;
  16048. }
  16049. mg_set_thread_name("master");
  16050. /* Increase priority of the master thread */
  16051. #if defined(_WIN32)
  16052. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16053. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16054. int min_prio = sched_get_priority_min(SCHED_RR);
  16055. int max_prio = sched_get_priority_max(SCHED_RR);
  16056. if ((min_prio >= 0) && (max_prio >= 0)
  16057. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16058. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16059. struct sched_param sched_param = {0};
  16060. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16061. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16062. }
  16063. #endif
  16064. /* Initialize thread local storage */
  16065. #if defined(_WIN32)
  16066. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16067. #endif
  16068. tls.is_master = 1;
  16069. pthread_setspecific(sTlsKey, &tls);
  16070. if (ctx->callbacks.init_thread) {
  16071. /* Callback for the master thread (type 0) */
  16072. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16073. } else {
  16074. tls.user_ptr = NULL;
  16075. }
  16076. /* Server starts *now* */
  16077. ctx->start_time = time(NULL);
  16078. /* Start the server */
  16079. pfd = ctx->listening_socket_fds;
  16080. while (ctx->stop_flag == 0) {
  16081. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16082. pfd[i].fd = ctx->listening_sockets[i].sock;
  16083. pfd[i].events = POLLIN;
  16084. }
  16085. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16086. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16087. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16088. * successful poll, and POLLIN is defined as
  16089. * (POLLRDNORM | POLLRDBAND)
  16090. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16091. * pfd[i].revents == POLLIN. */
  16092. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  16093. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16094. }
  16095. }
  16096. }
  16097. }
  16098. /* Here stop_flag is 1 - Initiate shutdown. */
  16099. DEBUG_TRACE("%s", "stopping workers");
  16100. /* Stop signal received: somebody called mg_stop. Quit. */
  16101. close_all_listening_sockets(ctx);
  16102. /* Wakeup workers that are waiting for connections to handle. */
  16103. #if defined(ALTERNATIVE_QUEUE)
  16104. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16105. event_signal(ctx->client_wait_events[i]);
  16106. }
  16107. #else
  16108. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16109. pthread_cond_broadcast(&ctx->sq_full);
  16110. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16111. #endif
  16112. /* Join all worker threads to avoid leaking threads. */
  16113. workerthreadcount = ctx->cfg_worker_threads;
  16114. for (i = 0; i < workerthreadcount; i++) {
  16115. if (ctx->worker_threadids[i] != 0) {
  16116. mg_join_thread(ctx->worker_threadids[i]);
  16117. }
  16118. }
  16119. #if defined(USE_LUA)
  16120. /* Free Lua state of lua background task */
  16121. if (ctx->lua_background_state) {
  16122. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16123. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16124. if (lua_istable(lstate, -1)) {
  16125. reg_boolean(lstate, "shutdown", 1);
  16126. lua_pop(lstate, 1);
  16127. mg_sleep(2);
  16128. }
  16129. lua_close(lstate);
  16130. ctx->lua_background_state = 0;
  16131. }
  16132. #endif
  16133. DEBUG_TRACE("%s", "exiting");
  16134. /* call exit thread callback */
  16135. if (ctx->callbacks.exit_thread) {
  16136. /* Callback for the master thread (type 0) */
  16137. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16138. }
  16139. #if defined(_WIN32)
  16140. CloseHandle(tls.pthread_cond_helper_mutex);
  16141. #endif
  16142. pthread_setspecific(sTlsKey, NULL);
  16143. /* Signal mg_stop() that we're done.
  16144. * WARNING: This must be the very last thing this
  16145. * thread does, as ctx becomes invalid after this line. */
  16146. ctx->stop_flag = 2;
  16147. }
  16148. /* Threads have different return types on Windows and Unix. */
  16149. #if defined(_WIN32)
  16150. static unsigned __stdcall master_thread(void *thread_func_param)
  16151. {
  16152. master_thread_run((struct mg_context *)thread_func_param);
  16153. return 0;
  16154. }
  16155. #else
  16156. static void *
  16157. master_thread(void *thread_func_param)
  16158. {
  16159. #if !defined(__ZEPHYR__)
  16160. struct sigaction sa;
  16161. /* Ignore SIGPIPE */
  16162. memset(&sa, 0, sizeof(sa));
  16163. sa.sa_handler = SIG_IGN;
  16164. sigaction(SIGPIPE, &sa, NULL);
  16165. #endif
  16166. master_thread_run((struct mg_context *)thread_func_param);
  16167. return NULL;
  16168. }
  16169. #endif /* _WIN32 */
  16170. static void
  16171. free_context(struct mg_context *ctx)
  16172. {
  16173. int i;
  16174. struct mg_handler_info *tmp_rh;
  16175. if (ctx == NULL) {
  16176. return;
  16177. }
  16178. if (ctx->callbacks.exit_context) {
  16179. ctx->callbacks.exit_context(ctx);
  16180. }
  16181. /* All threads exited, no sync is needed. Destroy thread mutex and
  16182. * condvars
  16183. */
  16184. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16185. #if defined(ALTERNATIVE_QUEUE)
  16186. mg_free(ctx->client_socks);
  16187. if (ctx->client_wait_events != NULL) {
  16188. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16189. event_destroy(ctx->client_wait_events[i]);
  16190. }
  16191. mg_free(ctx->client_wait_events);
  16192. }
  16193. #else
  16194. (void)pthread_cond_destroy(&ctx->sq_empty);
  16195. (void)pthread_cond_destroy(&ctx->sq_full);
  16196. mg_free(ctx->squeue);
  16197. #endif
  16198. /* Destroy other context global data structures mutex */
  16199. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16200. #if defined(USE_TIMERS)
  16201. timers_exit(ctx);
  16202. #endif
  16203. /* Deallocate config parameters */
  16204. for (i = 0; i < NUM_OPTIONS; i++) {
  16205. if (ctx->dd.config[i] != NULL) {
  16206. #if defined(_MSC_VER)
  16207. #pragma warning(suppress : 6001)
  16208. #endif
  16209. mg_free(ctx->dd.config[i]);
  16210. }
  16211. }
  16212. /* Deallocate request handlers */
  16213. while (ctx->dd.handlers) {
  16214. tmp_rh = ctx->dd.handlers;
  16215. ctx->dd.handlers = tmp_rh->next;
  16216. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  16217. pthread_cond_destroy(&tmp_rh->refcount_cond);
  16218. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  16219. }
  16220. mg_free(tmp_rh->uri);
  16221. mg_free(tmp_rh);
  16222. }
  16223. #if !defined(NO_SSL)
  16224. /* Deallocate SSL context */
  16225. if (ctx->dd.ssl_ctx != NULL) {
  16226. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16227. int callback_ret =
  16228. (ctx->callbacks.external_ssl_ctx == NULL)
  16229. ? 0
  16230. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16231. if (callback_ret == 0) {
  16232. SSL_CTX_free(ctx->dd.ssl_ctx);
  16233. }
  16234. /* else: ignore error and ommit SSL_CTX_free in case
  16235. * callback_ret is 1 */
  16236. }
  16237. #endif /* !NO_SSL */
  16238. /* Deallocate worker thread ID array */
  16239. mg_free(ctx->worker_threadids);
  16240. /* Deallocate worker thread ID array */
  16241. mg_free(ctx->worker_connections);
  16242. /* deallocate system name string */
  16243. mg_free(ctx->systemName);
  16244. /* Deallocate context itself */
  16245. mg_free(ctx);
  16246. }
  16247. void
  16248. mg_stop(struct mg_context *ctx)
  16249. {
  16250. pthread_t mt;
  16251. if (!ctx) {
  16252. return;
  16253. }
  16254. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16255. * two threads is not allowed. */
  16256. mt = ctx->masterthreadid;
  16257. if (mt == 0) {
  16258. return;
  16259. }
  16260. ctx->masterthreadid = 0;
  16261. /* Set stop flag, so all threads know they have to exit. */
  16262. ctx->stop_flag = 1;
  16263. /* Wait until everything has stopped. */
  16264. while (ctx->stop_flag != 2) {
  16265. (void)mg_sleep(10);
  16266. }
  16267. mg_join_thread(mt);
  16268. free_context(ctx);
  16269. #if defined(_WIN32)
  16270. (void)WSACleanup();
  16271. #endif /* _WIN32 */
  16272. }
  16273. static void
  16274. get_system_name(char **sysName)
  16275. {
  16276. #if defined(_WIN32)
  16277. #if defined(_WIN32_WCE)
  16278. *sysName = mg_strdup("WinCE");
  16279. #else
  16280. char name[128];
  16281. DWORD dwVersion = 0;
  16282. DWORD dwMajorVersion = 0;
  16283. DWORD dwMinorVersion = 0;
  16284. DWORD dwBuild = 0;
  16285. BOOL wowRet, isWoW = FALSE;
  16286. #if defined(_MSC_VER)
  16287. #pragma warning(push)
  16288. /* GetVersion was declared deprecated */
  16289. #pragma warning(disable : 4996)
  16290. #endif
  16291. dwVersion = GetVersion();
  16292. #if defined(_MSC_VER)
  16293. #pragma warning(pop)
  16294. #endif
  16295. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16296. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16297. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16298. (void)dwBuild;
  16299. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16300. sprintf(name,
  16301. "Windows %u.%u%s",
  16302. (unsigned)dwMajorVersion,
  16303. (unsigned)dwMinorVersion,
  16304. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16305. *sysName = mg_strdup(name);
  16306. #endif
  16307. #elif defined(__ZEPHYR__)
  16308. *sysName = mg_strdup("Zephyr OS");
  16309. #else
  16310. struct utsname name;
  16311. memset(&name, 0, sizeof(name));
  16312. uname(&name);
  16313. *sysName = mg_strdup(name.sysname);
  16314. #endif
  16315. }
  16316. static void
  16317. legacy_init(const char **options)
  16318. {
  16319. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16320. if (options) {
  16321. const char **run_options = options;
  16322. const char *optname = config_options[LISTENING_PORTS].name;
  16323. /* Try to find the "listening_ports" option */
  16324. while (*run_options) {
  16325. if (!strcmp(*run_options, optname)) {
  16326. ports_option = run_options[1];
  16327. }
  16328. run_options += 2;
  16329. }
  16330. }
  16331. if (is_ssl_port_used(ports_option)) {
  16332. /* Initialize with SSL support */
  16333. mg_init_library(MG_FEATURES_TLS);
  16334. } else {
  16335. /* Initialize without SSL support */
  16336. mg_init_library(MG_FEATURES_DEFAULT);
  16337. }
  16338. }
  16339. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16340. static
  16341. #endif
  16342. struct mg_context *
  16343. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16344. {
  16345. struct mg_context *ctx;
  16346. const char *name, *value, *default_value;
  16347. int idx, ok, workerthreadcount;
  16348. unsigned int i;
  16349. int itmp;
  16350. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16351. const char **options =
  16352. ((init != NULL) ? (init->configuration_options) : (NULL));
  16353. struct mg_workerTLS tls;
  16354. #if defined(_WIN32)
  16355. WSADATA data;
  16356. WSAStartup(MAKEWORD(2, 2), &data);
  16357. #endif /* _WIN32 */
  16358. if (error != NULL) {
  16359. error->code = 0;
  16360. if (error->text_buffer_size > 0) {
  16361. *error->text = 0;
  16362. }
  16363. }
  16364. if (mg_init_library_called == 0) {
  16365. /* Legacy INIT, if mg_start is called without mg_init_library.
  16366. * Note: This will cause a memory leak when unloading the library. */
  16367. legacy_init(options);
  16368. }
  16369. /* Allocate context and initialize reasonable general case defaults. */
  16370. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16371. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16372. mg_snprintf(NULL,
  16373. NULL, /* No truncation check for error buffers */
  16374. error->text,
  16375. error->text_buffer_size,
  16376. "%s",
  16377. "Out of memory");
  16378. }
  16379. return NULL;
  16380. }
  16381. /* Random number generator will initialize at the first call */
  16382. ctx->dd.auth_nonce_mask =
  16383. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16384. /* Save started thread index to reuse in other external API calls
  16385. * For the sake of thread synchronization all non-civetweb threads
  16386. * can be considered as single external thread */
  16387. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16388. tls.is_master = -1; /* Thread calling mg_start */
  16389. tls.thread_idx = ctx->starter_thread_idx;
  16390. #if defined(_WIN32)
  16391. tls.pthread_cond_helper_mutex = NULL;
  16392. #endif
  16393. pthread_setspecific(sTlsKey, &tls);
  16394. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16395. #if !defined(ALTERNATIVE_QUEUE)
  16396. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16397. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16398. ctx->sq_blocked = 0;
  16399. #endif
  16400. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16401. if (!ok) {
  16402. const char *err_msg =
  16403. "Cannot initialize thread synchronization objects";
  16404. /* Fatal error - abort start. However, this situation should never
  16405. * occur in practice. */
  16406. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16407. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16408. mg_snprintf(NULL,
  16409. NULL, /* No truncation check for error buffers */
  16410. error->text,
  16411. error->text_buffer_size,
  16412. "%s",
  16413. err_msg);
  16414. }
  16415. mg_free(ctx);
  16416. pthread_setspecific(sTlsKey, NULL);
  16417. return NULL;
  16418. }
  16419. if ((init != NULL) && (init->callbacks != NULL)) {
  16420. /* Set all callbacks except exit_context. */
  16421. ctx->callbacks = *init->callbacks;
  16422. exit_callback = init->callbacks->exit_context;
  16423. /* The exit callback is activated once the context is successfully
  16424. * created. It should not be called, if an incomplete context object is
  16425. * deleted during a failed initialization. */
  16426. ctx->callbacks.exit_context = 0;
  16427. }
  16428. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16429. ctx->dd.handlers = NULL;
  16430. ctx->dd.next = NULL;
  16431. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16432. ctx->dd.shared_lua_websockets = NULL;
  16433. #endif
  16434. /* Store options */
  16435. while (options && (name = *options++) != NULL) {
  16436. if ((idx = get_option_index(name)) == -1) {
  16437. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16438. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16439. mg_snprintf(NULL,
  16440. NULL, /* No truncation check for error buffers */
  16441. error->text,
  16442. error->text_buffer_size,
  16443. "Invalid configuration option: %s",
  16444. name);
  16445. }
  16446. free_context(ctx);
  16447. pthread_setspecific(sTlsKey, NULL);
  16448. return NULL;
  16449. } else if ((value = *options++) == NULL) {
  16450. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16451. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16452. mg_snprintf(NULL,
  16453. NULL, /* No truncation check for error buffers */
  16454. error->text,
  16455. error->text_buffer_size,
  16456. "Invalid configuration option value: %s",
  16457. name);
  16458. }
  16459. free_context(ctx);
  16460. pthread_setspecific(sTlsKey, NULL);
  16461. return NULL;
  16462. }
  16463. if (ctx->dd.config[idx] != NULL) {
  16464. /* A duplicate configuration option is not an error - the last
  16465. * option value will be used. */
  16466. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16467. mg_free(ctx->dd.config[idx]);
  16468. }
  16469. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16470. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16471. }
  16472. /* Set default value if needed */
  16473. for (i = 0; config_options[i].name != NULL; i++) {
  16474. default_value = config_options[i].default_value;
  16475. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16476. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16477. }
  16478. }
  16479. /* Request size option */
  16480. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16481. if (itmp < 1024) {
  16482. mg_cry_ctx_internal(ctx,
  16483. "%s too small",
  16484. config_options[MAX_REQUEST_SIZE].name);
  16485. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16486. mg_snprintf(NULL,
  16487. NULL, /* No truncation check for error buffers */
  16488. error->text,
  16489. error->text_buffer_size,
  16490. "Invalid configuration option value: %s",
  16491. config_options[MAX_REQUEST_SIZE].name);
  16492. }
  16493. free_context(ctx);
  16494. pthread_setspecific(sTlsKey, NULL);
  16495. return NULL;
  16496. }
  16497. ctx->max_request_size = (unsigned)itmp;
  16498. /* Queue length */
  16499. #if !defined(ALTERNATIVE_QUEUE)
  16500. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16501. if (itmp < 1) {
  16502. mg_cry_ctx_internal(ctx,
  16503. "%s too small",
  16504. config_options[CONNECTION_QUEUE_SIZE].name);
  16505. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16506. mg_snprintf(NULL,
  16507. NULL, /* No truncation check for error buffers */
  16508. error->text,
  16509. error->text_buffer_size,
  16510. "Invalid configuration option value: %s",
  16511. config_options[CONNECTION_QUEUE_SIZE].name);
  16512. }
  16513. free_context(ctx);
  16514. pthread_setspecific(sTlsKey, NULL);
  16515. return NULL;
  16516. }
  16517. ctx->squeue = (struct socket *)mg_calloc(itmp, sizeof(struct socket));
  16518. if (ctx->squeue == NULL) {
  16519. mg_cry_ctx_internal(ctx,
  16520. "Out of memory: Cannot allocate %s",
  16521. config_options[CONNECTION_QUEUE_SIZE].name);
  16522. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16523. mg_snprintf(NULL,
  16524. NULL, /* No truncation check for error buffers */
  16525. error->text,
  16526. error->text_buffer_size,
  16527. "Out of memory: Cannot allocate %s",
  16528. config_options[CONNECTION_QUEUE_SIZE].name);
  16529. }
  16530. free_context(ctx);
  16531. pthread_setspecific(sTlsKey, NULL);
  16532. return NULL;
  16533. }
  16534. ctx->sq_size = itmp;
  16535. #endif
  16536. /* Worker thread count option */
  16537. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16538. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16539. if (workerthreadcount <= 0) {
  16540. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16541. } else {
  16542. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16543. }
  16544. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16545. mg_snprintf(NULL,
  16546. NULL, /* No truncation check for error buffers */
  16547. error->text,
  16548. error->text_buffer_size,
  16549. "Invalid configuration option value: %s",
  16550. config_options[NUM_THREADS].name);
  16551. }
  16552. free_context(ctx);
  16553. pthread_setspecific(sTlsKey, NULL);
  16554. return NULL;
  16555. }
  16556. /* Document root */
  16557. #if defined(NO_FILES)
  16558. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16559. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16560. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16561. mg_snprintf(NULL,
  16562. NULL, /* No truncation check for error buffers */
  16563. error->text,
  16564. error->text_buffer_size,
  16565. "Invalid configuration option value: %s",
  16566. config_options[DOCUMENT_ROOT].name);
  16567. }
  16568. free_context(ctx);
  16569. pthread_setspecific(sTlsKey, NULL);
  16570. return NULL;
  16571. }
  16572. #endif
  16573. get_system_name(&ctx->systemName);
  16574. #if defined(USE_LUA)
  16575. /* If a Lua background script has been configured, start it. */
  16576. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16577. char ebuf[256];
  16578. struct vec opt_vec;
  16579. struct vec eq_vec;
  16580. const char *sparams;
  16581. lua_State *state = mg_prepare_lua_context_script(
  16582. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16583. if (!state) {
  16584. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16585. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16586. mg_snprintf(NULL,
  16587. NULL, /* No truncation check for error buffers */
  16588. error->text,
  16589. error->text_buffer_size,
  16590. "Error in script %s: %s",
  16591. config_options[DOCUMENT_ROOT].name,
  16592. ebuf);
  16593. }
  16594. free_context(ctx);
  16595. pthread_setspecific(sTlsKey, NULL);
  16596. return NULL;
  16597. }
  16598. ctx->lua_background_state = (void *)state;
  16599. lua_newtable(state);
  16600. reg_boolean(state, "shutdown", 0);
  16601. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16602. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16603. reg_llstring(
  16604. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16605. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16606. break;
  16607. }
  16608. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16609. } else {
  16610. ctx->lua_background_state = 0;
  16611. }
  16612. #endif
  16613. /* Step by step initialization of ctx - depending on build options */
  16614. #if !defined(NO_FILESYSTEMS)
  16615. if (!set_gpass_option(ctx, NULL)) {
  16616. const char *err_msg = "Invalid global password file";
  16617. /* Fatal error - abort start. */
  16618. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16619. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16620. mg_snprintf(NULL,
  16621. NULL, /* No truncation check for error buffers */
  16622. error->text,
  16623. error->text_buffer_size,
  16624. "%s",
  16625. err_msg);
  16626. }
  16627. free_context(ctx);
  16628. pthread_setspecific(sTlsKey, NULL);
  16629. return NULL;
  16630. }
  16631. #endif
  16632. #if !defined(NO_SSL)
  16633. if (!init_ssl_ctx(ctx, NULL)) {
  16634. const char *err_msg = "Error initializing SSL context";
  16635. /* Fatal error - abort start. */
  16636. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16637. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16638. mg_snprintf(NULL,
  16639. NULL, /* No truncation check for error buffers */
  16640. error->text,
  16641. error->text_buffer_size,
  16642. "%s",
  16643. err_msg);
  16644. }
  16645. free_context(ctx);
  16646. pthread_setspecific(sTlsKey, NULL);
  16647. return NULL;
  16648. }
  16649. #endif
  16650. if (!set_ports_option(ctx)) {
  16651. const char *err_msg = "Failed to setup server ports";
  16652. /* Fatal error - abort start. */
  16653. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16654. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16655. mg_snprintf(NULL,
  16656. NULL, /* No truncation check for error buffers */
  16657. error->text,
  16658. error->text_buffer_size,
  16659. "%s",
  16660. err_msg);
  16661. }
  16662. free_context(ctx);
  16663. pthread_setspecific(sTlsKey, NULL);
  16664. return NULL;
  16665. }
  16666. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16667. if (!set_uid_option(ctx)) {
  16668. const char *err_msg = "Failed to run as configured user";
  16669. /* Fatal error - abort start. */
  16670. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16671. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16672. mg_snprintf(NULL,
  16673. NULL, /* No truncation check for error buffers */
  16674. error->text,
  16675. error->text_buffer_size,
  16676. "%s",
  16677. err_msg);
  16678. }
  16679. free_context(ctx);
  16680. pthread_setspecific(sTlsKey, NULL);
  16681. return NULL;
  16682. }
  16683. #endif
  16684. if (!set_acl_option(ctx)) {
  16685. const char *err_msg = "Failed to setup access control list";
  16686. /* Fatal error - abort start. */
  16687. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16688. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16689. mg_snprintf(NULL,
  16690. NULL, /* No truncation check for error buffers */
  16691. error->text,
  16692. error->text_buffer_size,
  16693. "%s",
  16694. err_msg);
  16695. }
  16696. free_context(ctx);
  16697. pthread_setspecific(sTlsKey, NULL);
  16698. return NULL;
  16699. }
  16700. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16701. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16702. sizeof(pthread_t),
  16703. ctx);
  16704. if (ctx->worker_threadids == NULL) {
  16705. const char *err_msg = "Not enough memory for worker thread ID array";
  16706. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16707. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16708. mg_snprintf(NULL,
  16709. NULL, /* No truncation check for error buffers */
  16710. error->text,
  16711. error->text_buffer_size,
  16712. "%s",
  16713. err_msg);
  16714. }
  16715. free_context(ctx);
  16716. pthread_setspecific(sTlsKey, NULL);
  16717. return NULL;
  16718. }
  16719. ctx->worker_connections =
  16720. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16721. sizeof(struct mg_connection),
  16722. ctx);
  16723. if (ctx->worker_connections == NULL) {
  16724. const char *err_msg =
  16725. "Not enough memory for worker thread connection array";
  16726. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16727. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16728. mg_snprintf(NULL,
  16729. NULL, /* No truncation check for error buffers */
  16730. error->text,
  16731. error->text_buffer_size,
  16732. "%s",
  16733. err_msg);
  16734. }
  16735. free_context(ctx);
  16736. pthread_setspecific(sTlsKey, NULL);
  16737. return NULL;
  16738. }
  16739. #if defined(ALTERNATIVE_QUEUE)
  16740. ctx->client_wait_events =
  16741. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16742. sizeof(ctx->client_wait_events[0]),
  16743. ctx);
  16744. if (ctx->client_wait_events == NULL) {
  16745. const char *err_msg = "Not enough memory for worker event array";
  16746. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16747. mg_free(ctx->worker_threadids);
  16748. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16749. mg_snprintf(NULL,
  16750. NULL, /* No truncation check for error buffers */
  16751. error->text,
  16752. error->text_buffer_size,
  16753. "%s",
  16754. err_msg);
  16755. }
  16756. free_context(ctx);
  16757. pthread_setspecific(sTlsKey, NULL);
  16758. return NULL;
  16759. }
  16760. ctx->client_socks =
  16761. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16762. sizeof(ctx->client_socks[0]),
  16763. ctx);
  16764. if (ctx->client_socks == NULL) {
  16765. const char *err_msg = "Not enough memory for worker socket array";
  16766. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16767. mg_free(ctx->client_wait_events);
  16768. mg_free(ctx->worker_threadids);
  16769. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16770. mg_snprintf(NULL,
  16771. NULL, /* No truncation check for error buffers */
  16772. error->text,
  16773. error->text_buffer_size,
  16774. "%s",
  16775. err_msg);
  16776. }
  16777. free_context(ctx);
  16778. pthread_setspecific(sTlsKey, NULL);
  16779. return NULL;
  16780. }
  16781. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16782. ctx->client_wait_events[i] = event_create();
  16783. if (ctx->client_wait_events[i] == 0) {
  16784. const char *err_msg = "Error creating worker event %i";
  16785. mg_cry_ctx_internal(ctx, err_msg, i);
  16786. while (i > 0) {
  16787. i--;
  16788. event_destroy(ctx->client_wait_events[i]);
  16789. }
  16790. mg_free(ctx->client_socks);
  16791. mg_free(ctx->client_wait_events);
  16792. mg_free(ctx->worker_threadids);
  16793. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16794. mg_snprintf(NULL,
  16795. NULL, /* No truncation check for error buffers */
  16796. error->text,
  16797. error->text_buffer_size,
  16798. err_msg,
  16799. i);
  16800. }
  16801. free_context(ctx);
  16802. pthread_setspecific(sTlsKey, NULL);
  16803. return NULL;
  16804. }
  16805. }
  16806. #endif
  16807. #if defined(USE_TIMERS)
  16808. if (timers_init(ctx) != 0) {
  16809. const char *err_msg = "Error creating timers";
  16810. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16811. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16812. mg_snprintf(NULL,
  16813. NULL, /* No truncation check for error buffers */
  16814. error->text,
  16815. error->text_buffer_size,
  16816. "%s",
  16817. err_msg);
  16818. }
  16819. free_context(ctx);
  16820. pthread_setspecific(sTlsKey, NULL);
  16821. return NULL;
  16822. }
  16823. #endif
  16824. /* Context has been created - init user libraries */
  16825. if (ctx->callbacks.init_context) {
  16826. ctx->callbacks.init_context(ctx);
  16827. }
  16828. /* From now, the context is successfully created.
  16829. * When it is destroyed, the exit callback should be called. */
  16830. ctx->callbacks.exit_context = exit_callback;
  16831. ctx->context_type = CONTEXT_SERVER; /* server context */
  16832. /* Start master (listening) thread */
  16833. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16834. /* Start worker threads */
  16835. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16836. /* worker_thread sets up the other fields */
  16837. ctx->worker_connections[i].phys_ctx = ctx;
  16838. if (mg_start_thread_with_id(worker_thread,
  16839. &ctx->worker_connections[i],
  16840. &ctx->worker_threadids[i])
  16841. != 0) {
  16842. long error_no = (long)ERRNO;
  16843. /* thread was not created */
  16844. if (i > 0) {
  16845. /* If the second, third, ... thread cannot be created, set a
  16846. * warning, but keep running. */
  16847. mg_cry_ctx_internal(ctx,
  16848. "Cannot start worker thread %i: error %ld",
  16849. i + 1,
  16850. error_no);
  16851. /* If the server initialization should stop here, all threads
  16852. * that have already been created must be stopped first, before
  16853. * any free_context(ctx) call.
  16854. */
  16855. } else {
  16856. /* If the first worker thread cannot be created, stop
  16857. * initialization and free the entire server context. */
  16858. mg_cry_ctx_internal(ctx,
  16859. "Cannot create threads: error %ld",
  16860. error_no);
  16861. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16862. mg_snprintf(
  16863. NULL,
  16864. NULL, /* No truncation check for error buffers */
  16865. error->text,
  16866. error->text_buffer_size,
  16867. "Cannot create first worker thread: error %ld",
  16868. error_no);
  16869. }
  16870. free_context(ctx);
  16871. pthread_setspecific(sTlsKey, NULL);
  16872. return NULL;
  16873. }
  16874. break;
  16875. }
  16876. }
  16877. pthread_setspecific(sTlsKey, NULL);
  16878. return ctx;
  16879. }
  16880. struct mg_context *
  16881. mg_start(const struct mg_callbacks *callbacks,
  16882. void *user_data,
  16883. const char **options)
  16884. {
  16885. struct mg_init_data init = {0};
  16886. init.callbacks = callbacks;
  16887. init.user_data = user_data;
  16888. init.configuration_options = options;
  16889. return mg_start2(&init, NULL);
  16890. }
  16891. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16892. /* Add an additional domain to an already running web server. */
  16893. int
  16894. mg_start_domain2(struct mg_context *ctx,
  16895. const char **options,
  16896. struct mg_error_data *error)
  16897. {
  16898. const char *name;
  16899. const char *value;
  16900. const char *default_value;
  16901. struct mg_domain_context *new_dom;
  16902. struct mg_domain_context *dom;
  16903. int idx, i;
  16904. if (error != NULL) {
  16905. error->code = 0;
  16906. if (error->text_buffer_size > 0) {
  16907. *error->text = 0;
  16908. }
  16909. }
  16910. if ((ctx == NULL) || (options == NULL)) {
  16911. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16912. mg_snprintf(NULL,
  16913. NULL, /* No truncation check for error buffers */
  16914. error->text,
  16915. error->text_buffer_size,
  16916. "%s",
  16917. "Invalid parameters");
  16918. }
  16919. return -1;
  16920. }
  16921. if (ctx->stop_flag != 0) {
  16922. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16923. mg_snprintf(NULL,
  16924. NULL, /* No truncation check for error buffers */
  16925. error->text,
  16926. error->text_buffer_size,
  16927. "%s",
  16928. "Server already stopped");
  16929. }
  16930. return -1;
  16931. }
  16932. new_dom = (struct mg_domain_context *)
  16933. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16934. if (!new_dom) {
  16935. /* Out of memory */
  16936. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16937. mg_snprintf(NULL,
  16938. NULL, /* No truncation check for error buffers */
  16939. error->text,
  16940. error->text_buffer_size,
  16941. "%s",
  16942. "Out or memory");
  16943. }
  16944. return -6;
  16945. }
  16946. /* Store options - TODO: unite duplicate code */
  16947. while (options && (name = *options++) != NULL) {
  16948. if ((idx = get_option_index(name)) == -1) {
  16949. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16950. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16951. mg_snprintf(NULL,
  16952. NULL, /* No truncation check for error buffers */
  16953. error->text,
  16954. error->text_buffer_size,
  16955. "Invalid option: %s",
  16956. name);
  16957. }
  16958. mg_free(new_dom);
  16959. return -2;
  16960. } else if ((value = *options++) == NULL) {
  16961. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16962. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16963. mg_snprintf(NULL,
  16964. NULL, /* No truncation check for error buffers */
  16965. error->text,
  16966. error->text_buffer_size,
  16967. "Invalid option value: %s",
  16968. name);
  16969. }
  16970. mg_free(new_dom);
  16971. return -2;
  16972. }
  16973. if (new_dom->config[idx] != NULL) {
  16974. /* Duplicate option: Later values overwrite earlier ones. */
  16975. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16976. mg_free(new_dom->config[idx]);
  16977. }
  16978. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16979. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16980. }
  16981. /* Authentication domain is mandatory */
  16982. /* TODO: Maybe use a new option hostname? */
  16983. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16984. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16985. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16986. mg_snprintf(NULL,
  16987. NULL, /* No truncation check for error buffers */
  16988. error->text,
  16989. error->text_buffer_size,
  16990. "Mandatory option %s missing",
  16991. config_options[AUTHENTICATION_DOMAIN].name);
  16992. }
  16993. mg_free(new_dom);
  16994. return -4;
  16995. }
  16996. /* Set default value if needed. Take the config value from
  16997. * ctx as a default value. */
  16998. for (i = 0; config_options[i].name != NULL; i++) {
  16999. default_value = ctx->dd.config[i];
  17000. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17001. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17002. }
  17003. }
  17004. new_dom->handlers = NULL;
  17005. new_dom->next = NULL;
  17006. new_dom->nonce_count = 0;
  17007. new_dom->auth_nonce_mask =
  17008. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17009. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17010. new_dom->shared_lua_websockets = NULL;
  17011. #endif
  17012. if (!init_ssl_ctx(ctx, new_dom)) {
  17013. /* Init SSL failed */
  17014. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17015. mg_snprintf(NULL,
  17016. NULL, /* No truncation check for error buffers */
  17017. error->text,
  17018. error->text_buffer_size,
  17019. "%s",
  17020. "Initializing SSL context failed");
  17021. }
  17022. mg_free(new_dom);
  17023. return -3;
  17024. }
  17025. /* Add element to linked list. */
  17026. mg_lock_context(ctx);
  17027. idx = 0;
  17028. dom = &(ctx->dd);
  17029. for (;;) {
  17030. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17031. dom->config[AUTHENTICATION_DOMAIN])) {
  17032. /* Domain collision */
  17033. mg_cry_ctx_internal(ctx,
  17034. "domain %s already in use",
  17035. new_dom->config[AUTHENTICATION_DOMAIN]);
  17036. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17037. mg_snprintf(NULL,
  17038. NULL, /* No truncation check for error buffers */
  17039. error->text,
  17040. error->text_buffer_size,
  17041. "Domain %s specified by %s is already in use",
  17042. new_dom->config[AUTHENTICATION_DOMAIN],
  17043. config_options[AUTHENTICATION_DOMAIN].name);
  17044. }
  17045. mg_free(new_dom);
  17046. return -5;
  17047. }
  17048. /* Count number of domains */
  17049. idx++;
  17050. if (dom->next == NULL) {
  17051. dom->next = new_dom;
  17052. break;
  17053. }
  17054. dom = dom->next;
  17055. }
  17056. mg_unlock_context(ctx);
  17057. /* Return domain number */
  17058. return idx;
  17059. }
  17060. int
  17061. mg_start_domain(struct mg_context *ctx, const char **options)
  17062. {
  17063. return mg_start_domain2(ctx, options, NULL);
  17064. }
  17065. #endif
  17066. /* Feature check API function */
  17067. unsigned
  17068. mg_check_feature(unsigned feature)
  17069. {
  17070. static const unsigned feature_set = 0
  17071. /* Set bits for available features according to API documentation.
  17072. * This bit mask is created at compile time, according to the active
  17073. * preprocessor defines. It is a single const value at runtime. */
  17074. #if !defined(NO_FILES)
  17075. | MG_FEATURES_FILES
  17076. #endif
  17077. #if !defined(NO_SSL)
  17078. | MG_FEATURES_SSL
  17079. #endif
  17080. #if !defined(NO_CGI)
  17081. | MG_FEATURES_CGI
  17082. #endif
  17083. #if defined(USE_IPV6)
  17084. | MG_FEATURES_IPV6
  17085. #endif
  17086. #if defined(USE_WEBSOCKET)
  17087. | MG_FEATURES_WEBSOCKET
  17088. #endif
  17089. #if defined(USE_LUA)
  17090. | MG_FEATURES_LUA
  17091. #endif
  17092. #if defined(USE_DUKTAPE)
  17093. | MG_FEATURES_SSJS
  17094. #endif
  17095. #if !defined(NO_CACHING)
  17096. | MG_FEATURES_CACHE
  17097. #endif
  17098. #if defined(USE_SERVER_STATS)
  17099. | MG_FEATURES_STATS
  17100. #endif
  17101. #if defined(USE_ZLIB)
  17102. | MG_FEATURES_COMPRESSION
  17103. #endif
  17104. /* Set some extra bits not defined in the API documentation.
  17105. * These bits may change without further notice. */
  17106. #if defined(MG_LEGACY_INTERFACE)
  17107. | 0x00008000u
  17108. #endif
  17109. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17110. | 0x00004000u
  17111. #endif
  17112. #if defined(MEMORY_DEBUGGING)
  17113. | 0x00001000u
  17114. #endif
  17115. #if defined(USE_TIMERS)
  17116. | 0x00020000u
  17117. #endif
  17118. #if !defined(NO_NONCE_CHECK)
  17119. | 0x00040000u
  17120. #endif
  17121. #if !defined(NO_POPEN)
  17122. | 0x00080000u
  17123. #endif
  17124. ;
  17125. return (feature & feature_set);
  17126. }
  17127. static size_t
  17128. mg_str_append(char **dst, char *end, const char *src)
  17129. {
  17130. size_t len = strlen(src);
  17131. if (*dst != end) {
  17132. /* Append src if enough space, or close dst. */
  17133. if ((size_t)(end - *dst) > len) {
  17134. strcpy(*dst, src);
  17135. *dst += len;
  17136. } else {
  17137. *dst = end;
  17138. }
  17139. }
  17140. return len;
  17141. }
  17142. /* Get system information. It can be printed or stored by the caller.
  17143. * Return the size of available information. */
  17144. int
  17145. mg_get_system_info(char *buffer, int buflen)
  17146. {
  17147. char *end, *append_eoobj = NULL, block[256];
  17148. size_t system_info_length = 0;
  17149. #if defined(_WIN32)
  17150. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17151. #else
  17152. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17153. #endif
  17154. if ((buffer == NULL) || (buflen < 1)) {
  17155. buflen = 0;
  17156. end = buffer;
  17157. } else {
  17158. *buffer = 0;
  17159. end = buffer + buflen;
  17160. }
  17161. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17162. /* has enough space to append eoobj */
  17163. append_eoobj = buffer;
  17164. end -= sizeof(eoobj) - 1;
  17165. }
  17166. system_info_length += mg_str_append(&buffer, end, "{");
  17167. /* Server version */
  17168. {
  17169. const char *version = mg_version();
  17170. mg_snprintf(NULL,
  17171. NULL,
  17172. block,
  17173. sizeof(block),
  17174. "%s\"version\" : \"%s\"",
  17175. eol,
  17176. version);
  17177. system_info_length += mg_str_append(&buffer, end, block);
  17178. }
  17179. /* System info */
  17180. {
  17181. #if defined(_WIN32)
  17182. DWORD dwVersion = 0;
  17183. DWORD dwMajorVersion = 0;
  17184. DWORD dwMinorVersion = 0;
  17185. SYSTEM_INFO si;
  17186. GetSystemInfo(&si);
  17187. #if defined(_MSC_VER)
  17188. #pragma warning(push)
  17189. /* GetVersion was declared deprecated */
  17190. #pragma warning(disable : 4996)
  17191. #endif
  17192. dwVersion = GetVersion();
  17193. #if defined(_MSC_VER)
  17194. #pragma warning(pop)
  17195. #endif
  17196. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17197. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17198. mg_snprintf(NULL,
  17199. NULL,
  17200. block,
  17201. sizeof(block),
  17202. ",%s\"os\" : \"Windows %u.%u\"",
  17203. eol,
  17204. (unsigned)dwMajorVersion,
  17205. (unsigned)dwMinorVersion);
  17206. system_info_length += mg_str_append(&buffer, end, block);
  17207. mg_snprintf(NULL,
  17208. NULL,
  17209. block,
  17210. sizeof(block),
  17211. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17212. eol,
  17213. (unsigned)si.wProcessorArchitecture,
  17214. (unsigned)si.dwNumberOfProcessors,
  17215. (unsigned)si.dwActiveProcessorMask);
  17216. system_info_length += mg_str_append(&buffer, end, block);
  17217. #elif defined(__ZEPHYR__)
  17218. mg_snprintf(NULL,
  17219. NULL,
  17220. block,
  17221. sizeof(block),
  17222. ",%s\"os\" : \"%s %s\"",
  17223. eol,
  17224. "Zephyr OS",
  17225. ZEPHYR_VERSION);
  17226. system_info_length += mg_str_append(&buffer, end, block);
  17227. #else
  17228. struct utsname name;
  17229. memset(&name, 0, sizeof(name));
  17230. uname(&name);
  17231. mg_snprintf(NULL,
  17232. NULL,
  17233. block,
  17234. sizeof(block),
  17235. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17236. eol,
  17237. name.sysname,
  17238. name.version,
  17239. name.release,
  17240. name.machine);
  17241. system_info_length += mg_str_append(&buffer, end, block);
  17242. #endif
  17243. }
  17244. /* Features */
  17245. {
  17246. mg_snprintf(NULL,
  17247. NULL,
  17248. block,
  17249. sizeof(block),
  17250. ",%s\"features\" : %lu"
  17251. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17252. eol,
  17253. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17254. eol,
  17255. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17256. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17257. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17258. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17259. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17260. : "",
  17261. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17262. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17263. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17264. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17265. system_info_length += mg_str_append(&buffer, end, block);
  17266. #if defined(USE_LUA)
  17267. mg_snprintf(NULL,
  17268. NULL,
  17269. block,
  17270. sizeof(block),
  17271. ",%s\"lua_version\" : \"%u (%s)\"",
  17272. eol,
  17273. (unsigned)LUA_VERSION_NUM,
  17274. LUA_RELEASE);
  17275. system_info_length += mg_str_append(&buffer, end, block);
  17276. #endif
  17277. #if defined(USE_DUKTAPE)
  17278. mg_snprintf(NULL,
  17279. NULL,
  17280. block,
  17281. sizeof(block),
  17282. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17283. eol,
  17284. (unsigned)DUK_VERSION / 10000,
  17285. ((unsigned)DUK_VERSION / 100) % 100,
  17286. (unsigned)DUK_VERSION % 100);
  17287. system_info_length += mg_str_append(&buffer, end, block);
  17288. #endif
  17289. }
  17290. /* Build date */
  17291. {
  17292. #if defined(GCC_DIAGNOSTIC)
  17293. #if GCC_VERSION >= 40900
  17294. #pragma GCC diagnostic push
  17295. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17296. #pragma GCC diagnostic ignored "-Wdate-time"
  17297. #endif
  17298. #endif
  17299. mg_snprintf(NULL,
  17300. NULL,
  17301. block,
  17302. sizeof(block),
  17303. ",%s\"build\" : \"%s\"",
  17304. eol,
  17305. __DATE__);
  17306. #if defined(GCC_DIAGNOSTIC)
  17307. #if GCC_VERSION >= 40900
  17308. #pragma GCC diagnostic pop
  17309. #endif
  17310. #endif
  17311. system_info_length += mg_str_append(&buffer, end, block);
  17312. }
  17313. /* Compiler information */
  17314. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17315. {
  17316. #if defined(_MSC_VER)
  17317. mg_snprintf(NULL,
  17318. NULL,
  17319. block,
  17320. sizeof(block),
  17321. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17322. eol,
  17323. (unsigned)_MSC_VER,
  17324. (unsigned)_MSC_FULL_VER);
  17325. system_info_length += mg_str_append(&buffer, end, block);
  17326. #elif defined(__MINGW64__)
  17327. mg_snprintf(NULL,
  17328. NULL,
  17329. block,
  17330. sizeof(block),
  17331. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17332. eol,
  17333. (unsigned)__MINGW64_VERSION_MAJOR,
  17334. (unsigned)__MINGW64_VERSION_MINOR);
  17335. system_info_length += mg_str_append(&buffer, end, block);
  17336. mg_snprintf(NULL,
  17337. NULL,
  17338. block,
  17339. sizeof(block),
  17340. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17341. eol,
  17342. (unsigned)__MINGW32_MAJOR_VERSION,
  17343. (unsigned)__MINGW32_MINOR_VERSION);
  17344. system_info_length += mg_str_append(&buffer, end, block);
  17345. #elif defined(__MINGW32__)
  17346. mg_snprintf(NULL,
  17347. NULL,
  17348. block,
  17349. sizeof(block),
  17350. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17351. eol,
  17352. (unsigned)__MINGW32_MAJOR_VERSION,
  17353. (unsigned)__MINGW32_MINOR_VERSION);
  17354. system_info_length += mg_str_append(&buffer, end, block);
  17355. #elif defined(__clang__)
  17356. mg_snprintf(NULL,
  17357. NULL,
  17358. block,
  17359. sizeof(block),
  17360. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17361. eol,
  17362. __clang_major__,
  17363. __clang_minor__,
  17364. __clang_patchlevel__,
  17365. __clang_version__);
  17366. system_info_length += mg_str_append(&buffer, end, block);
  17367. #elif defined(__GNUC__)
  17368. mg_snprintf(NULL,
  17369. NULL,
  17370. block,
  17371. sizeof(block),
  17372. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17373. eol,
  17374. (unsigned)__GNUC__,
  17375. (unsigned)__GNUC_MINOR__,
  17376. (unsigned)__GNUC_PATCHLEVEL__);
  17377. system_info_length += mg_str_append(&buffer, end, block);
  17378. #elif defined(__INTEL_COMPILER)
  17379. mg_snprintf(NULL,
  17380. NULL,
  17381. block,
  17382. sizeof(block),
  17383. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17384. eol,
  17385. (unsigned)__INTEL_COMPILER);
  17386. system_info_length += mg_str_append(&buffer, end, block);
  17387. #elif defined(__BORLANDC__)
  17388. mg_snprintf(NULL,
  17389. NULL,
  17390. block,
  17391. sizeof(block),
  17392. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17393. eol,
  17394. (unsigned)__BORLANDC__);
  17395. system_info_length += mg_str_append(&buffer, end, block);
  17396. #elif defined(__SUNPRO_C)
  17397. mg_snprintf(NULL,
  17398. NULL,
  17399. block,
  17400. sizeof(block),
  17401. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17402. eol,
  17403. (unsigned)__SUNPRO_C);
  17404. system_info_length += mg_str_append(&buffer, end, block);
  17405. #else
  17406. mg_snprintf(NULL,
  17407. NULL,
  17408. block,
  17409. sizeof(block),
  17410. ",%s\"compiler\" : \"other\"",
  17411. eol);
  17412. system_info_length += mg_str_append(&buffer, end, block);
  17413. #endif
  17414. }
  17415. /* Determine 32/64 bit data mode.
  17416. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17417. {
  17418. mg_snprintf(NULL,
  17419. NULL,
  17420. block,
  17421. sizeof(block),
  17422. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17423. "char:%u/%u, "
  17424. "ptr:%u, size:%u, time:%u\"",
  17425. eol,
  17426. (unsigned)sizeof(short),
  17427. (unsigned)sizeof(int),
  17428. (unsigned)sizeof(long),
  17429. (unsigned)sizeof(long long),
  17430. (unsigned)sizeof(float),
  17431. (unsigned)sizeof(double),
  17432. (unsigned)sizeof(long double),
  17433. (unsigned)sizeof(char),
  17434. (unsigned)sizeof(wchar_t),
  17435. (unsigned)sizeof(void *),
  17436. (unsigned)sizeof(size_t),
  17437. (unsigned)sizeof(time_t));
  17438. system_info_length += mg_str_append(&buffer, end, block);
  17439. }
  17440. /* Terminate string */
  17441. if (append_eoobj) {
  17442. strcat(append_eoobj, eoobj);
  17443. }
  17444. system_info_length += sizeof(eoobj) - 1;
  17445. return (int)system_info_length;
  17446. }
  17447. /* Get context information. It can be printed or stored by the caller.
  17448. * Return the size of available information. */
  17449. int
  17450. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17451. {
  17452. #if defined(USE_SERVER_STATS)
  17453. char *end, *append_eoobj = NULL, block[256];
  17454. size_t context_info_length = 0;
  17455. #if defined(_WIN32)
  17456. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17457. #else
  17458. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17459. #endif
  17460. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17461. if ((buffer == NULL) || (buflen < 1)) {
  17462. buflen = 0;
  17463. end = buffer;
  17464. } else {
  17465. *buffer = 0;
  17466. end = buffer + buflen;
  17467. }
  17468. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17469. /* has enough space to append eoobj */
  17470. append_eoobj = buffer;
  17471. end -= sizeof(eoobj) - 1;
  17472. }
  17473. context_info_length += mg_str_append(&buffer, end, "{");
  17474. if (ms) { /* <-- should be always true */
  17475. /* Memory information */
  17476. mg_snprintf(NULL,
  17477. NULL,
  17478. block,
  17479. sizeof(block),
  17480. "%s\"memory\" : {%s"
  17481. "\"blocks\" : %i,%s"
  17482. "\"used\" : %" INT64_FMT ",%s"
  17483. "\"maxUsed\" : %" INT64_FMT "%s"
  17484. "}",
  17485. eol,
  17486. eol,
  17487. ms->blockCount,
  17488. eol,
  17489. ms->totalMemUsed,
  17490. eol,
  17491. ms->maxMemUsed,
  17492. eol);
  17493. context_info_length += mg_str_append(&buffer, end, block);
  17494. }
  17495. if (ctx) {
  17496. /* Declare all variables at begin of the block, to comply
  17497. * with old C standards. */
  17498. char start_time_str[64] = {0};
  17499. char now_str[64] = {0};
  17500. time_t start_time = ctx->start_time;
  17501. time_t now = time(NULL);
  17502. /* Connections information */
  17503. mg_snprintf(NULL,
  17504. NULL,
  17505. block,
  17506. sizeof(block),
  17507. ",%s\"connections\" : {%s"
  17508. "\"active\" : %i,%s"
  17509. "\"maxActive\" : %i,%s"
  17510. "\"total\" : %" INT64_FMT "%s"
  17511. "}",
  17512. eol,
  17513. eol,
  17514. ctx->active_connections,
  17515. eol,
  17516. ctx->max_active_connections,
  17517. eol,
  17518. ctx->total_connections,
  17519. eol);
  17520. context_info_length += mg_str_append(&buffer, end, block);
  17521. /* Queue information */
  17522. #if !defined(ALTERNATIVE_QUEUE)
  17523. mg_snprintf(NULL,
  17524. NULL,
  17525. block,
  17526. sizeof(block),
  17527. ",%s\"queue\" : {%s"
  17528. "\"length\" : %i,%s"
  17529. "\"filled\" : %i,%s"
  17530. "\"maxFilled\" : %i,%s"
  17531. "\"full\" : %s%s"
  17532. "}",
  17533. eol,
  17534. eol,
  17535. ctx->sq_size,
  17536. eol,
  17537. ctx->sq_head - ctx->sq_tail,
  17538. eol,
  17539. ctx->sq_max_fill,
  17540. eol,
  17541. (ctx->sq_blocked ? "true" : "false"),
  17542. eol);
  17543. context_info_length += mg_str_append(&buffer, end, block);
  17544. #endif
  17545. /* Requests information */
  17546. mg_snprintf(NULL,
  17547. NULL,
  17548. block,
  17549. sizeof(block),
  17550. ",%s\"requests\" : {%s"
  17551. "\"total\" : %" INT64_FMT "%s"
  17552. "}",
  17553. eol,
  17554. eol,
  17555. ctx->total_requests,
  17556. eol);
  17557. context_info_length += mg_str_append(&buffer, end, block);
  17558. /* Data information */
  17559. mg_snprintf(NULL,
  17560. NULL,
  17561. block,
  17562. sizeof(block),
  17563. ",%s\"data\" : {%s"
  17564. "\"read\" : %" INT64_FMT ",%s"
  17565. "\"written\" : %" INT64_FMT "%s"
  17566. "}",
  17567. eol,
  17568. eol,
  17569. ctx->total_data_read,
  17570. eol,
  17571. ctx->total_data_written,
  17572. eol);
  17573. context_info_length += mg_str_append(&buffer, end, block);
  17574. /* Execution time information */
  17575. gmt_time_string(start_time_str,
  17576. sizeof(start_time_str) - 1,
  17577. &start_time);
  17578. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17579. mg_snprintf(NULL,
  17580. NULL,
  17581. block,
  17582. sizeof(block),
  17583. ",%s\"time\" : {%s"
  17584. "\"uptime\" : %.0f,%s"
  17585. "\"start\" : \"%s\",%s"
  17586. "\"now\" : \"%s\"%s"
  17587. "}",
  17588. eol,
  17589. eol,
  17590. difftime(now, start_time),
  17591. eol,
  17592. start_time_str,
  17593. eol,
  17594. now_str,
  17595. eol);
  17596. context_info_length += mg_str_append(&buffer, end, block);
  17597. }
  17598. /* Terminate string */
  17599. if (append_eoobj) {
  17600. strcat(append_eoobj, eoobj);
  17601. }
  17602. context_info_length += sizeof(eoobj) - 1;
  17603. return (int)context_info_length;
  17604. #else
  17605. (void)ctx;
  17606. if ((buffer != NULL) && (buflen > 0)) {
  17607. *buffer = 0;
  17608. }
  17609. return 0;
  17610. #endif
  17611. }
  17612. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17613. /* Get connection information. It can be printed or stored by the caller.
  17614. * Return the size of available information. */
  17615. int
  17616. mg_get_connection_info(const struct mg_context *ctx,
  17617. int idx,
  17618. char *buffer,
  17619. int buflen)
  17620. {
  17621. const struct mg_connection *conn;
  17622. const struct mg_request_info *ri;
  17623. char *end, *append_eoobj = NULL, block[256];
  17624. size_t connection_info_length = 0;
  17625. int state = 0;
  17626. const char *state_str = "unknown";
  17627. #if defined(_WIN32)
  17628. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17629. #else
  17630. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17631. #endif
  17632. if ((buffer == NULL) || (buflen < 1)) {
  17633. buflen = 0;
  17634. end = buffer;
  17635. } else {
  17636. *buffer = 0;
  17637. end = buffer + buflen;
  17638. }
  17639. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17640. /* has enough space to append eoobj */
  17641. append_eoobj = buffer;
  17642. end -= sizeof(eoobj) - 1;
  17643. }
  17644. if ((ctx == NULL) || (idx < 0)) {
  17645. /* Parameter error */
  17646. return 0;
  17647. }
  17648. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  17649. /* Out of range */
  17650. return 0;
  17651. }
  17652. /* Take connection [idx]. This connection is not locked in
  17653. * any way, so some other thread might use it. */
  17654. conn = (ctx->worker_connections) + idx;
  17655. /* Initialize output string */
  17656. connection_info_length += mg_str_append(&buffer, end, "{");
  17657. /* Init variables */
  17658. ri = &(conn->request_info);
  17659. #if defined(USE_SERVER_STATS)
  17660. state = conn->conn_state;
  17661. /* State as string */
  17662. switch (state) {
  17663. case 0:
  17664. state_str = "undefined";
  17665. break;
  17666. case 1:
  17667. state_str = "not used";
  17668. break;
  17669. case 2:
  17670. state_str = "init";
  17671. break;
  17672. case 3:
  17673. state_str = "ready";
  17674. break;
  17675. case 4:
  17676. state_str = "processing";
  17677. break;
  17678. case 5:
  17679. state_str = "processed";
  17680. break;
  17681. case 6:
  17682. state_str = "to close";
  17683. break;
  17684. case 7:
  17685. state_str = "closing";
  17686. break;
  17687. case 8:
  17688. state_str = "closed";
  17689. break;
  17690. case 9:
  17691. state_str = "done";
  17692. break;
  17693. }
  17694. #endif
  17695. /* Connection info */
  17696. if ((state >= 3) && (state < 9)) {
  17697. mg_snprintf(NULL,
  17698. NULL,
  17699. block,
  17700. sizeof(block),
  17701. "%s\"connection\" : {%s"
  17702. "\"remote\" : {%s"
  17703. "\"protocol\" : \"%s\",%s"
  17704. "\"addr\" : \"%s\",%s"
  17705. "\"port\" : %u%s"
  17706. "},%s"
  17707. "\"handled_requests\" : %u%s"
  17708. "}",
  17709. eol,
  17710. eol,
  17711. eol,
  17712. get_proto_name(conn),
  17713. eol,
  17714. ri->remote_addr,
  17715. eol,
  17716. ri->remote_port,
  17717. eol,
  17718. eol,
  17719. conn->handled_requests,
  17720. eol);
  17721. connection_info_length += mg_str_append(&buffer, end, block);
  17722. }
  17723. /* Request info */
  17724. if ((state >= 4) && (state < 6)) {
  17725. mg_snprintf(NULL,
  17726. NULL,
  17727. block,
  17728. sizeof(block),
  17729. "%s%s\"request_info\" : {%s"
  17730. "\"method\" : \"%s\",%s"
  17731. "\"uri\" : \"%s\",%s"
  17732. "\"query\" : %s%s%s%s"
  17733. "}",
  17734. (connection_info_length > 1 ? "," : ""),
  17735. eol,
  17736. eol,
  17737. ri->request_method,
  17738. eol,
  17739. ri->request_uri,
  17740. eol,
  17741. ri->query_string ? "\"" : "",
  17742. ri->query_string ? ri->query_string : "null",
  17743. ri->query_string ? "\"" : "",
  17744. eol);
  17745. connection_info_length += mg_str_append(&buffer, end, block);
  17746. }
  17747. /* Execution time information */
  17748. if ((state >= 2) && (state < 9)) {
  17749. char start_time_str[64] = {0};
  17750. char close_time_str[64] = {0};
  17751. time_t start_time = conn->conn_birth_time;
  17752. time_t close_time = conn->conn_close_time;
  17753. double time_diff;
  17754. gmt_time_string(start_time_str,
  17755. sizeof(start_time_str) - 1,
  17756. &start_time);
  17757. if (close_time != 0) {
  17758. time_diff = difftime(close_time, start_time);
  17759. gmt_time_string(close_time_str,
  17760. sizeof(close_time_str) - 1,
  17761. &close_time);
  17762. } else {
  17763. time_t now = time(NULL);
  17764. time_diff = difftime(now, start_time);
  17765. close_time_str[0] = 0; /* or use "now" ? */
  17766. }
  17767. mg_snprintf(NULL,
  17768. NULL,
  17769. block,
  17770. sizeof(block),
  17771. "%s%s\"time\" : {%s"
  17772. "\"uptime\" : %.0f,%s"
  17773. "\"start\" : \"%s\",%s"
  17774. "\"closed\" : \"%s\"%s"
  17775. "}",
  17776. (connection_info_length > 1 ? "," : ""),
  17777. eol,
  17778. eol,
  17779. time_diff,
  17780. eol,
  17781. start_time_str,
  17782. eol,
  17783. close_time_str,
  17784. eol);
  17785. connection_info_length += mg_str_append(&buffer, end, block);
  17786. }
  17787. /* Remote user name */
  17788. if ((ri->remote_user) && (state < 9)) {
  17789. mg_snprintf(NULL,
  17790. NULL,
  17791. block,
  17792. sizeof(block),
  17793. "%s%s\"user\" : {%s"
  17794. "\"name\" : \"%s\",%s"
  17795. "}",
  17796. (connection_info_length > 1 ? "," : ""),
  17797. eol,
  17798. eol,
  17799. ri->remote_user,
  17800. eol);
  17801. connection_info_length += mg_str_append(&buffer, end, block);
  17802. }
  17803. /* Data block */
  17804. if (state >= 3) {
  17805. mg_snprintf(NULL,
  17806. NULL,
  17807. block,
  17808. sizeof(block),
  17809. "%s%s\"data\" : {%s"
  17810. "\"read\" : %" INT64_FMT ",%s"
  17811. "\"written\" : %" INT64_FMT "%s"
  17812. "}",
  17813. (connection_info_length > 1 ? "," : ""),
  17814. eol,
  17815. eol,
  17816. conn->consumed_content,
  17817. eol,
  17818. conn->num_bytes_sent,
  17819. eol);
  17820. connection_info_length += mg_str_append(&buffer, end, block);
  17821. }
  17822. /* State */
  17823. mg_snprintf(NULL,
  17824. NULL,
  17825. block,
  17826. sizeof(block),
  17827. "%s%s\"state\" : \"%s\"",
  17828. (connection_info_length > 1 ? "," : ""),
  17829. eol,
  17830. state_str);
  17831. connection_info_length += mg_str_append(&buffer, end, block);
  17832. /* Terminate string */
  17833. if (append_eoobj) {
  17834. strcat(append_eoobj, eoobj);
  17835. }
  17836. connection_info_length += sizeof(eoobj) - 1;
  17837. return (int)connection_info_length;
  17838. }
  17839. #endif
  17840. /* Initialize this library. This function does not need to be thread safe.
  17841. */
  17842. unsigned
  17843. mg_init_library(unsigned features)
  17844. {
  17845. #if !defined(NO_SSL)
  17846. char ebuf[128];
  17847. #endif
  17848. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17849. unsigned features_inited = features_to_init;
  17850. if (mg_init_library_called <= 0) {
  17851. /* Not initialized yet */
  17852. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17853. return 0;
  17854. }
  17855. }
  17856. mg_global_lock();
  17857. if (mg_init_library_called <= 0) {
  17858. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17859. /* Fatal error - abort start. However, this situation should
  17860. * never occur in practice. */
  17861. mg_global_unlock();
  17862. return 0;
  17863. }
  17864. #if defined(_WIN32)
  17865. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17866. #else
  17867. pthread_mutexattr_init(&pthread_mutex_attr);
  17868. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17869. #endif
  17870. #if defined(USE_LUA)
  17871. lua_init_optional_libraries();
  17872. #endif
  17873. }
  17874. mg_global_unlock();
  17875. #if !defined(NO_SSL)
  17876. if (features_to_init & MG_FEATURES_SSL) {
  17877. if (!mg_ssl_initialized) {
  17878. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17879. mg_ssl_initialized = 1;
  17880. } else {
  17881. (void)ebuf;
  17882. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17883. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17884. }
  17885. } else {
  17886. /* ssl already initialized */
  17887. }
  17888. }
  17889. #endif
  17890. /* Start WinSock for Windows */
  17891. mg_global_lock();
  17892. if (mg_init_library_called <= 0) {
  17893. #if defined(_WIN32)
  17894. WSADATA data;
  17895. WSAStartup(MAKEWORD(2, 2), &data);
  17896. #endif /* _WIN32 */
  17897. mg_init_library_called = 1;
  17898. } else {
  17899. mg_init_library_called++;
  17900. }
  17901. mg_global_unlock();
  17902. return features_inited;
  17903. }
  17904. /* Un-initialize this library. */
  17905. unsigned
  17906. mg_exit_library(void)
  17907. {
  17908. if (mg_init_library_called <= 0) {
  17909. return 0;
  17910. }
  17911. mg_global_lock();
  17912. mg_init_library_called--;
  17913. if (mg_init_library_called == 0) {
  17914. #if defined(_WIN32)
  17915. (void)WSACleanup();
  17916. #endif /* _WIN32 */
  17917. #if !defined(NO_SSL)
  17918. if (mg_ssl_initialized) {
  17919. uninitialize_ssl();
  17920. mg_ssl_initialized = 0;
  17921. }
  17922. #endif
  17923. #if defined(_WIN32)
  17924. (void)pthread_mutex_destroy(&global_log_file_lock);
  17925. #else
  17926. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17927. #endif
  17928. (void)pthread_key_delete(sTlsKey);
  17929. #if defined(USE_LUA)
  17930. lua_exit_optional_libraries();
  17931. #endif
  17932. mg_global_unlock();
  17933. (void)pthread_mutex_destroy(&global_lock_mutex);
  17934. return 1;
  17935. }
  17936. mg_global_unlock();
  17937. return 1;
  17938. }
  17939. /* End of civetweb.c */