civetweb.c 569 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138
  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. #ifndef DEBUG_TRACE_STREAM
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. /********************************************************************/
  369. /* CivetWeb configuration defines */
  370. /********************************************************************/
  371. /* Maximum number of threads that can be configured.
  372. * The number of threads actually created depends on the "num_threads"
  373. * configuration parameter, but this is the upper limit. */
  374. #if !defined(MAX_WORKER_THREADS)
  375. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  376. #endif
  377. /* Timeout interval for select/poll calls.
  378. * The timeouts depend on "*_timeout_ms" configuration values, but long
  379. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  380. * This reduces the time required to stop the server. */
  381. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  382. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  383. #endif
  384. /* Do not try to compress files smaller than this limit. */
  385. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  386. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  387. #endif
  388. #if !defined(PASSWORDS_FILE_NAME)
  389. #define PASSWORDS_FILE_NAME ".htpasswd"
  390. #endif
  391. /* Initial buffer size for all CGI environment variables. In case there is
  392. * not enough space, another block is allocated. */
  393. #if !defined(CGI_ENVIRONMENT_SIZE)
  394. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  395. #endif
  396. /* Maximum number of environment variables. */
  397. #if !defined(MAX_CGI_ENVIR_VARS)
  398. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  399. #endif
  400. /* General purpose buffer size. */
  401. #if !defined(MG_BUF_LEN) /* in bytes */
  402. #define MG_BUF_LEN (1024 * 8)
  403. #endif
  404. /********************************************************************/
  405. /* Helper makros */
  406. #if !defined(ARRAY_SIZE)
  407. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  408. #endif
  409. #include <stdint.h>
  410. /* Standard defines */
  411. #if !defined(INT64_MAX)
  412. #define INT64_MAX (9223372036854775807)
  413. #endif
  414. #define SHUTDOWN_RD (0)
  415. #define SHUTDOWN_WR (1)
  416. #define SHUTDOWN_BOTH (2)
  417. mg_static_assert(MAX_WORKER_THREADS >= 1,
  418. "worker threads must be a positive number");
  419. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  420. "size_t data type size check");
  421. #if defined(_WIN32) /* WINDOWS include block */
  422. #include <malloc.h> /* *alloc( */
  423. #include <stdlib.h> /* *alloc( */
  424. #include <time.h> /* struct timespec */
  425. #include <windows.h>
  426. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  427. #include <ws2tcpip.h>
  428. typedef const char *SOCK_OPT_TYPE;
  429. #if !defined(PATH_MAX)
  430. #define W_PATH_MAX (MAX_PATH)
  431. /* at most three UTF-8 chars per wchar_t */
  432. #define PATH_MAX (W_PATH_MAX * 3)
  433. #else
  434. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  435. #endif
  436. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  437. #if !defined(_IN_PORT_T)
  438. #if !defined(in_port_t)
  439. #define in_port_t u_short
  440. #endif
  441. #endif
  442. #if !defined(_WIN32_WCE)
  443. #include <direct.h>
  444. #include <io.h>
  445. #include <process.h>
  446. #else /* _WIN32_WCE */
  447. #define NO_CGI /* WinCE has no pipes */
  448. #define NO_POPEN /* WinCE has no popen */
  449. typedef long off_t;
  450. #define errno ((int)(GetLastError()))
  451. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  452. #endif /* _WIN32_WCE */
  453. #define MAKEUQUAD(lo, hi) \
  454. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  455. #define RATE_DIFF (10000000) /* 100 nsecs */
  456. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  457. #define SYS2UNIX_TIME(lo, hi) \
  458. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  459. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  460. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  461. * Also use _strtoui64 on modern M$ compilers */
  462. #if defined(_MSC_VER)
  463. #if (_MSC_VER < 1300)
  464. #define STRX(x) #x
  465. #define STR(x) STRX(x)
  466. #define __func__ __FILE__ ":" STR(__LINE__)
  467. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  468. #define strtoll(x, y, z) (_atoi64(x))
  469. #else
  470. #define __func__ __FUNCTION__
  471. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  472. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  473. #endif
  474. #endif /* _MSC_VER */
  475. #define ERRNO ((int)(GetLastError()))
  476. #define NO_SOCKLEN_T
  477. #if defined(_WIN64) || defined(__MINGW64__)
  478. #if !defined(SSL_LIB)
  479. #if defined(OPENSSL_API_1_1)
  480. #define SSL_LIB "libssl-1_1-x64.dll"
  481. #else /* OPENSSL_API_1_1 */
  482. #define SSL_LIB "ssleay64.dll"
  483. #endif /* OPENSSL_API_1_1 */
  484. #endif /* SSL_LIB */
  485. #if !defined(CRYPTO_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  488. #else /* OPENSSL_API_1_1 */
  489. #define CRYPTO_LIB "libeay64.dll"
  490. #endif /* OPENSSL_API_1_1 */
  491. #endif /* CRYPTO_LIB */
  492. #else /* defined(_WIN64) || defined(__MINGW64__) */
  493. #if !defined(SSL_LIB)
  494. #define SSL_LIB "ssleay32.dll"
  495. #endif /* SSL_LIB */
  496. #if !defined(CRYPTO_LIB)
  497. #define CRYPTO_LIB "libeay32.dll"
  498. #endif /* CRYPTO_LIB */
  499. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  500. #define O_NONBLOCK (0)
  501. #if !defined(W_OK)
  502. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  503. #endif
  504. #define _POSIX_
  505. #define INT64_FMT "I64d"
  506. #define UINT64_FMT "I64u"
  507. #define WINCDECL __cdecl
  508. #define vsnprintf_impl _vsnprintf
  509. #define access _access
  510. #define mg_sleep(x) (Sleep(x))
  511. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  512. #if !defined(popen)
  513. #define popen(x, y) (_popen(x, y))
  514. #endif
  515. #if !defined(pclose)
  516. #define pclose(x) (_pclose(x))
  517. #endif
  518. #define close(x) (_close(x))
  519. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  520. #define RTLD_LAZY (0)
  521. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  522. #define fdopen(x, y) (_fdopen((x), (y)))
  523. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  524. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  525. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  526. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  527. #define sleep(x) (Sleep((x)*1000))
  528. #define rmdir(x) (_rmdir(x))
  529. #if defined(_WIN64) || !defined(__MINGW32__)
  530. /* Only MinGW 32 bit is missing this function */
  531. #define timegm(x) (_mkgmtime(x))
  532. #else
  533. time_t timegm(struct tm *tm);
  534. #define NEED_TIMEGM
  535. #endif
  536. #if !defined(fileno)
  537. #define fileno(x) (_fileno(x))
  538. #endif /* !fileno MINGW #defines fileno */
  539. typedef struct {
  540. CRITICAL_SECTION sec; /* Immovable */
  541. } pthread_mutex_t;
  542. typedef DWORD pthread_key_t;
  543. typedef HANDLE pthread_t;
  544. typedef struct {
  545. pthread_mutex_t threadIdSec;
  546. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  547. } pthread_cond_t;
  548. #if !defined(__clockid_t_defined)
  549. typedef DWORD clockid_t;
  550. #endif
  551. #if !defined(CLOCK_MONOTONIC)
  552. #define CLOCK_MONOTONIC (1)
  553. #endif
  554. #if !defined(CLOCK_REALTIME)
  555. #define CLOCK_REALTIME (2)
  556. #endif
  557. #if !defined(CLOCK_THREAD)
  558. #define CLOCK_THREAD (3)
  559. #endif
  560. #if !defined(CLOCK_PROCESS)
  561. #define CLOCK_PROCESS (4)
  562. #endif
  563. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  564. #define _TIMESPEC_DEFINED
  565. #endif
  566. #if !defined(_TIMESPEC_DEFINED)
  567. struct timespec {
  568. time_t tv_sec; /* seconds */
  569. long tv_nsec; /* nanoseconds */
  570. };
  571. #endif
  572. #if !defined(WIN_PTHREADS_TIME_H)
  573. #define MUST_IMPLEMENT_CLOCK_GETTIME
  574. #endif
  575. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  576. #define clock_gettime mg_clock_gettime
  577. static int
  578. clock_gettime(clockid_t clk_id, struct timespec *tp)
  579. {
  580. FILETIME ft;
  581. ULARGE_INTEGER li, li2;
  582. BOOL ok = FALSE;
  583. double d;
  584. static double perfcnt_per_sec = 0.0;
  585. static BOOL initialized = FALSE;
  586. if (!initialized) {
  587. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  588. perfcnt_per_sec = 1.0 / li.QuadPart;
  589. initialized = TRUE;
  590. }
  591. if (tp) {
  592. memset(tp, 0, sizeof(*tp));
  593. if (clk_id == CLOCK_REALTIME) {
  594. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  595. GetSystemTimeAsFileTime(&ft);
  596. li.LowPart = ft.dwLowDateTime;
  597. li.HighPart = ft.dwHighDateTime;
  598. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  599. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  600. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  601. ok = TRUE;
  602. /* END: CLOCK_REALTIME */
  603. } else if (clk_id == CLOCK_MONOTONIC) {
  604. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  605. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  606. d = li.QuadPart * perfcnt_per_sec;
  607. tp->tv_sec = (time_t)d;
  608. d -= (double)tp->tv_sec;
  609. tp->tv_nsec = (long)(d * 1.0E9);
  610. ok = TRUE;
  611. /* END: CLOCK_MONOTONIC */
  612. } else if (clk_id == CLOCK_THREAD) {
  613. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  614. FILETIME t_create, t_exit, t_kernel, t_user;
  615. if (GetThreadTimes(GetCurrentThread(),
  616. &t_create,
  617. &t_exit,
  618. &t_kernel,
  619. &t_user)) {
  620. li.LowPart = t_user.dwLowDateTime;
  621. li.HighPart = t_user.dwHighDateTime;
  622. li2.LowPart = t_kernel.dwLowDateTime;
  623. li2.HighPart = t_kernel.dwHighDateTime;
  624. li.QuadPart += li2.QuadPart;
  625. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  626. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  627. ok = TRUE;
  628. }
  629. /* END: CLOCK_THREAD */
  630. } else if (clk_id == CLOCK_PROCESS) {
  631. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  632. FILETIME t_create, t_exit, t_kernel, t_user;
  633. if (GetProcessTimes(GetCurrentProcess(),
  634. &t_create,
  635. &t_exit,
  636. &t_kernel,
  637. &t_user)) {
  638. li.LowPart = t_user.dwLowDateTime;
  639. li.HighPart = t_user.dwHighDateTime;
  640. li2.LowPart = t_kernel.dwLowDateTime;
  641. li2.HighPart = t_kernel.dwHighDateTime;
  642. li.QuadPart += li2.QuadPart;
  643. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  644. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  645. ok = TRUE;
  646. }
  647. /* END: CLOCK_PROCESS */
  648. } else {
  649. /* BEGIN: unknown clock */
  650. /* ok = FALSE; already set by init */
  651. /* END: unknown clock */
  652. }
  653. }
  654. return ok ? 0 : -1;
  655. }
  656. #endif
  657. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  658. static int pthread_mutex_lock(pthread_mutex_t *);
  659. static int pthread_mutex_unlock(pthread_mutex_t *);
  660. static void path_to_unicode(const struct mg_connection *conn,
  661. const char *path,
  662. wchar_t *wbuf,
  663. size_t wbuf_len);
  664. /* All file operations need to be rewritten to solve #246. */
  665. struct mg_file;
  666. static const char *
  667. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  668. /* POSIX dirent interface */
  669. struct dirent {
  670. char d_name[PATH_MAX];
  671. };
  672. typedef struct DIR {
  673. HANDLE handle;
  674. WIN32_FIND_DATAW info;
  675. struct dirent result;
  676. } DIR;
  677. #if defined(HAVE_POLL)
  678. #define mg_pollfd pollfd
  679. #else
  680. struct mg_pollfd {
  681. SOCKET fd;
  682. short events;
  683. short revents;
  684. };
  685. #endif
  686. /* Mark required libraries */
  687. #if defined(_MSC_VER)
  688. #pragma comment(lib, "Ws2_32.lib")
  689. #endif
  690. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  691. #include <inttypes.h>
  692. typedef const void *SOCK_OPT_TYPE;
  693. #if defined(ANDROID)
  694. typedef unsigned short int in_port_t;
  695. #endif
  696. #if !defined(__ZEPHYR__)
  697. #include <arpa/inet.h>
  698. #include <ctype.h>
  699. #include <dirent.h>
  700. #include <grp.h>
  701. #include <limits.h>
  702. #include <netdb.h>
  703. #include <netinet/in.h>
  704. #include <netinet/tcp.h>
  705. #include <pthread.h>
  706. #include <pwd.h>
  707. #include <stdarg.h>
  708. #include <stddef.h>
  709. #include <stdio.h>
  710. #include <stdlib.h>
  711. #include <string.h>
  712. #include <sys/poll.h>
  713. #include <sys/socket.h>
  714. #include <sys/time.h>
  715. #include <sys/utsname.h>
  716. #include <sys/wait.h>
  717. #include <time.h>
  718. #include <unistd.h>
  719. #endif
  720. #define vsnprintf_impl vsnprintf
  721. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  722. #include <dlfcn.h>
  723. #endif
  724. #if defined(__MACH__)
  725. #define SSL_LIB "libssl.dylib"
  726. #define CRYPTO_LIB "libcrypto.dylib"
  727. #else
  728. #if !defined(SSL_LIB)
  729. #define SSL_LIB "libssl.so"
  730. #endif
  731. #if !defined(CRYPTO_LIB)
  732. #define CRYPTO_LIB "libcrypto.so"
  733. #endif
  734. #endif
  735. #if !defined(O_BINARY)
  736. #define O_BINARY (0)
  737. #endif /* O_BINARY */
  738. #define closesocket(a) (close(a))
  739. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  740. #define mg_remove(conn, x) (remove(x))
  741. #define mg_sleep(x) (usleep((x)*1000))
  742. #define mg_opendir(conn, x) (opendir(x))
  743. #define mg_closedir(x) (closedir(x))
  744. #define mg_readdir(x) (readdir(x))
  745. #define ERRNO (errno)
  746. #define INVALID_SOCKET (-1)
  747. #define INT64_FMT PRId64
  748. #define UINT64_FMT PRIu64
  749. typedef int SOCKET;
  750. #define WINCDECL
  751. #if defined(__hpux)
  752. /* HPUX 11 does not have monotonic, fall back to realtime */
  753. #if !defined(CLOCK_MONOTONIC)
  754. #define CLOCK_MONOTONIC CLOCK_REALTIME
  755. #endif
  756. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  757. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  758. * the prototypes use int* rather than socklen_t* which matches the
  759. * actual library expectation. When called with the wrong size arg
  760. * accept() returns a zero client inet addr and check_acl() always
  761. * fails. Since socklen_t is widely used below, just force replace
  762. * their typedef with int. - DTL
  763. */
  764. #define socklen_t int
  765. #endif /* hpux */
  766. #define mg_pollfd pollfd
  767. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  768. /* In case our C library is missing "timegm", provide an implementation */
  769. #if defined(NEED_TIMEGM)
  770. static inline int
  771. is_leap(int y)
  772. {
  773. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  774. }
  775. static inline int
  776. count_leap(int y)
  777. {
  778. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  779. }
  780. time_t
  781. timegm(struct tm *tm)
  782. {
  783. static const unsigned short ydays[] = {
  784. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  785. int year = tm->tm_year + 1900;
  786. int mon = tm->tm_mon;
  787. int mday = tm->tm_mday - 1;
  788. int hour = tm->tm_hour;
  789. int min = tm->tm_min;
  790. int sec = tm->tm_sec;
  791. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  792. || (mday >= ydays[mon + 1] - ydays[mon]
  793. + (mon == 1 && is_leap(year) ? 1 : 0))
  794. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  795. return -1;
  796. time_t res = year - 1970;
  797. res *= 365;
  798. res += mday;
  799. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  800. res += count_leap(year);
  801. res *= 24;
  802. res += hour;
  803. res *= 60;
  804. res += min;
  805. res *= 60;
  806. res += sec;
  807. return res;
  808. }
  809. #endif /* NEED_TIMEGM */
  810. /* va_copy should always be a macro, C99 and C++11 - DTL */
  811. #if !defined(va_copy)
  812. #define va_copy(x, y) ((x) = (y))
  813. #endif
  814. #if defined(_WIN32)
  815. /* Create substitutes for POSIX functions in Win32. */
  816. #if defined(GCC_DIAGNOSTIC)
  817. /* Show no warning in case system functions are not used. */
  818. #pragma GCC diagnostic push
  819. #pragma GCC diagnostic ignored "-Wunused-function"
  820. #endif
  821. static pthread_mutex_t global_log_file_lock;
  822. FUNCTION_MAY_BE_UNUSED
  823. static DWORD
  824. pthread_self(void)
  825. {
  826. return GetCurrentThreadId();
  827. }
  828. FUNCTION_MAY_BE_UNUSED
  829. static int
  830. pthread_key_create(
  831. pthread_key_t *key,
  832. void (*_ignored)(void *) /* destructor not supported for Windows */
  833. )
  834. {
  835. (void)_ignored;
  836. if ((key != 0)) {
  837. *key = TlsAlloc();
  838. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  839. }
  840. return -2;
  841. }
  842. FUNCTION_MAY_BE_UNUSED
  843. static int
  844. pthread_key_delete(pthread_key_t key)
  845. {
  846. return TlsFree(key) ? 0 : 1;
  847. }
  848. FUNCTION_MAY_BE_UNUSED
  849. static int
  850. pthread_setspecific(pthread_key_t key, void *value)
  851. {
  852. return TlsSetValue(key, value) ? 0 : 1;
  853. }
  854. FUNCTION_MAY_BE_UNUSED
  855. static void *
  856. pthread_getspecific(pthread_key_t key)
  857. {
  858. return TlsGetValue(key);
  859. }
  860. #if defined(GCC_DIAGNOSTIC)
  861. /* Enable unused function warning again */
  862. #pragma GCC diagnostic pop
  863. #endif
  864. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  865. #else
  866. static pthread_mutexattr_t pthread_mutex_attr;
  867. #endif /* _WIN32 */
  868. #if defined(_WIN32_WCE)
  869. /* Create substitutes for POSIX functions in Win32. */
  870. #if defined(GCC_DIAGNOSTIC)
  871. /* Show no warning in case system functions are not used. */
  872. #pragma GCC diagnostic push
  873. #pragma GCC diagnostic ignored "-Wunused-function"
  874. #endif
  875. FUNCTION_MAY_BE_UNUSED
  876. static time_t
  877. time(time_t *ptime)
  878. {
  879. time_t t;
  880. SYSTEMTIME st;
  881. FILETIME ft;
  882. GetSystemTime(&st);
  883. SystemTimeToFileTime(&st, &ft);
  884. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  885. if (ptime != NULL) {
  886. *ptime = t;
  887. }
  888. return t;
  889. }
  890. FUNCTION_MAY_BE_UNUSED
  891. static struct tm *
  892. localtime_s(const time_t *ptime, struct tm *ptm)
  893. {
  894. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  895. FILETIME ft, lft;
  896. SYSTEMTIME st;
  897. TIME_ZONE_INFORMATION tzinfo;
  898. if (ptm == NULL) {
  899. return NULL;
  900. }
  901. *(int64_t *)&ft = t;
  902. FileTimeToLocalFileTime(&ft, &lft);
  903. FileTimeToSystemTime(&lft, &st);
  904. ptm->tm_year = st.wYear - 1900;
  905. ptm->tm_mon = st.wMonth - 1;
  906. ptm->tm_wday = st.wDayOfWeek;
  907. ptm->tm_mday = st.wDay;
  908. ptm->tm_hour = st.wHour;
  909. ptm->tm_min = st.wMinute;
  910. ptm->tm_sec = st.wSecond;
  911. ptm->tm_yday = 0; /* hope nobody uses this */
  912. ptm->tm_isdst =
  913. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  914. return ptm;
  915. }
  916. FUNCTION_MAY_BE_UNUSED
  917. static struct tm *
  918. gmtime_s(const time_t *ptime, struct tm *ptm)
  919. {
  920. /* FIXME(lsm): fix this. */
  921. return localtime_s(ptime, ptm);
  922. }
  923. static int mg_atomic_inc(volatile int *addr);
  924. static struct tm tm_array[MAX_WORKER_THREADS];
  925. static int tm_index = 0;
  926. FUNCTION_MAY_BE_UNUSED
  927. static struct tm *
  928. localtime(const time_t *ptime)
  929. {
  930. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  931. return localtime_s(ptime, tm_array + i);
  932. }
  933. FUNCTION_MAY_BE_UNUSED
  934. static struct tm *
  935. gmtime(const time_t *ptime)
  936. {
  937. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  938. return gmtime_s(ptime, tm_array + i);
  939. }
  940. FUNCTION_MAY_BE_UNUSED
  941. static size_t
  942. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  943. {
  944. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  945. * for WinCE"); */
  946. return 0;
  947. }
  948. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  949. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  950. #define remove(f) mg_remove(NULL, f)
  951. FUNCTION_MAY_BE_UNUSED
  952. static int
  953. rename(const char *a, const char *b)
  954. {
  955. wchar_t wa[W_PATH_MAX];
  956. wchar_t wb[W_PATH_MAX];
  957. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  958. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  959. return MoveFileW(wa, wb) ? 0 : -1;
  960. }
  961. struct stat {
  962. int64_t st_size;
  963. time_t st_mtime;
  964. };
  965. FUNCTION_MAY_BE_UNUSED
  966. static int
  967. stat(const char *name, struct stat *st)
  968. {
  969. wchar_t wbuf[W_PATH_MAX];
  970. WIN32_FILE_ATTRIBUTE_DATA attr;
  971. time_t creation_time, write_time;
  972. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  973. memset(&attr, 0, sizeof(attr));
  974. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  975. st->st_size =
  976. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  977. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  978. attr.ftLastWriteTime.dwHighDateTime);
  979. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  980. attr.ftCreationTime.dwHighDateTime);
  981. if (creation_time > write_time) {
  982. st->st_mtime = creation_time;
  983. } else {
  984. st->st_mtime = write_time;
  985. }
  986. return 0;
  987. }
  988. #define access(x, a) 1 /* not required anyway */
  989. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  990. /* Values from errno.h in Windows SDK (Visual Studio). */
  991. #define EEXIST 17
  992. #define EACCES 13
  993. #define ENOENT 2
  994. #if defined(GCC_DIAGNOSTIC)
  995. /* Enable unused function warning again */
  996. #pragma GCC diagnostic pop
  997. #endif
  998. #endif /* defined(_WIN32_WCE) */
  999. #if defined(GCC_DIAGNOSTIC)
  1000. /* Show no warning in case system functions are not used. */
  1001. #pragma GCC diagnostic push
  1002. #pragma GCC diagnostic ignored "-Wunused-function"
  1003. #endif /* defined(GCC_DIAGNOSTIC) */
  1004. #if defined(__clang__)
  1005. /* Show no warning in case system functions are not used. */
  1006. #pragma clang diagnostic push
  1007. #pragma clang diagnostic ignored "-Wunused-function"
  1008. #endif
  1009. static pthread_mutex_t global_lock_mutex;
  1010. FUNCTION_MAY_BE_UNUSED
  1011. static void
  1012. mg_global_lock(void)
  1013. {
  1014. (void)pthread_mutex_lock(&global_lock_mutex);
  1015. }
  1016. FUNCTION_MAY_BE_UNUSED
  1017. static void
  1018. mg_global_unlock(void)
  1019. {
  1020. (void)pthread_mutex_unlock(&global_lock_mutex);
  1021. }
  1022. FUNCTION_MAY_BE_UNUSED
  1023. static int
  1024. mg_atomic_inc(volatile int *addr)
  1025. {
  1026. int ret;
  1027. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1028. /* Depending on the SDK, this function uses either
  1029. * (volatile unsigned int *) or (volatile LONG *),
  1030. * so whatever you use, the other SDK is likely to raise a warning. */
  1031. ret = InterlockedIncrement((volatile long *)addr);
  1032. #elif defined(__GNUC__) \
  1033. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1034. && !defined(NO_ATOMICS)
  1035. ret = __sync_add_and_fetch(addr, 1);
  1036. #else
  1037. mg_global_lock();
  1038. ret = (++(*addr));
  1039. mg_global_unlock();
  1040. #endif
  1041. return ret;
  1042. }
  1043. FUNCTION_MAY_BE_UNUSED
  1044. static int
  1045. mg_atomic_dec(volatile int *addr)
  1046. {
  1047. int ret;
  1048. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1049. /* Depending on the SDK, this function uses either
  1050. * (volatile unsigned int *) or (volatile LONG *),
  1051. * so whatever you use, the other SDK is likely to raise a warning. */
  1052. ret = InterlockedDecrement((volatile long *)addr);
  1053. #elif defined(__GNUC__) \
  1054. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1055. && !defined(NO_ATOMICS)
  1056. ret = __sync_sub_and_fetch(addr, 1);
  1057. #else
  1058. mg_global_lock();
  1059. ret = (--(*addr));
  1060. mg_global_unlock();
  1061. #endif
  1062. return ret;
  1063. }
  1064. #if defined(USE_SERVER_STATS)
  1065. static int64_t
  1066. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1067. {
  1068. int64_t ret;
  1069. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1070. ret = InterlockedAdd64(addr, value);
  1071. #elif defined(__GNUC__) \
  1072. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1073. && !defined(NO_ATOMICS)
  1074. ret = __sync_add_and_fetch(addr, value);
  1075. #else
  1076. mg_global_lock();
  1077. *addr += value;
  1078. ret = (*addr);
  1079. mg_global_unlock();
  1080. #endif
  1081. return ret;
  1082. }
  1083. #endif
  1084. #if defined(GCC_DIAGNOSTIC)
  1085. /* Show no warning in case system functions are not used. */
  1086. #pragma GCC diagnostic pop
  1087. #endif /* defined(GCC_DIAGNOSTIC) */
  1088. #if defined(__clang__)
  1089. /* Show no warning in case system functions are not used. */
  1090. #pragma clang diagnostic pop
  1091. #endif
  1092. #if defined(USE_SERVER_STATS)
  1093. struct mg_memory_stat {
  1094. volatile int64_t totalMemUsed;
  1095. volatile int64_t maxMemUsed;
  1096. volatile int blockCount;
  1097. };
  1098. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1099. static void *
  1100. mg_malloc_ex(size_t size,
  1101. struct mg_context *ctx,
  1102. const char *file,
  1103. unsigned line)
  1104. {
  1105. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1106. void *memory = 0;
  1107. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1108. #if defined(MEMORY_DEBUGGING)
  1109. char mallocStr[256];
  1110. #else
  1111. (void)file;
  1112. (void)line;
  1113. #endif
  1114. if (data) {
  1115. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1116. if (mmem > mstat->maxMemUsed) {
  1117. /* could use atomic compare exchange, but this
  1118. * seems overkill for statistics data */
  1119. mstat->maxMemUsed = mmem;
  1120. }
  1121. mg_atomic_inc(&mstat->blockCount);
  1122. ((uintptr_t *)data)[0] = size;
  1123. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1124. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1125. }
  1126. #if defined(MEMORY_DEBUGGING)
  1127. sprintf(mallocStr,
  1128. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1129. memory,
  1130. (unsigned long)size,
  1131. (unsigned long)mstat->totalMemUsed,
  1132. (unsigned long)mstat->blockCount,
  1133. file,
  1134. line);
  1135. #if defined(_WIN32)
  1136. OutputDebugStringA(mallocStr);
  1137. #else
  1138. DEBUG_TRACE("%s", mallocStr);
  1139. #endif
  1140. #endif
  1141. return memory;
  1142. }
  1143. static void *
  1144. mg_calloc_ex(size_t count,
  1145. size_t size,
  1146. struct mg_context *ctx,
  1147. const char *file,
  1148. unsigned line)
  1149. {
  1150. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1151. if (data) {
  1152. memset(data, 0, size * count);
  1153. }
  1154. return data;
  1155. }
  1156. static void
  1157. mg_free_ex(void *memory, const char *file, unsigned line)
  1158. {
  1159. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1160. #if defined(MEMORY_DEBUGGING)
  1161. char mallocStr[256];
  1162. #else
  1163. (void)file;
  1164. (void)line;
  1165. #endif
  1166. if (memory) {
  1167. uintptr_t size = ((uintptr_t *)data)[0];
  1168. struct mg_memory_stat *mstat =
  1169. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1170. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1171. mg_atomic_dec(&mstat->blockCount);
  1172. #if defined(MEMORY_DEBUGGING)
  1173. sprintf(mallocStr,
  1174. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1175. memory,
  1176. (unsigned long)size,
  1177. (unsigned long)mstat->totalMemUsed,
  1178. (unsigned long)mstat->blockCount,
  1179. file,
  1180. line);
  1181. #if defined(_WIN32)
  1182. OutputDebugStringA(mallocStr);
  1183. #else
  1184. DEBUG_TRACE("%s", mallocStr);
  1185. #endif
  1186. #endif
  1187. free(data);
  1188. }
  1189. }
  1190. static void *
  1191. mg_realloc_ex(void *memory,
  1192. size_t newsize,
  1193. struct mg_context *ctx,
  1194. const char *file,
  1195. unsigned line)
  1196. {
  1197. void *data;
  1198. void *_realloc;
  1199. uintptr_t oldsize;
  1200. #if defined(MEMORY_DEBUGGING)
  1201. char mallocStr[256];
  1202. #else
  1203. (void)file;
  1204. (void)line;
  1205. #endif
  1206. if (newsize) {
  1207. if (memory) {
  1208. /* Reallocate existing block */
  1209. struct mg_memory_stat *mstat;
  1210. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1211. oldsize = ((uintptr_t *)data)[0];
  1212. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1213. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1214. if (_realloc) {
  1215. data = _realloc;
  1216. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1217. #if defined(MEMORY_DEBUGGING)
  1218. sprintf(mallocStr,
  1219. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1220. memory,
  1221. (unsigned long)oldsize,
  1222. (unsigned long)mstat->totalMemUsed,
  1223. (unsigned long)mstat->blockCount,
  1224. file,
  1225. line);
  1226. #if defined(_WIN32)
  1227. OutputDebugStringA(mallocStr);
  1228. #else
  1229. DEBUG_TRACE("%s", mallocStr);
  1230. #endif
  1231. #endif
  1232. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1233. #if defined(MEMORY_DEBUGGING)
  1234. sprintf(mallocStr,
  1235. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1236. memory,
  1237. (unsigned long)newsize,
  1238. (unsigned long)mstat->totalMemUsed,
  1239. (unsigned long)mstat->blockCount,
  1240. file,
  1241. line);
  1242. #if defined(_WIN32)
  1243. OutputDebugStringA(mallocStr);
  1244. #else
  1245. DEBUG_TRACE("%s", mallocStr);
  1246. #endif
  1247. #endif
  1248. *(uintptr_t *)data = newsize;
  1249. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1250. } else {
  1251. #if defined(MEMORY_DEBUGGING)
  1252. #if defined(_WIN32)
  1253. OutputDebugStringA("MEM: realloc failed\n");
  1254. #else
  1255. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1256. #endif
  1257. #endif
  1258. return _realloc;
  1259. }
  1260. } else {
  1261. /* Allocate new block */
  1262. data = mg_malloc_ex(newsize, ctx, file, line);
  1263. }
  1264. } else {
  1265. /* Free existing block */
  1266. data = 0;
  1267. mg_free_ex(memory, file, line);
  1268. }
  1269. return data;
  1270. }
  1271. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1272. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1273. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1274. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1275. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1276. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1277. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1278. #else /* USE_SERVER_STATS */
  1279. static __inline void *
  1280. mg_malloc(size_t a)
  1281. {
  1282. return malloc(a);
  1283. }
  1284. static __inline void *
  1285. mg_calloc(size_t a, size_t b)
  1286. {
  1287. return calloc(a, b);
  1288. }
  1289. static __inline void *
  1290. mg_realloc(void *a, size_t b)
  1291. {
  1292. return realloc(a, b);
  1293. }
  1294. static __inline void
  1295. mg_free(void *a)
  1296. {
  1297. free(a);
  1298. }
  1299. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1300. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1301. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1302. #define mg_free_ctx(a, c) mg_free(a)
  1303. #endif /* USE_SERVER_STATS */
  1304. static void mg_vsnprintf(const struct mg_connection *conn,
  1305. int *truncated,
  1306. char *buf,
  1307. size_t buflen,
  1308. const char *fmt,
  1309. va_list ap);
  1310. static void mg_snprintf(const struct mg_connection *conn,
  1311. int *truncated,
  1312. char *buf,
  1313. size_t buflen,
  1314. PRINTF_FORMAT_STRING(const char *fmt),
  1315. ...) PRINTF_ARGS(5, 6);
  1316. /* This following lines are just meant as a reminder to use the mg-functions
  1317. * for memory management */
  1318. #if defined(malloc)
  1319. #undef malloc
  1320. #endif
  1321. #if defined(calloc)
  1322. #undef calloc
  1323. #endif
  1324. #if defined(realloc)
  1325. #undef realloc
  1326. #endif
  1327. #if defined(free)
  1328. #undef free
  1329. #endif
  1330. #if defined(snprintf)
  1331. #undef snprintf
  1332. #endif
  1333. #if defined(vsnprintf)
  1334. #undef vsnprintf
  1335. #endif
  1336. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1337. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1338. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1339. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1340. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1341. #if defined(_WIN32)
  1342. /* vsnprintf must not be used in any system,
  1343. * but this define only works well for Windows. */
  1344. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1345. #endif
  1346. /* mg_init_library counter */
  1347. static int mg_init_library_called = 0;
  1348. #if !defined(NO_SSL)
  1349. static int mg_ssl_initialized = 0;
  1350. #endif
  1351. static pthread_key_t sTlsKey; /* Thread local storage index */
  1352. static int thread_idx_max = 0;
  1353. #if defined(MG_LEGACY_INTERFACE)
  1354. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1355. #endif
  1356. struct mg_workerTLS {
  1357. int is_master;
  1358. unsigned long thread_idx;
  1359. void *user_ptr;
  1360. #if defined(_WIN32)
  1361. HANDLE pthread_cond_helper_mutex;
  1362. struct mg_workerTLS *next_waiting_thread;
  1363. #endif
  1364. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1365. char txtbuf[4];
  1366. #endif
  1367. };
  1368. #if defined(GCC_DIAGNOSTIC)
  1369. /* Show no warning in case system functions are not used. */
  1370. #pragma GCC diagnostic push
  1371. #pragma GCC diagnostic ignored "-Wunused-function"
  1372. #endif /* defined(GCC_DIAGNOSTIC) */
  1373. #if defined(__clang__)
  1374. /* Show no warning in case system functions are not used. */
  1375. #pragma clang diagnostic push
  1376. #pragma clang diagnostic ignored "-Wunused-function"
  1377. #endif
  1378. /* Get a unique thread ID as unsigned long, independent from the data type
  1379. * of thread IDs defined by the operating system API.
  1380. * If two calls to mg_current_thread_id return the same value, they calls
  1381. * are done from the same thread. If they return different values, they are
  1382. * done from different threads. (Provided this function is used in the same
  1383. * process context and threads are not repeatedly created and deleted, but
  1384. * CivetWeb does not do that).
  1385. * This function must match the signature required for SSL id callbacks:
  1386. * CRYPTO_set_id_callback
  1387. */
  1388. FUNCTION_MAY_BE_UNUSED
  1389. static unsigned long
  1390. mg_current_thread_id(void)
  1391. {
  1392. #if defined(_WIN32)
  1393. return GetCurrentThreadId();
  1394. #else
  1395. #if defined(__clang__)
  1396. #pragma clang diagnostic push
  1397. #pragma clang diagnostic ignored "-Wunreachable-code"
  1398. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1399. * or not, so one of the two conditions will be unreachable by construction.
  1400. * Unfortunately the C standard does not define a way to check this at
  1401. * compile time, since the #if preprocessor conditions can not use the sizeof
  1402. * operator as an argument. */
  1403. #endif
  1404. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1405. /* This is the problematic case for CRYPTO_set_id_callback:
  1406. * The OS pthread_t can not be cast to unsigned long. */
  1407. struct mg_workerTLS *tls =
  1408. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1409. if (tls == NULL) {
  1410. /* SSL called from an unknown thread: Create some thread index.
  1411. */
  1412. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1413. tls->is_master = -2; /* -2 means "3rd party thread" */
  1414. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1415. pthread_setspecific(sTlsKey, tls);
  1416. }
  1417. return tls->thread_idx;
  1418. } else {
  1419. /* pthread_t may be any data type, so a simple cast to unsigned long
  1420. * can rise a warning/error, depending on the platform.
  1421. * Here memcpy is used as an anything-to-anything cast. */
  1422. unsigned long ret = 0;
  1423. pthread_t t = pthread_self();
  1424. memcpy(&ret, &t, sizeof(pthread_t));
  1425. return ret;
  1426. }
  1427. #if defined(__clang__)
  1428. #pragma clang diagnostic pop
  1429. #endif
  1430. #endif
  1431. }
  1432. FUNCTION_MAY_BE_UNUSED
  1433. static uint64_t
  1434. mg_get_current_time_ns(void)
  1435. {
  1436. struct timespec tsnow;
  1437. clock_gettime(CLOCK_REALTIME, &tsnow);
  1438. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1439. }
  1440. #if defined(GCC_DIAGNOSTIC)
  1441. /* Show no warning in case system functions are not used. */
  1442. #pragma GCC diagnostic pop
  1443. #endif /* defined(GCC_DIAGNOSTIC) */
  1444. #if defined(__clang__)
  1445. /* Show no warning in case system functions are not used. */
  1446. #pragma clang diagnostic pop
  1447. #endif
  1448. #if defined(NEED_DEBUG_TRACE_FUNC)
  1449. static void
  1450. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1451. {
  1452. va_list args;
  1453. uint64_t nsnow;
  1454. static uint64_t nslast;
  1455. struct timespec tsnow;
  1456. /* Get some operating system independent thread id */
  1457. unsigned long thread_id = mg_current_thread_id();
  1458. clock_gettime(CLOCK_REALTIME, &tsnow);
  1459. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1460. + ((uint64_t)tsnow.tv_nsec);
  1461. if (!nslast) {
  1462. nslast = nsnow;
  1463. }
  1464. flockfile(DEBUG_TRACE_STREAM);
  1465. fprintf(DEBUG_TRACE_STREAM,
  1466. "*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1467. (unsigned long)tsnow.tv_sec,
  1468. (unsigned long)tsnow.tv_nsec,
  1469. nsnow - nslast,
  1470. thread_id,
  1471. func,
  1472. line);
  1473. va_start(args, fmt);
  1474. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1475. va_end(args);
  1476. putc('\n', DEBUG_TRACE_STREAM);
  1477. fflush(DEBUG_TRACE_STREAM);
  1478. funlockfile(DEBUG_TRACE_STREAM);
  1479. nslast = nsnow;
  1480. }
  1481. #endif /* NEED_DEBUG_TRACE_FUNC */
  1482. #define MD5_STATIC static
  1483. #include "md5.inl"
  1484. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1485. #if defined(NO_SOCKLEN_T)
  1486. typedef int socklen_t;
  1487. #endif /* NO_SOCKLEN_T */
  1488. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1489. #if !defined(MSG_NOSIGNAL)
  1490. #define MSG_NOSIGNAL (0)
  1491. #endif
  1492. #if defined(NO_SSL)
  1493. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1494. typedef struct SSL_CTX SSL_CTX;
  1495. #else
  1496. #if defined(NO_SSL_DL)
  1497. #include <openssl/bn.h>
  1498. #include <openssl/conf.h>
  1499. #include <openssl/crypto.h>
  1500. #include <openssl/dh.h>
  1501. #include <openssl/engine.h>
  1502. #include <openssl/err.h>
  1503. #include <openssl/opensslv.h>
  1504. #include <openssl/pem.h>
  1505. #include <openssl/ssl.h>
  1506. #include <openssl/tls1.h>
  1507. #include <openssl/x509.h>
  1508. #if defined(WOLFSSL_VERSION)
  1509. /* Additional defines for WolfSSL, see
  1510. * https://github.com/civetweb/civetweb/issues/583 */
  1511. #include "wolfssl_extras.inl"
  1512. #endif
  1513. #if defined(OPENSSL_IS_BORINGSSL)
  1514. /* From boringssl/src/include/openssl/mem.h:
  1515. *
  1516. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1517. * However, that was written in a time before Valgrind and ASAN. Since we now
  1518. * have those tools, the OpenSSL allocation functions are simply macros around
  1519. * the standard memory functions.
  1520. *
  1521. * #define OPENSSL_free free */
  1522. #define free free
  1523. // disable for boringssl
  1524. #define CONF_modules_unload(a) ((void)0)
  1525. #define ENGINE_cleanup() ((void)0)
  1526. #endif
  1527. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1528. /* If OpenSSL headers are included, automatically select the API version */
  1529. #if !defined(OPENSSL_API_1_1)
  1530. #define OPENSSL_API_1_1
  1531. #endif
  1532. #define OPENSSL_REMOVE_THREAD_STATE()
  1533. #else
  1534. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1535. #endif
  1536. #else
  1537. /* SSL loaded dynamically from DLL.
  1538. * I put the prototypes here to be independent from OpenSSL source
  1539. * installation. */
  1540. typedef struct ssl_st SSL;
  1541. typedef struct ssl_method_st SSL_METHOD;
  1542. typedef struct ssl_ctx_st SSL_CTX;
  1543. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1544. typedef struct x509_name X509_NAME;
  1545. typedef struct asn1_integer ASN1_INTEGER;
  1546. typedef struct bignum BIGNUM;
  1547. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1548. typedef struct evp_md EVP_MD;
  1549. typedef struct x509 X509;
  1550. #define SSL_CTRL_OPTIONS (32)
  1551. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1552. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1553. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1554. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1555. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1556. #define SSL_VERIFY_NONE (0)
  1557. #define SSL_VERIFY_PEER (1)
  1558. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1559. #define SSL_VERIFY_CLIENT_ONCE (4)
  1560. #define SSL_OP_ALL (0x80000BFFul)
  1561. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1562. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1563. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1564. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1565. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1566. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1567. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1568. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1569. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1570. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1571. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1572. #define SSL_CB_HANDSHAKE_START (0x10)
  1573. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1574. #define SSL_ERROR_NONE (0)
  1575. #define SSL_ERROR_SSL (1)
  1576. #define SSL_ERROR_WANT_READ (2)
  1577. #define SSL_ERROR_WANT_WRITE (3)
  1578. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1579. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1580. #define SSL_ERROR_ZERO_RETURN (6)
  1581. #define SSL_ERROR_WANT_CONNECT (7)
  1582. #define SSL_ERROR_WANT_ACCEPT (8)
  1583. #define TLSEXT_TYPE_server_name (0)
  1584. #define TLSEXT_NAMETYPE_host_name (0)
  1585. #define SSL_TLSEXT_ERR_OK (0)
  1586. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1587. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1588. #define SSL_TLSEXT_ERR_NOACK (3)
  1589. struct ssl_func {
  1590. const char *name; /* SSL function name */
  1591. void (*ptr)(void); /* Function pointer */
  1592. };
  1593. #if defined(OPENSSL_API_1_1)
  1594. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1595. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1596. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1597. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1598. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1599. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1600. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1601. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1602. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1603. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1604. #define OPENSSL_init_ssl \
  1605. (*(int (*)(uint64_t opts, \
  1606. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1607. .ptr)
  1608. #define SSL_CTX_use_PrivateKey_file \
  1609. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1610. #define SSL_CTX_use_certificate_file \
  1611. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1612. #define SSL_CTX_set_default_passwd_cb \
  1613. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1614. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1615. #define SSL_CTX_use_certificate_chain_file \
  1616. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1617. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1618. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1619. #define SSL_CTX_set_verify \
  1620. (*(void (*)(SSL_CTX *, \
  1621. int, \
  1622. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1623. .ptr)
  1624. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1625. #define SSL_CTX_load_verify_locations \
  1626. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1627. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1628. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1629. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1630. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1631. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1632. #define SSL_CIPHER_get_name \
  1633. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1634. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1635. #define SSL_CTX_set_session_id_context \
  1636. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1637. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1638. #define SSL_CTX_set_cipher_list \
  1639. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1640. #define SSL_CTX_set_options \
  1641. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1642. #define SSL_CTX_set_info_callback \
  1643. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1644. ssl_sw[32] \
  1645. .ptr)
  1646. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1647. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1648. #define SSL_CTX_callback_ctrl \
  1649. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1650. #define SSL_get_servername \
  1651. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1652. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1653. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1654. #define SSL_CTX_set_alpn_protos \
  1655. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1656. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1657. const unsigned char **out,
  1658. unsigned char *outlen,
  1659. const unsigned char *in,
  1660. unsigned int inlen,
  1661. void *arg);
  1662. #define SSL_CTX_set_alpn_select_cb \
  1663. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1664. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1665. const unsigned char **out,
  1666. unsigned int *outlen,
  1667. void *arg);
  1668. #define SSL_CTX_set_next_protos_advertised_cb \
  1669. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1670. .ptr)
  1671. #define SSL_CTX_clear_options(ctx, op) \
  1672. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1673. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1674. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1675. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1676. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1677. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1678. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1679. SSL_CTX_callback_ctrl(ctx, \
  1680. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1681. (void (*)(void))cb)
  1682. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1683. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1684. #define SSL_set_tlsext_host_name(ctx, arg) \
  1685. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1686. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1687. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1688. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1689. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1690. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1691. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1692. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1693. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1694. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1695. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1696. #define X509_NAME_oneline \
  1697. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1698. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1699. #define EVP_get_digestbyname \
  1700. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1701. #define EVP_Digest \
  1702. (*(int (*)( \
  1703. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1704. crypto_sw[9] \
  1705. .ptr)
  1706. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1707. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1708. #define ASN1_INTEGER_to_BN \
  1709. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1710. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1711. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1712. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1713. #define OPENSSL_free(a) CRYPTO_free(a)
  1714. #define OPENSSL_REMOVE_THREAD_STATE()
  1715. /* init_ssl_ctx() function updates this array.
  1716. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1717. * of respective functions. The macros above (like SSL_connect()) are really
  1718. * just calling these functions indirectly via the pointer. */
  1719. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1720. {"SSL_accept", NULL},
  1721. {"SSL_connect", NULL},
  1722. {"SSL_read", NULL},
  1723. {"SSL_write", NULL},
  1724. {"SSL_get_error", NULL},
  1725. {"SSL_set_fd", NULL},
  1726. {"SSL_new", NULL},
  1727. {"SSL_CTX_new", NULL},
  1728. {"TLS_server_method", NULL},
  1729. {"OPENSSL_init_ssl", NULL},
  1730. {"SSL_CTX_use_PrivateKey_file", NULL},
  1731. {"SSL_CTX_use_certificate_file", NULL},
  1732. {"SSL_CTX_set_default_passwd_cb", NULL},
  1733. {"SSL_CTX_free", NULL},
  1734. {"SSL_CTX_use_certificate_chain_file", NULL},
  1735. {"TLS_client_method", NULL},
  1736. {"SSL_pending", NULL},
  1737. {"SSL_CTX_set_verify", NULL},
  1738. {"SSL_shutdown", NULL},
  1739. {"SSL_CTX_load_verify_locations", NULL},
  1740. {"SSL_CTX_set_default_verify_paths", NULL},
  1741. {"SSL_CTX_set_verify_depth", NULL},
  1742. {"SSL_get_peer_certificate", NULL},
  1743. {"SSL_get_version", NULL},
  1744. {"SSL_get_current_cipher", NULL},
  1745. {"SSL_CIPHER_get_name", NULL},
  1746. {"SSL_CTX_check_private_key", NULL},
  1747. {"SSL_CTX_set_session_id_context", NULL},
  1748. {"SSL_CTX_ctrl", NULL},
  1749. {"SSL_CTX_set_cipher_list", NULL},
  1750. {"SSL_CTX_set_options", NULL},
  1751. {"SSL_CTX_set_info_callback", NULL},
  1752. {"SSL_get_ex_data", NULL},
  1753. {"SSL_set_ex_data", NULL},
  1754. {"SSL_CTX_callback_ctrl", NULL},
  1755. {"SSL_get_servername", NULL},
  1756. {"SSL_set_SSL_CTX", NULL},
  1757. {"SSL_ctrl", NULL},
  1758. {"SSL_CTX_set_alpn_protos", NULL},
  1759. {"SSL_CTX_set_alpn_select_cb", NULL},
  1760. {"SSL_CTX_set_next_protos_advertised_cb",
  1761. NULL},
  1762. {NULL, NULL}};
  1763. /* Similar array as ssl_sw. These functions could be located in different
  1764. * lib. */
  1765. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1766. {"ERR_error_string", NULL},
  1767. {"CONF_modules_unload", NULL},
  1768. {"X509_free", NULL},
  1769. {"X509_get_subject_name", NULL},
  1770. {"X509_get_issuer_name", NULL},
  1771. {"X509_NAME_oneline", NULL},
  1772. {"X509_get_serialNumber", NULL},
  1773. {"EVP_get_digestbyname", NULL},
  1774. {"EVP_Digest", NULL},
  1775. {"i2d_X509", NULL},
  1776. {"BN_bn2hex", NULL},
  1777. {"ASN1_INTEGER_to_BN", NULL},
  1778. {"BN_free", NULL},
  1779. {"CRYPTO_free", NULL},
  1780. {"ERR_clear_error", NULL},
  1781. {NULL, NULL}};
  1782. #else
  1783. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1784. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1785. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1786. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1787. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1788. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1789. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1790. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1791. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1792. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1793. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1794. #define SSL_CTX_use_PrivateKey_file \
  1795. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1796. #define SSL_CTX_use_certificate_file \
  1797. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1798. #define SSL_CTX_set_default_passwd_cb \
  1799. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1800. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1801. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1802. #define SSL_CTX_use_certificate_chain_file \
  1803. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1804. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1805. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1806. #define SSL_CTX_set_verify \
  1807. (*(void (*)(SSL_CTX *, \
  1808. int, \
  1809. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1810. .ptr)
  1811. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1812. #define SSL_CTX_load_verify_locations \
  1813. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1814. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1815. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1816. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1817. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1818. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1819. #define SSL_CIPHER_get_name \
  1820. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1821. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1822. #define SSL_CTX_set_session_id_context \
  1823. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1824. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1825. #define SSL_CTX_set_cipher_list \
  1826. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1827. #define SSL_CTX_set_info_callback \
  1828. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1829. .ptr)
  1830. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1831. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1832. #define SSL_CTX_callback_ctrl \
  1833. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1834. #define SSL_get_servername \
  1835. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1836. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1837. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1838. #define SSL_CTX_set_alpn_protos \
  1839. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1840. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1841. const unsigned char **out,
  1842. unsigned char *outlen,
  1843. const unsigned char *in,
  1844. unsigned int inlen,
  1845. void *arg);
  1846. #define SSL_CTX_set_alpn_select_cb \
  1847. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1848. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1849. const unsigned char **out,
  1850. unsigned int *outlen,
  1851. void *arg);
  1852. #define SSL_CTX_set_next_protos_advertised_cb \
  1853. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1854. .ptr)
  1855. #define SSL_CTX_set_options(ctx, op) \
  1856. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1857. #define SSL_CTX_clear_options(ctx, op) \
  1858. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1859. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1860. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1861. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1862. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1863. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1864. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1865. SSL_CTX_callback_ctrl(ctx, \
  1866. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1867. (void (*)(void))cb)
  1868. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1869. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1870. #define SSL_set_tlsext_host_name(ctx, arg) \
  1871. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1872. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1873. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1874. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1875. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1876. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1877. #define CRYPTO_set_locking_callback \
  1878. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1879. #define CRYPTO_set_id_callback \
  1880. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1881. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1882. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1883. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1884. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1885. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1886. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1887. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1888. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1889. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1890. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1891. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1892. #define X509_NAME_oneline \
  1893. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1894. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1895. #define i2c_ASN1_INTEGER \
  1896. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1897. #define EVP_get_digestbyname \
  1898. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1899. #define EVP_Digest \
  1900. (*(int (*)( \
  1901. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1902. crypto_sw[18] \
  1903. .ptr)
  1904. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1905. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1906. #define ASN1_INTEGER_to_BN \
  1907. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1908. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1909. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1910. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1911. #define OPENSSL_free(a) CRYPTO_free(a)
  1912. /* use here ERR_remove_state,
  1913. * while on some platforms function is not included into library due to
  1914. * deprication */
  1915. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1916. /* init_ssl_ctx() function updates this array.
  1917. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1918. * of respective functions. The macros above (like SSL_connect()) are really
  1919. * just calling these functions indirectly via the pointer. */
  1920. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1921. {"SSL_accept", NULL},
  1922. {"SSL_connect", NULL},
  1923. {"SSL_read", NULL},
  1924. {"SSL_write", NULL},
  1925. {"SSL_get_error", NULL},
  1926. {"SSL_set_fd", NULL},
  1927. {"SSL_new", NULL},
  1928. {"SSL_CTX_new", NULL},
  1929. {"SSLv23_server_method", NULL},
  1930. {"SSL_library_init", NULL},
  1931. {"SSL_CTX_use_PrivateKey_file", NULL},
  1932. {"SSL_CTX_use_certificate_file", NULL},
  1933. {"SSL_CTX_set_default_passwd_cb", NULL},
  1934. {"SSL_CTX_free", NULL},
  1935. {"SSL_load_error_strings", NULL},
  1936. {"SSL_CTX_use_certificate_chain_file", NULL},
  1937. {"SSLv23_client_method", NULL},
  1938. {"SSL_pending", NULL},
  1939. {"SSL_CTX_set_verify", NULL},
  1940. {"SSL_shutdown", NULL},
  1941. {"SSL_CTX_load_verify_locations", NULL},
  1942. {"SSL_CTX_set_default_verify_paths", NULL},
  1943. {"SSL_CTX_set_verify_depth", NULL},
  1944. {"SSL_get_peer_certificate", NULL},
  1945. {"SSL_get_version", NULL},
  1946. {"SSL_get_current_cipher", NULL},
  1947. {"SSL_CIPHER_get_name", NULL},
  1948. {"SSL_CTX_check_private_key", NULL},
  1949. {"SSL_CTX_set_session_id_context", NULL},
  1950. {"SSL_CTX_ctrl", NULL},
  1951. {"SSL_CTX_set_cipher_list", NULL},
  1952. {"SSL_CTX_set_info_callback", NULL},
  1953. {"SSL_get_ex_data", NULL},
  1954. {"SSL_set_ex_data", NULL},
  1955. {"SSL_CTX_callback_ctrl", NULL},
  1956. {"SSL_get_servername", NULL},
  1957. {"SSL_set_SSL_CTX", NULL},
  1958. {"SSL_ctrl", NULL},
  1959. {"SSL_CTX_set_alpn_protos", NULL},
  1960. {"SSL_CTX_set_alpn_select_cb", NULL},
  1961. {"SSL_CTX_set_next_protos_advertised_cb",
  1962. NULL},
  1963. {NULL, NULL}};
  1964. /* Similar array as ssl_sw. These functions could be located in different
  1965. * lib. */
  1966. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1967. {"CRYPTO_set_locking_callback", NULL},
  1968. {"CRYPTO_set_id_callback", NULL},
  1969. {"ERR_get_error", NULL},
  1970. {"ERR_error_string", NULL},
  1971. {"ERR_remove_state", NULL},
  1972. {"ERR_free_strings", NULL},
  1973. {"ENGINE_cleanup", NULL},
  1974. {"CONF_modules_unload", NULL},
  1975. {"CRYPTO_cleanup_all_ex_data", NULL},
  1976. {"EVP_cleanup", NULL},
  1977. {"X509_free", NULL},
  1978. {"X509_get_subject_name", NULL},
  1979. {"X509_get_issuer_name", NULL},
  1980. {"X509_NAME_oneline", NULL},
  1981. {"X509_get_serialNumber", NULL},
  1982. {"i2c_ASN1_INTEGER", NULL},
  1983. {"EVP_get_digestbyname", NULL},
  1984. {"EVP_Digest", NULL},
  1985. {"i2d_X509", NULL},
  1986. {"BN_bn2hex", NULL},
  1987. {"ASN1_INTEGER_to_BN", NULL},
  1988. {"BN_free", NULL},
  1989. {"CRYPTO_free", NULL},
  1990. {"ERR_clear_error", NULL},
  1991. {NULL, NULL}};
  1992. #endif /* OPENSSL_API_1_1 */
  1993. #endif /* NO_SSL_DL */
  1994. #endif /* NO_SSL */
  1995. #if !defined(NO_CACHING)
  1996. static const char month_names[][4] = {"Jan",
  1997. "Feb",
  1998. "Mar",
  1999. "Apr",
  2000. "May",
  2001. "Jun",
  2002. "Jul",
  2003. "Aug",
  2004. "Sep",
  2005. "Oct",
  2006. "Nov",
  2007. "Dec"};
  2008. #endif /* !NO_CACHING */
  2009. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2010. * the
  2011. * union u. */
  2012. union usa {
  2013. struct sockaddr sa;
  2014. struct sockaddr_in sin;
  2015. #if defined(USE_IPV6)
  2016. struct sockaddr_in6 sin6;
  2017. #endif
  2018. };
  2019. /* Describes a string (chunk of memory). */
  2020. struct vec {
  2021. const char *ptr;
  2022. size_t len;
  2023. };
  2024. struct mg_file_stat {
  2025. /* File properties filled by mg_stat: */
  2026. uint64_t size;
  2027. time_t last_modified;
  2028. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2029. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2030. * case we need a "Content-Eencoding: gzip" header */
  2031. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2032. };
  2033. struct mg_file_in_memory {
  2034. char *p;
  2035. uint32_t pos;
  2036. char mode;
  2037. };
  2038. struct mg_file_access {
  2039. /* File properties filled by mg_fopen: */
  2040. FILE *fp;
  2041. #if defined(MG_USE_OPEN_FILE)
  2042. /* TODO (low): Remove obsolete "file in memory" implementation.
  2043. * In an "early 2017" discussion at Google groups
  2044. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2045. * we decided to get rid of this feature (after some fade-out
  2046. * phase). */
  2047. const char *membuf;
  2048. #endif
  2049. };
  2050. struct mg_file {
  2051. struct mg_file_stat stat;
  2052. struct mg_file_access access;
  2053. };
  2054. #if defined(MG_USE_OPEN_FILE)
  2055. #define STRUCT_FILE_INITIALIZER \
  2056. { \
  2057. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2058. { \
  2059. (FILE *)NULL, (const char *)NULL \
  2060. } \
  2061. }
  2062. #else
  2063. #define STRUCT_FILE_INITIALIZER \
  2064. { \
  2065. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2066. { \
  2067. (FILE *)NULL \
  2068. } \
  2069. }
  2070. #endif
  2071. /* Describes listening socket, or socket which was accept()-ed by the master
  2072. * thread and queued for future handling by the worker thread. */
  2073. struct socket {
  2074. SOCKET sock; /* Listening socket */
  2075. union usa lsa; /* Local socket address */
  2076. union usa rsa; /* Remote socket address */
  2077. unsigned char is_ssl; /* Is port SSL-ed */
  2078. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2079. * port */
  2080. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2081. };
  2082. /* Enum const for all options must be in sync with
  2083. * static struct mg_option config_options[]
  2084. * This is tested in the unit test (test/private.c)
  2085. * "Private Config Options"
  2086. */
  2087. enum {
  2088. /* Once for each server */
  2089. LISTENING_PORTS,
  2090. NUM_THREADS,
  2091. RUN_AS_USER,
  2092. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2093. * socket option typedef TCP_NODELAY. */
  2094. MAX_REQUEST_SIZE,
  2095. LINGER_TIMEOUT,
  2096. CONNECTION_QUEUE_SIZE,
  2097. LISTEN_BACKLOG_SIZE,
  2098. #if defined(__linux__)
  2099. ALLOW_SENDFILE_CALL,
  2100. #endif
  2101. #if defined(_WIN32)
  2102. CASE_SENSITIVE_FILES,
  2103. #endif
  2104. THROTTLE,
  2105. ACCESS_LOG_FILE,
  2106. ERROR_LOG_FILE,
  2107. ENABLE_KEEP_ALIVE,
  2108. REQUEST_TIMEOUT,
  2109. KEEP_ALIVE_TIMEOUT,
  2110. #if defined(USE_WEBSOCKET)
  2111. WEBSOCKET_TIMEOUT,
  2112. ENABLE_WEBSOCKET_PING_PONG,
  2113. #endif
  2114. DECODE_URL,
  2115. #if defined(USE_LUA)
  2116. LUA_BACKGROUND_SCRIPT,
  2117. LUA_BACKGROUND_SCRIPT_PARAMS,
  2118. #endif
  2119. #if defined(USE_TIMERS)
  2120. CGI_TIMEOUT,
  2121. #endif
  2122. /* Once for each domain */
  2123. DOCUMENT_ROOT,
  2124. CGI_EXTENSIONS,
  2125. CGI_ENVIRONMENT,
  2126. PUT_DELETE_PASSWORDS_FILE,
  2127. CGI_INTERPRETER,
  2128. CGI_INTERPRETER_ARGS,
  2129. PROTECT_URI,
  2130. AUTHENTICATION_DOMAIN,
  2131. ENABLE_AUTH_DOMAIN_CHECK,
  2132. SSI_EXTENSIONS,
  2133. ENABLE_DIRECTORY_LISTING,
  2134. GLOBAL_PASSWORDS_FILE,
  2135. INDEX_FILES,
  2136. ACCESS_CONTROL_LIST,
  2137. EXTRA_MIME_TYPES,
  2138. SSL_CERTIFICATE,
  2139. SSL_CERTIFICATE_CHAIN,
  2140. URL_REWRITE_PATTERN,
  2141. HIDE_FILES,
  2142. SSL_DO_VERIFY_PEER,
  2143. SSL_CA_PATH,
  2144. SSL_CA_FILE,
  2145. SSL_VERIFY_DEPTH,
  2146. SSL_DEFAULT_VERIFY_PATHS,
  2147. SSL_CIPHER_LIST,
  2148. SSL_PROTOCOL_VERSION,
  2149. SSL_SHORT_TRUST,
  2150. #if defined(USE_LUA)
  2151. LUA_PRELOAD_FILE,
  2152. LUA_SCRIPT_EXTENSIONS,
  2153. LUA_SERVER_PAGE_EXTENSIONS,
  2154. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2155. LUA_DEBUG_PARAMS,
  2156. #endif
  2157. #endif
  2158. #if defined(USE_DUKTAPE)
  2159. DUKTAPE_SCRIPT_EXTENSIONS,
  2160. #endif
  2161. #if defined(USE_WEBSOCKET)
  2162. WEBSOCKET_ROOT,
  2163. #endif
  2164. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2165. LUA_WEBSOCKET_EXTENSIONS,
  2166. #endif
  2167. ACCESS_CONTROL_ALLOW_ORIGIN,
  2168. ACCESS_CONTROL_ALLOW_METHODS,
  2169. ACCESS_CONTROL_ALLOW_HEADERS,
  2170. ERROR_PAGES,
  2171. #if !defined(NO_CACHING)
  2172. STATIC_FILE_MAX_AGE,
  2173. STATIC_FILE_CACHE_CONTROL,
  2174. #endif
  2175. #if !defined(NO_SSL)
  2176. STRICT_HTTPS_MAX_AGE,
  2177. #endif
  2178. ADDITIONAL_HEADER,
  2179. ALLOW_INDEX_SCRIPT_SUB_RES,
  2180. #if defined(DAEMONIZE)
  2181. ENABLE_DAEMONIZE,
  2182. #endif
  2183. NUM_OPTIONS
  2184. };
  2185. /* Config option name, config types, default value.
  2186. * Must be in the same order as the enum const above.
  2187. */
  2188. static const struct mg_option config_options[] = {
  2189. /* Once for each server */
  2190. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2191. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2192. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2193. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2194. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2195. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2196. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2197. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2198. #if defined(__linux__)
  2199. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2200. #endif
  2201. #if defined(_WIN32)
  2202. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2203. #endif
  2204. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2205. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2206. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2207. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2208. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2209. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2210. #if defined(USE_WEBSOCKET)
  2211. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2212. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2213. #endif
  2214. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2215. #if defined(USE_LUA)
  2216. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2217. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2218. #endif
  2219. #if defined(USE_TIMERS)
  2220. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2221. #endif
  2222. /* Once for each domain */
  2223. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2224. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2225. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2226. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2227. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2228. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2229. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2230. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2231. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2232. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2233. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2234. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2235. {"index_files",
  2236. MG_CONFIG_TYPE_STRING_LIST,
  2237. #if defined(USE_LUA)
  2238. "index.xhtml,index.html,index.htm,"
  2239. "index.lp,index.lsp,index.lua,index.cgi,"
  2240. "index.shtml,index.php"},
  2241. #else
  2242. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2243. #endif
  2244. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2245. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2246. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2247. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2248. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2249. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2250. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2251. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2252. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2253. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2254. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2255. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2256. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2257. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2258. #if defined(USE_LUA)
  2259. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2260. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2261. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2262. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2263. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2264. #endif
  2265. #endif
  2266. #if defined(USE_DUKTAPE)
  2267. /* The support for duktape is still in alpha version state.
  2268. * The name of this config option might change. */
  2269. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2270. #endif
  2271. #if defined(USE_WEBSOCKET)
  2272. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2273. #endif
  2274. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2275. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2276. #endif
  2277. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2278. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2279. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2280. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2281. #if !defined(NO_CACHING)
  2282. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2283. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2284. #endif
  2285. #if !defined(NO_SSL)
  2286. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2287. #endif
  2288. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2289. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2290. #if defined(DAEMONIZE)
  2291. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2292. #endif
  2293. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2294. /* Check if the config_options and the corresponding enum have compatible
  2295. * sizes. */
  2296. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2297. == (NUM_OPTIONS + 1),
  2298. "config_options and enum not sync");
  2299. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2300. struct mg_handler_info {
  2301. /* Name/Pattern of the URI. */
  2302. char *uri;
  2303. size_t uri_len;
  2304. /* handler type */
  2305. int handler_type;
  2306. /* Handler for http/https or authorization requests. */
  2307. mg_request_handler handler;
  2308. unsigned int refcount;
  2309. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2310. pthread_cond_t
  2311. refcount_cond; /* Signaled when handler refcount is decremented */
  2312. /* Handler for ws/wss (websocket) requests. */
  2313. mg_websocket_connect_handler connect_handler;
  2314. mg_websocket_ready_handler ready_handler;
  2315. mg_websocket_data_handler data_handler;
  2316. mg_websocket_close_handler close_handler;
  2317. /* accepted subprotocols for ws/wss requests. */
  2318. struct mg_websocket_subprotocols *subprotocols;
  2319. /* Handler for authorization requests */
  2320. mg_authorization_handler auth_handler;
  2321. /* User supplied argument for the handler function. */
  2322. void *cbdata;
  2323. /* next handler in a linked list */
  2324. struct mg_handler_info *next;
  2325. };
  2326. enum {
  2327. CONTEXT_INVALID,
  2328. CONTEXT_SERVER,
  2329. CONTEXT_HTTP_CLIENT,
  2330. CONTEXT_WS_CLIENT
  2331. };
  2332. struct mg_domain_context {
  2333. SSL_CTX *ssl_ctx; /* SSL context */
  2334. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2335. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2336. /* Server nonce */
  2337. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2338. unsigned long nonce_count; /* Used nonces, used for authentication */
  2339. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2340. /* linked list of shared lua websockets */
  2341. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2342. #endif
  2343. /* Linked list of domains */
  2344. struct mg_domain_context *next;
  2345. };
  2346. struct mg_context {
  2347. /* Part 1 - Physical context:
  2348. * This holds threads, ports, timeouts, ...
  2349. * set for the entire server, independent from the
  2350. * addressed hostname.
  2351. */
  2352. /* Connection related */
  2353. int context_type; /* See CONTEXT_* above */
  2354. struct socket *listening_sockets;
  2355. struct mg_pollfd *listening_socket_fds;
  2356. unsigned int num_listening_sockets;
  2357. struct mg_connection *worker_connections; /* The connection struct, pre-
  2358. * allocated for each worker */
  2359. #if defined(USE_SERVER_STATS)
  2360. int active_connections;
  2361. int max_active_connections;
  2362. int64_t total_connections;
  2363. int64_t total_requests;
  2364. int64_t total_data_read;
  2365. int64_t total_data_written;
  2366. #endif
  2367. /* Thread related */
  2368. volatile int stop_flag; /* Should we stop event loop */
  2369. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2370. pthread_t masterthreadid; /* The master thread ID */
  2371. unsigned int
  2372. cfg_worker_threads; /* The number of configured worker threads. */
  2373. pthread_t *worker_threadids; /* The worker thread IDs */
  2374. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2375. /* Connection to thread dispatching */
  2376. #if defined(ALTERNATIVE_QUEUE)
  2377. struct socket *client_socks;
  2378. void **client_wait_events;
  2379. #else
  2380. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2381. worker thread */
  2382. volatile int sq_head; /* Head of the socket queue */
  2383. volatile int sq_tail; /* Tail of the socket queue */
  2384. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2385. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2386. volatile int sq_blocked; /* Status information: sq is full */
  2387. int sq_size; /* No of elements in socket queue */
  2388. #if defined(USE_SERVER_STATS)
  2389. int sq_max_fill;
  2390. #endif /* USE_SERVER_STATS */
  2391. #endif /* ALTERNATIVE_QUEUE */
  2392. /* Memory related */
  2393. unsigned int max_request_size; /* The max request size */
  2394. #if defined(USE_SERVER_STATS)
  2395. struct mg_memory_stat ctx_memory;
  2396. #endif
  2397. /* Operating system related */
  2398. char *systemName; /* What operating system is running */
  2399. time_t start_time; /* Server start time, used for authentication
  2400. * and for diagnstics. */
  2401. #if defined(USE_TIMERS)
  2402. struct ttimers *timers;
  2403. #endif
  2404. /* Lua specific: Background operations and shared websockets */
  2405. #if defined(USE_LUA)
  2406. void *lua_background_state;
  2407. #endif
  2408. /* Server nonce */
  2409. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2410. /* Server callbacks */
  2411. struct mg_callbacks callbacks; /* User-defined callback function */
  2412. void *user_data; /* User-defined data */
  2413. /* Part 2 - Logical domain:
  2414. * This holds hostname, TLS certificate, document root, ...
  2415. * set for a domain hosted at the server.
  2416. * There may be multiple domains hosted at one physical server.
  2417. * The default domain "dd" is the first element of a list of
  2418. * domains.
  2419. */
  2420. struct mg_domain_context dd; /* default domain */
  2421. };
  2422. #if defined(USE_SERVER_STATS)
  2423. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2424. static struct mg_memory_stat *
  2425. get_memory_stat(struct mg_context *ctx)
  2426. {
  2427. if (ctx) {
  2428. return &(ctx->ctx_memory);
  2429. }
  2430. return &mg_common_memory;
  2431. }
  2432. #endif
  2433. enum {
  2434. CONNECTION_TYPE_INVALID,
  2435. CONNECTION_TYPE_REQUEST,
  2436. CONNECTION_TYPE_RESPONSE
  2437. };
  2438. struct mg_connection {
  2439. int connection_type; /* see CONNECTION_TYPE_* above */
  2440. struct mg_request_info request_info;
  2441. struct mg_response_info response_info;
  2442. struct mg_context *phys_ctx;
  2443. struct mg_domain_context *dom_ctx;
  2444. #if defined(USE_SERVER_STATS)
  2445. int conn_state; /* 0 = undef, numerical value may change in different
  2446. * versions. For the current definition, see
  2447. * mg_get_connection_info_impl */
  2448. #endif
  2449. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2450. SSL *ssl; /* SSL descriptor */
  2451. struct socket client; /* Connected client */
  2452. time_t conn_birth_time; /* Time (wall clock) when connection was
  2453. * established */
  2454. #if defined(USE_SERVER_STATS)
  2455. time_t conn_close_time; /* Time (wall clock) when connection was
  2456. * closed (or 0 if still open) */
  2457. #endif
  2458. struct timespec req_time; /* Time (since system start) when the request
  2459. * was received */
  2460. int64_t num_bytes_sent; /* Total bytes sent to client */
  2461. int64_t content_len; /* How many bytes of content can be read
  2462. * !is_chunked: Content-Length header value
  2463. * or -1 (until connection closed,
  2464. * not allowed for a request)
  2465. * is_chunked: >= 0, appended gradually
  2466. */
  2467. int64_t consumed_content; /* How many bytes of content have been read */
  2468. int is_chunked; /* Transfer-Encoding is chunked:
  2469. * 0 = not chunked,
  2470. * 1 = chunked, not yet, or some data read,
  2471. * 2 = chunked, has error,
  2472. * 3 = chunked, all data read except trailer,
  2473. * 4 = chunked, all data read
  2474. */
  2475. char *buf; /* Buffer for received data */
  2476. char *path_info; /* PATH_INFO part of the URL */
  2477. int must_close; /* 1 if connection must be closed */
  2478. int accept_gzip; /* 1 if gzip encoding is accepted */
  2479. int in_error_handler; /* 1 if in handler for user defined error
  2480. * pages */
  2481. #if defined(USE_WEBSOCKET)
  2482. int in_websocket_handling; /* 1 if in read_websocket */
  2483. #endif
  2484. int handled_requests; /* Number of requests handled by this connection
  2485. */
  2486. int buf_size; /* Buffer size */
  2487. int request_len; /* Size of the request + headers in a buffer */
  2488. int data_len; /* Total size of data in a buffer */
  2489. int status_code; /* HTTP reply status code, e.g. 200 */
  2490. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2491. * throttle */
  2492. time_t last_throttle_time; /* Last time throttled data was sent */
  2493. int last_throttle_bytes; /* Bytes sent this second */
  2494. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2495. * atomic transmissions for websockets */
  2496. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2497. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2498. #endif
  2499. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2500. * for quick access */
  2501. };
  2502. /* Directory entry */
  2503. struct de {
  2504. struct mg_connection *conn;
  2505. char *file_name;
  2506. struct mg_file_stat file;
  2507. };
  2508. #if defined(USE_WEBSOCKET)
  2509. static int is_websocket_protocol(const struct mg_connection *conn);
  2510. #else
  2511. #define is_websocket_protocol(conn) (0)
  2512. #endif
  2513. #define mg_cry_internal(conn, fmt, ...) \
  2514. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2515. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2516. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2517. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2518. struct mg_context *ctx,
  2519. const char *func,
  2520. unsigned line,
  2521. const char *fmt,
  2522. ...) PRINTF_ARGS(5, 6);
  2523. #if !defined(NO_THREAD_NAME)
  2524. #if defined(_WIN32) && defined(_MSC_VER)
  2525. /* Set the thread name for debugging purposes in Visual Studio
  2526. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2527. */
  2528. #pragma pack(push, 8)
  2529. typedef struct tagTHREADNAME_INFO {
  2530. DWORD dwType; /* Must be 0x1000. */
  2531. LPCSTR szName; /* Pointer to name (in user addr space). */
  2532. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2533. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2534. } THREADNAME_INFO;
  2535. #pragma pack(pop)
  2536. #elif defined(__linux__)
  2537. #include <sys/prctl.h>
  2538. #include <sys/sendfile.h>
  2539. #if defined(ALTERNATIVE_QUEUE)
  2540. #include <sys/eventfd.h>
  2541. #endif /* ALTERNATIVE_QUEUE */
  2542. #if defined(ALTERNATIVE_QUEUE)
  2543. static void *
  2544. event_create(void)
  2545. {
  2546. int evhdl = eventfd(0, EFD_CLOEXEC);
  2547. int *ret;
  2548. if (evhdl == -1) {
  2549. /* Linux uses -1 on error, Windows NULL. */
  2550. /* However, Linux does not return 0 on success either. */
  2551. return 0;
  2552. }
  2553. ret = (int *)mg_malloc(sizeof(int));
  2554. if (ret) {
  2555. *ret = evhdl;
  2556. } else {
  2557. (void)close(evhdl);
  2558. }
  2559. return (void *)ret;
  2560. }
  2561. static int
  2562. event_wait(void *eventhdl)
  2563. {
  2564. uint64_t u;
  2565. int evhdl, s;
  2566. if (!eventhdl) {
  2567. /* error */
  2568. return 0;
  2569. }
  2570. evhdl = *(int *)eventhdl;
  2571. s = (int)read(evhdl, &u, sizeof(u));
  2572. if (s != sizeof(u)) {
  2573. /* error */
  2574. return 0;
  2575. }
  2576. (void)u; /* the value is not required */
  2577. return 1;
  2578. }
  2579. static int
  2580. event_signal(void *eventhdl)
  2581. {
  2582. uint64_t u = 1;
  2583. int evhdl, s;
  2584. if (!eventhdl) {
  2585. /* error */
  2586. return 0;
  2587. }
  2588. evhdl = *(int *)eventhdl;
  2589. s = (int)write(evhdl, &u, sizeof(u));
  2590. if (s != sizeof(u)) {
  2591. /* error */
  2592. return 0;
  2593. }
  2594. return 1;
  2595. }
  2596. static void
  2597. event_destroy(void *eventhdl)
  2598. {
  2599. int evhdl;
  2600. if (!eventhdl) {
  2601. /* error */
  2602. return;
  2603. }
  2604. evhdl = *(int *)eventhdl;
  2605. close(evhdl);
  2606. mg_free(eventhdl);
  2607. }
  2608. #endif
  2609. #endif
  2610. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2611. struct posix_event {
  2612. pthread_mutex_t mutex;
  2613. pthread_cond_t cond;
  2614. int signaled;
  2615. };
  2616. static void *
  2617. event_create(void)
  2618. {
  2619. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2620. if (ret == 0) {
  2621. /* out of memory */
  2622. return 0;
  2623. }
  2624. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2625. /* pthread mutex not available */
  2626. mg_free(ret);
  2627. return 0;
  2628. }
  2629. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2630. /* pthread cond not available */
  2631. pthread_mutex_destroy(&(ret->mutex));
  2632. mg_free(ret);
  2633. return 0;
  2634. }
  2635. ret->signaled = 0;
  2636. return (void *)ret;
  2637. }
  2638. static int
  2639. event_wait(void *eventhdl)
  2640. {
  2641. struct posix_event *ev = (struct posix_event *)eventhdl;
  2642. pthread_mutex_lock(&(ev->mutex));
  2643. while (!ev->signaled) {
  2644. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2645. }
  2646. ev->signaled = 0;
  2647. pthread_mutex_unlock(&(ev->mutex));
  2648. return 1;
  2649. }
  2650. static int
  2651. event_signal(void *eventhdl)
  2652. {
  2653. struct posix_event *ev = (struct posix_event *)eventhdl;
  2654. pthread_mutex_lock(&(ev->mutex));
  2655. pthread_cond_signal(&(ev->cond));
  2656. ev->signaled = 1;
  2657. pthread_mutex_unlock(&(ev->mutex));
  2658. return 1;
  2659. }
  2660. static void
  2661. event_destroy(void *eventhdl)
  2662. {
  2663. struct posix_event *ev = (struct posix_event *)eventhdl;
  2664. pthread_cond_destroy(&(ev->cond));
  2665. pthread_mutex_destroy(&(ev->mutex));
  2666. mg_free(ev);
  2667. }
  2668. #endif
  2669. static void
  2670. mg_set_thread_name(const char *name)
  2671. {
  2672. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2673. mg_snprintf(
  2674. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2675. #if defined(_WIN32)
  2676. #if defined(_MSC_VER)
  2677. /* Windows and Visual Studio Compiler */
  2678. __try {
  2679. THREADNAME_INFO info;
  2680. info.dwType = 0x1000;
  2681. info.szName = threadName;
  2682. info.dwThreadID = ~0U;
  2683. info.dwFlags = 0;
  2684. RaiseException(0x406D1388,
  2685. 0,
  2686. sizeof(info) / sizeof(ULONG_PTR),
  2687. (ULONG_PTR *)&info);
  2688. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2689. }
  2690. #elif defined(__MINGW32__)
  2691. /* No option known to set thread name for MinGW known */
  2692. #endif
  2693. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2694. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2695. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2696. #if defined(__MACH__)
  2697. /* OS X only current thread name can be changed */
  2698. (void)pthread_setname_np(threadName);
  2699. #else
  2700. (void)pthread_setname_np(pthread_self(), threadName);
  2701. #endif
  2702. #elif defined(__linux__)
  2703. /* On Linux we can use the prctl function.
  2704. * When building for Linux Standard Base (LSB) use
  2705. * NO_THREAD_NAME. However, thread names are a big
  2706. * help for debugging, so the stadard is to set them.
  2707. */
  2708. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2709. #endif
  2710. }
  2711. #else /* !defined(NO_THREAD_NAME) */
  2712. void
  2713. mg_set_thread_name(const char *threadName)
  2714. {
  2715. }
  2716. #endif
  2717. #if defined(MG_LEGACY_INTERFACE)
  2718. const char **
  2719. mg_get_valid_option_names(void)
  2720. {
  2721. /* This function is deprecated. Use mg_get_valid_options instead. */
  2722. static const char
  2723. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2724. int i;
  2725. for (i = 0; config_options[i].name != NULL; i++) {
  2726. data[i * 2] = config_options[i].name;
  2727. data[i * 2 + 1] = config_options[i].default_value;
  2728. }
  2729. return data;
  2730. }
  2731. #endif
  2732. const struct mg_option *
  2733. mg_get_valid_options(void)
  2734. {
  2735. return config_options;
  2736. }
  2737. /* Do not open file (used in is_file_in_memory) */
  2738. #define MG_FOPEN_MODE_NONE (0)
  2739. /* Open file for read only access */
  2740. #define MG_FOPEN_MODE_READ (1)
  2741. /* Open file for writing, create and overwrite */
  2742. #define MG_FOPEN_MODE_WRITE (2)
  2743. /* Open file for writing, create and append */
  2744. #define MG_FOPEN_MODE_APPEND (4)
  2745. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2746. * output filep and return 1, otherwise return 0 and don't modify anything.
  2747. */
  2748. static int
  2749. open_file_in_memory(const struct mg_connection *conn,
  2750. const char *path,
  2751. struct mg_file *filep,
  2752. int mode)
  2753. {
  2754. #if defined(MG_USE_OPEN_FILE)
  2755. size_t size = 0;
  2756. const char *buf = NULL;
  2757. if (!conn) {
  2758. return 0;
  2759. }
  2760. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2761. return 0;
  2762. }
  2763. if (conn->phys_ctx->callbacks.open_file) {
  2764. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2765. if (buf != NULL) {
  2766. if (filep == NULL) {
  2767. /* This is a file in memory, but we cannot store the
  2768. * properties
  2769. * now.
  2770. * Called from "is_file_in_memory" function. */
  2771. return 1;
  2772. }
  2773. /* NOTE: override filep->size only on success. Otherwise, it
  2774. * might
  2775. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2776. filep->access.membuf = buf;
  2777. filep->access.fp = NULL;
  2778. /* Size was set by the callback */
  2779. filep->stat.size = size;
  2780. /* Assume the data may change during runtime by setting
  2781. * last_modified = now */
  2782. filep->stat.last_modified = time(NULL);
  2783. filep->stat.is_directory = 0;
  2784. filep->stat.is_gzipped = 0;
  2785. }
  2786. }
  2787. return (buf != NULL);
  2788. #else
  2789. (void)conn;
  2790. (void)path;
  2791. (void)filep;
  2792. (void)mode;
  2793. return 0;
  2794. #endif
  2795. }
  2796. static int
  2797. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2798. {
  2799. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2800. }
  2801. static int
  2802. is_file_opened(const struct mg_file_access *fileacc)
  2803. {
  2804. if (!fileacc) {
  2805. return 0;
  2806. }
  2807. #if defined(MG_USE_OPEN_FILE)
  2808. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2809. #else
  2810. return (fileacc->fp != NULL);
  2811. #endif
  2812. }
  2813. #if !defined(NO_FILESYSTEMS)
  2814. static int mg_stat(const struct mg_connection *conn,
  2815. const char *path,
  2816. struct mg_file_stat *filep);
  2817. /* mg_fopen will open a file either in memory or on the disk.
  2818. * The input parameter path is a string in UTF-8 encoding.
  2819. * The input parameter mode is MG_FOPEN_MODE_*
  2820. * On success, either fp or membuf will be set in the output
  2821. * struct file. All status members will also be set.
  2822. * The function returns 1 on success, 0 on error. */
  2823. static int
  2824. mg_fopen(const struct mg_connection *conn,
  2825. const char *path,
  2826. int mode,
  2827. struct mg_file *filep)
  2828. {
  2829. int found;
  2830. if (!filep) {
  2831. return 0;
  2832. }
  2833. filep->access.fp = NULL;
  2834. #if defined(MG_USE_OPEN_FILE)
  2835. filep->access.membuf = NULL;
  2836. #endif
  2837. if (!is_file_in_memory(conn, path)) {
  2838. /* filep is initialized in mg_stat: all fields with memset to,
  2839. * some fields like size and modification date with values */
  2840. found = mg_stat(conn, path, &(filep->stat));
  2841. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2842. /* file does not exist and will not be created */
  2843. return 0;
  2844. }
  2845. #if defined(_WIN32)
  2846. {
  2847. wchar_t wbuf[W_PATH_MAX];
  2848. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2849. switch (mode) {
  2850. case MG_FOPEN_MODE_READ:
  2851. filep->access.fp = _wfopen(wbuf, L"rb");
  2852. break;
  2853. case MG_FOPEN_MODE_WRITE:
  2854. filep->access.fp = _wfopen(wbuf, L"wb");
  2855. break;
  2856. case MG_FOPEN_MODE_APPEND:
  2857. filep->access.fp = _wfopen(wbuf, L"ab");
  2858. break;
  2859. }
  2860. }
  2861. #else
  2862. /* Linux et al already use unicode. No need to convert. */
  2863. switch (mode) {
  2864. case MG_FOPEN_MODE_READ:
  2865. filep->access.fp = fopen(path, "r");
  2866. break;
  2867. case MG_FOPEN_MODE_WRITE:
  2868. filep->access.fp = fopen(path, "w");
  2869. break;
  2870. case MG_FOPEN_MODE_APPEND:
  2871. filep->access.fp = fopen(path, "a");
  2872. break;
  2873. }
  2874. #endif
  2875. if (!found) {
  2876. /* File did not exist before fopen was called.
  2877. * Maybe it has been created now. Get stat info
  2878. * like creation time now. */
  2879. found = mg_stat(conn, path, &(filep->stat));
  2880. (void)found;
  2881. }
  2882. /* file is on disk */
  2883. return (filep->access.fp != NULL);
  2884. } else {
  2885. #if defined(MG_USE_OPEN_FILE)
  2886. /* is_file_in_memory returned true */
  2887. if (open_file_in_memory(conn, path, filep, mode)) {
  2888. /* file is in memory */
  2889. return (filep->access.membuf != NULL);
  2890. }
  2891. #endif
  2892. }
  2893. /* Open failed */
  2894. return 0;
  2895. }
  2896. /* return 0 on success, just like fclose */
  2897. static int
  2898. mg_fclose(struct mg_file_access *fileacc)
  2899. {
  2900. int ret = -1;
  2901. if (fileacc != NULL) {
  2902. if (fileacc->fp != NULL) {
  2903. ret = fclose(fileacc->fp);
  2904. #if defined(MG_USE_OPEN_FILE)
  2905. } else if (fileacc->membuf != NULL) {
  2906. ret = 0;
  2907. #endif
  2908. }
  2909. /* reset all members of fileacc */
  2910. memset(fileacc, 0, sizeof(*fileacc));
  2911. }
  2912. return ret;
  2913. }
  2914. #endif /* NO_FILESYSTEMS */
  2915. static void
  2916. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2917. {
  2918. for (; *src != '\0' && n > 1; n--) {
  2919. *dst++ = *src++;
  2920. }
  2921. *dst = '\0';
  2922. }
  2923. static int
  2924. lowercase(const char *s)
  2925. {
  2926. return tolower((unsigned char)*s);
  2927. }
  2928. int
  2929. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2930. {
  2931. int diff = 0;
  2932. if (len > 0) {
  2933. do {
  2934. diff = lowercase(s1++) - lowercase(s2++);
  2935. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2936. }
  2937. return diff;
  2938. }
  2939. int
  2940. mg_strcasecmp(const char *s1, const char *s2)
  2941. {
  2942. int diff;
  2943. do {
  2944. diff = lowercase(s1++) - lowercase(s2++);
  2945. } while (diff == 0 && s1[-1] != '\0');
  2946. return diff;
  2947. }
  2948. static char *
  2949. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2950. {
  2951. char *p;
  2952. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2953. * defined */
  2954. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2955. mg_strlcpy(p, ptr, len + 1);
  2956. }
  2957. return p;
  2958. }
  2959. static char *
  2960. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2961. {
  2962. return mg_strndup_ctx(str, strlen(str), ctx);
  2963. }
  2964. static char *
  2965. mg_strdup(const char *str)
  2966. {
  2967. return mg_strndup_ctx(str, strlen(str), NULL);
  2968. }
  2969. static const char *
  2970. mg_strcasestr(const char *big_str, const char *small_str)
  2971. {
  2972. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2973. if (big_len >= small_len) {
  2974. for (i = 0; i <= (big_len - small_len); i++) {
  2975. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2976. return big_str + i;
  2977. }
  2978. }
  2979. }
  2980. return NULL;
  2981. }
  2982. /* Return null terminated string of given maximum length.
  2983. * Report errors if length is exceeded. */
  2984. static void
  2985. mg_vsnprintf(const struct mg_connection *conn,
  2986. int *truncated,
  2987. char *buf,
  2988. size_t buflen,
  2989. const char *fmt,
  2990. va_list ap)
  2991. {
  2992. int n, ok;
  2993. if (buflen == 0) {
  2994. if (truncated) {
  2995. *truncated = 1;
  2996. }
  2997. return;
  2998. }
  2999. #if defined(__clang__)
  3000. #pragma clang diagnostic push
  3001. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3002. /* Using fmt as a non-literal is intended here, since it is mostly called
  3003. * indirectly by mg_snprintf */
  3004. #endif
  3005. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3006. ok = (n >= 0) && ((size_t)n < buflen);
  3007. #if defined(__clang__)
  3008. #pragma clang diagnostic pop
  3009. #endif
  3010. if (ok) {
  3011. if (truncated) {
  3012. *truncated = 0;
  3013. }
  3014. } else {
  3015. if (truncated) {
  3016. *truncated = 1;
  3017. }
  3018. mg_cry_internal(conn,
  3019. "truncating vsnprintf buffer: [%.*s]",
  3020. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3021. buf);
  3022. n = (int)buflen - 1;
  3023. }
  3024. buf[n] = '\0';
  3025. }
  3026. static void
  3027. mg_snprintf(const struct mg_connection *conn,
  3028. int *truncated,
  3029. char *buf,
  3030. size_t buflen,
  3031. const char *fmt,
  3032. ...)
  3033. {
  3034. va_list ap;
  3035. va_start(ap, fmt);
  3036. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3037. va_end(ap);
  3038. }
  3039. static int
  3040. get_option_index(const char *name)
  3041. {
  3042. int i;
  3043. for (i = 0; config_options[i].name != NULL; i++) {
  3044. if (strcmp(config_options[i].name, name) == 0) {
  3045. return i;
  3046. }
  3047. }
  3048. return -1;
  3049. }
  3050. const char *
  3051. mg_get_option(const struct mg_context *ctx, const char *name)
  3052. {
  3053. int i;
  3054. if ((i = get_option_index(name)) == -1) {
  3055. return NULL;
  3056. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3057. return "";
  3058. } else {
  3059. return ctx->dd.config[i];
  3060. }
  3061. }
  3062. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3063. struct mg_context *
  3064. mg_get_context(const struct mg_connection *conn)
  3065. {
  3066. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3067. }
  3068. void *
  3069. mg_get_user_data(const struct mg_context *ctx)
  3070. {
  3071. return (ctx == NULL) ? NULL : ctx->user_data;
  3072. }
  3073. void *
  3074. mg_get_user_context_data(const struct mg_connection *conn)
  3075. {
  3076. return mg_get_user_data(mg_get_context(conn));
  3077. }
  3078. void *
  3079. mg_get_thread_pointer(const struct mg_connection *conn)
  3080. {
  3081. /* both methods should return the same pointer */
  3082. if (conn) {
  3083. /* quick access, in case conn is known */
  3084. return conn->tls_user_ptr;
  3085. } else {
  3086. /* otherwise get pointer from thread local storage (TLS) */
  3087. struct mg_workerTLS *tls =
  3088. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3089. return tls->user_ptr;
  3090. }
  3091. }
  3092. void
  3093. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3094. {
  3095. if (conn != NULL) {
  3096. conn->request_info.conn_data = data;
  3097. }
  3098. }
  3099. void *
  3100. mg_get_user_connection_data(const struct mg_connection *conn)
  3101. {
  3102. if (conn != NULL) {
  3103. return conn->request_info.conn_data;
  3104. }
  3105. return NULL;
  3106. }
  3107. #if defined(MG_LEGACY_INTERFACE)
  3108. /* Deprecated: Use mg_get_server_ports instead. */
  3109. size_t
  3110. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3111. {
  3112. size_t i;
  3113. if (!ctx) {
  3114. return 0;
  3115. }
  3116. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3117. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3118. ports[i] =
  3119. #if defined(USE_IPV6)
  3120. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3121. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3122. :
  3123. #endif
  3124. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3125. }
  3126. return i;
  3127. }
  3128. #endif
  3129. int
  3130. mg_get_server_ports(const struct mg_context *ctx,
  3131. int size,
  3132. struct mg_server_port *ports)
  3133. {
  3134. int i, cnt = 0;
  3135. if (size <= 0) {
  3136. return -1;
  3137. }
  3138. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3139. if (!ctx) {
  3140. return -1;
  3141. }
  3142. if (!ctx->listening_sockets) {
  3143. return -1;
  3144. }
  3145. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3146. ports[cnt].port =
  3147. #if defined(USE_IPV6)
  3148. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3149. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3150. :
  3151. #endif
  3152. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3153. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3154. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3155. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3156. /* IPv4 */
  3157. ports[cnt].protocol = 1;
  3158. cnt++;
  3159. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3160. /* IPv6 */
  3161. ports[cnt].protocol = 3;
  3162. cnt++;
  3163. }
  3164. }
  3165. return cnt;
  3166. }
  3167. static void
  3168. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3169. {
  3170. buf[0] = '\0';
  3171. if (!usa) {
  3172. return;
  3173. }
  3174. if (usa->sa.sa_family == AF_INET) {
  3175. getnameinfo(&usa->sa,
  3176. sizeof(usa->sin),
  3177. buf,
  3178. (unsigned)len,
  3179. NULL,
  3180. 0,
  3181. NI_NUMERICHOST);
  3182. }
  3183. #if defined(USE_IPV6)
  3184. else if (usa->sa.sa_family == AF_INET6) {
  3185. getnameinfo(&usa->sa,
  3186. sizeof(usa->sin6),
  3187. buf,
  3188. (unsigned)len,
  3189. NULL,
  3190. 0,
  3191. NI_NUMERICHOST);
  3192. }
  3193. #endif
  3194. }
  3195. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3196. * included in all responses other than 100, 101, 5xx. */
  3197. static void
  3198. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3199. {
  3200. #if !defined(REENTRANT_TIME)
  3201. struct tm *tm;
  3202. tm = ((t != NULL) ? gmtime(t) : NULL);
  3203. if (tm != NULL) {
  3204. #else
  3205. struct tm _tm;
  3206. struct tm *tm = &_tm;
  3207. if (t != NULL) {
  3208. gmtime_r(t, tm);
  3209. #endif
  3210. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3211. } else {
  3212. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3213. buf[buf_len - 1] = '\0';
  3214. }
  3215. }
  3216. /* difftime for struct timespec. Return value is in seconds. */
  3217. static double
  3218. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3219. {
  3220. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3221. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3222. }
  3223. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3224. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3225. const char *func,
  3226. unsigned line,
  3227. const char *fmt,
  3228. va_list ap);
  3229. #include "external_mg_cry_internal_impl.inl"
  3230. #elif !defined(NO_FILESYSTEMS)
  3231. /* Print error message to the opened error log stream. */
  3232. static void
  3233. mg_cry_internal_impl(const struct mg_connection *conn,
  3234. const char *func,
  3235. unsigned line,
  3236. const char *fmt,
  3237. va_list ap)
  3238. {
  3239. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3240. struct mg_file fi;
  3241. time_t timestamp;
  3242. /* Unused, in the RELEASE build */
  3243. (void)func;
  3244. (void)line;
  3245. #if defined(GCC_DIAGNOSTIC)
  3246. #pragma GCC diagnostic push
  3247. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3248. #endif
  3249. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3250. #if defined(GCC_DIAGNOSTIC)
  3251. #pragma GCC diagnostic pop
  3252. #endif
  3253. buf[sizeof(buf) - 1] = 0;
  3254. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3255. if (!conn) {
  3256. puts(buf);
  3257. return;
  3258. }
  3259. /* Do not lock when getting the callback value, here and below.
  3260. * I suppose this is fine, since function cannot disappear in the
  3261. * same way string option can. */
  3262. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3263. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3264. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3265. if (mg_fopen(conn,
  3266. conn->dom_ctx->config[ERROR_LOG_FILE],
  3267. MG_FOPEN_MODE_APPEND,
  3268. &fi)
  3269. == 0) {
  3270. fi.access.fp = NULL;
  3271. }
  3272. } else {
  3273. fi.access.fp = NULL;
  3274. }
  3275. if (fi.access.fp != NULL) {
  3276. flockfile(fi.access.fp);
  3277. timestamp = time(NULL);
  3278. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3279. fprintf(fi.access.fp,
  3280. "[%010lu] [error] [client %s] ",
  3281. (unsigned long)timestamp,
  3282. src_addr);
  3283. if (conn->request_info.request_method != NULL) {
  3284. fprintf(fi.access.fp,
  3285. "%s %s: ",
  3286. conn->request_info.request_method,
  3287. conn->request_info.request_uri
  3288. ? conn->request_info.request_uri
  3289. : "");
  3290. }
  3291. fprintf(fi.access.fp, "%s", buf);
  3292. fputc('\n', fi.access.fp);
  3293. fflush(fi.access.fp);
  3294. funlockfile(fi.access.fp);
  3295. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3296. * mg_cry here anyway ;-) */
  3297. }
  3298. }
  3299. }
  3300. #else
  3301. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3302. #endif /* Externally provided function */
  3303. /* Construct fake connection structure. Used for logging, if connection
  3304. * is not applicable at the moment of logging. */
  3305. static struct mg_connection *
  3306. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3307. {
  3308. static const struct mg_connection conn_zero = {0};
  3309. *fc = conn_zero;
  3310. fc->phys_ctx = ctx;
  3311. fc->dom_ctx = &(ctx->dd);
  3312. return fc;
  3313. }
  3314. static void
  3315. mg_cry_internal_wrap(const struct mg_connection *conn,
  3316. struct mg_context *ctx,
  3317. const char *func,
  3318. unsigned line,
  3319. const char *fmt,
  3320. ...)
  3321. {
  3322. va_list ap;
  3323. va_start(ap, fmt);
  3324. if (!conn && ctx) {
  3325. struct mg_connection fc;
  3326. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3327. } else {
  3328. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3329. }
  3330. va_end(ap);
  3331. }
  3332. void
  3333. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3334. {
  3335. va_list ap;
  3336. va_start(ap, fmt);
  3337. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3338. va_end(ap);
  3339. }
  3340. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3341. const char *
  3342. mg_version(void)
  3343. {
  3344. return CIVETWEB_VERSION;
  3345. }
  3346. const struct mg_request_info *
  3347. mg_get_request_info(const struct mg_connection *conn)
  3348. {
  3349. if (!conn) {
  3350. return NULL;
  3351. }
  3352. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3353. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3354. char txt[16];
  3355. struct mg_workerTLS *tls =
  3356. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3357. sprintf(txt, "%03i", conn->response_info.status_code);
  3358. if (strlen(txt) == 3) {
  3359. memcpy(tls->txtbuf, txt, 4);
  3360. } else {
  3361. strcpy(tls->txtbuf, "ERR");
  3362. }
  3363. ((struct mg_connection *)conn)->request_info.local_uri =
  3364. ((struct mg_connection *)conn)->request_info.request_uri =
  3365. tls->txtbuf; /* use thread safe buffer */
  3366. ((struct mg_connection *)conn)->request_info.num_headers =
  3367. conn->response_info.num_headers;
  3368. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3369. conn->response_info.http_headers,
  3370. sizeof(conn->response_info.http_headers));
  3371. } else
  3372. #endif
  3373. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3374. return NULL;
  3375. }
  3376. return &conn->request_info;
  3377. }
  3378. const struct mg_response_info *
  3379. mg_get_response_info(const struct mg_connection *conn)
  3380. {
  3381. if (!conn) {
  3382. return NULL;
  3383. }
  3384. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3385. return NULL;
  3386. }
  3387. return &conn->response_info;
  3388. }
  3389. static const char *
  3390. get_proto_name(const struct mg_connection *conn)
  3391. {
  3392. #if defined(__clang__)
  3393. #pragma clang diagnostic push
  3394. #pragma clang diagnostic ignored "-Wunreachable-code"
  3395. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3396. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3397. * unreachable, but splitting into four different #ifdef clauses here is more
  3398. * complicated.
  3399. */
  3400. #endif
  3401. const struct mg_request_info *ri = &conn->request_info;
  3402. const char *proto =
  3403. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3404. : (ri->is_ssl ? "https" : "http"));
  3405. return proto;
  3406. #if defined(__clang__)
  3407. #pragma clang diagnostic pop
  3408. #endif
  3409. }
  3410. int
  3411. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3412. {
  3413. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3414. return -1;
  3415. } else {
  3416. int truncated = 0;
  3417. const struct mg_request_info *ri = &conn->request_info;
  3418. const char *proto = get_proto_name(conn);
  3419. if (ri->local_uri == NULL) {
  3420. return -1;
  3421. }
  3422. if ((ri->request_uri != NULL)
  3423. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3424. /* The request uri is different from the local uri.
  3425. * This is usually if an absolute URI, including server
  3426. * name has been provided. */
  3427. mg_snprintf(conn,
  3428. &truncated,
  3429. buf,
  3430. buflen,
  3431. "%s://%s",
  3432. proto,
  3433. ri->request_uri);
  3434. if (truncated) {
  3435. return -1;
  3436. }
  3437. return 0;
  3438. } else {
  3439. /* The common case is a relative URI, so we have to
  3440. * construct an absolute URI from server name and port */
  3441. #if defined(USE_IPV6)
  3442. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3443. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3444. : htons(conn->client.lsa.sin.sin_port);
  3445. #else
  3446. int port = htons(conn->client.lsa.sin.sin_port);
  3447. #endif
  3448. int def_port = ri->is_ssl ? 443 : 80;
  3449. int auth_domain_check_enabled =
  3450. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3451. && (!mg_strcasecmp(
  3452. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3453. const char *server_domain =
  3454. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3455. char portstr[16];
  3456. char server_ip[48];
  3457. if (port != def_port) {
  3458. sprintf(portstr, ":%u", (unsigned)port);
  3459. } else {
  3460. portstr[0] = 0;
  3461. }
  3462. if (!auth_domain_check_enabled || !server_domain) {
  3463. sockaddr_to_string(server_ip,
  3464. sizeof(server_ip),
  3465. &conn->client.lsa);
  3466. server_domain = server_ip;
  3467. }
  3468. mg_snprintf(conn,
  3469. &truncated,
  3470. buf,
  3471. buflen,
  3472. "%s://%s%s%s",
  3473. proto,
  3474. server_domain,
  3475. portstr,
  3476. ri->local_uri);
  3477. if (truncated) {
  3478. return -1;
  3479. }
  3480. return 0;
  3481. }
  3482. }
  3483. }
  3484. /* Skip the characters until one of the delimiters characters found.
  3485. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3486. * Advance pointer to buffer to the next word. Return found 0-terminated
  3487. * word.
  3488. * Delimiters can be quoted with quotechar. */
  3489. static char *
  3490. skip_quoted(char **buf,
  3491. const char *delimiters,
  3492. const char *whitespace,
  3493. char quotechar)
  3494. {
  3495. char *p, *begin_word, *end_word, *end_whitespace;
  3496. begin_word = *buf;
  3497. end_word = begin_word + strcspn(begin_word, delimiters);
  3498. /* Check for quotechar */
  3499. if (end_word > begin_word) {
  3500. p = end_word - 1;
  3501. while (*p == quotechar) {
  3502. /* While the delimiter is quoted, look for the next delimiter.
  3503. */
  3504. /* This happens, e.g., in calls from parse_auth_header,
  3505. * if the user name contains a " character. */
  3506. /* If there is anything beyond end_word, copy it. */
  3507. if (*end_word != '\0') {
  3508. size_t end_off = strcspn(end_word + 1, delimiters);
  3509. memmove(p, end_word, end_off + 1);
  3510. p += end_off; /* p must correspond to end_word - 1 */
  3511. end_word += end_off + 1;
  3512. } else {
  3513. *p = '\0';
  3514. break;
  3515. }
  3516. }
  3517. for (p++; p < end_word; p++) {
  3518. *p = '\0';
  3519. }
  3520. }
  3521. if (*end_word == '\0') {
  3522. *buf = end_word;
  3523. } else {
  3524. #if defined(GCC_DIAGNOSTIC)
  3525. /* Disable spurious conversion warning for GCC */
  3526. #pragma GCC diagnostic push
  3527. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3528. #endif /* defined(GCC_DIAGNOSTIC) */
  3529. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3530. #if defined(GCC_DIAGNOSTIC)
  3531. #pragma GCC diagnostic pop
  3532. #endif /* defined(GCC_DIAGNOSTIC) */
  3533. for (p = end_word; p < end_whitespace; p++) {
  3534. *p = '\0';
  3535. }
  3536. *buf = end_whitespace;
  3537. }
  3538. return begin_word;
  3539. }
  3540. /* Return HTTP header value, or NULL if not found. */
  3541. static const char *
  3542. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3543. {
  3544. int i;
  3545. for (i = 0; i < num_hdr; i++) {
  3546. if (!mg_strcasecmp(name, hdr[i].name)) {
  3547. return hdr[i].value;
  3548. }
  3549. }
  3550. return NULL;
  3551. }
  3552. #if defined(USE_WEBSOCKET)
  3553. /* Retrieve requested HTTP header multiple values, and return the number of
  3554. * found occurrences */
  3555. static int
  3556. get_req_headers(const struct mg_request_info *ri,
  3557. const char *name,
  3558. const char **output,
  3559. int output_max_size)
  3560. {
  3561. int i;
  3562. int cnt = 0;
  3563. if (ri) {
  3564. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3565. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3566. output[cnt++] = ri->http_headers[i].value;
  3567. }
  3568. }
  3569. }
  3570. return cnt;
  3571. }
  3572. #endif
  3573. const char *
  3574. mg_get_header(const struct mg_connection *conn, const char *name)
  3575. {
  3576. if (!conn) {
  3577. return NULL;
  3578. }
  3579. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3580. return get_header(conn->request_info.http_headers,
  3581. conn->request_info.num_headers,
  3582. name);
  3583. }
  3584. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3585. return get_header(conn->response_info.http_headers,
  3586. conn->response_info.num_headers,
  3587. name);
  3588. }
  3589. return NULL;
  3590. }
  3591. static const char *
  3592. get_http_version(const struct mg_connection *conn)
  3593. {
  3594. if (!conn) {
  3595. return NULL;
  3596. }
  3597. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3598. return conn->request_info.http_version;
  3599. }
  3600. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3601. return conn->response_info.http_version;
  3602. }
  3603. return NULL;
  3604. }
  3605. /* A helper function for traversing a comma separated list of values.
  3606. * It returns a list pointer shifted to the next value, or NULL if the end
  3607. * of the list found.
  3608. * Value is stored in val vector. If value has form "x=y", then eq_val
  3609. * vector is initialized to point to the "y" part, and val vector length
  3610. * is adjusted to point only to "x". */
  3611. static const char *
  3612. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3613. {
  3614. int end;
  3615. reparse:
  3616. if (val == NULL || list == NULL || *list == '\0') {
  3617. /* End of the list */
  3618. return NULL;
  3619. }
  3620. /* Skip over leading LWS */
  3621. while (*list == ' ' || *list == '\t')
  3622. list++;
  3623. val->ptr = list;
  3624. if ((list = strchr(val->ptr, ',')) != NULL) {
  3625. /* Comma found. Store length and shift the list ptr */
  3626. val->len = ((size_t)(list - val->ptr));
  3627. list++;
  3628. } else {
  3629. /* This value is the last one */
  3630. list = val->ptr + strlen(val->ptr);
  3631. val->len = ((size_t)(list - val->ptr));
  3632. }
  3633. /* Adjust length for trailing LWS */
  3634. end = (int)val->len - 1;
  3635. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3636. end--;
  3637. val->len = (size_t)(end) + (size_t)(1);
  3638. if (val->len == 0) {
  3639. /* Ignore any empty entries. */
  3640. goto reparse;
  3641. }
  3642. if (eq_val != NULL) {
  3643. /* Value has form "x=y", adjust pointers and lengths
  3644. * so that val points to "x", and eq_val points to "y". */
  3645. eq_val->len = 0;
  3646. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3647. if (eq_val->ptr != NULL) {
  3648. eq_val->ptr++; /* Skip over '=' character */
  3649. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3650. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3651. }
  3652. }
  3653. return list;
  3654. }
  3655. /* A helper function for checking if a comma separated list of values
  3656. * contains
  3657. * the given option (case insensitvely).
  3658. * 'header' can be NULL, in which case false is returned. */
  3659. static int
  3660. header_has_option(const char *header, const char *option)
  3661. {
  3662. struct vec opt_vec;
  3663. struct vec eq_vec;
  3664. DEBUG_ASSERT(option != NULL);
  3665. DEBUG_ASSERT(option[0] != '\0');
  3666. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3667. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3668. return 1;
  3669. }
  3670. return 0;
  3671. }
  3672. /* Perform case-insensitive match of string against pattern */
  3673. static ptrdiff_t
  3674. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3675. {
  3676. const char *or_str;
  3677. ptrdiff_t i, j, len, res;
  3678. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3679. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3680. return (res > 0) ? res
  3681. : match_prefix(or_str + 1,
  3682. (size_t)((pattern + pattern_len)
  3683. - (or_str + 1)),
  3684. str);
  3685. }
  3686. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3687. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3688. continue;
  3689. } else if (pattern[i] == '$') {
  3690. return (str[j] == '\0') ? j : -1;
  3691. } else if (pattern[i] == '*') {
  3692. i++;
  3693. if (pattern[i] == '*') {
  3694. i++;
  3695. len = (ptrdiff_t)strlen(str + j);
  3696. } else {
  3697. len = (ptrdiff_t)strcspn(str + j, "/");
  3698. }
  3699. if (i == (ptrdiff_t)pattern_len) {
  3700. return j + len;
  3701. }
  3702. do {
  3703. res = match_prefix(pattern + i,
  3704. (pattern_len - (size_t)i),
  3705. str + j + len);
  3706. } while (res == -1 && len-- > 0);
  3707. return (res == -1) ? -1 : j + res + len;
  3708. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3709. return -1;
  3710. }
  3711. }
  3712. return (ptrdiff_t)j;
  3713. }
  3714. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3715. * This function must tolerate situations when connection info is not
  3716. * set up, for example if request parsing failed. */
  3717. static int
  3718. should_keep_alive(const struct mg_connection *conn)
  3719. {
  3720. const char *http_version;
  3721. const char *header;
  3722. /* First satisfy needs of the server */
  3723. if ((conn == NULL) || conn->must_close) {
  3724. /* Close, if civetweb framework needs to close */
  3725. return 0;
  3726. }
  3727. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3728. /* Close, if keep alive is not enabled */
  3729. return 0;
  3730. }
  3731. /* Check explicit wish of the client */
  3732. header = mg_get_header(conn, "Connection");
  3733. if (header) {
  3734. /* If there is a connection header from the client, obey */
  3735. if (header_has_option(header, "keep-alive")) {
  3736. return 1;
  3737. }
  3738. return 0;
  3739. }
  3740. /* Use default of the standard */
  3741. http_version = get_http_version(conn);
  3742. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3743. /* HTTP 1.1 default is keep alive */
  3744. return 1;
  3745. }
  3746. /* HTTP 1.0 (and earlier) default is to close the connection */
  3747. return 0;
  3748. }
  3749. static int
  3750. should_decode_url(const struct mg_connection *conn)
  3751. {
  3752. if (!conn || !conn->dom_ctx) {
  3753. return 0;
  3754. }
  3755. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3756. }
  3757. static const char *
  3758. suggest_connection_header(const struct mg_connection *conn)
  3759. {
  3760. return should_keep_alive(conn) ? "keep-alive" : "close";
  3761. }
  3762. static int
  3763. send_no_cache_header(struct mg_connection *conn)
  3764. {
  3765. /* Send all current and obsolete cache opt-out directives. */
  3766. return mg_printf(conn,
  3767. "Cache-Control: no-cache, no-store, "
  3768. "must-revalidate, private, max-age=0\r\n"
  3769. "Pragma: no-cache\r\n"
  3770. "Expires: 0\r\n");
  3771. }
  3772. static int
  3773. send_static_cache_header(struct mg_connection *conn)
  3774. {
  3775. #if !defined(NO_CACHING)
  3776. int max_age;
  3777. const char *cache_control =
  3778. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3779. if (cache_control != NULL) {
  3780. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3781. }
  3782. /* Read the server config to check how long a file may be cached.
  3783. * The configuration is in seconds. */
  3784. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3785. if (max_age <= 0) {
  3786. /* 0 means "do not cache". All values <0 are reserved
  3787. * and may be used differently in the future. */
  3788. /* If a file should not be cached, do not only send
  3789. * max-age=0, but also pragmas and Expires headers. */
  3790. return send_no_cache_header(conn);
  3791. }
  3792. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3793. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3794. /* See also https://www.mnot.net/cache_docs/ */
  3795. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3796. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3797. * leap
  3798. * year to 31622400 seconds. For the moment, we just send whatever has
  3799. * been configured, still the behavior for >1 year should be considered
  3800. * as undefined. */
  3801. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3802. #else /* NO_CACHING */
  3803. return send_no_cache_header(conn);
  3804. #endif /* !NO_CACHING */
  3805. }
  3806. static int
  3807. send_additional_header(struct mg_connection *conn)
  3808. {
  3809. int i = 0;
  3810. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3811. #if !defined(NO_SSL)
  3812. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3813. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3814. if (max_age >= 0) {
  3815. i += mg_printf(conn,
  3816. "Strict-Transport-Security: max-age=%u\r\n",
  3817. (unsigned)max_age);
  3818. }
  3819. }
  3820. #endif
  3821. if (header && header[0]) {
  3822. i += mg_printf(conn, "%s\r\n", header);
  3823. }
  3824. return i;
  3825. }
  3826. #if !defined(NO_FILESYSTEMS)
  3827. static void handle_file_based_request(struct mg_connection *conn,
  3828. const char *path,
  3829. struct mg_file *filep);
  3830. #endif /* NO_FILESYSTEMS */
  3831. const char *
  3832. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3833. {
  3834. /* See IANA HTTP status code assignment:
  3835. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3836. */
  3837. switch (response_code) {
  3838. /* RFC2616 Section 10.1 - Informational 1xx */
  3839. case 100:
  3840. return "Continue"; /* RFC2616 Section 10.1.1 */
  3841. case 101:
  3842. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3843. case 102:
  3844. return "Processing"; /* RFC2518 Section 10.1 */
  3845. /* RFC2616 Section 10.2 - Successful 2xx */
  3846. case 200:
  3847. return "OK"; /* RFC2616 Section 10.2.1 */
  3848. case 201:
  3849. return "Created"; /* RFC2616 Section 10.2.2 */
  3850. case 202:
  3851. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3852. case 203:
  3853. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3854. case 204:
  3855. return "No Content"; /* RFC2616 Section 10.2.5 */
  3856. case 205:
  3857. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3858. case 206:
  3859. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3860. case 207:
  3861. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3862. */
  3863. case 208:
  3864. return "Already Reported"; /* RFC5842 Section 7.1 */
  3865. case 226:
  3866. return "IM used"; /* RFC3229 Section 10.4.1 */
  3867. /* RFC2616 Section 10.3 - Redirection 3xx */
  3868. case 300:
  3869. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3870. case 301:
  3871. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3872. case 302:
  3873. return "Found"; /* RFC2616 Section 10.3.3 */
  3874. case 303:
  3875. return "See Other"; /* RFC2616 Section 10.3.4 */
  3876. case 304:
  3877. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3878. case 305:
  3879. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3880. case 307:
  3881. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3882. case 308:
  3883. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3884. /* RFC2616 Section 10.4 - Client Error 4xx */
  3885. case 400:
  3886. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3887. case 401:
  3888. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3889. case 402:
  3890. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3891. case 403:
  3892. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3893. case 404:
  3894. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3895. case 405:
  3896. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3897. case 406:
  3898. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3899. case 407:
  3900. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3901. case 408:
  3902. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3903. case 409:
  3904. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3905. case 410:
  3906. return "Gone"; /* RFC2616 Section 10.4.11 */
  3907. case 411:
  3908. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3909. case 412:
  3910. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3911. case 413:
  3912. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3913. case 414:
  3914. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3915. case 415:
  3916. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3917. case 416:
  3918. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3919. */
  3920. case 417:
  3921. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3922. case 421:
  3923. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3924. case 422:
  3925. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3926. * Section 11.2 */
  3927. case 423:
  3928. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3929. case 424:
  3930. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3931. * Section 11.4 */
  3932. case 426:
  3933. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3934. case 428:
  3935. return "Precondition Required"; /* RFC 6585, Section 3 */
  3936. case 429:
  3937. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3938. case 431:
  3939. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3940. case 451:
  3941. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3942. * Section 3 */
  3943. /* RFC2616 Section 10.5 - Server Error 5xx */
  3944. case 500:
  3945. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3946. case 501:
  3947. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3948. case 502:
  3949. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3950. case 503:
  3951. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3952. case 504:
  3953. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3954. case 505:
  3955. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3956. case 506:
  3957. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3958. case 507:
  3959. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3960. * Section 11.5 */
  3961. case 508:
  3962. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3963. case 510:
  3964. return "Not Extended"; /* RFC 2774, Section 7 */
  3965. case 511:
  3966. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3967. /* Other status codes, not shown in the IANA HTTP status code
  3968. * assignment.
  3969. * E.g., "de facto" standards due to common use, ... */
  3970. case 418:
  3971. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3972. case 419:
  3973. return "Authentication Timeout"; /* common use */
  3974. case 420:
  3975. return "Enhance Your Calm"; /* common use */
  3976. case 440:
  3977. return "Login Timeout"; /* common use */
  3978. case 509:
  3979. return "Bandwidth Limit Exceeded"; /* common use */
  3980. default:
  3981. /* This error code is unknown. This should not happen. */
  3982. if (conn) {
  3983. mg_cry_internal(conn,
  3984. "Unknown HTTP response code: %u",
  3985. response_code);
  3986. }
  3987. /* Return at least a category according to RFC 2616 Section 10. */
  3988. if (response_code >= 100 && response_code < 200) {
  3989. /* Unknown informational status code */
  3990. return "Information";
  3991. }
  3992. if (response_code >= 200 && response_code < 300) {
  3993. /* Unknown success code */
  3994. return "Success";
  3995. }
  3996. if (response_code >= 300 && response_code < 400) {
  3997. /* Unknown redirection code */
  3998. return "Redirection";
  3999. }
  4000. if (response_code >= 400 && response_code < 500) {
  4001. /* Unknown request error code */
  4002. return "Client Error";
  4003. }
  4004. if (response_code >= 500 && response_code < 600) {
  4005. /* Unknown server error code */
  4006. return "Server Error";
  4007. }
  4008. /* Response code not even within reasonable range */
  4009. return "";
  4010. }
  4011. }
  4012. static int
  4013. mg_send_http_error_impl(struct mg_connection *conn,
  4014. int status,
  4015. const char *fmt,
  4016. va_list args)
  4017. {
  4018. char errmsg_buf[MG_BUF_LEN];
  4019. va_list ap;
  4020. int has_body;
  4021. char date[64];
  4022. time_t curtime = time(NULL);
  4023. #if !defined(NO_FILESYSTEMS)
  4024. char path_buf[PATH_MAX];
  4025. int len, i, page_handler_found, scope, truncated;
  4026. const char *error_handler = NULL;
  4027. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4028. const char *error_page_file_ext, *tstr;
  4029. #endif /* NO_FILESYSTEMS */
  4030. int handled_by_callback = 0;
  4031. const char *status_text = mg_get_response_code_text(conn, status);
  4032. if ((conn == NULL) || (fmt == NULL)) {
  4033. return -2;
  4034. }
  4035. /* Set status (for log) */
  4036. conn->status_code = status;
  4037. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4038. has_body = ((status > 199) && (status != 204) && (status != 304));
  4039. /* Prepare message in buf, if required */
  4040. if (has_body
  4041. || (!conn->in_error_handler
  4042. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4043. /* Store error message in errmsg_buf */
  4044. va_copy(ap, args);
  4045. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4046. va_end(ap);
  4047. /* In a debug build, print all html errors */
  4048. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4049. }
  4050. /* If there is a http_error callback, call it.
  4051. * But don't do it recursively, if callback calls mg_send_http_error again.
  4052. */
  4053. if (!conn->in_error_handler
  4054. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4055. /* Mark in_error_handler to avoid recursion and call user callback. */
  4056. conn->in_error_handler = 1;
  4057. handled_by_callback =
  4058. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4059. == 0);
  4060. conn->in_error_handler = 0;
  4061. }
  4062. if (!handled_by_callback) {
  4063. /* Check for recursion */
  4064. if (conn->in_error_handler) {
  4065. DEBUG_TRACE(
  4066. "Recursion when handling error %u - fall back to default",
  4067. status);
  4068. #if !defined(NO_FILESYSTEMS)
  4069. } else {
  4070. /* Send user defined error pages, if defined */
  4071. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4072. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4073. page_handler_found = 0;
  4074. if (error_handler != NULL) {
  4075. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4076. switch (scope) {
  4077. case 1: /* Handler for specific error, e.g. 404 error */
  4078. mg_snprintf(conn,
  4079. &truncated,
  4080. path_buf,
  4081. sizeof(path_buf) - 32,
  4082. "%serror%03u.",
  4083. error_handler,
  4084. status);
  4085. break;
  4086. case 2: /* Handler for error group, e.g., 5xx error
  4087. * handler
  4088. * for all server errors (500-599) */
  4089. mg_snprintf(conn,
  4090. &truncated,
  4091. path_buf,
  4092. sizeof(path_buf) - 32,
  4093. "%serror%01uxx.",
  4094. error_handler,
  4095. status / 100);
  4096. break;
  4097. default: /* Handler for all errors */
  4098. mg_snprintf(conn,
  4099. &truncated,
  4100. path_buf,
  4101. sizeof(path_buf) - 32,
  4102. "%serror.",
  4103. error_handler);
  4104. break;
  4105. }
  4106. /* String truncation in buf may only occur if
  4107. * error_handler is too long. This string is
  4108. * from the config, not from a client. */
  4109. (void)truncated;
  4110. /* The following code is redundant, but it should avoid
  4111. * false positives in static source code analyzers and
  4112. * vulnerability scanners.
  4113. */
  4114. path_buf[sizeof(path_buf) - 32] = 0;
  4115. len = (int)strlen(path_buf);
  4116. if (len > (int)sizeof(path_buf) - 32) {
  4117. len = (int)sizeof(path_buf) - 32;
  4118. }
  4119. /* Start with the file extenstion from the configuration. */
  4120. tstr = strchr(error_page_file_ext, '.');
  4121. while (tstr) {
  4122. for (i = 1;
  4123. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4124. i++) {
  4125. /* buffer overrun is not possible here, since
  4126. * (i < 32) && (len < sizeof(path_buf) - 32)
  4127. * ==> (i + len) < sizeof(path_buf) */
  4128. path_buf[len + i - 1] = tstr[i];
  4129. }
  4130. /* buffer overrun is not possible here, since
  4131. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4132. * ==> (i + len) <= sizeof(path_buf) */
  4133. path_buf[len + i - 1] = 0;
  4134. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4135. DEBUG_TRACE("Check error page %s - found",
  4136. path_buf);
  4137. page_handler_found = 1;
  4138. break;
  4139. }
  4140. DEBUG_TRACE("Check error page %s - not found",
  4141. path_buf);
  4142. /* Continue with the next file extenstion from the
  4143. * configuration (if there is a next one). */
  4144. tstr = strchr(tstr + i, '.');
  4145. }
  4146. }
  4147. }
  4148. if (page_handler_found) {
  4149. conn->in_error_handler = 1;
  4150. handle_file_based_request(conn, path_buf, &error_page_file);
  4151. conn->in_error_handler = 0;
  4152. return 0;
  4153. }
  4154. #endif /* NO_FILESYSTEMS */
  4155. }
  4156. /* No custom error page. Send default error page. */
  4157. gmt_time_string(date, sizeof(date), &curtime);
  4158. conn->must_close = 1;
  4159. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4160. send_no_cache_header(conn);
  4161. send_additional_header(conn);
  4162. if (has_body) {
  4163. mg_printf(conn,
  4164. "%s",
  4165. "Content-Type: text/plain; charset=utf-8\r\n");
  4166. }
  4167. mg_printf(conn,
  4168. "Date: %s\r\n"
  4169. "Connection: close\r\n\r\n",
  4170. date);
  4171. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4172. if (has_body) {
  4173. /* For other errors, send a generic error message. */
  4174. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4175. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4176. } else {
  4177. /* No body allowed. Close the connection. */
  4178. DEBUG_TRACE("Error %i", status);
  4179. }
  4180. }
  4181. return 0;
  4182. }
  4183. int
  4184. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4185. {
  4186. va_list ap;
  4187. int ret;
  4188. va_start(ap, fmt);
  4189. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4190. va_end(ap);
  4191. return ret;
  4192. }
  4193. int
  4194. mg_send_http_ok(struct mg_connection *conn,
  4195. const char *mime_type,
  4196. long long content_length)
  4197. {
  4198. char date[64];
  4199. time_t curtime = time(NULL);
  4200. if ((mime_type == NULL) || (*mime_type == 0)) {
  4201. /* No content type defined: default to text/html */
  4202. mime_type = "text/html";
  4203. }
  4204. gmt_time_string(date, sizeof(date), &curtime);
  4205. mg_printf(conn,
  4206. "HTTP/1.1 200 OK\r\n"
  4207. "Content-Type: %s\r\n"
  4208. "Date: %s\r\n"
  4209. "Connection: %s\r\n",
  4210. mime_type,
  4211. date,
  4212. suggest_connection_header(conn));
  4213. send_no_cache_header(conn);
  4214. send_additional_header(conn);
  4215. if (content_length < 0) {
  4216. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4217. } else {
  4218. mg_printf(conn,
  4219. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4220. (uint64_t)content_length);
  4221. }
  4222. return 0;
  4223. }
  4224. int
  4225. mg_send_http_redirect(struct mg_connection *conn,
  4226. const char *target_url,
  4227. int redirect_code)
  4228. {
  4229. /* Send a 30x redirect response.
  4230. *
  4231. * Redirect types (status codes):
  4232. *
  4233. * Status | Perm/Temp | Method | Version
  4234. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4235. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4236. * 303 | temporary | always use GET | HTTP/1.1
  4237. * 307 | temporary | always keep method | HTTP/1.1
  4238. * 308 | permanent | always keep method | HTTP/1.1
  4239. */
  4240. const char *redirect_text;
  4241. int ret;
  4242. size_t content_len = 0;
  4243. char reply[MG_BUF_LEN];
  4244. /* In case redirect_code=0, use 307. */
  4245. if (redirect_code == 0) {
  4246. redirect_code = 307;
  4247. }
  4248. /* In case redirect_code is none of the above, return error. */
  4249. if ((redirect_code != 301) && (redirect_code != 302)
  4250. && (redirect_code != 303) && (redirect_code != 307)
  4251. && (redirect_code != 308)) {
  4252. /* Parameter error */
  4253. return -2;
  4254. }
  4255. /* Get proper text for response code */
  4256. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4257. /* If target_url is not defined, redirect to "/". */
  4258. if ((target_url == NULL) || (*target_url == 0)) {
  4259. target_url = "/";
  4260. }
  4261. #if defined(MG_SEND_REDIRECT_BODY)
  4262. /* TODO: condition name? */
  4263. /* Prepare a response body with a hyperlink.
  4264. *
  4265. * According to RFC2616 (and RFC1945 before):
  4266. * Unless the request method was HEAD, the entity of the
  4267. * response SHOULD contain a short hypertext note with a hyperlink to
  4268. * the new URI(s).
  4269. *
  4270. * However, this response body is not useful in M2M communication.
  4271. * Probably the original reason in the RFC was, clients not supporting
  4272. * a 30x HTTP redirect could still show the HTML page and let the user
  4273. * press the link. Since current browsers support 30x HTTP, the additional
  4274. * HTML body does not seem to make sense anymore.
  4275. *
  4276. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4277. * but it only notes:
  4278. * The server's response payload usually contains a short
  4279. * hypertext note with a hyperlink to the new URI(s).
  4280. *
  4281. * Deactivated by default. If you need the 30x body, set the define.
  4282. */
  4283. mg_snprintf(
  4284. conn,
  4285. NULL /* ignore truncation */,
  4286. reply,
  4287. sizeof(reply),
  4288. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4289. redirect_text,
  4290. target_url,
  4291. target_url);
  4292. content_len = strlen(reply);
  4293. #else
  4294. reply[0] = 0;
  4295. #endif
  4296. /* Do not send any additional header. For all other options,
  4297. * including caching, there are suitable defaults. */
  4298. ret = mg_printf(conn,
  4299. "HTTP/1.1 %i %s\r\n"
  4300. "Location: %s\r\n"
  4301. "Content-Length: %u\r\n"
  4302. "Connection: %s\r\n\r\n",
  4303. redirect_code,
  4304. redirect_text,
  4305. target_url,
  4306. (unsigned int)content_len,
  4307. suggest_connection_header(conn));
  4308. /* Send response body */
  4309. if (ret > 0) {
  4310. /* ... unless it is a HEAD request */
  4311. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4312. ret = mg_write(conn, reply, content_len);
  4313. }
  4314. }
  4315. return (ret > 0) ? ret : -1;
  4316. }
  4317. #if defined(_WIN32)
  4318. /* Create substitutes for POSIX functions in Win32. */
  4319. #if defined(GCC_DIAGNOSTIC)
  4320. /* Show no warning in case system functions are not used. */
  4321. #pragma GCC diagnostic push
  4322. #pragma GCC diagnostic ignored "-Wunused-function"
  4323. #endif
  4324. static int
  4325. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4326. {
  4327. (void)unused;
  4328. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4329. InitializeCriticalSection(&mutex->sec);
  4330. return 0;
  4331. }
  4332. static int
  4333. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4334. {
  4335. DeleteCriticalSection(&mutex->sec);
  4336. return 0;
  4337. }
  4338. static int
  4339. pthread_mutex_lock(pthread_mutex_t *mutex)
  4340. {
  4341. EnterCriticalSection(&mutex->sec);
  4342. return 0;
  4343. }
  4344. static int
  4345. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4346. {
  4347. LeaveCriticalSection(&mutex->sec);
  4348. return 0;
  4349. }
  4350. FUNCTION_MAY_BE_UNUSED
  4351. static int
  4352. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4353. {
  4354. (void)unused;
  4355. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4356. cv->waiting_thread = NULL;
  4357. return 0;
  4358. }
  4359. FUNCTION_MAY_BE_UNUSED
  4360. static int
  4361. pthread_cond_timedwait(pthread_cond_t *cv,
  4362. pthread_mutex_t *mutex,
  4363. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4364. {
  4365. struct mg_workerTLS **ptls,
  4366. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4367. int ok;
  4368. int64_t nsnow, nswaitabs, nswaitrel;
  4369. DWORD mswaitrel;
  4370. pthread_mutex_lock(&cv->threadIdSec);
  4371. /* Add this thread to cv's waiting list */
  4372. ptls = &cv->waiting_thread;
  4373. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4374. ;
  4375. tls->next_waiting_thread = NULL;
  4376. *ptls = tls;
  4377. pthread_mutex_unlock(&cv->threadIdSec);
  4378. if (abstime) {
  4379. nsnow = mg_get_current_time_ns();
  4380. nswaitabs =
  4381. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4382. nswaitrel = nswaitabs - nsnow;
  4383. if (nswaitrel < 0) {
  4384. nswaitrel = 0;
  4385. }
  4386. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4387. } else {
  4388. mswaitrel = (DWORD)INFINITE;
  4389. }
  4390. pthread_mutex_unlock(mutex);
  4391. ok = (WAIT_OBJECT_0
  4392. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4393. if (!ok) {
  4394. ok = 1;
  4395. pthread_mutex_lock(&cv->threadIdSec);
  4396. ptls = &cv->waiting_thread;
  4397. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4398. if (*ptls == tls) {
  4399. *ptls = tls->next_waiting_thread;
  4400. ok = 0;
  4401. break;
  4402. }
  4403. }
  4404. pthread_mutex_unlock(&cv->threadIdSec);
  4405. if (ok) {
  4406. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4407. (DWORD)INFINITE);
  4408. }
  4409. }
  4410. /* This thread has been removed from cv's waiting list */
  4411. pthread_mutex_lock(mutex);
  4412. return ok ? 0 : -1;
  4413. }
  4414. FUNCTION_MAY_BE_UNUSED
  4415. static int
  4416. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4417. {
  4418. return pthread_cond_timedwait(cv, mutex, NULL);
  4419. }
  4420. FUNCTION_MAY_BE_UNUSED
  4421. static int
  4422. pthread_cond_signal(pthread_cond_t *cv)
  4423. {
  4424. HANDLE wkup = NULL;
  4425. BOOL ok = FALSE;
  4426. pthread_mutex_lock(&cv->threadIdSec);
  4427. if (cv->waiting_thread) {
  4428. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4429. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4430. ok = SetEvent(wkup);
  4431. DEBUG_ASSERT(ok);
  4432. }
  4433. pthread_mutex_unlock(&cv->threadIdSec);
  4434. return ok ? 0 : 1;
  4435. }
  4436. FUNCTION_MAY_BE_UNUSED
  4437. static int
  4438. pthread_cond_broadcast(pthread_cond_t *cv)
  4439. {
  4440. pthread_mutex_lock(&cv->threadIdSec);
  4441. while (cv->waiting_thread) {
  4442. pthread_cond_signal(cv);
  4443. }
  4444. pthread_mutex_unlock(&cv->threadIdSec);
  4445. return 0;
  4446. }
  4447. FUNCTION_MAY_BE_UNUSED
  4448. static int
  4449. pthread_cond_destroy(pthread_cond_t *cv)
  4450. {
  4451. pthread_mutex_lock(&cv->threadIdSec);
  4452. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4453. pthread_mutex_unlock(&cv->threadIdSec);
  4454. pthread_mutex_destroy(&cv->threadIdSec);
  4455. return 0;
  4456. }
  4457. #if defined(ALTERNATIVE_QUEUE)
  4458. FUNCTION_MAY_BE_UNUSED
  4459. static void *
  4460. event_create(void)
  4461. {
  4462. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4463. }
  4464. FUNCTION_MAY_BE_UNUSED
  4465. static int
  4466. event_wait(void *eventhdl)
  4467. {
  4468. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4469. return (res == WAIT_OBJECT_0);
  4470. }
  4471. FUNCTION_MAY_BE_UNUSED
  4472. static int
  4473. event_signal(void *eventhdl)
  4474. {
  4475. return (int)SetEvent((HANDLE)eventhdl);
  4476. }
  4477. FUNCTION_MAY_BE_UNUSED
  4478. static void
  4479. event_destroy(void *eventhdl)
  4480. {
  4481. CloseHandle((HANDLE)eventhdl);
  4482. }
  4483. #endif
  4484. #if defined(GCC_DIAGNOSTIC)
  4485. /* Enable unused function warning again */
  4486. #pragma GCC diagnostic pop
  4487. #endif
  4488. /* For Windows, change all slashes to backslashes in path names. */
  4489. static void
  4490. change_slashes_to_backslashes(char *path)
  4491. {
  4492. int i;
  4493. for (i = 0; path[i] != '\0'; i++) {
  4494. if (path[i] == '/') {
  4495. path[i] = '\\';
  4496. }
  4497. /* remove double backslash (check i > 0 to preserve UNC paths,
  4498. * like \\server\file.txt) */
  4499. if ((i > 0) && (path[i] == '\\')) {
  4500. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4501. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4502. }
  4503. }
  4504. }
  4505. }
  4506. static int
  4507. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4508. {
  4509. int diff;
  4510. do {
  4511. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4512. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4513. s1++;
  4514. s2++;
  4515. } while ((diff == 0) && (s1[-1] != L'\0'));
  4516. return diff;
  4517. }
  4518. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4519. * wbuf and wbuf_len is a target buffer and its length. */
  4520. static void
  4521. path_to_unicode(const struct mg_connection *conn,
  4522. const char *path,
  4523. wchar_t *wbuf,
  4524. size_t wbuf_len)
  4525. {
  4526. char buf[PATH_MAX], buf2[PATH_MAX];
  4527. wchar_t wbuf2[W_PATH_MAX + 1];
  4528. DWORD long_len, err;
  4529. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4530. mg_strlcpy(buf, path, sizeof(buf));
  4531. change_slashes_to_backslashes(buf);
  4532. /* Convert to Unicode and back. If doubly-converted string does not
  4533. * match the original, something is fishy, reject. */
  4534. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4535. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4536. WideCharToMultiByte(
  4537. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4538. if (strcmp(buf, buf2) != 0) {
  4539. wbuf[0] = L'\0';
  4540. }
  4541. /* Windows file systems are not case sensitive, but you can still use
  4542. * uppercase and lowercase letters (on all modern file systems).
  4543. * The server can check if the URI uses the same upper/lowercase
  4544. * letters an the file system, effectively making Windows servers
  4545. * case sensitive (like Linux servers are). It is still not possible
  4546. * to use two files with the same name in different cases on Windows
  4547. * (like /a and /A) - this would be possible in Linux.
  4548. * As a default, Windows is not case sensitive, but the case sensitive
  4549. * file name check can be activated by an additional configuration. */
  4550. if (conn) {
  4551. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4552. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4553. "yes")) {
  4554. /* Use case sensitive compare function */
  4555. fcompare = wcscmp;
  4556. }
  4557. }
  4558. (void)conn; /* conn is currently unused */
  4559. #if !defined(_WIN32_WCE)
  4560. /* Only accept a full file path, not a Windows short (8.3) path. */
  4561. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4562. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4563. if (long_len == 0) {
  4564. err = GetLastError();
  4565. if (err == ERROR_FILE_NOT_FOUND) {
  4566. /* File does not exist. This is not always a problem here. */
  4567. return;
  4568. }
  4569. }
  4570. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4571. /* Short name is used. */
  4572. wbuf[0] = L'\0';
  4573. }
  4574. #else
  4575. (void)long_len;
  4576. (void)wbuf2;
  4577. (void)err;
  4578. if (strchr(path, '~')) {
  4579. wbuf[0] = L'\0';
  4580. }
  4581. #endif
  4582. }
  4583. #if !defined(NO_FILESYSTEMS)
  4584. static int
  4585. mg_stat(const struct mg_connection *conn,
  4586. const char *path,
  4587. struct mg_file_stat *filep)
  4588. {
  4589. wchar_t wbuf[W_PATH_MAX];
  4590. WIN32_FILE_ATTRIBUTE_DATA info;
  4591. time_t creation_time;
  4592. size_t len;
  4593. if (!filep) {
  4594. return 0;
  4595. }
  4596. memset(filep, 0, sizeof(*filep));
  4597. if (conn && is_file_in_memory(conn, path)) {
  4598. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4599. * memset */
  4600. /* Quick fix (for 1.9.x): */
  4601. /* mg_stat must fill all fields, also for files in memory */
  4602. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4603. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4604. filep->size = tmp_file.stat.size;
  4605. filep->location = 2;
  4606. /* TODO: for 1.10: restructure how files in memory are handled */
  4607. /* The "file in memory" feature is a candidate for deletion.
  4608. * Please join the discussion at
  4609. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4610. */
  4611. filep->last_modified = time(NULL); /* TODO */
  4612. /* last_modified = now ... assumes the file may change during
  4613. * runtime,
  4614. * so every mg_fopen call may return different data */
  4615. /* last_modified = conn->phys_ctx.start_time;
  4616. * May be used it the data does not change during runtime. This
  4617. * allows
  4618. * browser caching. Since we do not know, we have to assume the file
  4619. * in memory may change. */
  4620. return 1;
  4621. }
  4622. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4623. /* Windows happily opens files with some garbage at the end of file name.
  4624. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4625. * "a.cgi", despite one would expect an error back. */
  4626. len = strlen(path);
  4627. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4628. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4629. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4630. filep->last_modified =
  4631. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4632. info.ftLastWriteTime.dwHighDateTime);
  4633. /* On Windows, the file creation time can be higher than the
  4634. * modification time, e.g. when a file is copied.
  4635. * Since the Last-Modified timestamp is used for caching
  4636. * it should be based on the most recent timestamp. */
  4637. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4638. info.ftCreationTime.dwHighDateTime);
  4639. if (creation_time > filep->last_modified) {
  4640. filep->last_modified = creation_time;
  4641. }
  4642. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4643. return 1;
  4644. }
  4645. return 0;
  4646. }
  4647. #endif
  4648. static int
  4649. mg_remove(const struct mg_connection *conn, const char *path)
  4650. {
  4651. wchar_t wbuf[W_PATH_MAX];
  4652. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4653. return DeleteFileW(wbuf) ? 0 : -1;
  4654. }
  4655. static int
  4656. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4657. {
  4658. wchar_t wbuf[W_PATH_MAX];
  4659. (void)mode;
  4660. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4661. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4662. }
  4663. /* Create substitutes for POSIX functions in Win32. */
  4664. #if defined(GCC_DIAGNOSTIC)
  4665. /* Show no warning in case system functions are not used. */
  4666. #pragma GCC diagnostic push
  4667. #pragma GCC diagnostic ignored "-Wunused-function"
  4668. #endif
  4669. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4670. FUNCTION_MAY_BE_UNUSED
  4671. static DIR *
  4672. mg_opendir(const struct mg_connection *conn, const char *name)
  4673. {
  4674. DIR *dir = NULL;
  4675. wchar_t wpath[W_PATH_MAX];
  4676. DWORD attrs;
  4677. if (name == NULL) {
  4678. SetLastError(ERROR_BAD_ARGUMENTS);
  4679. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4680. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4681. } else {
  4682. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4683. attrs = GetFileAttributesW(wpath);
  4684. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4685. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4686. (void)wcscat(wpath, L"\\*");
  4687. dir->handle = FindFirstFileW(wpath, &dir->info);
  4688. dir->result.d_name[0] = '\0';
  4689. } else {
  4690. mg_free(dir);
  4691. dir = NULL;
  4692. }
  4693. }
  4694. return dir;
  4695. }
  4696. FUNCTION_MAY_BE_UNUSED
  4697. static int
  4698. mg_closedir(DIR *dir)
  4699. {
  4700. int result = 0;
  4701. if (dir != NULL) {
  4702. if (dir->handle != INVALID_HANDLE_VALUE)
  4703. result = FindClose(dir->handle) ? 0 : -1;
  4704. mg_free(dir);
  4705. } else {
  4706. result = -1;
  4707. SetLastError(ERROR_BAD_ARGUMENTS);
  4708. }
  4709. return result;
  4710. }
  4711. FUNCTION_MAY_BE_UNUSED
  4712. static struct dirent *
  4713. mg_readdir(DIR *dir)
  4714. {
  4715. struct dirent *result = 0;
  4716. if (dir) {
  4717. if (dir->handle != INVALID_HANDLE_VALUE) {
  4718. result = &dir->result;
  4719. (void)WideCharToMultiByte(CP_UTF8,
  4720. 0,
  4721. dir->info.cFileName,
  4722. -1,
  4723. result->d_name,
  4724. sizeof(result->d_name),
  4725. NULL,
  4726. NULL);
  4727. if (!FindNextFileW(dir->handle, &dir->info)) {
  4728. (void)FindClose(dir->handle);
  4729. dir->handle = INVALID_HANDLE_VALUE;
  4730. }
  4731. } else {
  4732. SetLastError(ERROR_FILE_NOT_FOUND);
  4733. }
  4734. } else {
  4735. SetLastError(ERROR_BAD_ARGUMENTS);
  4736. }
  4737. return result;
  4738. }
  4739. #if !defined(HAVE_POLL)
  4740. #undef POLLIN
  4741. #undef POLLPRI
  4742. #undef POLLOUT
  4743. #define POLLIN (1) /* Data ready - read will not block. */
  4744. #define POLLPRI (2) /* Priority data ready. */
  4745. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4746. FUNCTION_MAY_BE_UNUSED
  4747. static int
  4748. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4749. {
  4750. struct timeval tv;
  4751. fd_set rset;
  4752. fd_set wset;
  4753. unsigned int i;
  4754. int result;
  4755. SOCKET maxfd = 0;
  4756. memset(&tv, 0, sizeof(tv));
  4757. tv.tv_sec = milliseconds / 1000;
  4758. tv.tv_usec = (milliseconds % 1000) * 1000;
  4759. FD_ZERO(&rset);
  4760. FD_ZERO(&wset);
  4761. for (i = 0; i < n; i++) {
  4762. if (pfd[i].events & POLLIN) {
  4763. FD_SET(pfd[i].fd, &rset);
  4764. }
  4765. if (pfd[i].events & POLLOUT) {
  4766. FD_SET(pfd[i].fd, &wset);
  4767. }
  4768. pfd[i].revents = 0;
  4769. if (pfd[i].fd > maxfd) {
  4770. maxfd = pfd[i].fd;
  4771. }
  4772. }
  4773. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4774. for (i = 0; i < n; i++) {
  4775. if (FD_ISSET(pfd[i].fd, &rset)) {
  4776. pfd[i].revents |= POLLIN;
  4777. }
  4778. if (FD_ISSET(pfd[i].fd, &wset)) {
  4779. pfd[i].revents |= POLLOUT;
  4780. }
  4781. }
  4782. }
  4783. /* We should subtract the time used in select from remaining
  4784. * "milliseconds", in particular if called from mg_poll with a
  4785. * timeout quantum.
  4786. * Unfortunately, the remaining time is not stored in "tv" in all
  4787. * implementations, so the result in "tv" must be considered undefined.
  4788. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4789. return result;
  4790. }
  4791. #endif /* HAVE_POLL */
  4792. #if defined(GCC_DIAGNOSTIC)
  4793. /* Enable unused function warning again */
  4794. #pragma GCC diagnostic pop
  4795. #endif
  4796. static void
  4797. set_close_on_exec(SOCKET sock,
  4798. const struct mg_connection *conn /* may be null */,
  4799. struct mg_context *ctx /* may be null */)
  4800. {
  4801. (void)conn; /* Unused. */
  4802. (void)ctx;
  4803. #if defined(_WIN32_WCE)
  4804. (void)sock;
  4805. #else
  4806. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4807. #endif
  4808. }
  4809. int
  4810. mg_start_thread(mg_thread_func_t f, void *p)
  4811. {
  4812. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4813. /* Compile-time option to control stack size, e.g.
  4814. * -DUSE_STACK_SIZE=16384
  4815. */
  4816. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4817. == ((uintptr_t)(-1L)))
  4818. ? -1
  4819. : 0);
  4820. #else
  4821. return (
  4822. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4823. ? -1
  4824. : 0);
  4825. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4826. }
  4827. /* Start a thread storing the thread context. */
  4828. static int
  4829. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4830. void *p,
  4831. pthread_t *threadidptr)
  4832. {
  4833. uintptr_t uip;
  4834. HANDLE threadhandle;
  4835. int result = -1;
  4836. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4837. threadhandle = (HANDLE)uip;
  4838. if ((uip != 0) && (threadidptr != NULL)) {
  4839. *threadidptr = threadhandle;
  4840. result = 0;
  4841. }
  4842. return result;
  4843. }
  4844. /* Wait for a thread to finish. */
  4845. static int
  4846. mg_join_thread(pthread_t threadid)
  4847. {
  4848. int result;
  4849. DWORD dwevent;
  4850. result = -1;
  4851. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4852. if (dwevent == WAIT_FAILED) {
  4853. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4854. } else {
  4855. if (dwevent == WAIT_OBJECT_0) {
  4856. CloseHandle(threadid);
  4857. result = 0;
  4858. }
  4859. }
  4860. return result;
  4861. }
  4862. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4863. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4864. /* Create substitutes for POSIX functions in Win32. */
  4865. #if defined(GCC_DIAGNOSTIC)
  4866. /* Show no warning in case system functions are not used. */
  4867. #pragma GCC diagnostic push
  4868. #pragma GCC diagnostic ignored "-Wunused-function"
  4869. #endif
  4870. FUNCTION_MAY_BE_UNUSED
  4871. static HANDLE
  4872. dlopen(const char *dll_name, int flags)
  4873. {
  4874. wchar_t wbuf[W_PATH_MAX];
  4875. (void)flags;
  4876. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4877. return LoadLibraryW(wbuf);
  4878. }
  4879. FUNCTION_MAY_BE_UNUSED
  4880. static int
  4881. dlclose(void *handle)
  4882. {
  4883. int result;
  4884. if (FreeLibrary((HMODULE)handle) != 0) {
  4885. result = 0;
  4886. } else {
  4887. result = -1;
  4888. }
  4889. return result;
  4890. }
  4891. #if defined(GCC_DIAGNOSTIC)
  4892. /* Enable unused function warning again */
  4893. #pragma GCC diagnostic pop
  4894. #endif
  4895. #endif
  4896. #if !defined(NO_CGI)
  4897. #define SIGKILL (0)
  4898. static int
  4899. kill(pid_t pid, int sig_num)
  4900. {
  4901. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4902. (void)CloseHandle((HANDLE)pid);
  4903. return 0;
  4904. }
  4905. #if !defined(WNOHANG)
  4906. #define WNOHANG (1)
  4907. #endif
  4908. static pid_t
  4909. waitpid(pid_t pid, int *status, int flags)
  4910. {
  4911. DWORD timeout = INFINITE;
  4912. DWORD waitres;
  4913. (void)status; /* Currently not used by any client here */
  4914. if ((flags | WNOHANG) == WNOHANG) {
  4915. timeout = 0;
  4916. }
  4917. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4918. if (waitres == WAIT_OBJECT_0) {
  4919. return pid;
  4920. }
  4921. if (waitres == WAIT_TIMEOUT) {
  4922. return 0;
  4923. }
  4924. return (pid_t)-1;
  4925. }
  4926. static void
  4927. trim_trailing_whitespaces(char *s)
  4928. {
  4929. char *e = s + strlen(s);
  4930. while ((e > s) && isspace((unsigned char)e[-1])) {
  4931. *(--e) = '\0';
  4932. }
  4933. }
  4934. static pid_t
  4935. spawn_process(struct mg_connection *conn,
  4936. const char *prog,
  4937. char *envblk,
  4938. char *envp[],
  4939. int fdin[2],
  4940. int fdout[2],
  4941. int fderr[2],
  4942. const char *dir)
  4943. {
  4944. HANDLE me;
  4945. char *p, *interp;
  4946. char *interp_arg = 0;
  4947. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4948. buf[PATH_MAX];
  4949. int truncated;
  4950. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4951. STARTUPINFOA si;
  4952. PROCESS_INFORMATION pi = {0};
  4953. (void)envp;
  4954. memset(&si, 0, sizeof(si));
  4955. si.cb = sizeof(si);
  4956. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4957. si.wShowWindow = SW_HIDE;
  4958. me = GetCurrentProcess();
  4959. DuplicateHandle(me,
  4960. (HANDLE)_get_osfhandle(fdin[0]),
  4961. me,
  4962. &si.hStdInput,
  4963. 0,
  4964. TRUE,
  4965. DUPLICATE_SAME_ACCESS);
  4966. DuplicateHandle(me,
  4967. (HANDLE)_get_osfhandle(fdout[1]),
  4968. me,
  4969. &si.hStdOutput,
  4970. 0,
  4971. TRUE,
  4972. DUPLICATE_SAME_ACCESS);
  4973. DuplicateHandle(me,
  4974. (HANDLE)_get_osfhandle(fderr[1]),
  4975. me,
  4976. &si.hStdError,
  4977. 0,
  4978. TRUE,
  4979. DUPLICATE_SAME_ACCESS);
  4980. /* Mark handles that should not be inherited. See
  4981. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4982. */
  4983. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4984. HANDLE_FLAG_INHERIT,
  4985. 0);
  4986. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4987. HANDLE_FLAG_INHERIT,
  4988. 0);
  4989. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4990. HANDLE_FLAG_INHERIT,
  4991. 0);
  4992. /* First check, if there is a CGI interpreter configured for all CGI
  4993. * scripts. */
  4994. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4995. if (interp != NULL) {
  4996. /* If there is a configured interpreter, check for additional arguments
  4997. */
  4998. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  4999. } else {
  5000. /* Otherwise, the interpreter must be stated in the first line of the
  5001. * CGI script file, after a #! (shebang) mark. */
  5002. buf[0] = buf[1] = '\0';
  5003. /* Get the full script path */
  5004. mg_snprintf(
  5005. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5006. if (truncated) {
  5007. pi.hProcess = (pid_t)-1;
  5008. goto spawn_cleanup;
  5009. }
  5010. /* Open the script file, to read the first line */
  5011. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5012. #if defined(MG_USE_OPEN_FILE)
  5013. p = (char *)file.access.membuf;
  5014. #else
  5015. p = (char *)NULL;
  5016. #endif
  5017. /* Read the first line of the script into the buffer */
  5018. mg_fgets(buf, sizeof(buf), &file, &p);
  5019. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5020. buf[sizeof(buf) - 1] = '\0';
  5021. }
  5022. if ((buf[0] == '#') && (buf[1] == '!')) {
  5023. trim_trailing_whitespaces(buf + 2);
  5024. } else {
  5025. buf[2] = '\0';
  5026. }
  5027. interp = buf + 2;
  5028. }
  5029. if (interp[0] != '\0') {
  5030. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5031. interp = full_interp;
  5032. }
  5033. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5034. if (interp[0] != '\0') {
  5035. /* This is an interpreted script file. We must call the interpreter. */
  5036. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5037. mg_snprintf(conn,
  5038. &truncated,
  5039. cmdline,
  5040. sizeof(cmdline),
  5041. "\"%s\" %s \"%s\\%s\"",
  5042. interp,
  5043. interp_arg,
  5044. full_dir,
  5045. prog);
  5046. } else {
  5047. mg_snprintf(conn,
  5048. &truncated,
  5049. cmdline,
  5050. sizeof(cmdline),
  5051. "\"%s\" \"%s\\%s\"",
  5052. interp,
  5053. full_dir,
  5054. prog);
  5055. }
  5056. } else {
  5057. /* This is (probably) a compiled program. We call it directly. */
  5058. mg_snprintf(conn,
  5059. &truncated,
  5060. cmdline,
  5061. sizeof(cmdline),
  5062. "\"%s\\%s\"",
  5063. full_dir,
  5064. prog);
  5065. }
  5066. if (truncated) {
  5067. pi.hProcess = (pid_t)-1;
  5068. goto spawn_cleanup;
  5069. }
  5070. DEBUG_TRACE("Running [%s]", cmdline);
  5071. if (CreateProcessA(NULL,
  5072. cmdline,
  5073. NULL,
  5074. NULL,
  5075. TRUE,
  5076. CREATE_NEW_PROCESS_GROUP,
  5077. envblk,
  5078. NULL,
  5079. &si,
  5080. &pi)
  5081. == 0) {
  5082. mg_cry_internal(
  5083. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5084. pi.hProcess = (pid_t)-1;
  5085. /* goto spawn_cleanup; */
  5086. }
  5087. spawn_cleanup:
  5088. (void)CloseHandle(si.hStdOutput);
  5089. (void)CloseHandle(si.hStdError);
  5090. (void)CloseHandle(si.hStdInput);
  5091. if (pi.hThread != NULL) {
  5092. (void)CloseHandle(pi.hThread);
  5093. }
  5094. return (pid_t)pi.hProcess;
  5095. }
  5096. #endif /* !NO_CGI */
  5097. static int
  5098. set_blocking_mode(SOCKET sock)
  5099. {
  5100. unsigned long non_blocking = 0;
  5101. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5102. }
  5103. static int
  5104. set_non_blocking_mode(SOCKET sock)
  5105. {
  5106. unsigned long non_blocking = 1;
  5107. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5108. }
  5109. #else
  5110. #if !defined(NO_FILESYSTEMS)
  5111. static int
  5112. mg_stat(const struct mg_connection *conn,
  5113. const char *path,
  5114. struct mg_file_stat *filep)
  5115. {
  5116. struct stat st;
  5117. if (!filep) {
  5118. return 0;
  5119. }
  5120. memset(filep, 0, sizeof(*filep));
  5121. if (conn && is_file_in_memory(conn, path)) {
  5122. /* Quick fix (for 1.9.x): */
  5123. /* mg_stat must fill all fields, also for files in memory */
  5124. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5125. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5126. filep->size = tmp_file.stat.size;
  5127. filep->last_modified = time(NULL);
  5128. filep->location = 2;
  5129. /* TODO: remove legacy "files in memory" feature */
  5130. return 1;
  5131. }
  5132. if (0 == stat(path, &st)) {
  5133. filep->size = (uint64_t)(st.st_size);
  5134. filep->last_modified = st.st_mtime;
  5135. filep->is_directory = S_ISDIR(st.st_mode);
  5136. return 1;
  5137. }
  5138. return 0;
  5139. }
  5140. #endif /* NO_FILESYSTEMS */
  5141. static void
  5142. set_close_on_exec(int fd,
  5143. const struct mg_connection *conn /* may be null */,
  5144. struct mg_context *ctx /* may be null */)
  5145. {
  5146. #if defined(__ZEPHYR__)
  5147. (void)fd;
  5148. (void)conn;
  5149. (void)ctx;
  5150. #else
  5151. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5152. if (conn || ctx) {
  5153. struct mg_connection fc;
  5154. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5155. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5156. __func__,
  5157. strerror(ERRNO));
  5158. }
  5159. }
  5160. #endif
  5161. }
  5162. int
  5163. mg_start_thread(mg_thread_func_t func, void *param)
  5164. {
  5165. pthread_t thread_id;
  5166. pthread_attr_t attr;
  5167. int result;
  5168. (void)pthread_attr_init(&attr);
  5169. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5170. #if defined(__ZEPHYR__)
  5171. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5172. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5173. /* Compile-time option to control stack size,
  5174. * e.g. -DUSE_STACK_SIZE=16384 */
  5175. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5176. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5177. result = pthread_create(&thread_id, &attr, func, param);
  5178. pthread_attr_destroy(&attr);
  5179. return result;
  5180. }
  5181. /* Start a thread storing the thread context. */
  5182. static int
  5183. mg_start_thread_with_id(mg_thread_func_t func,
  5184. void *param,
  5185. pthread_t *threadidptr)
  5186. {
  5187. pthread_t thread_id;
  5188. pthread_attr_t attr;
  5189. int result;
  5190. (void)pthread_attr_init(&attr);
  5191. #if defined(__ZEPHYR__)
  5192. pthread_attr_setstack(&attr,
  5193. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5194. ZEPHYR_STACK_SIZE);
  5195. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5196. /* Compile-time option to control stack size,
  5197. * e.g. -DUSE_STACK_SIZE=16384 */
  5198. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5199. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5200. result = pthread_create(&thread_id, &attr, func, param);
  5201. pthread_attr_destroy(&attr);
  5202. if ((result == 0) && (threadidptr != NULL)) {
  5203. *threadidptr = thread_id;
  5204. }
  5205. return result;
  5206. }
  5207. /* Wait for a thread to finish. */
  5208. static int
  5209. mg_join_thread(pthread_t threadid)
  5210. {
  5211. int result;
  5212. result = pthread_join(threadid, NULL);
  5213. return result;
  5214. }
  5215. #if !defined(NO_CGI)
  5216. static pid_t
  5217. spawn_process(struct mg_connection *conn,
  5218. const char *prog,
  5219. char *envblk,
  5220. char *envp[],
  5221. int fdin[2],
  5222. int fdout[2],
  5223. int fderr[2],
  5224. const char *dir)
  5225. {
  5226. pid_t pid;
  5227. const char *interp;
  5228. (void)envblk;
  5229. if ((pid = fork()) == -1) {
  5230. /* Parent */
  5231. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5232. } else if (pid != 0) {
  5233. /* Make sure children close parent-side descriptors.
  5234. * The caller will close the child-side immediately. */
  5235. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5236. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5237. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5238. } else {
  5239. /* Child */
  5240. if (chdir(dir) != 0) {
  5241. mg_cry_internal(
  5242. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5243. } else if (dup2(fdin[0], 0) == -1) {
  5244. mg_cry_internal(conn,
  5245. "%s: dup2(%d, 0): %s",
  5246. __func__,
  5247. fdin[0],
  5248. strerror(ERRNO));
  5249. } else if (dup2(fdout[1], 1) == -1) {
  5250. mg_cry_internal(conn,
  5251. "%s: dup2(%d, 1): %s",
  5252. __func__,
  5253. fdout[1],
  5254. strerror(ERRNO));
  5255. } else if (dup2(fderr[1], 2) == -1) {
  5256. mg_cry_internal(conn,
  5257. "%s: dup2(%d, 2): %s",
  5258. __func__,
  5259. fderr[1],
  5260. strerror(ERRNO));
  5261. } else {
  5262. struct sigaction sa;
  5263. /* Keep stderr and stdout in two different pipes.
  5264. * Stdout will be sent back to the client,
  5265. * stderr should go into a server error log. */
  5266. (void)close(fdin[0]);
  5267. (void)close(fdout[1]);
  5268. (void)close(fderr[1]);
  5269. /* Close write end fdin and read end fdout and fderr */
  5270. (void)close(fdin[1]);
  5271. (void)close(fdout[0]);
  5272. (void)close(fderr[0]);
  5273. /* After exec, all signal handlers are restored to their default
  5274. * values, with one exception of SIGCHLD. According to
  5275. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5276. * will leave unchanged after exec if it was set to be ignored.
  5277. * Restore it to default action. */
  5278. memset(&sa, 0, sizeof(sa));
  5279. sa.sa_handler = SIG_DFL;
  5280. sigaction(SIGCHLD, &sa, NULL);
  5281. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5282. if (interp == NULL) {
  5283. /* no interpreter configured, call the programm directly */
  5284. (void)execle(prog, prog, NULL, envp);
  5285. mg_cry_internal(conn,
  5286. "%s: execle(%s): %s",
  5287. __func__,
  5288. prog,
  5289. strerror(ERRNO));
  5290. } else {
  5291. /* call the configured interpreter */
  5292. const char *interp_args =
  5293. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5294. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5295. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5296. } else {
  5297. (void)execle(interp, interp, prog, NULL, envp);
  5298. }
  5299. mg_cry_internal(conn,
  5300. "%s: execle(%s %s): %s",
  5301. __func__,
  5302. interp,
  5303. prog,
  5304. strerror(ERRNO));
  5305. }
  5306. }
  5307. exit(EXIT_FAILURE);
  5308. }
  5309. return pid;
  5310. }
  5311. #endif /* !NO_CGI */
  5312. static int
  5313. set_non_blocking_mode(SOCKET sock)
  5314. {
  5315. int flags = fcntl(sock, F_GETFL, 0);
  5316. if (flags < 0) {
  5317. return -1;
  5318. }
  5319. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5320. return -1;
  5321. }
  5322. return 0;
  5323. }
  5324. static int
  5325. set_blocking_mode(SOCKET sock)
  5326. {
  5327. int flags = fcntl(sock, F_GETFL, 0);
  5328. if (flags < 0) {
  5329. return -1;
  5330. }
  5331. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5332. return -1;
  5333. }
  5334. return 0;
  5335. }
  5336. #endif /* _WIN32 / else */
  5337. /* End of initial operating system specific define block. */
  5338. /* Get a random number (independent of C rand function) */
  5339. static uint64_t
  5340. get_random(void)
  5341. {
  5342. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5343. static uint64_t lcg = 0; /* Linear congruential generator */
  5344. uint64_t now = mg_get_current_time_ns();
  5345. if (lfsr == 0) {
  5346. /* lfsr will be only 0 if has not been initialized,
  5347. * so this code is called only once. */
  5348. lfsr = mg_get_current_time_ns();
  5349. lcg = mg_get_current_time_ns();
  5350. } else {
  5351. /* Get the next step of both random number generators. */
  5352. lfsr = (lfsr >> 1)
  5353. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5354. << 63);
  5355. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5356. }
  5357. /* Combining two pseudo-random number generators and a high resolution
  5358. * part
  5359. * of the current server time will make it hard (impossible?) to guess
  5360. * the
  5361. * next number. */
  5362. return (lfsr ^ lcg ^ now);
  5363. }
  5364. static int
  5365. mg_poll(struct mg_pollfd *pfd,
  5366. unsigned int n,
  5367. int milliseconds,
  5368. volatile int *stop_server)
  5369. {
  5370. /* Call poll, but only for a maximum time of a few seconds.
  5371. * This will allow to stop the server after some seconds, instead
  5372. * of having to wait for a long socket timeout. */
  5373. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5374. do {
  5375. int result;
  5376. if (*stop_server) {
  5377. /* Shut down signal */
  5378. return -2;
  5379. }
  5380. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5381. ms_now = milliseconds;
  5382. }
  5383. result = poll(pfd, n, ms_now);
  5384. if (result != 0) {
  5385. /* Poll returned either success (1) or error (-1).
  5386. * Forward both to the caller. */
  5387. return result;
  5388. }
  5389. /* Poll returned timeout (0). */
  5390. if (milliseconds > 0) {
  5391. milliseconds -= ms_now;
  5392. }
  5393. } while (milliseconds != 0);
  5394. /* timeout: return 0 */
  5395. return 0;
  5396. }
  5397. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5398. * descriptor.
  5399. * Return value:
  5400. * >=0 .. number of bytes successfully written
  5401. * -1 .. timeout
  5402. * -2 .. error
  5403. */
  5404. static int
  5405. push_inner(struct mg_context *ctx,
  5406. FILE *fp,
  5407. SOCKET sock,
  5408. SSL *ssl,
  5409. const char *buf,
  5410. int len,
  5411. double timeout)
  5412. {
  5413. uint64_t start = 0, now = 0, timeout_ns = 0;
  5414. int n, err;
  5415. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5416. #if defined(_WIN32)
  5417. typedef int len_t;
  5418. #else
  5419. typedef size_t len_t;
  5420. #endif
  5421. if (timeout > 0) {
  5422. now = mg_get_current_time_ns();
  5423. start = now;
  5424. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5425. }
  5426. if (ctx == NULL) {
  5427. return -2;
  5428. }
  5429. #if defined(NO_SSL)
  5430. if (ssl) {
  5431. return -2;
  5432. }
  5433. #endif
  5434. /* Try to read until it succeeds, fails, times out, or the server
  5435. * shuts down. */
  5436. for (;;) {
  5437. #if !defined(NO_SSL)
  5438. if (ssl != NULL) {
  5439. n = SSL_write(ssl, buf, len);
  5440. if (n <= 0) {
  5441. err = SSL_get_error(ssl, n);
  5442. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5443. err = ERRNO;
  5444. } else if ((err == SSL_ERROR_WANT_READ)
  5445. || (err == SSL_ERROR_WANT_WRITE)) {
  5446. n = 0;
  5447. } else {
  5448. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5449. return -2;
  5450. }
  5451. } else {
  5452. err = 0;
  5453. }
  5454. } else
  5455. #endif
  5456. if (fp != NULL) {
  5457. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5458. if (ferror(fp)) {
  5459. n = -1;
  5460. err = ERRNO;
  5461. } else {
  5462. err = 0;
  5463. }
  5464. } else {
  5465. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5466. err = (n < 0) ? ERRNO : 0;
  5467. #if defined(_WIN32)
  5468. if (err == WSAEWOULDBLOCK) {
  5469. err = 0;
  5470. n = 0;
  5471. }
  5472. #else
  5473. if (err == EWOULDBLOCK) {
  5474. err = 0;
  5475. n = 0;
  5476. }
  5477. #endif
  5478. if (n < 0) {
  5479. /* shutdown of the socket at client side */
  5480. return -2;
  5481. }
  5482. }
  5483. if (ctx->stop_flag) {
  5484. return -2;
  5485. }
  5486. if ((n > 0) || ((n == 0) && (len == 0))) {
  5487. /* some data has been read, or no data was requested */
  5488. return n;
  5489. }
  5490. if (n < 0) {
  5491. /* socket error - check errno */
  5492. DEBUG_TRACE("send() failed, error %d", err);
  5493. /* TODO (mid): error handling depending on the error code.
  5494. * These codes are different between Windows and Linux.
  5495. * Currently there is no problem with failing send calls,
  5496. * if there is a reproducible situation, it should be
  5497. * investigated in detail.
  5498. */
  5499. return -2;
  5500. }
  5501. /* Only in case n=0 (timeout), repeat calling the write function */
  5502. /* If send failed, wait before retry */
  5503. if (fp != NULL) {
  5504. /* For files, just wait a fixed time.
  5505. * Maybe it helps, maybe not. */
  5506. mg_sleep(5);
  5507. } else {
  5508. /* For sockets, wait for the socket using poll */
  5509. struct mg_pollfd pfd[1];
  5510. int pollres;
  5511. pfd[0].fd = sock;
  5512. pfd[0].events = POLLOUT;
  5513. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5514. if (ctx->stop_flag) {
  5515. return -2;
  5516. }
  5517. if (pollres > 0) {
  5518. continue;
  5519. }
  5520. }
  5521. if (timeout > 0) {
  5522. now = mg_get_current_time_ns();
  5523. if ((now - start) > timeout_ns) {
  5524. /* Timeout */
  5525. break;
  5526. }
  5527. }
  5528. }
  5529. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5530. used */
  5531. return -1;
  5532. }
  5533. static int
  5534. push_all(struct mg_context *ctx,
  5535. FILE *fp,
  5536. SOCKET sock,
  5537. SSL *ssl,
  5538. const char *buf,
  5539. int len)
  5540. {
  5541. double timeout = -1.0;
  5542. int n, nwritten = 0;
  5543. if (ctx == NULL) {
  5544. return -1;
  5545. }
  5546. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5547. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5548. }
  5549. while ((len > 0) && (ctx->stop_flag == 0)) {
  5550. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5551. if (n < 0) {
  5552. if (nwritten == 0) {
  5553. nwritten = -1; /* Propagate the error */
  5554. }
  5555. break;
  5556. } else if (n == 0) {
  5557. break; /* No more data to write */
  5558. } else {
  5559. nwritten += n;
  5560. len -= n;
  5561. }
  5562. }
  5563. return nwritten;
  5564. }
  5565. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5566. * Return value:
  5567. * >=0 .. number of bytes successfully read
  5568. * -1 .. timeout
  5569. * -2 .. error
  5570. */
  5571. static int
  5572. pull_inner(FILE *fp,
  5573. struct mg_connection *conn,
  5574. char *buf,
  5575. int len,
  5576. double timeout)
  5577. {
  5578. int nread, err = 0;
  5579. #if defined(_WIN32)
  5580. typedef int len_t;
  5581. #else
  5582. typedef size_t len_t;
  5583. #endif
  5584. #if !defined(NO_SSL)
  5585. int ssl_pending;
  5586. #endif
  5587. /* We need an additional wait loop around this, because in some cases
  5588. * with TLSwe may get data from the socket but not from SSL_read.
  5589. * In this case we need to repeat at least once.
  5590. */
  5591. if (fp != NULL) {
  5592. #if !defined(_WIN32_WCE)
  5593. /* Use read() instead of fread(), because if we're reading from the
  5594. * CGI pipe, fread() may block until IO buffer is filled up. We
  5595. * cannot afford to block and must pass all read bytes immediately
  5596. * to the client. */
  5597. nread = (int)read(fileno(fp), buf, (size_t)len);
  5598. #else
  5599. /* WinCE does not support CGI pipes */
  5600. nread = (int)fread(buf, 1, (size_t)len, fp);
  5601. #endif
  5602. err = (nread < 0) ? ERRNO : 0;
  5603. if ((nread == 0) && (len > 0)) {
  5604. /* Should get data, but got EOL */
  5605. return -2;
  5606. }
  5607. #if !defined(NO_SSL)
  5608. } else if ((conn->ssl != NULL)
  5609. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5610. /* We already know there is no more data buffered in conn->buf
  5611. * but there is more available in the SSL layer. So don't poll
  5612. * conn->client.sock yet. */
  5613. if (ssl_pending > len) {
  5614. ssl_pending = len;
  5615. }
  5616. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5617. if (nread <= 0) {
  5618. err = SSL_get_error(conn->ssl, nread);
  5619. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5620. err = ERRNO;
  5621. } else if ((err == SSL_ERROR_WANT_READ)
  5622. || (err == SSL_ERROR_WANT_WRITE)) {
  5623. nread = 0;
  5624. } else {
  5625. /* All errors should return -2 */
  5626. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5627. return -2;
  5628. }
  5629. ERR_clear_error();
  5630. } else {
  5631. err = 0;
  5632. }
  5633. } else if (conn->ssl != NULL) {
  5634. struct mg_pollfd pfd[1];
  5635. int pollres;
  5636. pfd[0].fd = conn->client.sock;
  5637. pfd[0].events = POLLIN;
  5638. pollres = mg_poll(pfd,
  5639. 1,
  5640. (int)(timeout * 1000.0),
  5641. &(conn->phys_ctx->stop_flag));
  5642. if (conn->phys_ctx->stop_flag) {
  5643. return -2;
  5644. }
  5645. if (pollres > 0) {
  5646. nread = SSL_read(conn->ssl, buf, len);
  5647. if (nread <= 0) {
  5648. err = SSL_get_error(conn->ssl, nread);
  5649. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5650. err = ERRNO;
  5651. } else if ((err == SSL_ERROR_WANT_READ)
  5652. || (err == SSL_ERROR_WANT_WRITE)) {
  5653. nread = 0;
  5654. } else {
  5655. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5656. return -2;
  5657. }
  5658. } else {
  5659. err = 0;
  5660. }
  5661. ERR_clear_error();
  5662. } else if (pollres < 0) {
  5663. /* Error */
  5664. return -2;
  5665. } else {
  5666. /* pollres = 0 means timeout */
  5667. nread = 0;
  5668. }
  5669. #endif
  5670. } else {
  5671. struct mg_pollfd pfd[1];
  5672. int pollres;
  5673. pfd[0].fd = conn->client.sock;
  5674. pfd[0].events = POLLIN;
  5675. pollres = mg_poll(pfd,
  5676. 1,
  5677. (int)(timeout * 1000.0),
  5678. &(conn->phys_ctx->stop_flag));
  5679. if (conn->phys_ctx->stop_flag) {
  5680. return -2;
  5681. }
  5682. if (pollres > 0) {
  5683. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5684. err = (nread < 0) ? ERRNO : 0;
  5685. if (nread <= 0) {
  5686. /* shutdown of the socket at client side */
  5687. return -2;
  5688. }
  5689. } else if (pollres < 0) {
  5690. /* error callint poll */
  5691. return -2;
  5692. } else {
  5693. /* pollres = 0 means timeout */
  5694. nread = 0;
  5695. }
  5696. }
  5697. if (conn->phys_ctx->stop_flag) {
  5698. return -2;
  5699. }
  5700. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5701. /* some data has been read, or no data was requested */
  5702. return nread;
  5703. }
  5704. if (nread < 0) {
  5705. /* socket error - check errno */
  5706. #if defined(_WIN32)
  5707. if (err == WSAEWOULDBLOCK) {
  5708. /* TODO (low): check if this is still required */
  5709. /* standard case if called from close_socket_gracefully */
  5710. return -2;
  5711. } else if (err == WSAETIMEDOUT) {
  5712. /* TODO (low): check if this is still required */
  5713. /* timeout is handled by the while loop */
  5714. return 0;
  5715. } else if (err == WSAECONNABORTED) {
  5716. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5717. return -2;
  5718. } else {
  5719. DEBUG_TRACE("recv() failed, error %d", err);
  5720. return -2;
  5721. }
  5722. #else
  5723. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5724. * if the timeout is reached and if the socket was set to non-
  5725. * blocking in close_socket_gracefully, so we can not distinguish
  5726. * here. We have to wait for the timeout in both cases for now.
  5727. */
  5728. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5729. /* TODO (low): check if this is still required */
  5730. /* EAGAIN/EWOULDBLOCK:
  5731. * standard case if called from close_socket_gracefully
  5732. * => should return -1 */
  5733. /* or timeout occurred
  5734. * => the code must stay in the while loop */
  5735. /* EINTR can be generated on a socket with a timeout set even
  5736. * when SA_RESTART is effective for all relevant signals
  5737. * (see signal(7)).
  5738. * => stay in the while loop */
  5739. } else {
  5740. DEBUG_TRACE("recv() failed, error %d", err);
  5741. return -2;
  5742. }
  5743. #endif
  5744. }
  5745. /* Timeout occurred, but no data available. */
  5746. return -1;
  5747. }
  5748. static int
  5749. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5750. {
  5751. int n, nread = 0;
  5752. double timeout = -1.0;
  5753. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5754. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5755. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5756. }
  5757. if (timeout >= 0.0) {
  5758. start_time = mg_get_current_time_ns();
  5759. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5760. }
  5761. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5762. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5763. if (n == -2) {
  5764. if (nread == 0) {
  5765. nread = -1; /* Propagate the error */
  5766. }
  5767. break;
  5768. } else if (n == -1) {
  5769. /* timeout */
  5770. if (timeout >= 0.0) {
  5771. now = mg_get_current_time_ns();
  5772. if ((now - start_time) <= timeout_ns) {
  5773. continue;
  5774. }
  5775. }
  5776. break;
  5777. } else if (n == 0) {
  5778. break; /* No more data to read */
  5779. } else {
  5780. nread += n;
  5781. len -= n;
  5782. }
  5783. }
  5784. return nread;
  5785. }
  5786. static void
  5787. discard_unread_request_data(struct mg_connection *conn)
  5788. {
  5789. char buf[MG_BUF_LEN];
  5790. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5791. ;
  5792. }
  5793. static int
  5794. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5795. {
  5796. int64_t content_len, n, buffered_len, nread;
  5797. int64_t len64 =
  5798. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5799. * int, we may not read more
  5800. * bytes */
  5801. const char *body;
  5802. if (conn == NULL) {
  5803. return 0;
  5804. }
  5805. /* If Content-Length is not set for a response with body data,
  5806. * we do not know in advance how much data should be read. */
  5807. content_len = conn->content_len;
  5808. if (content_len < 0) {
  5809. /* The body data is completed when the connection is closed. */
  5810. content_len = INT64_MAX;
  5811. }
  5812. nread = 0;
  5813. if (conn->consumed_content < content_len) {
  5814. /* Adjust number of bytes to read. */
  5815. int64_t left_to_read = content_len - conn->consumed_content;
  5816. if (left_to_read < len64) {
  5817. /* Do not read more than the total content length of the
  5818. * request.
  5819. */
  5820. len64 = left_to_read;
  5821. }
  5822. /* Return buffered data */
  5823. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5824. - conn->consumed_content;
  5825. if (buffered_len > 0) {
  5826. if (len64 < buffered_len) {
  5827. buffered_len = len64;
  5828. }
  5829. body = conn->buf + conn->request_len + conn->consumed_content;
  5830. memcpy(buf, body, (size_t)buffered_len);
  5831. len64 -= buffered_len;
  5832. conn->consumed_content += buffered_len;
  5833. nread += buffered_len;
  5834. buf = (char *)buf + buffered_len;
  5835. }
  5836. /* We have returned all buffered data. Read new data from the remote
  5837. * socket.
  5838. */
  5839. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5840. conn->consumed_content += n;
  5841. nread += n;
  5842. } else {
  5843. nread = ((nread > 0) ? nread : n);
  5844. }
  5845. }
  5846. return (int)nread;
  5847. }
  5848. int
  5849. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5850. {
  5851. if (len > INT_MAX) {
  5852. len = INT_MAX;
  5853. }
  5854. if (conn == NULL) {
  5855. return 0;
  5856. }
  5857. if (conn->is_chunked) {
  5858. size_t all_read = 0;
  5859. while (len > 0) {
  5860. if (conn->is_chunked >= 3) {
  5861. /* No more data left to read */
  5862. return 0;
  5863. }
  5864. if (conn->is_chunked != 1) {
  5865. /* Has error */
  5866. return -1;
  5867. }
  5868. if (conn->consumed_content != conn->content_len) {
  5869. /* copy from the current chunk */
  5870. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5871. if (read_ret < 1) {
  5872. /* read error */
  5873. conn->is_chunked = 2;
  5874. return -1;
  5875. }
  5876. all_read += (size_t)read_ret;
  5877. len -= (size_t)read_ret;
  5878. if (conn->consumed_content == conn->content_len) {
  5879. /* Add data bytes in the current chunk have been read,
  5880. * so we are expecting \r\n now. */
  5881. char x[2];
  5882. conn->content_len += 2;
  5883. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5884. || (x[1] != '\n')) {
  5885. /* Protocol violation */
  5886. conn->is_chunked = 2;
  5887. return -1;
  5888. }
  5889. }
  5890. } else {
  5891. /* fetch a new chunk */
  5892. size_t i;
  5893. char lenbuf[64];
  5894. char *end = NULL;
  5895. unsigned long chunkSize = 0;
  5896. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5897. conn->content_len++;
  5898. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5899. lenbuf[i] = 0;
  5900. }
  5901. if ((i > 0) && (lenbuf[i] == '\r')
  5902. && (lenbuf[i - 1] != '\r')) {
  5903. continue;
  5904. }
  5905. if ((i > 1) && (lenbuf[i] == '\n')
  5906. && (lenbuf[i - 1] == '\r')) {
  5907. lenbuf[i + 1] = 0;
  5908. chunkSize = strtoul(lenbuf, &end, 16);
  5909. if (chunkSize == 0) {
  5910. /* regular end of content */
  5911. conn->is_chunked = 3;
  5912. }
  5913. break;
  5914. }
  5915. if (!isxdigit((unsigned char)lenbuf[i])) {
  5916. /* illegal character for chunk length */
  5917. conn->is_chunked = 2;
  5918. return -1;
  5919. }
  5920. }
  5921. if ((end == NULL) || (*end != '\r')) {
  5922. /* chunksize not set correctly */
  5923. conn->is_chunked = 2;
  5924. return -1;
  5925. }
  5926. if (chunkSize == 0) {
  5927. /* try discarding trailer for keep-alive */
  5928. conn->content_len += 2;
  5929. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5930. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5931. conn->is_chunked = 4;
  5932. }
  5933. break;
  5934. }
  5935. /* append a new chunk */
  5936. conn->content_len += (int64_t)chunkSize;
  5937. }
  5938. }
  5939. return (int)all_read;
  5940. }
  5941. return mg_read_inner(conn, buf, len);
  5942. }
  5943. int
  5944. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5945. {
  5946. time_t now;
  5947. int n, total, allowed;
  5948. if (conn == NULL) {
  5949. return 0;
  5950. }
  5951. if (len > INT_MAX) {
  5952. return -1;
  5953. }
  5954. if (conn->throttle > 0) {
  5955. if ((now = time(NULL)) != conn->last_throttle_time) {
  5956. conn->last_throttle_time = now;
  5957. conn->last_throttle_bytes = 0;
  5958. }
  5959. allowed = conn->throttle - conn->last_throttle_bytes;
  5960. if (allowed > (int)len) {
  5961. allowed = (int)len;
  5962. }
  5963. if ((total = push_all(conn->phys_ctx,
  5964. NULL,
  5965. conn->client.sock,
  5966. conn->ssl,
  5967. (const char *)buf,
  5968. allowed))
  5969. == allowed) {
  5970. buf = (const char *)buf + total;
  5971. conn->last_throttle_bytes += total;
  5972. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5973. allowed = (conn->throttle > ((int)len - total))
  5974. ? (int)len - total
  5975. : conn->throttle;
  5976. if ((n = push_all(conn->phys_ctx,
  5977. NULL,
  5978. conn->client.sock,
  5979. conn->ssl,
  5980. (const char *)buf,
  5981. allowed))
  5982. != allowed) {
  5983. break;
  5984. }
  5985. sleep(1);
  5986. conn->last_throttle_bytes = allowed;
  5987. conn->last_throttle_time = time(NULL);
  5988. buf = (const char *)buf + n;
  5989. total += n;
  5990. }
  5991. }
  5992. } else {
  5993. total = push_all(conn->phys_ctx,
  5994. NULL,
  5995. conn->client.sock,
  5996. conn->ssl,
  5997. (const char *)buf,
  5998. (int)len);
  5999. }
  6000. if (total > 0) {
  6001. conn->num_bytes_sent += total;
  6002. }
  6003. return total;
  6004. }
  6005. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6006. int
  6007. mg_send_chunk(struct mg_connection *conn,
  6008. const char *chunk,
  6009. unsigned int chunk_len)
  6010. {
  6011. char lenbuf[16];
  6012. size_t lenbuf_len;
  6013. int ret;
  6014. int t;
  6015. /* First store the length information in a text buffer. */
  6016. sprintf(lenbuf, "%x\r\n", chunk_len);
  6017. lenbuf_len = strlen(lenbuf);
  6018. /* Then send length information, chunk and terminating \r\n. */
  6019. ret = mg_write(conn, lenbuf, lenbuf_len);
  6020. if (ret != (int)lenbuf_len) {
  6021. return -1;
  6022. }
  6023. t = ret;
  6024. ret = mg_write(conn, chunk, chunk_len);
  6025. if (ret != (int)chunk_len) {
  6026. return -1;
  6027. }
  6028. t += ret;
  6029. ret = mg_write(conn, "\r\n", 2);
  6030. if (ret != 2) {
  6031. return -1;
  6032. }
  6033. t += ret;
  6034. return t;
  6035. }
  6036. #if defined(GCC_DIAGNOSTIC)
  6037. /* This block forwards format strings to printf implementations,
  6038. * so we need to disable the format-nonliteral warning. */
  6039. #pragma GCC diagnostic push
  6040. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6041. #endif
  6042. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6043. static int
  6044. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6045. {
  6046. va_list ap_copy;
  6047. size_t size = MG_BUF_LEN / 4;
  6048. int len = -1;
  6049. *buf = NULL;
  6050. while (len < 0) {
  6051. if (*buf) {
  6052. mg_free(*buf);
  6053. }
  6054. size *= 4;
  6055. *buf = (char *)mg_malloc(size);
  6056. if (!*buf) {
  6057. break;
  6058. }
  6059. va_copy(ap_copy, ap);
  6060. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6061. va_end(ap_copy);
  6062. (*buf)[size - 1] = 0;
  6063. }
  6064. return len;
  6065. }
  6066. /* Print message to buffer. If buffer is large enough to hold the message,
  6067. * return buffer. If buffer is to small, allocate large enough buffer on
  6068. * heap,
  6069. * and return allocated buffer. */
  6070. static int
  6071. alloc_vprintf(char **out_buf,
  6072. char *prealloc_buf,
  6073. size_t prealloc_size,
  6074. const char *fmt,
  6075. va_list ap)
  6076. {
  6077. va_list ap_copy;
  6078. int len;
  6079. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6080. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6081. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6082. * Therefore, we make two passes: on first pass, get required message
  6083. * length.
  6084. * On second pass, actually print the message. */
  6085. va_copy(ap_copy, ap);
  6086. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6087. va_end(ap_copy);
  6088. if (len < 0) {
  6089. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6090. * Switch to alternative code path that uses incremental
  6091. * allocations.
  6092. */
  6093. va_copy(ap_copy, ap);
  6094. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6095. va_end(ap_copy);
  6096. } else if ((size_t)(len) >= prealloc_size) {
  6097. /* The pre-allocated buffer not large enough. */
  6098. /* Allocate a new buffer. */
  6099. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6100. if (!*out_buf) {
  6101. /* Allocation failed. Return -1 as "out of memory" error. */
  6102. return -1;
  6103. }
  6104. /* Buffer allocation successful. Store the string there. */
  6105. va_copy(ap_copy, ap);
  6106. IGNORE_UNUSED_RESULT(
  6107. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6108. va_end(ap_copy);
  6109. } else {
  6110. /* The pre-allocated buffer is large enough.
  6111. * Use it to store the string and return the address. */
  6112. va_copy(ap_copy, ap);
  6113. IGNORE_UNUSED_RESULT(
  6114. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6115. va_end(ap_copy);
  6116. *out_buf = prealloc_buf;
  6117. }
  6118. return len;
  6119. }
  6120. #if defined(GCC_DIAGNOSTIC)
  6121. /* Enable format-nonliteral warning again. */
  6122. #pragma GCC diagnostic pop
  6123. #endif
  6124. static int
  6125. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6126. {
  6127. char mem[MG_BUF_LEN];
  6128. char *buf = NULL;
  6129. int len;
  6130. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6131. len = mg_write(conn, buf, (size_t)len);
  6132. }
  6133. if (buf != mem) {
  6134. mg_free(buf);
  6135. }
  6136. return len;
  6137. }
  6138. int
  6139. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6140. {
  6141. va_list ap;
  6142. int result;
  6143. va_start(ap, fmt);
  6144. result = mg_vprintf(conn, fmt, ap);
  6145. va_end(ap);
  6146. return result;
  6147. }
  6148. int
  6149. mg_url_decode(const char *src,
  6150. int src_len,
  6151. char *dst,
  6152. int dst_len,
  6153. int is_form_url_encoded)
  6154. {
  6155. int i, j, a, b;
  6156. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6157. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6158. if ((i < src_len - 2) && (src[i] == '%')
  6159. && isxdigit((unsigned char)src[i + 1])
  6160. && isxdigit((unsigned char)src[i + 2])) {
  6161. a = tolower((unsigned char)src[i + 1]);
  6162. b = tolower((unsigned char)src[i + 2]);
  6163. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6164. i += 2;
  6165. } else if (is_form_url_encoded && (src[i] == '+')) {
  6166. dst[j] = ' ';
  6167. } else {
  6168. dst[j] = src[i];
  6169. }
  6170. }
  6171. dst[j] = '\0'; /* Null-terminate the destination */
  6172. return (i >= src_len) ? j : -1;
  6173. }
  6174. /* form url decoding of an entire string */
  6175. static void
  6176. url_decode_in_place(char *buf)
  6177. {
  6178. size_t len = strlen(buf);
  6179. while (*buf) {
  6180. if (*buf == '%') {
  6181. if (isxdigit((unsigned char)buf[1])) {
  6182. if (isxdigit((unsigned char)buf[2])) {
  6183. int a = tolower((unsigned char)buf[1]);
  6184. int b = tolower((unsigned char)buf[2]);
  6185. char c = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6186. memmove(buf + 1, buf + 3, len - 2);
  6187. *buf = c;
  6188. len -= 2;
  6189. }
  6190. }
  6191. } else if (*buf == '+') {
  6192. *buf = ' ';
  6193. }
  6194. buf++;
  6195. len--;
  6196. }
  6197. }
  6198. int
  6199. mg_get_var(const char *data,
  6200. size_t data_len,
  6201. const char *name,
  6202. char *dst,
  6203. size_t dst_len)
  6204. {
  6205. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6206. }
  6207. int
  6208. mg_get_var2(const char *data,
  6209. size_t data_len,
  6210. const char *name,
  6211. char *dst,
  6212. size_t dst_len,
  6213. size_t occurrence)
  6214. {
  6215. const char *p, *e, *s;
  6216. size_t name_len;
  6217. int len;
  6218. if ((dst == NULL) || (dst_len == 0)) {
  6219. len = -2;
  6220. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6221. len = -1;
  6222. dst[0] = '\0';
  6223. } else {
  6224. name_len = strlen(name);
  6225. e = data + data_len;
  6226. len = -1;
  6227. dst[0] = '\0';
  6228. /* data is "var1=val1&var2=val2...". Find variable first */
  6229. for (p = data; p + name_len < e; p++) {
  6230. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6231. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6232. /* Point p to variable value */
  6233. p += name_len + 1;
  6234. /* Point s to the end of the value */
  6235. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6236. if (s == NULL) {
  6237. s = e;
  6238. }
  6239. DEBUG_ASSERT(s >= p);
  6240. if (s < p) {
  6241. return -3;
  6242. }
  6243. /* Decode variable into destination buffer */
  6244. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6245. /* Redirect error code from -1 to -2 (destination buffer too
  6246. * small). */
  6247. if (len == -1) {
  6248. len = -2;
  6249. }
  6250. break;
  6251. }
  6252. }
  6253. }
  6254. return len;
  6255. }
  6256. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6257. int
  6258. mg_split_form_urlencoded(char *data,
  6259. struct mg_header *form_fields,
  6260. unsigned num_form_fields)
  6261. {
  6262. char *b;
  6263. int i;
  6264. int num = 0;
  6265. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6266. /* determine the number of expected fields */
  6267. if (data[0] == 0) {
  6268. return 0;
  6269. }
  6270. /* count number of & to return the number of key-value-pairs */
  6271. num = 1;
  6272. while (*data) {
  6273. if (*data == '&') {
  6274. num++;
  6275. }
  6276. data++;
  6277. }
  6278. return num;
  6279. }
  6280. if ((data == NULL) || (form_fields == NULL)
  6281. || ((int)num_form_fields <= 0)) {
  6282. /* parameter error */
  6283. return -1;
  6284. }
  6285. for (i = 0; i < (int)num_form_fields; i++) {
  6286. /* extract key-value pairs from input data */
  6287. while ((*data == ' ') || (*data == '\t')) {
  6288. /* skip initial spaces */
  6289. data++;
  6290. }
  6291. if (*data == 0) {
  6292. /* end of string reached */
  6293. break;
  6294. }
  6295. form_fields[num].name = data;
  6296. /* find & or = */
  6297. b = data;
  6298. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6299. b++;
  6300. }
  6301. if (*b == 0) {
  6302. /* last key without value */
  6303. form_fields[num].value = NULL;
  6304. } else if (*b == '&') {
  6305. /* mid key without value */
  6306. form_fields[num].value = NULL;
  6307. } else {
  6308. /* terminate string */
  6309. *b = 0;
  6310. /* value starts after '=' */
  6311. data = b + 1;
  6312. form_fields[num].value = data;
  6313. }
  6314. /* new field is stored */
  6315. num++;
  6316. /* find a next key */
  6317. b = strchr(data, '&');
  6318. if (b == 0) {
  6319. /* no more data */
  6320. break;
  6321. } else {
  6322. /* terminate value of last field at '&' */
  6323. *b = 0;
  6324. /* next key-value-pairs starts after '&' */
  6325. data = b + 1;
  6326. }
  6327. }
  6328. /* Decode all values */
  6329. for (i = 0; i < num; i++) {
  6330. if (form_fields[i].name) {
  6331. url_decode_in_place((char *)form_fields[i].name);
  6332. }
  6333. if (form_fields[i].value) {
  6334. url_decode_in_place((char *)form_fields[i].value);
  6335. }
  6336. }
  6337. /* return number of fields found */
  6338. return num;
  6339. }
  6340. /* HCP24: some changes to compare hole var_name */
  6341. int
  6342. mg_get_cookie(const char *cookie_header,
  6343. const char *var_name,
  6344. char *dst,
  6345. size_t dst_size)
  6346. {
  6347. const char *s, *p, *end;
  6348. int name_len, len = -1;
  6349. if ((dst == NULL) || (dst_size == 0)) {
  6350. return -2;
  6351. }
  6352. dst[0] = '\0';
  6353. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6354. return -1;
  6355. }
  6356. name_len = (int)strlen(var_name);
  6357. end = s + strlen(s);
  6358. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6359. if (s[name_len] == '=') {
  6360. /* HCP24: now check is it a substring or a full cookie name */
  6361. if ((s == cookie_header) || (s[-1] == ' ')) {
  6362. s += name_len + 1;
  6363. if ((p = strchr(s, ' ')) == NULL) {
  6364. p = end;
  6365. }
  6366. if (p[-1] == ';') {
  6367. p--;
  6368. }
  6369. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6370. s++;
  6371. p--;
  6372. }
  6373. if ((size_t)(p - s) < dst_size) {
  6374. len = (int)(p - s);
  6375. mg_strlcpy(dst, s, (size_t)len + 1);
  6376. } else {
  6377. len = -3;
  6378. }
  6379. break;
  6380. }
  6381. }
  6382. }
  6383. return len;
  6384. }
  6385. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6386. static void
  6387. base64_encode(const unsigned char *src, int src_len, char *dst)
  6388. {
  6389. static const char *b64 =
  6390. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6391. int i, j, a, b, c;
  6392. for (i = j = 0; i < src_len; i += 3) {
  6393. a = src[i];
  6394. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6395. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6396. dst[j++] = b64[a >> 2];
  6397. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6398. if (i + 1 < src_len) {
  6399. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6400. }
  6401. if (i + 2 < src_len) {
  6402. dst[j++] = b64[c & 63];
  6403. }
  6404. }
  6405. while (j % 4 != 0) {
  6406. dst[j++] = '=';
  6407. }
  6408. dst[j++] = '\0';
  6409. }
  6410. #endif
  6411. #if defined(USE_LUA)
  6412. static unsigned char
  6413. b64reverse(char letter)
  6414. {
  6415. if ((letter >= 'A') && (letter <= 'Z')) {
  6416. return letter - 'A';
  6417. }
  6418. if ((letter >= 'a') && (letter <= 'z')) {
  6419. return letter - 'a' + 26;
  6420. }
  6421. if ((letter >= '0') && (letter <= '9')) {
  6422. return letter - '0' + 52;
  6423. }
  6424. if (letter == '+') {
  6425. return 62;
  6426. }
  6427. if (letter == '/') {
  6428. return 63;
  6429. }
  6430. if (letter == '=') {
  6431. return 255; /* normal end */
  6432. }
  6433. return 254; /* error */
  6434. }
  6435. static int
  6436. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6437. {
  6438. int i;
  6439. unsigned char a, b, c, d;
  6440. *dst_len = 0;
  6441. for (i = 0; i < src_len; i += 4) {
  6442. a = b64reverse(src[i]);
  6443. if (a >= 254) {
  6444. return i;
  6445. }
  6446. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6447. if (b >= 254) {
  6448. return i + 1;
  6449. }
  6450. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6451. if (c == 254) {
  6452. return i + 2;
  6453. }
  6454. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6455. if (d == 254) {
  6456. return i + 3;
  6457. }
  6458. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6459. if (c != 255) {
  6460. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6461. if (d != 255) {
  6462. dst[(*dst_len)++] = (c << 6) + d;
  6463. }
  6464. }
  6465. }
  6466. return -1;
  6467. }
  6468. #endif
  6469. static int
  6470. is_put_or_delete_method(const struct mg_connection *conn)
  6471. {
  6472. if (conn) {
  6473. const char *s = conn->request_info.request_method;
  6474. return (s != NULL)
  6475. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6476. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6477. }
  6478. return 0;
  6479. }
  6480. #if !defined(NO_FILES)
  6481. static int
  6482. extention_matches_script(
  6483. struct mg_connection *conn, /* in: request (must be valid) */
  6484. const char *filename /* in: filename (must be valid) */
  6485. )
  6486. {
  6487. #if !defined(NO_CGI)
  6488. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6489. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6490. filename)
  6491. > 0) {
  6492. return 1;
  6493. }
  6494. #endif
  6495. #if defined(USE_LUA)
  6496. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6497. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6498. filename)
  6499. > 0) {
  6500. return 1;
  6501. }
  6502. #endif
  6503. #if defined(USE_DUKTAPE)
  6504. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6505. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6506. filename)
  6507. > 0) {
  6508. return 1;
  6509. }
  6510. #endif
  6511. /* filename and conn could be unused, if all preocessor conditions
  6512. * are false (no script language supported). */
  6513. (void)filename;
  6514. (void)conn;
  6515. return 0;
  6516. }
  6517. /* For given directory path, substitute it to valid index file.
  6518. * Return 1 if index file has been found, 0 if not found.
  6519. * If the file is found, it's stats is returned in stp. */
  6520. static int
  6521. substitute_index_file(struct mg_connection *conn,
  6522. char *path,
  6523. size_t path_len,
  6524. struct mg_file_stat *filestat)
  6525. {
  6526. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6527. struct vec filename_vec;
  6528. size_t n = strlen(path);
  6529. int found = 0;
  6530. /* The 'path' given to us points to the directory. Remove all trailing
  6531. * directory separator characters from the end of the path, and
  6532. * then append single directory separator character. */
  6533. while ((n > 0) && (path[n - 1] == '/')) {
  6534. n--;
  6535. }
  6536. path[n] = '/';
  6537. /* Traverse index files list. For each entry, append it to the given
  6538. * path and see if the file exists. If it exists, break the loop */
  6539. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6540. /* Ignore too long entries that may overflow path buffer */
  6541. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6542. continue;
  6543. }
  6544. /* Prepare full path to the index file */
  6545. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6546. /* Does it exist? */
  6547. if (mg_stat(conn, path, filestat)) {
  6548. /* Yes it does, break the loop */
  6549. found = 1;
  6550. break;
  6551. }
  6552. }
  6553. /* If no index file exists, restore directory path */
  6554. if (!found) {
  6555. path[n] = '\0';
  6556. }
  6557. return found;
  6558. }
  6559. #endif
  6560. static void
  6561. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6562. char *filename, /* out: filename */
  6563. size_t filename_buf_len, /* in: size of filename buffer */
  6564. struct mg_file_stat *filestat, /* out: file status structure */
  6565. int *is_found, /* out: file found (directly) */
  6566. int *is_script_resource, /* out: handled by a script? */
  6567. int *is_websocket_request, /* out: websocket connetion? */
  6568. int *is_put_or_delete_request /* out: put/delete a file? */
  6569. )
  6570. {
  6571. char const *accept_encoding;
  6572. #if !defined(NO_FILES)
  6573. const char *uri = conn->request_info.local_uri;
  6574. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6575. const char *rewrite;
  6576. struct vec a, b;
  6577. ptrdiff_t match_len;
  6578. char gz_path[PATH_MAX];
  6579. int truncated;
  6580. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6581. char *tmp_str;
  6582. size_t tmp_str_len, sep_pos;
  6583. int allow_substitute_script_subresources;
  6584. #endif
  6585. #else
  6586. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6587. #endif
  6588. /* Step 1: Set all initially unknown outputs to zero */
  6589. memset(filestat, 0, sizeof(*filestat));
  6590. *filename = 0;
  6591. *is_found = 0;
  6592. *is_script_resource = 0;
  6593. /* Step 2: Check if the request attempts to modify the file system */
  6594. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6595. /* Step 3: Check if it is a websocket request, and modify the document
  6596. * root if required */
  6597. #if defined(USE_WEBSOCKET)
  6598. *is_websocket_request = is_websocket_protocol(conn);
  6599. #if !defined(NO_FILES)
  6600. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6601. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6602. }
  6603. #endif /* !NO_FILES */
  6604. #else /* USE_WEBSOCKET */
  6605. *is_websocket_request = 0;
  6606. #endif /* USE_WEBSOCKET */
  6607. /* Step 4: Check if gzip encoded response is allowed */
  6608. conn->accept_gzip = 0;
  6609. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6610. if (strstr(accept_encoding, "gzip") != NULL) {
  6611. conn->accept_gzip = 1;
  6612. }
  6613. }
  6614. #if !defined(NO_FILES)
  6615. /* Step 5: If there is no root directory, don't look for files. */
  6616. /* Note that root == NULL is a regular use case here. This occurs,
  6617. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6618. * config is not required. */
  6619. if (root == NULL) {
  6620. /* all file related outputs have already been set to 0, just return
  6621. */
  6622. return;
  6623. }
  6624. /* Step 6: Determine the local file path from the root path and the
  6625. * request uri. */
  6626. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6627. * part of the path one byte on the right. */
  6628. mg_snprintf(
  6629. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6630. if (truncated) {
  6631. goto interpret_cleanup;
  6632. }
  6633. /* Step 7: URI rewriting */
  6634. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6635. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6636. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6637. mg_snprintf(conn,
  6638. &truncated,
  6639. filename,
  6640. filename_buf_len - 1,
  6641. "%.*s%s",
  6642. (int)b.len,
  6643. b.ptr,
  6644. uri + match_len);
  6645. break;
  6646. }
  6647. }
  6648. if (truncated) {
  6649. goto interpret_cleanup;
  6650. }
  6651. /* Step 8: Check if the file exists at the server */
  6652. /* Local file path and name, corresponding to requested URI
  6653. * is now stored in "filename" variable. */
  6654. if (mg_stat(conn, filename, filestat)) {
  6655. int uri_len = (int)strlen(uri);
  6656. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6657. /* 8.1: File exists. */
  6658. *is_found = 1;
  6659. /* 8.2: Check if it is a script type. */
  6660. if (extention_matches_script(conn, filename)) {
  6661. /* The request addresses a CGI resource, Lua script or
  6662. * server-side javascript.
  6663. * The URI corresponds to the script itself (like
  6664. * /path/script.cgi), and there is no additional resource
  6665. * path (like /path/script.cgi/something).
  6666. * Requests that modify (replace or delete) a resource, like
  6667. * PUT and DELETE requests, should replace/delete the script
  6668. * file.
  6669. * Requests that read or write from/to a resource, like GET and
  6670. * POST requests, should call the script and return the
  6671. * generated response. */
  6672. *is_script_resource = (!*is_put_or_delete_request);
  6673. }
  6674. /* 8.3: If the request target is a directory, there could be
  6675. * a substitute file (index.html, index.cgi, ...). */
  6676. if (filestat->is_directory && is_uri_end_slash) {
  6677. /* Use a local copy here, since substitute_index_file will
  6678. * change the content of the file status */
  6679. struct mg_file_stat tmp_filestat;
  6680. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6681. if (substitute_index_file(
  6682. conn, filename, filename_buf_len, &tmp_filestat)) {
  6683. /* Substitute file found. Copy stat to the output, then
  6684. * check if the file is a script file */
  6685. *filestat = tmp_filestat;
  6686. if (extention_matches_script(conn, filename)) {
  6687. /* Substitute file is a script file */
  6688. *is_script_resource = 1;
  6689. } else {
  6690. /* Substitute file is a regular file */
  6691. *is_script_resource = 0;
  6692. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6693. }
  6694. }
  6695. /* If there is no substitute file, the server could return
  6696. * a directory listing in a later step */
  6697. }
  6698. return;
  6699. }
  6700. /* Step 9: Check for zipped files: */
  6701. /* If we can't find the actual file, look for the file
  6702. * with the same name but a .gz extension. If we find it,
  6703. * use that and set the gzipped flag in the file struct
  6704. * to indicate that the response need to have the content-
  6705. * encoding: gzip header.
  6706. * We can only do this if the browser declares support. */
  6707. if (conn->accept_gzip) {
  6708. mg_snprintf(
  6709. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6710. if (truncated) {
  6711. goto interpret_cleanup;
  6712. }
  6713. if (mg_stat(conn, gz_path, filestat)) {
  6714. if (filestat) {
  6715. filestat->is_gzipped = 1;
  6716. *is_found = 1;
  6717. }
  6718. /* Currently gz files can not be scripts. */
  6719. return;
  6720. }
  6721. }
  6722. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6723. /* Step 10: Script resources may handle sub-resources */
  6724. /* Support PATH_INFO for CGI scripts. */
  6725. tmp_str_len = strlen(filename);
  6726. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6727. if (!tmp_str) {
  6728. /* Out of memory */
  6729. goto interpret_cleanup;
  6730. }
  6731. memcpy(tmp_str, filename, tmp_str_len + 1);
  6732. /* Check config, if index scripts may have sub-resources */
  6733. allow_substitute_script_subresources =
  6734. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6735. "yes");
  6736. sep_pos = tmp_str_len;
  6737. while (sep_pos > 0) {
  6738. sep_pos--;
  6739. if (tmp_str[sep_pos] == '/') {
  6740. int is_script = 0, does_exist = 0;
  6741. tmp_str[sep_pos] = 0;
  6742. if (tmp_str[0]) {
  6743. is_script = extention_matches_script(conn, tmp_str);
  6744. does_exist = mg_stat(conn, tmp_str, filestat);
  6745. }
  6746. if (does_exist && is_script) {
  6747. filename[sep_pos] = 0;
  6748. memmove(filename + sep_pos + 2,
  6749. filename + sep_pos + 1,
  6750. strlen(filename + sep_pos + 1) + 1);
  6751. conn->path_info = filename + sep_pos + 1;
  6752. filename[sep_pos + 1] = '/';
  6753. *is_script_resource = 1;
  6754. *is_found = 1;
  6755. break;
  6756. }
  6757. if (allow_substitute_script_subresources) {
  6758. if (substitute_index_file(
  6759. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6760. /* some intermediate directory has an index file */
  6761. if (extention_matches_script(conn, tmp_str)) {
  6762. DEBUG_TRACE("Substitute script %s serving path %s",
  6763. tmp_str,
  6764. filename);
  6765. /* this index file is a script */
  6766. mg_snprintf(conn,
  6767. &truncated,
  6768. filename,
  6769. filename_buf_len,
  6770. "%s//%s",
  6771. tmp_str,
  6772. filename + sep_pos + 1);
  6773. if (truncated) {
  6774. mg_free(tmp_str);
  6775. goto interpret_cleanup;
  6776. }
  6777. sep_pos = strlen(tmp_str);
  6778. filename[sep_pos] = 0;
  6779. conn->path_info = filename + sep_pos + 1;
  6780. *is_script_resource = 1;
  6781. *is_found = 1;
  6782. break;
  6783. } else {
  6784. DEBUG_TRACE("Substitute file %s serving path %s",
  6785. tmp_str,
  6786. filename);
  6787. /* non-script files will not have sub-resources */
  6788. filename[sep_pos] = 0;
  6789. conn->path_info = 0;
  6790. *is_script_resource = 0;
  6791. *is_found = 0;
  6792. break;
  6793. }
  6794. }
  6795. }
  6796. tmp_str[sep_pos] = '/';
  6797. }
  6798. }
  6799. mg_free(tmp_str);
  6800. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6801. #endif /* !defined(NO_FILES) */
  6802. return;
  6803. #if !defined(NO_FILES)
  6804. /* Reset all outputs */
  6805. interpret_cleanup:
  6806. memset(filestat, 0, sizeof(*filestat));
  6807. *filename = 0;
  6808. *is_found = 0;
  6809. *is_script_resource = 0;
  6810. *is_websocket_request = 0;
  6811. *is_put_or_delete_request = 0;
  6812. #endif /* !defined(NO_FILES) */
  6813. }
  6814. /* Check whether full request is buffered. Return:
  6815. * -1 if request or response is malformed
  6816. * 0 if request or response is not yet fully buffered
  6817. * >0 actual request length, including last \r\n\r\n */
  6818. static int
  6819. get_http_header_len(const char *buf, int buflen)
  6820. {
  6821. int i;
  6822. for (i = 0; i < buflen; i++) {
  6823. /* Do an unsigned comparison in some conditions below */
  6824. const unsigned char c = (unsigned char)buf[i];
  6825. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6826. && !isprint(c)) {
  6827. /* abort scan as soon as one malformed character is found */
  6828. return -1;
  6829. }
  6830. if (i < buflen - 1) {
  6831. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6832. /* Two newline, no carriage return - not standard compliant,
  6833. * but it should be accepted */
  6834. return i + 2;
  6835. }
  6836. }
  6837. if (i < buflen - 3) {
  6838. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6839. && (buf[i + 3] == '\n')) {
  6840. /* Two \r\n - standard compliant */
  6841. return i + 4;
  6842. }
  6843. }
  6844. }
  6845. return 0;
  6846. }
  6847. #if !defined(NO_CACHING)
  6848. /* Convert month to the month number. Return -1 on error, or month number */
  6849. static int
  6850. get_month_index(const char *s)
  6851. {
  6852. size_t i;
  6853. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6854. if (!strcmp(s, month_names[i])) {
  6855. return (int)i;
  6856. }
  6857. }
  6858. return -1;
  6859. }
  6860. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6861. static time_t
  6862. parse_date_string(const char *datetime)
  6863. {
  6864. char month_str[32] = {0};
  6865. int second, minute, hour, day, month, year;
  6866. time_t result = (time_t)0;
  6867. struct tm tm;
  6868. if ((sscanf(datetime,
  6869. "%d/%3s/%d %d:%d:%d",
  6870. &day,
  6871. month_str,
  6872. &year,
  6873. &hour,
  6874. &minute,
  6875. &second)
  6876. == 6)
  6877. || (sscanf(datetime,
  6878. "%d %3s %d %d:%d:%d",
  6879. &day,
  6880. month_str,
  6881. &year,
  6882. &hour,
  6883. &minute,
  6884. &second)
  6885. == 6)
  6886. || (sscanf(datetime,
  6887. "%*3s, %d %3s %d %d:%d:%d",
  6888. &day,
  6889. month_str,
  6890. &year,
  6891. &hour,
  6892. &minute,
  6893. &second)
  6894. == 6)
  6895. || (sscanf(datetime,
  6896. "%d-%3s-%d %d:%d:%d",
  6897. &day,
  6898. month_str,
  6899. &year,
  6900. &hour,
  6901. &minute,
  6902. &second)
  6903. == 6)) {
  6904. month = get_month_index(month_str);
  6905. if ((month >= 0) && (year >= 1970)) {
  6906. memset(&tm, 0, sizeof(tm));
  6907. tm.tm_year = year - 1900;
  6908. tm.tm_mon = month;
  6909. tm.tm_mday = day;
  6910. tm.tm_hour = hour;
  6911. tm.tm_min = minute;
  6912. tm.tm_sec = second;
  6913. result = timegm(&tm);
  6914. }
  6915. }
  6916. return result;
  6917. }
  6918. #endif /* !NO_CACHING */
  6919. /* Pre-process URIs according to RFC + protect against directory disclosure
  6920. * attacks by removing '..', excessive '/' and '\' characters */
  6921. static void
  6922. remove_dot_segments(char *inout)
  6923. {
  6924. /* Windows backend protection
  6925. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6926. * in URI by slash */
  6927. char *in_copy = inout ? mg_strdup(inout) : NULL;
  6928. char *out_begin = inout;
  6929. char *out_end = inout;
  6930. char *in = in_copy;
  6931. int replaced;
  6932. if (!in) {
  6933. /* Param error or OOM. */
  6934. return;
  6935. }
  6936. while (*in) {
  6937. if (*in == '\\') {
  6938. *in = '/';
  6939. }
  6940. in++;
  6941. }
  6942. /* Algorithm "remove_dot_segments" from
  6943. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6944. /* Step 1:
  6945. * The input buffer is initialized.
  6946. * The output buffer is initialized to the empty string.
  6947. */
  6948. in = in_copy;
  6949. /* Step 2:
  6950. * While the input buffer is not empty, loop as follows:
  6951. */
  6952. while (*in) {
  6953. /* Step 2a:
  6954. * If the input buffer begins with a prefix of "../" or "./",
  6955. * then remove that prefix from the input buffer;
  6956. */
  6957. if (!strncmp(in, "../", 3)) {
  6958. in += 3;
  6959. } else if (!strncmp(in, "./", 2)) {
  6960. in += 2;
  6961. }
  6962. /* otherwise */
  6963. /* Step 2b:
  6964. * if the input buffer begins with a prefix of "/./" or "/.",
  6965. * where "." is a complete path segment, then replace that
  6966. * prefix with "/" in the input buffer;
  6967. */
  6968. else if (!strncmp(in, "/./", 3)) {
  6969. in += 2;
  6970. } else if (!strcmp(in, "/.")) {
  6971. in[1] = 0;
  6972. }
  6973. /* otherwise */
  6974. /* Step 2c:
  6975. * if the input buffer begins with a prefix of "/../" or "/..",
  6976. * where ".." is a complete path segment, then replace that
  6977. * prefix with "/" in the input buffer and remove the last
  6978. * segment and its preceding "/" (if any) from the output
  6979. * buffer;
  6980. */
  6981. else if (!strncmp(in, "/../", 4)) {
  6982. in += 3;
  6983. if (out_begin != out_end) {
  6984. /* remove last segment */
  6985. do {
  6986. out_end--;
  6987. *out_end = 0;
  6988. } while ((out_begin != out_end) && (*out_end != '/'));
  6989. }
  6990. } else if (!strcmp(in, "/..")) {
  6991. in[1] = 0;
  6992. if (out_begin != out_end) {
  6993. /* remove last segment */
  6994. do {
  6995. out_end--;
  6996. *out_end = 0;
  6997. } while ((out_begin != out_end) && (*out_end != '/'));
  6998. }
  6999. }
  7000. /* otherwise */
  7001. /* Step 2d:
  7002. * if the input buffer consists only of "." or "..", then remove
  7003. * that from the input buffer;
  7004. */
  7005. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7006. *in = 0;
  7007. }
  7008. /* otherwise */
  7009. /* Step 2e:
  7010. * move the first path segment in the input buffer to the end of
  7011. * the output buffer, including the initial "/" character (if
  7012. * any) and any subsequent characters up to, but not including,
  7013. * the next "/" character or the end of the input buffer.
  7014. */
  7015. else {
  7016. do {
  7017. *out_end = *in;
  7018. out_end++;
  7019. in++;
  7020. } while ((*in != 0) && (*in != '/'));
  7021. }
  7022. }
  7023. /* Step 3:
  7024. * Finally, the output buffer is returned as the result of
  7025. * remove_dot_segments.
  7026. */
  7027. /* Terminate output */
  7028. *out_end = 0;
  7029. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7030. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7031. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7032. * or "//" anymore.
  7033. */
  7034. do {
  7035. replaced = 0;
  7036. /* replace ./ by / */
  7037. out_end = out_begin;
  7038. while (*out_end) {
  7039. if ((*out_end == '.')
  7040. && ((out_end[1] == '/') || (out_end[1] == 0))) {
  7041. char *r = out_end;
  7042. do {
  7043. r[0] = r[1];
  7044. r++;
  7045. replaced = 1;
  7046. } while (r[0] != 0);
  7047. }
  7048. out_end++;
  7049. }
  7050. /* replace ./ by / */
  7051. out_end = out_begin;
  7052. while (*out_end) {
  7053. if ((out_end[0] == '/') && (out_end[1] == '/')) {
  7054. char *c = out_end;
  7055. while (*c) {
  7056. c[0] = c[1];
  7057. c++;
  7058. }
  7059. replaced = 1;
  7060. }
  7061. out_end++;
  7062. }
  7063. } while (replaced);
  7064. /* Free temporary copies */
  7065. mg_free(in_copy);
  7066. }
  7067. static const struct {
  7068. const char *extension;
  7069. size_t ext_len;
  7070. const char *mime_type;
  7071. } builtin_mime_types[] = {
  7072. /* IANA registered MIME types
  7073. * (http://www.iana.org/assignments/media-types)
  7074. * application types */
  7075. {".doc", 4, "application/msword"},
  7076. {".eps", 4, "application/postscript"},
  7077. {".exe", 4, "application/octet-stream"},
  7078. {".js", 3, "application/javascript"},
  7079. {".json", 5, "application/json"},
  7080. {".pdf", 4, "application/pdf"},
  7081. {".ps", 3, "application/postscript"},
  7082. {".rtf", 4, "application/rtf"},
  7083. {".xhtml", 6, "application/xhtml+xml"},
  7084. {".xsl", 4, "application/xml"},
  7085. {".xslt", 5, "application/xml"},
  7086. /* fonts */
  7087. {".ttf", 4, "application/font-sfnt"},
  7088. {".cff", 4, "application/font-sfnt"},
  7089. {".otf", 4, "application/font-sfnt"},
  7090. {".aat", 4, "application/font-sfnt"},
  7091. {".sil", 4, "application/font-sfnt"},
  7092. {".pfr", 4, "application/font-tdpfr"},
  7093. {".woff", 5, "application/font-woff"},
  7094. /* audio */
  7095. {".mp3", 4, "audio/mpeg"},
  7096. {".oga", 4, "audio/ogg"},
  7097. {".ogg", 4, "audio/ogg"},
  7098. /* image */
  7099. {".gif", 4, "image/gif"},
  7100. {".ief", 4, "image/ief"},
  7101. {".jpeg", 5, "image/jpeg"},
  7102. {".jpg", 4, "image/jpeg"},
  7103. {".jpm", 4, "image/jpm"},
  7104. {".jpx", 4, "image/jpx"},
  7105. {".png", 4, "image/png"},
  7106. {".svg", 4, "image/svg+xml"},
  7107. {".tif", 4, "image/tiff"},
  7108. {".tiff", 5, "image/tiff"},
  7109. /* model */
  7110. {".wrl", 4, "model/vrml"},
  7111. /* text */
  7112. {".css", 4, "text/css"},
  7113. {".csv", 4, "text/csv"},
  7114. {".htm", 4, "text/html"},
  7115. {".html", 5, "text/html"},
  7116. {".sgm", 4, "text/sgml"},
  7117. {".shtm", 5, "text/html"},
  7118. {".shtml", 6, "text/html"},
  7119. {".txt", 4, "text/plain"},
  7120. {".xml", 4, "text/xml"},
  7121. /* video */
  7122. {".mov", 4, "video/quicktime"},
  7123. {".mp4", 4, "video/mp4"},
  7124. {".mpeg", 5, "video/mpeg"},
  7125. {".mpg", 4, "video/mpeg"},
  7126. {".ogv", 4, "video/ogg"},
  7127. {".qt", 3, "video/quicktime"},
  7128. /* not registered types
  7129. * (http://reference.sitepoint.com/html/mime-types-full,
  7130. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7131. {".arj", 4, "application/x-arj-compressed"},
  7132. {".gz", 3, "application/x-gunzip"},
  7133. {".rar", 4, "application/x-arj-compressed"},
  7134. {".swf", 4, "application/x-shockwave-flash"},
  7135. {".tar", 4, "application/x-tar"},
  7136. {".tgz", 4, "application/x-tar-gz"},
  7137. {".torrent", 8, "application/x-bittorrent"},
  7138. {".ppt", 4, "application/x-mspowerpoint"},
  7139. {".xls", 4, "application/x-msexcel"},
  7140. {".zip", 4, "application/x-zip-compressed"},
  7141. {".aac",
  7142. 4,
  7143. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7144. {".aif", 4, "audio/x-aif"},
  7145. {".m3u", 4, "audio/x-mpegurl"},
  7146. {".mid", 4, "audio/x-midi"},
  7147. {".ra", 3, "audio/x-pn-realaudio"},
  7148. {".ram", 4, "audio/x-pn-realaudio"},
  7149. {".wav", 4, "audio/x-wav"},
  7150. {".bmp", 4, "image/bmp"},
  7151. {".ico", 4, "image/x-icon"},
  7152. {".pct", 4, "image/x-pct"},
  7153. {".pict", 5, "image/pict"},
  7154. {".rgb", 4, "image/x-rgb"},
  7155. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7156. {".asf", 4, "video/x-ms-asf"},
  7157. {".avi", 4, "video/x-msvideo"},
  7158. {".m4v", 4, "video/x-m4v"},
  7159. {NULL, 0, NULL}};
  7160. const char *
  7161. mg_get_builtin_mime_type(const char *path)
  7162. {
  7163. const char *ext;
  7164. size_t i, path_len;
  7165. path_len = strlen(path);
  7166. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7167. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7168. if ((path_len > builtin_mime_types[i].ext_len)
  7169. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7170. return builtin_mime_types[i].mime_type;
  7171. }
  7172. }
  7173. return "text/plain";
  7174. }
  7175. /* Look at the "path" extension and figure what mime type it has.
  7176. * Store mime type in the vector. */
  7177. static void
  7178. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7179. {
  7180. struct vec ext_vec, mime_vec;
  7181. const char *list, *ext;
  7182. size_t path_len;
  7183. path_len = strlen(path);
  7184. if ((conn == NULL) || (vec == NULL)) {
  7185. if (vec != NULL) {
  7186. memset(vec, '\0', sizeof(struct vec));
  7187. }
  7188. return;
  7189. }
  7190. /* Scan user-defined mime types first, in case user wants to
  7191. * override default mime types. */
  7192. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7193. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7194. /* ext now points to the path suffix */
  7195. ext = path + path_len - ext_vec.len;
  7196. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7197. *vec = mime_vec;
  7198. return;
  7199. }
  7200. }
  7201. vec->ptr = mg_get_builtin_mime_type(path);
  7202. vec->len = strlen(vec->ptr);
  7203. }
  7204. /* Stringify binary data. Output buffer must be twice as big as input,
  7205. * because each byte takes 2 bytes in string representation */
  7206. static void
  7207. bin2str(char *to, const unsigned char *p, size_t len)
  7208. {
  7209. static const char *hex = "0123456789abcdef";
  7210. for (; len--; p++) {
  7211. *to++ = hex[p[0] >> 4];
  7212. *to++ = hex[p[0] & 0x0f];
  7213. }
  7214. *to = '\0';
  7215. }
  7216. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7217. */
  7218. char *
  7219. mg_md5(char buf[33], ...)
  7220. {
  7221. md5_byte_t hash[16];
  7222. const char *p;
  7223. va_list ap;
  7224. md5_state_t ctx;
  7225. md5_init(&ctx);
  7226. va_start(ap, buf);
  7227. while ((p = va_arg(ap, const char *)) != NULL) {
  7228. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7229. }
  7230. va_end(ap);
  7231. md5_finish(&ctx, hash);
  7232. bin2str(buf, hash, sizeof(hash));
  7233. return buf;
  7234. }
  7235. /* Check the user's password, return 1 if OK */
  7236. static int
  7237. check_password(const char *method,
  7238. const char *ha1,
  7239. const char *uri,
  7240. const char *nonce,
  7241. const char *nc,
  7242. const char *cnonce,
  7243. const char *qop,
  7244. const char *response)
  7245. {
  7246. char ha2[32 + 1], expected_response[32 + 1];
  7247. /* Some of the parameters may be NULL */
  7248. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7249. || (qop == NULL) || (response == NULL)) {
  7250. return 0;
  7251. }
  7252. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7253. if (strlen(response) != 32) {
  7254. return 0;
  7255. }
  7256. mg_md5(ha2, method, ":", uri, NULL);
  7257. mg_md5(expected_response,
  7258. ha1,
  7259. ":",
  7260. nonce,
  7261. ":",
  7262. nc,
  7263. ":",
  7264. cnonce,
  7265. ":",
  7266. qop,
  7267. ":",
  7268. ha2,
  7269. NULL);
  7270. return mg_strcasecmp(response, expected_response) == 0;
  7271. }
  7272. #if !defined(NO_FILESYSTEMS)
  7273. /* Use the global passwords file, if specified by auth_gpass option,
  7274. * or search for .htpasswd in the requested directory. */
  7275. static void
  7276. open_auth_file(struct mg_connection *conn,
  7277. const char *path,
  7278. struct mg_file *filep)
  7279. {
  7280. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7281. char name[PATH_MAX];
  7282. const char *p, *e,
  7283. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7284. int truncated;
  7285. if (gpass != NULL) {
  7286. /* Use global passwords file */
  7287. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7288. #if defined(DEBUG)
  7289. /* Use mg_cry_internal here, since gpass has been
  7290. * configured. */
  7291. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7292. #endif
  7293. }
  7294. /* Important: using local struct mg_file to test path for
  7295. * is_directory flag. If filep is used, mg_stat() makes it
  7296. * appear as if auth file was opened.
  7297. * TODO(mid): Check if this is still required after rewriting
  7298. * mg_stat */
  7299. } else if (mg_stat(conn, path, &filep->stat)
  7300. && filep->stat.is_directory) {
  7301. mg_snprintf(conn,
  7302. &truncated,
  7303. name,
  7304. sizeof(name),
  7305. "%s/%s",
  7306. path,
  7307. PASSWORDS_FILE_NAME);
  7308. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7309. #if defined(DEBUG)
  7310. /* Don't use mg_cry_internal here, but only a trace, since
  7311. * this is a typical case. It will occur for every directory
  7312. * without a password file. */
  7313. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7314. #endif
  7315. }
  7316. } else {
  7317. /* Try to find .htpasswd in requested directory. */
  7318. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7319. if (e[0] == '/') {
  7320. break;
  7321. }
  7322. }
  7323. mg_snprintf(conn,
  7324. &truncated,
  7325. name,
  7326. sizeof(name),
  7327. "%.*s/%s",
  7328. (int)(e - p),
  7329. p,
  7330. PASSWORDS_FILE_NAME);
  7331. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7332. #if defined(DEBUG)
  7333. /* Don't use mg_cry_internal here, but only a trace, since
  7334. * this is a typical case. It will occur for every directory
  7335. * without a password file. */
  7336. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7337. #endif
  7338. }
  7339. }
  7340. }
  7341. }
  7342. #endif /* NO_FILESYSTEMS */
  7343. /* Parsed Authorization header */
  7344. struct ah {
  7345. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7346. };
  7347. /* Return 1 on success. Always initializes the ah structure. */
  7348. static int
  7349. parse_auth_header(struct mg_connection *conn,
  7350. char *buf,
  7351. size_t buf_size,
  7352. struct ah *ah)
  7353. {
  7354. char *name, *value, *s;
  7355. const char *auth_header;
  7356. uint64_t nonce;
  7357. if (!ah || !conn) {
  7358. return 0;
  7359. }
  7360. (void)memset(ah, 0, sizeof(*ah));
  7361. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7362. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7363. return 0;
  7364. }
  7365. /* Make modifiable copy of the auth header */
  7366. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7367. s = buf;
  7368. /* Parse authorization header */
  7369. for (;;) {
  7370. /* Gobble initial spaces */
  7371. while (isspace((unsigned char)*s)) {
  7372. s++;
  7373. }
  7374. name = skip_quoted(&s, "=", " ", 0);
  7375. /* Value is either quote-delimited, or ends at first comma or space.
  7376. */
  7377. if (s[0] == '\"') {
  7378. s++;
  7379. value = skip_quoted(&s, "\"", " ", '\\');
  7380. if (s[0] == ',') {
  7381. s++;
  7382. }
  7383. } else {
  7384. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7385. * uses spaces */
  7386. }
  7387. if (*name == '\0') {
  7388. break;
  7389. }
  7390. if (!strcmp(name, "username")) {
  7391. ah->user = value;
  7392. } else if (!strcmp(name, "cnonce")) {
  7393. ah->cnonce = value;
  7394. } else if (!strcmp(name, "response")) {
  7395. ah->response = value;
  7396. } else if (!strcmp(name, "uri")) {
  7397. ah->uri = value;
  7398. } else if (!strcmp(name, "qop")) {
  7399. ah->qop = value;
  7400. } else if (!strcmp(name, "nc")) {
  7401. ah->nc = value;
  7402. } else if (!strcmp(name, "nonce")) {
  7403. ah->nonce = value;
  7404. }
  7405. }
  7406. #if !defined(NO_NONCE_CHECK)
  7407. /* Read the nonce from the response. */
  7408. if (ah->nonce == NULL) {
  7409. return 0;
  7410. }
  7411. s = NULL;
  7412. nonce = strtoull(ah->nonce, &s, 10);
  7413. if ((s == NULL) || (*s != 0)) {
  7414. return 0;
  7415. }
  7416. /* Convert the nonce from the client to a number. */
  7417. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7418. /* The converted number corresponds to the time the nounce has been
  7419. * created. This should not be earlier than the server start. */
  7420. /* Server side nonce check is valuable in all situations but one:
  7421. * if the server restarts frequently, but the client should not see
  7422. * that, so the server should accept nonces from previous starts. */
  7423. /* However, the reasonable default is to not accept a nonce from a
  7424. * previous start, so if anyone changed the access rights between
  7425. * two restarts, a new login is required. */
  7426. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7427. /* nonce is from a previous start of the server and no longer valid
  7428. * (replay attack?) */
  7429. return 0;
  7430. }
  7431. /* Check if the nonce is too high, so it has not (yet) been used by the
  7432. * server. */
  7433. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7434. + conn->dom_ctx->nonce_count)) {
  7435. return 0;
  7436. }
  7437. #else
  7438. (void)nonce;
  7439. #endif
  7440. /* CGI needs it as REMOTE_USER */
  7441. if (ah->user != NULL) {
  7442. conn->request_info.remote_user =
  7443. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7444. } else {
  7445. return 0;
  7446. }
  7447. return 1;
  7448. }
  7449. static const char *
  7450. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7451. {
  7452. #if defined(MG_USE_OPEN_FILE)
  7453. const char *eof;
  7454. size_t len;
  7455. const char *memend;
  7456. #else
  7457. (void)p; /* parameter is unused */
  7458. #endif
  7459. if (!filep) {
  7460. return NULL;
  7461. }
  7462. #if defined(MG_USE_OPEN_FILE)
  7463. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7464. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7465. /* Search for \n from p till the end of stream */
  7466. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7467. if (eof != NULL) {
  7468. eof += 1; /* Include \n */
  7469. } else {
  7470. eof = memend; /* Copy remaining data */
  7471. }
  7472. len =
  7473. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7474. memcpy(buf, *p, len);
  7475. buf[len] = '\0';
  7476. *p += len;
  7477. return len ? eof : NULL;
  7478. } else /* filep->access.fp block below */
  7479. #endif
  7480. if (filep->access.fp != NULL) {
  7481. return fgets(buf, (int)size, filep->access.fp);
  7482. } else {
  7483. return NULL;
  7484. }
  7485. }
  7486. /* Define the initial recursion depth for procesesing htpasswd files that
  7487. * include other htpasswd
  7488. * (or even the same) files. It is not difficult to provide a file or files
  7489. * s.t. they force civetweb
  7490. * to infinitely recurse and then crash.
  7491. */
  7492. #define INITIAL_DEPTH 9
  7493. #if INITIAL_DEPTH <= 0
  7494. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7495. #endif
  7496. #if !defined(NO_FILESYSTEMS)
  7497. struct read_auth_file_struct {
  7498. struct mg_connection *conn;
  7499. struct ah ah;
  7500. const char *domain;
  7501. char buf[256 + 256 + 40];
  7502. const char *f_user;
  7503. const char *f_domain;
  7504. const char *f_ha1;
  7505. };
  7506. static int
  7507. read_auth_file(struct mg_file *filep,
  7508. struct read_auth_file_struct *workdata,
  7509. int depth)
  7510. {
  7511. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7512. int is_authorized = 0;
  7513. struct mg_file fp;
  7514. size_t l;
  7515. if (!filep || !workdata || (0 == depth)) {
  7516. return 0;
  7517. }
  7518. /* Loop over passwords file */
  7519. #if defined(MG_USE_OPEN_FILE)
  7520. p = (char *)filep->access.membuf;
  7521. #endif
  7522. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7523. l = strlen(workdata->buf);
  7524. while (l > 0) {
  7525. if (isspace((unsigned char)workdata->buf[l - 1])
  7526. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7527. l--;
  7528. workdata->buf[l] = 0;
  7529. } else
  7530. break;
  7531. }
  7532. if (l < 1) {
  7533. continue;
  7534. }
  7535. workdata->f_user = workdata->buf;
  7536. if (workdata->f_user[0] == ':') {
  7537. /* user names may not contain a ':' and may not be empty,
  7538. * so lines starting with ':' may be used for a special purpose
  7539. */
  7540. if (workdata->f_user[1] == '#') {
  7541. /* :# is a comment */
  7542. continue;
  7543. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7544. if (mg_fopen(workdata->conn,
  7545. workdata->f_user + 9,
  7546. MG_FOPEN_MODE_READ,
  7547. &fp)) {
  7548. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7549. (void)mg_fclose(
  7550. &fp.access); /* ignore error on read only file */
  7551. /* No need to continue processing files once we have a
  7552. * match, since nothing will reset it back
  7553. * to 0.
  7554. */
  7555. if (is_authorized) {
  7556. return is_authorized;
  7557. }
  7558. } else {
  7559. mg_cry_internal(workdata->conn,
  7560. "%s: cannot open authorization file: %s",
  7561. __func__,
  7562. workdata->buf);
  7563. }
  7564. continue;
  7565. }
  7566. /* everything is invalid for the moment (might change in the
  7567. * future) */
  7568. mg_cry_internal(workdata->conn,
  7569. "%s: syntax error in authorization file: %s",
  7570. __func__,
  7571. workdata->buf);
  7572. continue;
  7573. }
  7574. workdata->f_domain = strchr(workdata->f_user, ':');
  7575. if (workdata->f_domain == NULL) {
  7576. mg_cry_internal(workdata->conn,
  7577. "%s: syntax error in authorization file: %s",
  7578. __func__,
  7579. workdata->buf);
  7580. continue;
  7581. }
  7582. *(char *)(workdata->f_domain) = 0;
  7583. (workdata->f_domain)++;
  7584. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7585. if (workdata->f_ha1 == NULL) {
  7586. mg_cry_internal(workdata->conn,
  7587. "%s: syntax error in authorization file: %s",
  7588. __func__,
  7589. workdata->buf);
  7590. continue;
  7591. }
  7592. *(char *)(workdata->f_ha1) = 0;
  7593. (workdata->f_ha1)++;
  7594. if (!strcmp(workdata->ah.user, workdata->f_user)
  7595. && !strcmp(workdata->domain, workdata->f_domain)) {
  7596. return check_password(workdata->conn->request_info.request_method,
  7597. workdata->f_ha1,
  7598. workdata->ah.uri,
  7599. workdata->ah.nonce,
  7600. workdata->ah.nc,
  7601. workdata->ah.cnonce,
  7602. workdata->ah.qop,
  7603. workdata->ah.response);
  7604. }
  7605. }
  7606. return is_authorized;
  7607. }
  7608. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7609. static int
  7610. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7611. {
  7612. struct read_auth_file_struct workdata;
  7613. char buf[MG_BUF_LEN];
  7614. if (!conn || !conn->dom_ctx) {
  7615. return 0;
  7616. }
  7617. memset(&workdata, 0, sizeof(workdata));
  7618. workdata.conn = conn;
  7619. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7620. return 0;
  7621. }
  7622. if (realm) {
  7623. workdata.domain = realm;
  7624. } else {
  7625. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7626. }
  7627. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7628. }
  7629. /* Public function to check http digest authentication header */
  7630. int
  7631. mg_check_digest_access_authentication(struct mg_connection *conn,
  7632. const char *realm,
  7633. const char *filename)
  7634. {
  7635. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7636. int auth;
  7637. if (!conn || !filename) {
  7638. return -1;
  7639. }
  7640. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7641. return -2;
  7642. }
  7643. auth = authorize(conn, &file, realm);
  7644. mg_fclose(&file.access);
  7645. return auth;
  7646. }
  7647. #endif /* NO_FILESYSTEMS */
  7648. /* Return 1 if request is authorised, 0 otherwise. */
  7649. static int
  7650. check_authorization(struct mg_connection *conn, const char *path)
  7651. {
  7652. #if !defined(NO_FILESYSTEMS)
  7653. char fname[PATH_MAX];
  7654. struct vec uri_vec, filename_vec;
  7655. const char *list;
  7656. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7657. int authorized = 1, truncated;
  7658. if (!conn || !conn->dom_ctx) {
  7659. return 0;
  7660. }
  7661. list = conn->dom_ctx->config[PROTECT_URI];
  7662. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7663. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7664. mg_snprintf(conn,
  7665. &truncated,
  7666. fname,
  7667. sizeof(fname),
  7668. "%.*s",
  7669. (int)filename_vec.len,
  7670. filename_vec.ptr);
  7671. if (truncated
  7672. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7673. mg_cry_internal(conn,
  7674. "%s: cannot open %s: %s",
  7675. __func__,
  7676. fname,
  7677. strerror(errno));
  7678. }
  7679. break;
  7680. }
  7681. }
  7682. if (!is_file_opened(&file.access)) {
  7683. open_auth_file(conn, path, &file);
  7684. }
  7685. if (is_file_opened(&file.access)) {
  7686. authorized = authorize(conn, &file, NULL);
  7687. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7688. }
  7689. return authorized;
  7690. #else
  7691. (void)conn;
  7692. (void)path;
  7693. return 1;
  7694. #endif /* NO_FILESYSTEMS */
  7695. }
  7696. /* Internal function. Assumes conn is valid */
  7697. static void
  7698. send_authorization_request(struct mg_connection *conn, const char *realm)
  7699. {
  7700. char date[64];
  7701. time_t curtime = time(NULL);
  7702. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7703. if (!realm) {
  7704. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7705. }
  7706. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7707. nonce += conn->dom_ctx->nonce_count;
  7708. ++conn->dom_ctx->nonce_count;
  7709. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7710. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7711. conn->status_code = 401;
  7712. conn->must_close = 1;
  7713. gmt_time_string(date, sizeof(date), &curtime);
  7714. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7715. send_no_cache_header(conn);
  7716. send_additional_header(conn);
  7717. mg_printf(conn,
  7718. "Date: %s\r\n"
  7719. "Connection: %s\r\n"
  7720. "Content-Length: 0\r\n"
  7721. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7722. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7723. date,
  7724. suggest_connection_header(conn),
  7725. realm,
  7726. nonce);
  7727. }
  7728. /* Interface function. Parameters are provided by the user, so do
  7729. * at least some basic checks.
  7730. */
  7731. int
  7732. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7733. const char *realm)
  7734. {
  7735. if (conn && conn->dom_ctx) {
  7736. send_authorization_request(conn, realm);
  7737. return 0;
  7738. }
  7739. return -1;
  7740. }
  7741. #if !defined(NO_FILES)
  7742. static int
  7743. is_authorized_for_put(struct mg_connection *conn)
  7744. {
  7745. if (conn) {
  7746. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7747. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7748. int ret = 0;
  7749. if (passfile != NULL
  7750. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7751. ret = authorize(conn, &file, NULL);
  7752. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7753. }
  7754. return ret;
  7755. }
  7756. return 0;
  7757. }
  7758. #endif
  7759. int
  7760. mg_modify_passwords_file(const char *fname,
  7761. const char *domain,
  7762. const char *user,
  7763. const char *pass)
  7764. {
  7765. int found, i;
  7766. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7767. FILE *fp, *fp2;
  7768. found = 0;
  7769. fp = fp2 = NULL;
  7770. /* Regard empty password as no password - remove user record. */
  7771. if ((pass != NULL) && (pass[0] == '\0')) {
  7772. pass = NULL;
  7773. }
  7774. /* Other arguments must not be empty */
  7775. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7776. return 0;
  7777. }
  7778. /* Using the given file format, user name and domain must not contain
  7779. * ':'
  7780. */
  7781. if (strchr(user, ':') != NULL) {
  7782. return 0;
  7783. }
  7784. if (strchr(domain, ':') != NULL) {
  7785. return 0;
  7786. }
  7787. /* Do not allow control characters like newline in user name and domain.
  7788. * Do not allow excessively long names either. */
  7789. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7790. if (iscntrl((unsigned char)user[i])) {
  7791. return 0;
  7792. }
  7793. }
  7794. if (user[i]) {
  7795. return 0;
  7796. }
  7797. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7798. if (iscntrl((unsigned char)domain[i])) {
  7799. return 0;
  7800. }
  7801. }
  7802. if (domain[i]) {
  7803. return 0;
  7804. }
  7805. /* The maximum length of the path to the password file is limited */
  7806. if ((strlen(fname) + 4) >= PATH_MAX) {
  7807. return 0;
  7808. }
  7809. /* Create a temporary file name. Length has been checked before. */
  7810. strcpy(tmp, fname);
  7811. strcat(tmp, ".tmp");
  7812. /* Create the file if does not exist */
  7813. /* Use of fopen here is OK, since fname is only ASCII */
  7814. if ((fp = fopen(fname, "a+")) != NULL) {
  7815. (void)fclose(fp);
  7816. }
  7817. /* Open the given file and temporary file */
  7818. if ((fp = fopen(fname, "r")) == NULL) {
  7819. return 0;
  7820. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7821. fclose(fp);
  7822. return 0;
  7823. }
  7824. /* Copy the stuff to temporary file */
  7825. while (fgets(line, sizeof(line), fp) != NULL) {
  7826. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7827. continue;
  7828. }
  7829. u[255] = 0;
  7830. d[255] = 0;
  7831. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7832. found++;
  7833. if (pass != NULL) {
  7834. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7835. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7836. }
  7837. } else {
  7838. fprintf(fp2, "%s", line);
  7839. }
  7840. }
  7841. /* If new user, just add it */
  7842. if (!found && (pass != NULL)) {
  7843. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7844. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7845. }
  7846. /* Close files */
  7847. fclose(fp);
  7848. fclose(fp2);
  7849. /* Put the temp file in place of real file */
  7850. IGNORE_UNUSED_RESULT(remove(fname));
  7851. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7852. return 1;
  7853. }
  7854. static int
  7855. is_valid_port(unsigned long port)
  7856. {
  7857. return (port <= 0xffff);
  7858. }
  7859. static int
  7860. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7861. {
  7862. struct addrinfo hints, *res, *ressave;
  7863. int func_ret = 0;
  7864. int gai_ret;
  7865. memset(&hints, 0, sizeof(struct addrinfo));
  7866. hints.ai_family = af;
  7867. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7868. if (gai_ret != 0) {
  7869. /* gai_strerror could be used to convert gai_ret to a string */
  7870. /* POSIX return values: see
  7871. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7872. */
  7873. /* Windows return values: see
  7874. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7875. */
  7876. return 0;
  7877. }
  7878. ressave = res;
  7879. while (res) {
  7880. if (dstlen >= (size_t)res->ai_addrlen) {
  7881. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7882. func_ret = 1;
  7883. }
  7884. res = res->ai_next;
  7885. }
  7886. freeaddrinfo(ressave);
  7887. return func_ret;
  7888. }
  7889. static int
  7890. connect_socket(struct mg_context *ctx /* may be NULL */,
  7891. const char *host,
  7892. int port,
  7893. int use_ssl,
  7894. char *ebuf,
  7895. size_t ebuf_len,
  7896. SOCKET *sock /* output: socket, must not be NULL */,
  7897. union usa *sa /* output: socket address, must not be NULL */
  7898. )
  7899. {
  7900. int ip_ver = 0;
  7901. int conn_ret = -1;
  7902. int sockerr = 0;
  7903. *sock = INVALID_SOCKET;
  7904. memset(sa, 0, sizeof(*sa));
  7905. if (ebuf_len > 0) {
  7906. *ebuf = 0;
  7907. }
  7908. if (host == NULL) {
  7909. mg_snprintf(NULL,
  7910. NULL, /* No truncation check for ebuf */
  7911. ebuf,
  7912. ebuf_len,
  7913. "%s",
  7914. "NULL host");
  7915. return 0;
  7916. }
  7917. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7918. mg_snprintf(NULL,
  7919. NULL, /* No truncation check for ebuf */
  7920. ebuf,
  7921. ebuf_len,
  7922. "%s",
  7923. "invalid port");
  7924. return 0;
  7925. }
  7926. #if !defined(NO_SSL)
  7927. #if !defined(NO_SSL_DL)
  7928. #if defined(OPENSSL_API_1_1)
  7929. if (use_ssl && (TLS_client_method == NULL)) {
  7930. mg_snprintf(NULL,
  7931. NULL, /* No truncation check for ebuf */
  7932. ebuf,
  7933. ebuf_len,
  7934. "%s",
  7935. "SSL is not initialized");
  7936. return 0;
  7937. }
  7938. #else
  7939. if (use_ssl && (SSLv23_client_method == NULL)) {
  7940. mg_snprintf(NULL,
  7941. NULL, /* No truncation check for ebuf */
  7942. ebuf,
  7943. ebuf_len,
  7944. "%s",
  7945. "SSL is not initialized");
  7946. return 0;
  7947. }
  7948. #endif /* OPENSSL_API_1_1 */
  7949. #else
  7950. (void)use_ssl;
  7951. #endif /* NO_SSL_DL */
  7952. #else
  7953. (void)use_ssl;
  7954. #endif /* !defined(NO_SSL) */
  7955. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7956. sa->sin.sin_family = AF_INET;
  7957. sa->sin.sin_port = htons((uint16_t)port);
  7958. ip_ver = 4;
  7959. #if defined(USE_IPV6)
  7960. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7961. sa->sin6.sin6_family = AF_INET6;
  7962. sa->sin6.sin6_port = htons((uint16_t)port);
  7963. ip_ver = 6;
  7964. } else if (host[0] == '[') {
  7965. /* While getaddrinfo on Windows will work with [::1],
  7966. * getaddrinfo on Linux only works with ::1 (without []). */
  7967. size_t l = strlen(host + 1);
  7968. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7969. if (h) {
  7970. h[l - 1] = 0;
  7971. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7972. sa->sin6.sin6_family = AF_INET6;
  7973. sa->sin6.sin6_port = htons((uint16_t)port);
  7974. ip_ver = 6;
  7975. }
  7976. mg_free(h);
  7977. }
  7978. #endif
  7979. }
  7980. if (ip_ver == 0) {
  7981. mg_snprintf(NULL,
  7982. NULL, /* No truncation check for ebuf */
  7983. ebuf,
  7984. ebuf_len,
  7985. "%s",
  7986. "host not found");
  7987. return 0;
  7988. }
  7989. if (ip_ver
  7990. == 4) { //-V547 - condition is always true, if USE_IPV6 is not set
  7991. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7992. }
  7993. #if defined(USE_IPV6)
  7994. else if (ip_ver == 6) {
  7995. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7996. }
  7997. #endif
  7998. if (*sock == INVALID_SOCKET) {
  7999. mg_snprintf(NULL,
  8000. NULL, /* No truncation check for ebuf */
  8001. ebuf,
  8002. ebuf_len,
  8003. "socket(): %s",
  8004. strerror(ERRNO));
  8005. return 0;
  8006. }
  8007. if (0 != set_non_blocking_mode(*sock)) {
  8008. mg_snprintf(NULL,
  8009. NULL, /* No truncation check for ebuf */
  8010. ebuf,
  8011. ebuf_len,
  8012. "Cannot set socket to non-blocking: %s",
  8013. strerror(ERRNO));
  8014. closesocket(*sock);
  8015. *sock = INVALID_SOCKET;
  8016. return 0;
  8017. }
  8018. set_close_on_exec(*sock, NULL, ctx);
  8019. if (ip_ver
  8020. == 4) { //-V547 - condition is always true, if USE_IPV6 is not set
  8021. /* connected with IPv4 */
  8022. conn_ret = connect(*sock,
  8023. (struct sockaddr *)((void *)&sa->sin),
  8024. sizeof(sa->sin));
  8025. }
  8026. #if defined(USE_IPV6)
  8027. else if (ip_ver == 6) {
  8028. /* connected with IPv6 */
  8029. conn_ret = connect(*sock,
  8030. (struct sockaddr *)((void *)&sa->sin6),
  8031. sizeof(sa->sin6));
  8032. }
  8033. #endif
  8034. if (conn_ret != 0) {
  8035. sockerr = ERRNO;
  8036. }
  8037. #if defined(_WIN32)
  8038. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8039. #else
  8040. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8041. #endif
  8042. /* Data for getsockopt */
  8043. void *psockerr = &sockerr;
  8044. int ret;
  8045. #if defined(_WIN32)
  8046. int len = (int)sizeof(sockerr);
  8047. #else
  8048. socklen_t len = (socklen_t)sizeof(sockerr);
  8049. #endif
  8050. /* Data for poll */
  8051. struct mg_pollfd pfd[1];
  8052. int pollres;
  8053. int ms_wait = 10000; /* 10 second timeout */
  8054. int nonstop = 0;
  8055. /* For a non-blocking socket, the connect sequence is:
  8056. * 1) call connect (will not block)
  8057. * 2) wait until the socket is ready for writing (select or poll)
  8058. * 3) check connection state with getsockopt
  8059. */
  8060. pfd[0].fd = *sock;
  8061. pfd[0].events = POLLOUT;
  8062. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8063. if (pollres != 1) {
  8064. /* Not connected */
  8065. mg_snprintf(NULL,
  8066. NULL, /* No truncation check for ebuf */
  8067. ebuf,
  8068. ebuf_len,
  8069. "connect(%s:%d): timeout",
  8070. host,
  8071. port);
  8072. closesocket(*sock);
  8073. *sock = INVALID_SOCKET;
  8074. return 0;
  8075. }
  8076. #if defined(_WIN32)
  8077. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8078. #else
  8079. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8080. #endif
  8081. if ((ret == 0) && (sockerr == 0)) {
  8082. conn_ret = 0;
  8083. }
  8084. }
  8085. if (conn_ret != 0) {
  8086. /* Not connected */
  8087. mg_snprintf(NULL,
  8088. NULL, /* No truncation check for ebuf */
  8089. ebuf,
  8090. ebuf_len,
  8091. "connect(%s:%d): error %s",
  8092. host,
  8093. port,
  8094. strerror(sockerr));
  8095. closesocket(*sock);
  8096. *sock = INVALID_SOCKET;
  8097. return 0;
  8098. }
  8099. return 1;
  8100. }
  8101. int
  8102. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8103. {
  8104. static const char *dont_escape = "._-$,;~()";
  8105. static const char *hex = "0123456789abcdef";
  8106. char *pos = dst;
  8107. const char *end = dst + dst_len - 1;
  8108. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8109. if (isalnum((unsigned char)*src)
  8110. || (strchr(dont_escape, *src) != NULL)) {
  8111. *pos = *src;
  8112. } else if (pos + 2 < end) {
  8113. pos[0] = '%';
  8114. pos[1] = hex[(unsigned char)*src >> 4];
  8115. pos[2] = hex[(unsigned char)*src & 0xf];
  8116. pos += 2;
  8117. } else {
  8118. break;
  8119. }
  8120. }
  8121. *pos = '\0';
  8122. return (*src == '\0') ? (int)(pos - dst) : -1;
  8123. }
  8124. /* Return 0 on success, non-zero if an error occurs. */
  8125. static int
  8126. print_dir_entry(struct de *de)
  8127. {
  8128. size_t namesize, escsize, i;
  8129. char *href, *esc, *p;
  8130. char size[64], mod[64];
  8131. #if defined(REENTRANT_TIME)
  8132. struct tm _tm;
  8133. struct tm *tm = &_tm;
  8134. #else
  8135. struct tm *tm;
  8136. #endif
  8137. /* Estimate worst case size for encoding and escaping */
  8138. namesize = strlen(de->file_name) + 1;
  8139. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8140. href = (char *)mg_malloc(namesize * 3 + escsize);
  8141. if (href == NULL) {
  8142. return -1;
  8143. }
  8144. mg_url_encode(de->file_name, href, namesize * 3);
  8145. esc = NULL;
  8146. if (escsize > 0) {
  8147. /* HTML escaping needed */
  8148. esc = href + namesize * 3;
  8149. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8150. mg_strlcpy(p, de->file_name + i, 2);
  8151. if (*p == '&') {
  8152. strcpy(p, "&amp;");
  8153. } else if (*p == '<') {
  8154. strcpy(p, "&lt;");
  8155. } else if (*p == '>') {
  8156. strcpy(p, "&gt;");
  8157. }
  8158. }
  8159. }
  8160. if (de->file.is_directory) {
  8161. mg_snprintf(de->conn,
  8162. NULL, /* Buffer is big enough */
  8163. size,
  8164. sizeof(size),
  8165. "%s",
  8166. "[DIRECTORY]");
  8167. } else {
  8168. /* We use (signed) cast below because MSVC 6 compiler cannot
  8169. * convert unsigned __int64 to double. Sigh. */
  8170. if (de->file.size < 1024) {
  8171. mg_snprintf(de->conn,
  8172. NULL, /* Buffer is big enough */
  8173. size,
  8174. sizeof(size),
  8175. "%d",
  8176. (int)de->file.size);
  8177. } else if (de->file.size < 0x100000) {
  8178. mg_snprintf(de->conn,
  8179. NULL, /* Buffer is big enough */
  8180. size,
  8181. sizeof(size),
  8182. "%.1fk",
  8183. (double)de->file.size / 1024.0);
  8184. } else if (de->file.size < 0x40000000) {
  8185. mg_snprintf(de->conn,
  8186. NULL, /* Buffer is big enough */
  8187. size,
  8188. sizeof(size),
  8189. "%.1fM",
  8190. (double)de->file.size / 1048576);
  8191. } else {
  8192. mg_snprintf(de->conn,
  8193. NULL, /* Buffer is big enough */
  8194. size,
  8195. sizeof(size),
  8196. "%.1fG",
  8197. (double)de->file.size / 1073741824);
  8198. }
  8199. }
  8200. /* Note: mg_snprintf will not cause a buffer overflow above.
  8201. * So, string truncation checks are not required here. */
  8202. #if defined(REENTRANT_TIME)
  8203. localtime_r(&de->file.last_modified, tm);
  8204. #else
  8205. tm = localtime(&de->file.last_modified);
  8206. #endif
  8207. if (tm != NULL) {
  8208. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8209. } else {
  8210. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8211. mod[sizeof(mod) - 1] = '\0';
  8212. }
  8213. mg_printf(de->conn,
  8214. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8215. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8216. href,
  8217. de->file.is_directory ? "/" : "",
  8218. esc ? esc : de->file_name,
  8219. de->file.is_directory ? "/" : "",
  8220. mod,
  8221. size);
  8222. mg_free(href);
  8223. return 0;
  8224. }
  8225. /* This function is called from send_directory() and used for
  8226. * sorting directory entries by size, or name, or modification time.
  8227. * On windows, __cdecl specification is needed in case if project is built
  8228. * with __stdcall convention. qsort always requires __cdels callback. */
  8229. static int WINCDECL
  8230. compare_dir_entries(const void *p1, const void *p2)
  8231. {
  8232. if (p1 && p2) {
  8233. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8234. const char *query_string = a->conn->request_info.query_string;
  8235. int cmp_result = 0;
  8236. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8237. query_string = "n";
  8238. }
  8239. if (a->file.is_directory && !b->file.is_directory) {
  8240. return -1; /* Always put directories on top */
  8241. } else if (!a->file.is_directory && b->file.is_directory) {
  8242. return 1; /* Always put directories on top */
  8243. } else if (*query_string == 'n') {
  8244. cmp_result = strcmp(a->file_name, b->file_name);
  8245. } else if (*query_string == 's') {
  8246. cmp_result = (a->file.size == b->file.size)
  8247. ? 0
  8248. : ((a->file.size > b->file.size) ? 1 : -1);
  8249. } else if (*query_string == 'd') {
  8250. cmp_result =
  8251. (a->file.last_modified == b->file.last_modified)
  8252. ? 0
  8253. : ((a->file.last_modified > b->file.last_modified) ? 1
  8254. : -1);
  8255. }
  8256. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8257. }
  8258. return 0;
  8259. }
  8260. static int
  8261. must_hide_file(struct mg_connection *conn, const char *path)
  8262. {
  8263. if (conn && conn->dom_ctx) {
  8264. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8265. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8266. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8267. || ((pattern != NULL)
  8268. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8269. }
  8270. return 0;
  8271. }
  8272. #if !defined(NO_FILESYSTEMS)
  8273. static int
  8274. scan_directory(struct mg_connection *conn,
  8275. const char *dir,
  8276. void *data,
  8277. int (*cb)(struct de *, void *))
  8278. {
  8279. char path[PATH_MAX];
  8280. struct dirent *dp;
  8281. DIR *dirp;
  8282. struct de de;
  8283. int truncated;
  8284. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8285. return 0;
  8286. } else {
  8287. de.conn = conn;
  8288. while ((dp = mg_readdir(dirp)) != NULL) {
  8289. /* Do not show current dir and hidden files */
  8290. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8291. || must_hide_file(conn, dp->d_name)) {
  8292. continue;
  8293. }
  8294. mg_snprintf(
  8295. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8296. /* If we don't memset stat structure to zero, mtime will have
  8297. * garbage and strftime() will segfault later on in
  8298. * print_dir_entry(). memset is required only if mg_stat()
  8299. * fails. For more details, see
  8300. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8301. memset(&de.file, 0, sizeof(de.file));
  8302. if (truncated) {
  8303. /* If the path is not complete, skip processing. */
  8304. continue;
  8305. }
  8306. if (!mg_stat(conn, path, &de.file)) {
  8307. mg_cry_internal(conn,
  8308. "%s: mg_stat(%s) failed: %s",
  8309. __func__,
  8310. path,
  8311. strerror(ERRNO));
  8312. }
  8313. de.file_name = dp->d_name;
  8314. cb(&de, data);
  8315. }
  8316. (void)mg_closedir(dirp);
  8317. }
  8318. return 1;
  8319. }
  8320. #endif /* NO_FILESYSTEMS */
  8321. #if !defined(NO_FILES)
  8322. static int
  8323. remove_directory(struct mg_connection *conn, const char *dir)
  8324. {
  8325. char path[PATH_MAX];
  8326. struct dirent *dp;
  8327. DIR *dirp;
  8328. struct de de;
  8329. int truncated;
  8330. int ok = 1;
  8331. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8332. return 0;
  8333. } else {
  8334. de.conn = conn;
  8335. while ((dp = mg_readdir(dirp)) != NULL) {
  8336. /* Do not show current dir (but show hidden files as they will
  8337. * also be removed) */
  8338. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8339. continue;
  8340. }
  8341. mg_snprintf(
  8342. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8343. /* If we don't memset stat structure to zero, mtime will have
  8344. * garbage and strftime() will segfault later on in
  8345. * print_dir_entry(). memset is required only if mg_stat()
  8346. * fails. For more details, see
  8347. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8348. memset(&de.file, 0, sizeof(de.file));
  8349. if (truncated) {
  8350. /* Do not delete anything shorter */
  8351. ok = 0;
  8352. continue;
  8353. }
  8354. if (!mg_stat(conn, path, &de.file)) {
  8355. mg_cry_internal(conn,
  8356. "%s: mg_stat(%s) failed: %s",
  8357. __func__,
  8358. path,
  8359. strerror(ERRNO));
  8360. ok = 0;
  8361. }
  8362. if (de.file.is_directory) {
  8363. if (remove_directory(conn, path) == 0) {
  8364. ok = 0;
  8365. }
  8366. } else {
  8367. /* This will fail file is the file is in memory */
  8368. if (mg_remove(conn, path) == 0) {
  8369. ok = 0;
  8370. }
  8371. }
  8372. }
  8373. (void)mg_closedir(dirp);
  8374. IGNORE_UNUSED_RESULT(rmdir(dir));
  8375. }
  8376. return ok;
  8377. }
  8378. #endif
  8379. struct dir_scan_data {
  8380. struct de *entries;
  8381. unsigned int num_entries;
  8382. unsigned int arr_size;
  8383. };
  8384. /* Behaves like realloc(), but frees original pointer on failure */
  8385. static void *
  8386. realloc2(void *ptr, size_t size)
  8387. {
  8388. void *new_ptr = mg_realloc(ptr, size);
  8389. if ((new_ptr == NULL) && (size > 0)) {
  8390. mg_free(ptr);
  8391. }
  8392. return new_ptr;
  8393. }
  8394. #if !defined(NO_FILESYSTEMS)
  8395. static int
  8396. dir_scan_callback(struct de *de, void *data)
  8397. {
  8398. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8399. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8400. dsd->arr_size *= 2;
  8401. dsd->entries =
  8402. (struct de *)realloc2(dsd->entries,
  8403. dsd->arr_size * sizeof(dsd->entries[0]));
  8404. }
  8405. if (dsd->entries == NULL) {
  8406. /* TODO(lsm, low): propagate an error to the caller */
  8407. dsd->num_entries = 0;
  8408. } else {
  8409. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8410. dsd->entries[dsd->num_entries].file = de->file;
  8411. dsd->entries[dsd->num_entries].conn = de->conn;
  8412. dsd->num_entries++;
  8413. }
  8414. return 0;
  8415. }
  8416. static void
  8417. handle_directory_request(struct mg_connection *conn, const char *dir)
  8418. {
  8419. unsigned int i;
  8420. int sort_direction;
  8421. struct dir_scan_data data = {NULL, 0, 128};
  8422. char date[64], *esc, *p;
  8423. const char *title;
  8424. time_t curtime = time(NULL);
  8425. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8426. mg_send_http_error(conn,
  8427. 500,
  8428. "Error: Cannot open directory\nopendir(%s): %s",
  8429. dir,
  8430. strerror(ERRNO));
  8431. return;
  8432. }
  8433. gmt_time_string(date, sizeof(date), &curtime);
  8434. if (!conn) {
  8435. return;
  8436. }
  8437. esc = NULL;
  8438. title = conn->request_info.local_uri;
  8439. if (title[strcspn(title, "&<>")]) {
  8440. /* HTML escaping needed */
  8441. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8442. if (esc) {
  8443. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8444. mg_strlcpy(p, title + i, 2);
  8445. if (*p == '&') {
  8446. strcpy(p, "&amp;");
  8447. } else if (*p == '<') {
  8448. strcpy(p, "&lt;");
  8449. } else if (*p == '>') {
  8450. strcpy(p, "&gt;");
  8451. }
  8452. }
  8453. } else {
  8454. title = "";
  8455. }
  8456. }
  8457. sort_direction = ((conn->request_info.query_string != NULL)
  8458. && (conn->request_info.query_string[0] != '\0')
  8459. && (conn->request_info.query_string[1] == 'd'))
  8460. ? 'a'
  8461. : 'd';
  8462. conn->must_close = 1;
  8463. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8464. send_static_cache_header(conn);
  8465. send_additional_header(conn);
  8466. mg_printf(conn,
  8467. "Date: %s\r\n"
  8468. "Connection: close\r\n"
  8469. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8470. date);
  8471. mg_printf(conn,
  8472. "<html><head><title>Index of %s</title>"
  8473. "<style>th {text-align: left;}</style></head>"
  8474. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8475. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8476. "<th><a href=\"?d%c\">Modified</a></th>"
  8477. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8478. "<tr><td colspan=\"3\"><hr></td></tr>",
  8479. esc ? esc : title,
  8480. esc ? esc : title,
  8481. sort_direction,
  8482. sort_direction,
  8483. sort_direction);
  8484. mg_free(esc);
  8485. /* Print first entry - link to a parent directory */
  8486. mg_printf(conn,
  8487. "<tr><td><a href=\"%s\">%s</a></td>"
  8488. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8489. "..",
  8490. "Parent directory",
  8491. "-",
  8492. "-");
  8493. /* Sort and print directory entries */
  8494. if (data.entries != NULL) {
  8495. qsort(data.entries,
  8496. (size_t)data.num_entries,
  8497. sizeof(data.entries[0]),
  8498. compare_dir_entries);
  8499. for (i = 0; i < data.num_entries; i++) {
  8500. print_dir_entry(&data.entries[i]);
  8501. mg_free(data.entries[i].file_name);
  8502. }
  8503. mg_free(data.entries);
  8504. }
  8505. mg_printf(conn, "%s", "</table></pre></body></html>");
  8506. conn->status_code = 200;
  8507. }
  8508. #endif /* NO_FILESYSTEMS */
  8509. /* Send len bytes from the opened file to the client. */
  8510. static void
  8511. send_file_data(struct mg_connection *conn,
  8512. struct mg_file *filep,
  8513. int64_t offset,
  8514. int64_t len)
  8515. {
  8516. char buf[MG_BUF_LEN];
  8517. int to_read, num_read, num_written;
  8518. int64_t size;
  8519. if (!filep || !conn) {
  8520. return;
  8521. }
  8522. /* Sanity check the offset */
  8523. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8524. : (int64_t)(filep->stat.size);
  8525. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8526. #if defined(MG_USE_OPEN_FILE)
  8527. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8528. /* file stored in memory */
  8529. if (len > size - offset) {
  8530. len = size - offset;
  8531. }
  8532. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8533. } else /* else block below */
  8534. #endif
  8535. if (len > 0 && filep->access.fp != NULL) {
  8536. /* file stored on disk */
  8537. #if defined(__linux__)
  8538. /* sendfile is only available for Linux */
  8539. if ((conn->ssl == 0) && (conn->throttle == 0)
  8540. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8541. "yes"))) {
  8542. off_t sf_offs = (off_t)offset;
  8543. ssize_t sf_sent;
  8544. int sf_file = fileno(filep->access.fp);
  8545. int loop_cnt = 0;
  8546. do {
  8547. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8548. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8549. size_t sf_tosend =
  8550. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8551. sf_sent =
  8552. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8553. if (sf_sent > 0) {
  8554. len -= sf_sent;
  8555. offset += sf_sent;
  8556. } else if (loop_cnt == 0) {
  8557. /* This file can not be sent using sendfile.
  8558. * This might be the case for pseudo-files in the
  8559. * /sys/ and /proc/ file system.
  8560. * Use the regular user mode copy code instead. */
  8561. break;
  8562. } else if (sf_sent == 0) {
  8563. /* No error, but 0 bytes sent. May be EOF? */
  8564. return;
  8565. }
  8566. loop_cnt++;
  8567. } while ((len > 0) && (sf_sent >= 0));
  8568. if (sf_sent > 0) {
  8569. return; /* OK */
  8570. }
  8571. /* sf_sent<0 means error, thus fall back to the classic way */
  8572. /* This is always the case, if sf_file is not a "normal" file,
  8573. * e.g., for sending data from the output of a CGI process. */
  8574. offset = (int64_t)sf_offs;
  8575. }
  8576. #endif
  8577. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8578. mg_cry_internal(conn,
  8579. "%s: fseeko() failed: %s",
  8580. __func__,
  8581. strerror(ERRNO));
  8582. mg_send_http_error(
  8583. conn,
  8584. 500,
  8585. "%s",
  8586. "Error: Unable to access file at requested position.");
  8587. } else {
  8588. while (len > 0) {
  8589. /* Calculate how much to read from the file in the buffer */
  8590. to_read = sizeof(buf);
  8591. if ((int64_t)to_read > len) {
  8592. to_read = (int)len;
  8593. }
  8594. /* Read from file, exit the loop on error */
  8595. if ((num_read =
  8596. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8597. <= 0) {
  8598. break;
  8599. }
  8600. /* Send read bytes to the client, exit the loop on error */
  8601. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8602. != num_read) {
  8603. break;
  8604. }
  8605. /* Both read and were successful, adjust counters */
  8606. len -= num_written;
  8607. }
  8608. }
  8609. }
  8610. }
  8611. static int
  8612. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8613. {
  8614. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8615. }
  8616. static void
  8617. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8618. {
  8619. if ((filestat != NULL) && (buf != NULL)) {
  8620. mg_snprintf(NULL,
  8621. NULL, /* All calls to construct_etag use 64 byte buffer */
  8622. buf,
  8623. buf_len,
  8624. "\"%lx.%" INT64_FMT "\"",
  8625. (unsigned long)filestat->last_modified,
  8626. filestat->size);
  8627. }
  8628. }
  8629. static void
  8630. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8631. {
  8632. if (filep != NULL && filep->fp != NULL) {
  8633. #if defined(_WIN32)
  8634. (void)conn; /* Unused. */
  8635. #else
  8636. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8637. mg_cry_internal(conn,
  8638. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8639. __func__,
  8640. strerror(ERRNO));
  8641. }
  8642. #endif
  8643. }
  8644. }
  8645. #if defined(USE_ZLIB)
  8646. #include "mod_zlib.inl"
  8647. #endif
  8648. #if !defined(NO_FILESYSTEMS)
  8649. static void
  8650. handle_static_file_request(struct mg_connection *conn,
  8651. const char *path,
  8652. struct mg_file *filep,
  8653. const char *mime_type,
  8654. const char *additional_headers)
  8655. {
  8656. char date[64], lm[64], etag[64];
  8657. char range[128]; /* large enough, so there will be no overflow */
  8658. const char *msg = "OK";
  8659. const char *range_hdr;
  8660. time_t curtime = time(NULL);
  8661. int64_t cl, r1, r2;
  8662. struct vec mime_vec;
  8663. int n, truncated;
  8664. char gz_path[PATH_MAX];
  8665. const char *encoding = "";
  8666. const char *origin_hdr;
  8667. const char *cors_orig_cfg;
  8668. const char *cors1, *cors2, *cors3;
  8669. int is_head_request;
  8670. #if defined(USE_ZLIB)
  8671. /* Compression is allowed, unless there is a reason not to use
  8672. * compression. If the file is already compressed, too small or a
  8673. * "range" request was made, on the fly compression is not possible. */
  8674. int allow_on_the_fly_compression = 1;
  8675. #endif
  8676. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8677. return;
  8678. }
  8679. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8680. if (mime_type == NULL) {
  8681. get_mime_type(conn, path, &mime_vec);
  8682. } else {
  8683. mime_vec.ptr = mime_type;
  8684. mime_vec.len = strlen(mime_type);
  8685. }
  8686. if (filep->stat.size > INT64_MAX) {
  8687. mg_send_http_error(conn,
  8688. 500,
  8689. "Error: File size is too large to send\n%" INT64_FMT,
  8690. filep->stat.size);
  8691. return;
  8692. }
  8693. cl = (int64_t)filep->stat.size;
  8694. conn->status_code = 200;
  8695. range[0] = '\0';
  8696. #if defined(USE_ZLIB)
  8697. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8698. * it's important to rewrite the filename after resolving
  8699. * the mime type from it, to preserve the actual file's type */
  8700. if (!conn->accept_gzip) {
  8701. allow_on_the_fly_compression = 0;
  8702. }
  8703. #endif
  8704. /* Check if there is a range header */
  8705. range_hdr = mg_get_header(conn, "Range");
  8706. /* For gzipped files, add *.gz */
  8707. if (filep->stat.is_gzipped) {
  8708. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8709. if (truncated) {
  8710. mg_send_http_error(conn,
  8711. 500,
  8712. "Error: Path of zipped file too long (%s)",
  8713. path);
  8714. return;
  8715. }
  8716. path = gz_path;
  8717. encoding = "Content-Encoding: gzip\r\n";
  8718. #if defined(USE_ZLIB)
  8719. /* File is already compressed. No "on the fly" compression. */
  8720. allow_on_the_fly_compression = 0;
  8721. #endif
  8722. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8723. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8724. struct mg_file_stat file_stat;
  8725. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8726. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8727. && !file_stat.is_directory) {
  8728. file_stat.is_gzipped = 1;
  8729. filep->stat = file_stat;
  8730. cl = (int64_t)filep->stat.size;
  8731. path = gz_path;
  8732. encoding = "Content-Encoding: gzip\r\n";
  8733. #if defined(USE_ZLIB)
  8734. /* File is already compressed. No "on the fly" compression. */
  8735. allow_on_the_fly_compression = 0;
  8736. #endif
  8737. }
  8738. }
  8739. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8740. mg_send_http_error(conn,
  8741. 500,
  8742. "Error: Cannot open file\nfopen(%s): %s",
  8743. path,
  8744. strerror(ERRNO));
  8745. return;
  8746. }
  8747. fclose_on_exec(&filep->access, conn);
  8748. /* If "Range" request was made: parse header, send only selected part
  8749. * of the file. */
  8750. r1 = r2 = 0;
  8751. if ((range_hdr != NULL)
  8752. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8753. && (r2 >= 0)) {
  8754. /* actually, range requests don't play well with a pre-gzipped
  8755. * file (since the range is specified in the uncompressed space) */
  8756. if (filep->stat.is_gzipped) {
  8757. mg_send_http_error(
  8758. conn,
  8759. 416, /* 416 = Range Not Satisfiable */
  8760. "%s",
  8761. "Error: Range requests in gzipped files are not supported");
  8762. (void)mg_fclose(
  8763. &filep->access); /* ignore error on read only file */
  8764. return;
  8765. }
  8766. conn->status_code = 206;
  8767. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8768. mg_snprintf(conn,
  8769. NULL, /* range buffer is big enough */
  8770. range,
  8771. sizeof(range),
  8772. "Content-Range: bytes "
  8773. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8774. r1,
  8775. r1 + cl - 1,
  8776. filep->stat.size);
  8777. msg = "Partial Content";
  8778. #if defined(USE_ZLIB)
  8779. /* Do not compress ranges. */
  8780. allow_on_the_fly_compression = 0;
  8781. #endif
  8782. }
  8783. /* Do not compress small files. Small files do not benefit from file
  8784. * compression, but there is still some overhead. */
  8785. #if defined(USE_ZLIB)
  8786. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8787. /* File is below the size limit. */
  8788. allow_on_the_fly_compression = 0;
  8789. }
  8790. #endif
  8791. /* Standard CORS header */
  8792. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8793. origin_hdr = mg_get_header(conn, "Origin");
  8794. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8795. /* Cross-origin resource sharing (CORS), see
  8796. * http://www.html5rocks.com/en/tutorials/cors/,
  8797. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8798. * -
  8799. * preflight is not supported for files. */
  8800. cors1 = "Access-Control-Allow-Origin: ";
  8801. cors2 = cors_orig_cfg;
  8802. cors3 = "\r\n";
  8803. } else {
  8804. cors1 = cors2 = cors3 = "";
  8805. }
  8806. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8807. * according to
  8808. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8809. gmt_time_string(date, sizeof(date), &curtime);
  8810. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8811. construct_etag(etag, sizeof(etag), &filep->stat);
  8812. /* Send header */
  8813. (void)mg_printf(conn,
  8814. "HTTP/1.1 %d %s\r\n"
  8815. "%s%s%s" /* CORS */
  8816. "Date: %s\r\n"
  8817. "Last-Modified: %s\r\n"
  8818. "Etag: %s\r\n"
  8819. "Content-Type: %.*s\r\n"
  8820. "Connection: %s\r\n",
  8821. conn->status_code,
  8822. msg,
  8823. cors1,
  8824. cors2,
  8825. cors3,
  8826. date,
  8827. lm,
  8828. etag,
  8829. (int)mime_vec.len,
  8830. mime_vec.ptr,
  8831. suggest_connection_header(conn));
  8832. send_static_cache_header(conn);
  8833. send_additional_header(conn);
  8834. #if defined(USE_ZLIB)
  8835. /* On the fly compression allowed */
  8836. if (allow_on_the_fly_compression) {
  8837. /* For on the fly compression, we don't know the content size in
  8838. * advance, so we have to use chunked encoding */
  8839. (void)mg_printf(conn,
  8840. "Content-Encoding: gzip\r\n"
  8841. "Transfer-Encoding: chunked\r\n");
  8842. } else
  8843. #endif
  8844. {
  8845. /* Without on-the-fly compression, we know the content-length
  8846. * and we can use ranges (with on-the-fly compression we cannot).
  8847. * So we send these response headers only in this case. */
  8848. (void)mg_printf(conn,
  8849. "Content-Length: %" INT64_FMT "\r\n"
  8850. "Accept-Ranges: bytes\r\n"
  8851. "%s" /* range */
  8852. "%s" /* encoding */,
  8853. cl,
  8854. range,
  8855. encoding);
  8856. }
  8857. /* The previous code must not add any header starting with X- to make
  8858. * sure no one of the additional_headers is included twice */
  8859. if (additional_headers != NULL) {
  8860. (void)mg_printf(conn,
  8861. "%.*s\r\n\r\n",
  8862. (int)strlen(additional_headers),
  8863. additional_headers);
  8864. } else {
  8865. (void)mg_printf(conn, "\r\n");
  8866. }
  8867. if (!is_head_request) {
  8868. #if defined(USE_ZLIB)
  8869. if (allow_on_the_fly_compression) {
  8870. /* Compress and send */
  8871. send_compressed_data(conn, filep);
  8872. } else
  8873. #endif
  8874. {
  8875. /* Send file directly */
  8876. send_file_data(conn, filep, r1, cl);
  8877. }
  8878. }
  8879. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8880. }
  8881. int
  8882. mg_send_file_body(struct mg_connection *conn, const char *path)
  8883. {
  8884. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8885. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8886. return -1;
  8887. }
  8888. fclose_on_exec(&file.access, conn);
  8889. send_file_data(conn, &file, 0, INT64_MAX);
  8890. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8891. return 0; /* >= 0 for OK */
  8892. }
  8893. #endif /* NO_FILESYSTEMS */
  8894. #if !defined(NO_CACHING)
  8895. /* Return True if we should reply 304 Not Modified. */
  8896. static int
  8897. is_not_modified(const struct mg_connection *conn,
  8898. const struct mg_file_stat *filestat)
  8899. {
  8900. char etag[64];
  8901. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8902. const char *inm = mg_get_header(conn, "If-None-Match");
  8903. construct_etag(etag, sizeof(etag), filestat);
  8904. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8905. || ((ims != NULL)
  8906. && (filestat->last_modified <= parse_date_string(ims)));
  8907. }
  8908. static void
  8909. handle_not_modified_static_file_request(struct mg_connection *conn,
  8910. struct mg_file *filep)
  8911. {
  8912. char date[64], lm[64], etag[64];
  8913. time_t curtime = time(NULL);
  8914. if ((conn == NULL) || (filep == NULL)) {
  8915. return;
  8916. }
  8917. conn->status_code = 304;
  8918. gmt_time_string(date, sizeof(date), &curtime);
  8919. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8920. construct_etag(etag, sizeof(etag), &filep->stat);
  8921. (void)mg_printf(conn,
  8922. "HTTP/1.1 %d %s\r\n"
  8923. "Date: %s\r\n",
  8924. conn->status_code,
  8925. mg_get_response_code_text(conn, conn->status_code),
  8926. date);
  8927. send_static_cache_header(conn);
  8928. send_additional_header(conn);
  8929. (void)mg_printf(conn,
  8930. "Last-Modified: %s\r\n"
  8931. "Etag: %s\r\n"
  8932. "Connection: %s\r\n"
  8933. "\r\n",
  8934. lm,
  8935. etag,
  8936. suggest_connection_header(conn));
  8937. }
  8938. #endif
  8939. #if !defined(NO_FILESYSTEMS)
  8940. void
  8941. mg_send_file(struct mg_connection *conn, const char *path)
  8942. {
  8943. mg_send_mime_file2(conn, path, NULL, NULL);
  8944. }
  8945. void
  8946. mg_send_mime_file(struct mg_connection *conn,
  8947. const char *path,
  8948. const char *mime_type)
  8949. {
  8950. mg_send_mime_file2(conn, path, mime_type, NULL);
  8951. }
  8952. void
  8953. mg_send_mime_file2(struct mg_connection *conn,
  8954. const char *path,
  8955. const char *mime_type,
  8956. const char *additional_headers)
  8957. {
  8958. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8959. if (!conn) {
  8960. /* No conn */
  8961. return;
  8962. }
  8963. if (mg_stat(conn, path, &file.stat)) {
  8964. #if !defined(NO_CACHING)
  8965. if (is_not_modified(conn, &file.stat)) {
  8966. /* Send 304 "Not Modified" - this must not send any body data */
  8967. handle_not_modified_static_file_request(conn, &file);
  8968. } else
  8969. #endif /* NO_CACHING */
  8970. if (file.stat.is_directory) {
  8971. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8972. "yes")) {
  8973. handle_directory_request(conn, path);
  8974. } else {
  8975. mg_send_http_error(conn,
  8976. 403,
  8977. "%s",
  8978. "Error: Directory listing denied");
  8979. }
  8980. } else {
  8981. handle_static_file_request(
  8982. conn, path, &file, mime_type, additional_headers);
  8983. }
  8984. } else {
  8985. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8986. }
  8987. }
  8988. /* For a given PUT path, create all intermediate subdirectories.
  8989. * Return 0 if the path itself is a directory.
  8990. * Return 1 if the path leads to a file.
  8991. * Return -1 for if the path is too long.
  8992. * Return -2 if path can not be created.
  8993. */
  8994. static int
  8995. put_dir(struct mg_connection *conn, const char *path)
  8996. {
  8997. char buf[PATH_MAX];
  8998. const char *s, *p;
  8999. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9000. size_t len;
  9001. int res = 1;
  9002. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9003. len = (size_t)(p - path);
  9004. if (len >= sizeof(buf)) {
  9005. /* path too long */
  9006. res = -1;
  9007. break;
  9008. }
  9009. memcpy(buf, path, len);
  9010. buf[len] = '\0';
  9011. /* Try to create intermediate directory */
  9012. DEBUG_TRACE("mkdir(%s)", buf);
  9013. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9014. /* path does not exixt and can not be created */
  9015. res = -2;
  9016. break;
  9017. }
  9018. /* Is path itself a directory? */
  9019. if (p[1] == '\0') {
  9020. res = 0;
  9021. }
  9022. }
  9023. return res;
  9024. }
  9025. static void
  9026. remove_bad_file(const struct mg_connection *conn, const char *path)
  9027. {
  9028. int r = mg_remove(conn, path);
  9029. if (r != 0) {
  9030. mg_cry_internal(conn,
  9031. "%s: Cannot remove invalid file %s",
  9032. __func__,
  9033. path);
  9034. }
  9035. }
  9036. long long
  9037. mg_store_body(struct mg_connection *conn, const char *path)
  9038. {
  9039. char buf[MG_BUF_LEN];
  9040. long long len = 0;
  9041. int ret, n;
  9042. struct mg_file fi;
  9043. if (conn->consumed_content != 0) {
  9044. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9045. return -11;
  9046. }
  9047. ret = put_dir(conn, path);
  9048. if (ret < 0) {
  9049. /* -1 for path too long,
  9050. * -2 for path can not be created. */
  9051. return ret;
  9052. }
  9053. if (ret != 1) {
  9054. /* Return 0 means, path itself is a directory. */
  9055. return 0;
  9056. }
  9057. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9058. return -12;
  9059. }
  9060. ret = mg_read(conn, buf, sizeof(buf));
  9061. while (ret > 0) {
  9062. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9063. if (n != ret) {
  9064. (void)mg_fclose(
  9065. &fi.access); /* File is bad and will be removed anyway. */
  9066. remove_bad_file(conn, path);
  9067. return -13;
  9068. }
  9069. len += ret;
  9070. ret = mg_read(conn, buf, sizeof(buf));
  9071. }
  9072. /* File is open for writing. If fclose fails, there was probably an
  9073. * error flushing the buffer to disk, so the file on disk might be
  9074. * broken. Delete it and return an error to the caller. */
  9075. if (mg_fclose(&fi.access) != 0) {
  9076. remove_bad_file(conn, path);
  9077. return -14;
  9078. }
  9079. return len;
  9080. }
  9081. #endif /* NO_FILESYSTEMS */
  9082. /* Parse a buffer:
  9083. * Forward the string pointer till the end of a word, then
  9084. * terminate it and forward till the begin of the next word.
  9085. */
  9086. static int
  9087. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9088. {
  9089. /* Forward until a space is found - use isgraph here */
  9090. /* See http://www.cplusplus.com/reference/cctype/ */
  9091. while (isgraph((unsigned char)**ppw)) {
  9092. (*ppw)++;
  9093. }
  9094. /* Check end of word */
  9095. if (eol) {
  9096. /* must be a end of line */
  9097. if ((**ppw != '\r') && (**ppw != '\n')) {
  9098. return -1;
  9099. }
  9100. } else {
  9101. /* must be a end of a word, but not a line */
  9102. if (**ppw != ' ') {
  9103. return -1;
  9104. }
  9105. }
  9106. /* Terminate and forward to the next word */
  9107. do {
  9108. **ppw = 0;
  9109. (*ppw)++;
  9110. } while (isspace((unsigned char)**ppw));
  9111. /* Check after term */
  9112. if (!eol) {
  9113. /* if it's not the end of line, there must be a next word */
  9114. if (!isgraph((unsigned char)**ppw)) {
  9115. return -1;
  9116. }
  9117. }
  9118. /* ok */
  9119. return 1;
  9120. }
  9121. /* Parse HTTP headers from the given buffer, advance buf pointer
  9122. * to the point where parsing stopped.
  9123. * All parameters must be valid pointers (not NULL).
  9124. * Return <0 on error. */
  9125. static int
  9126. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9127. {
  9128. int i;
  9129. int num_headers = 0;
  9130. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9131. char *dp = *buf;
  9132. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9133. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9134. dp++;
  9135. }
  9136. if (dp == *buf) {
  9137. /* End of headers reached. */
  9138. break;
  9139. }
  9140. if (*dp != ':') {
  9141. /* This is not a valid field. */
  9142. return -1;
  9143. }
  9144. /* End of header key (*dp == ':') */
  9145. /* Truncate here and set the key name */
  9146. *dp = 0;
  9147. hdr[i].name = *buf;
  9148. /* Skip all spaces */
  9149. do {
  9150. dp++;
  9151. } while ((*dp == ' ') || (*dp == '\t'));
  9152. /* The rest of the line is the value */
  9153. hdr[i].value = dp;
  9154. /* Find end of line */
  9155. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9156. dp++;
  9157. };
  9158. /* eliminate \r */
  9159. if (*dp == '\r') {
  9160. *dp = 0;
  9161. dp++;
  9162. if (*dp != '\n') {
  9163. /* This is not a valid line. */
  9164. return -1;
  9165. }
  9166. }
  9167. /* here *dp is either 0 or '\n' */
  9168. /* in any case, we have a new header */
  9169. num_headers = i + 1;
  9170. if (*dp) {
  9171. *dp = 0;
  9172. dp++;
  9173. *buf = dp;
  9174. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9175. /* This is the end of the header */
  9176. break;
  9177. }
  9178. } else {
  9179. *buf = dp;
  9180. break;
  9181. }
  9182. }
  9183. return num_headers;
  9184. }
  9185. struct mg_http_method_info {
  9186. const char *name;
  9187. int request_has_body;
  9188. int response_has_body;
  9189. int is_safe;
  9190. int is_idempotent;
  9191. int is_cacheable;
  9192. };
  9193. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9194. static struct mg_http_method_info http_methods[] = {
  9195. /* HTTP (RFC 2616) */
  9196. {"GET", 0, 1, 1, 1, 1},
  9197. {"POST", 1, 1, 0, 0, 0},
  9198. {"PUT", 1, 0, 0, 1, 0},
  9199. {"DELETE", 0, 0, 0, 1, 0},
  9200. {"HEAD", 0, 0, 1, 1, 1},
  9201. {"OPTIONS", 0, 0, 1, 1, 0},
  9202. {"CONNECT", 1, 1, 0, 0, 0},
  9203. /* TRACE method (RFC 2616) is not supported for security reasons */
  9204. /* PATCH method (RFC 5789) */
  9205. {"PATCH", 1, 0, 0, 0, 0},
  9206. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9207. /* WEBDAV (RFC 2518) */
  9208. {"PROPFIND", 0, 1, 1, 1, 0},
  9209. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9210. * Some PROPFIND results MAY be cached, with care,
  9211. * as there is no cache validation mechanism for
  9212. * most properties. This method is both safe and
  9213. * idempotent (see Section 9.1 of [RFC2616]). */
  9214. {"MKCOL", 0, 0, 0, 1, 0},
  9215. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9216. * When MKCOL is invoked without a request body,
  9217. * the newly created collection SHOULD have no
  9218. * members. A MKCOL request message may contain
  9219. * a message body. The precise behavior of a MKCOL
  9220. * request when the body is present is undefined,
  9221. * ... ==> We do not support MKCOL with body data.
  9222. * This method is idempotent, but not safe (see
  9223. * Section 9.1 of [RFC2616]). Responses to this
  9224. * method MUST NOT be cached. */
  9225. /* Unsupported WEBDAV Methods: */
  9226. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9227. /* + 11 methods from RFC 3253 */
  9228. /* ORDERPATCH (RFC 3648) */
  9229. /* ACL (RFC 3744) */
  9230. /* SEARCH (RFC 5323) */
  9231. /* + MicroSoft extensions
  9232. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9233. /* REPORT method (RFC 3253) */
  9234. {"REPORT", 1, 1, 1, 1, 1},
  9235. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9236. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9237. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9238. * to be useful for REST in case a "GET request with body" is
  9239. * required. */
  9240. {NULL, 0, 0, 0, 0, 0}
  9241. /* end of list */
  9242. };
  9243. static const struct mg_http_method_info *
  9244. get_http_method_info(const char *method)
  9245. {
  9246. /* Check if the method is known to the server. The list of all known
  9247. * HTTP methods can be found here at
  9248. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9249. */
  9250. const struct mg_http_method_info *m = http_methods;
  9251. while (m->name) {
  9252. if (!strcmp(m->name, method)) {
  9253. return m;
  9254. }
  9255. m++;
  9256. }
  9257. return NULL;
  9258. }
  9259. static int
  9260. is_valid_http_method(const char *method)
  9261. {
  9262. return (get_http_method_info(method) != NULL);
  9263. }
  9264. /* Parse HTTP request, fill in mg_request_info structure.
  9265. * This function modifies the buffer by NUL-terminating
  9266. * HTTP request components, header names and header values.
  9267. * Parameters:
  9268. * buf (in/out): pointer to the HTTP header to parse and split
  9269. * len (in): length of HTTP header buffer
  9270. * re (out): parsed header as mg_request_info
  9271. * buf and ri must be valid pointers (not NULL), len>0.
  9272. * Returns <0 on error. */
  9273. static int
  9274. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9275. {
  9276. int request_length;
  9277. int init_skip = 0;
  9278. int is_http2 = 0;
  9279. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9280. * remote_port */
  9281. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9282. NULL;
  9283. ri->num_headers = 0;
  9284. /* RFC says that all initial whitespaces should be ingored */
  9285. /* This included all leading \r and \n (isspace) */
  9286. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9287. while ((len > 0) && isspace((unsigned char)*buf)) {
  9288. buf++;
  9289. len--;
  9290. init_skip++;
  9291. }
  9292. if (len == 0) {
  9293. /* Incomplete request */
  9294. return 0;
  9295. }
  9296. /* Control characters are not allowed, including zero */
  9297. if (iscntrl((unsigned char)*buf)) {
  9298. return -1;
  9299. }
  9300. /* Find end of HTTP header */
  9301. request_length = get_http_header_len(buf, len);
  9302. if (request_length <= 0) {
  9303. return request_length;
  9304. }
  9305. buf[request_length - 1] = '\0';
  9306. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9307. return -1;
  9308. }
  9309. #if defined(USE_HTTP2)
  9310. if (request_length >= http2_pri_hdr_line_len) {
  9311. if (0 == memcmp(buf, http2_pri, http2_pri_hdr_line_len)) {
  9312. is_http2 = 1;
  9313. }
  9314. }
  9315. #endif
  9316. /* The first word has to be the HTTP method */
  9317. ri->request_method = buf;
  9318. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9319. return -1;
  9320. }
  9321. /* Check for a valid http method */
  9322. if (!is_valid_http_method(ri->request_method)) {
  9323. /* "PRI" is valid for HTTP/2 connection initialization */
  9324. if (!is_http2) {
  9325. return -1;
  9326. }
  9327. }
  9328. /* The second word is the URI */
  9329. ri->request_uri = buf;
  9330. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9331. return -1;
  9332. }
  9333. /* Next would be the HTTP version */
  9334. ri->http_version = buf;
  9335. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9336. return -1;
  9337. }
  9338. /* Check for a valid HTTP version key */
  9339. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9340. /* Invalid request */
  9341. return -1;
  9342. }
  9343. ri->http_version += 5;
  9344. /* Parse all HTTP headers */
  9345. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9346. if (ri->num_headers < 0) {
  9347. /* Error while parsing headers */
  9348. return -1;
  9349. }
  9350. return request_length + init_skip;
  9351. }
  9352. static int
  9353. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9354. {
  9355. int response_length;
  9356. int init_skip = 0;
  9357. char *tmp, *tmp2;
  9358. long l;
  9359. /* Initialize elements. */
  9360. ri->http_version = ri->status_text = NULL;
  9361. ri->num_headers = ri->status_code = 0;
  9362. /* RFC says that all initial whitespaces should be ingored */
  9363. /* This included all leading \r and \n (isspace) */
  9364. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9365. while ((len > 0) && isspace((unsigned char)*buf)) {
  9366. buf++;
  9367. len--;
  9368. init_skip++;
  9369. }
  9370. if (len == 0) {
  9371. /* Incomplete request */
  9372. return 0;
  9373. }
  9374. /* Control characters are not allowed, including zero */
  9375. if (iscntrl((unsigned char)*buf)) {
  9376. return -1;
  9377. }
  9378. /* Find end of HTTP header */
  9379. response_length = get_http_header_len(buf, len);
  9380. if (response_length <= 0) {
  9381. return response_length;
  9382. }
  9383. buf[response_length - 1] = '\0';
  9384. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9385. return -1;
  9386. }
  9387. /* The first word is the HTTP version */
  9388. /* Check for a valid HTTP version key */
  9389. if (strncmp(buf, "HTTP/", 5) != 0) {
  9390. /* Invalid request */
  9391. return -1;
  9392. }
  9393. buf += 5;
  9394. if (!isgraph((unsigned char)buf[0])) {
  9395. /* Invalid request */
  9396. return -1;
  9397. }
  9398. ri->http_version = buf;
  9399. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9400. return -1;
  9401. }
  9402. /* The second word is the status as a number */
  9403. tmp = buf;
  9404. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9405. return -1;
  9406. }
  9407. l = strtol(tmp, &tmp2, 10);
  9408. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9409. /* Everything else but a 3 digit code is invalid */
  9410. return -1;
  9411. }
  9412. ri->status_code = (int)l;
  9413. /* The rest of the line is the status text */
  9414. ri->status_text = buf;
  9415. /* Find end of status text */
  9416. /* isgraph or isspace = isprint */
  9417. while (isprint((unsigned char)*buf)) {
  9418. buf++;
  9419. }
  9420. if ((*buf != '\r') && (*buf != '\n')) {
  9421. return -1;
  9422. }
  9423. /* Terminate string and forward buf to next line */
  9424. do {
  9425. *buf = 0;
  9426. buf++;
  9427. } while (isspace((unsigned char)*buf));
  9428. /* Parse all HTTP headers */
  9429. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9430. if (ri->num_headers < 0) {
  9431. /* Error while parsing headers */
  9432. return -1;
  9433. }
  9434. return response_length + init_skip;
  9435. }
  9436. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9437. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9438. * buffer (which marks the end of HTTP request). Buffer buf may already
  9439. * have some data. The length of the data is stored in nread.
  9440. * Upon every read operation, increase nread by the number of bytes read. */
  9441. static int
  9442. read_message(FILE *fp,
  9443. struct mg_connection *conn,
  9444. char *buf,
  9445. int bufsiz,
  9446. int *nread)
  9447. {
  9448. int request_len, n = 0;
  9449. struct timespec last_action_time;
  9450. double request_timeout;
  9451. if (!conn) {
  9452. return 0;
  9453. }
  9454. memset(&last_action_time, 0, sizeof(last_action_time));
  9455. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9456. /* value of request_timeout is in seconds, config in milliseconds */
  9457. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9458. } else {
  9459. request_timeout = -1.0;
  9460. }
  9461. if (conn->handled_requests > 0) {
  9462. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9463. request_timeout =
  9464. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9465. }
  9466. }
  9467. request_len = get_http_header_len(buf, *nread);
  9468. while (request_len == 0) {
  9469. /* Full request not yet received */
  9470. if (conn->phys_ctx->stop_flag != 0) {
  9471. /* Server is to be stopped. */
  9472. return -1;
  9473. }
  9474. if (*nread >= bufsiz) {
  9475. /* Request too long */
  9476. return -2;
  9477. }
  9478. n = pull_inner(
  9479. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9480. if (n == -2) {
  9481. /* Receive error */
  9482. return -1;
  9483. }
  9484. /* update clock after every read request */
  9485. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9486. if (n > 0) {
  9487. *nread += n;
  9488. request_len = get_http_header_len(buf, *nread);
  9489. }
  9490. if ((request_len == 0) && (request_timeout >= 0)) {
  9491. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9492. > request_timeout) {
  9493. /* Timeout */
  9494. return -1;
  9495. }
  9496. }
  9497. }
  9498. return request_len;
  9499. }
  9500. #if !defined(NO_CGI) || !defined(NO_FILES)
  9501. static int
  9502. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9503. {
  9504. const char *expect;
  9505. char buf[MG_BUF_LEN];
  9506. int success = 0;
  9507. if (!conn) {
  9508. return 0;
  9509. }
  9510. expect = mg_get_header(conn, "Expect");
  9511. DEBUG_ASSERT(fp != NULL);
  9512. if (!fp) {
  9513. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9514. return 0;
  9515. }
  9516. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9517. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9518. */
  9519. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9520. } else {
  9521. if (expect != NULL) {
  9522. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9523. conn->status_code = 100;
  9524. } else {
  9525. conn->status_code = 200;
  9526. }
  9527. DEBUG_ASSERT(conn->consumed_content == 0);
  9528. if (conn->consumed_content != 0) {
  9529. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9530. return 0;
  9531. }
  9532. for (;;) {
  9533. int nread = mg_read(conn, buf, sizeof(buf));
  9534. if (nread <= 0) {
  9535. success = (nread == 0);
  9536. break;
  9537. }
  9538. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9539. break;
  9540. }
  9541. }
  9542. /* Each error code path in this function must send an error */
  9543. if (!success) {
  9544. /* NOTE: Maybe some data has already been sent. */
  9545. /* TODO (low): If some data has been sent, a correct error
  9546. * reply can no longer be sent, so just close the connection */
  9547. mg_send_http_error(conn, 500, "%s", "");
  9548. }
  9549. }
  9550. return success;
  9551. }
  9552. #endif
  9553. #if defined(USE_TIMERS)
  9554. #define TIMER_API static
  9555. #include "timer.inl"
  9556. #endif /* USE_TIMERS */
  9557. #if !defined(NO_CGI)
  9558. /* This structure helps to create an environment for the spawned CGI
  9559. * program.
  9560. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9561. * last element must be NULL.
  9562. * However, on Windows there is a requirement that all these
  9563. * VARIABLE=VALUE\0
  9564. * strings must reside in a contiguous buffer. The end of the buffer is
  9565. * marked by two '\0' characters.
  9566. * We satisfy both worlds: we create an envp array (which is vars), all
  9567. * entries are actually pointers inside buf. */
  9568. struct cgi_environment {
  9569. struct mg_connection *conn;
  9570. /* Data block */
  9571. char *buf; /* Environment buffer */
  9572. size_t buflen; /* Space available in buf */
  9573. size_t bufused; /* Space taken in buf */
  9574. /* Index block */
  9575. char **var; /* char **envp */
  9576. size_t varlen; /* Number of variables available in var */
  9577. size_t varused; /* Number of variables stored in var */
  9578. };
  9579. static void addenv(struct cgi_environment *env,
  9580. PRINTF_FORMAT_STRING(const char *fmt),
  9581. ...) PRINTF_ARGS(2, 3);
  9582. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9583. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9584. static void
  9585. addenv(struct cgi_environment *env, const char *fmt, ...)
  9586. {
  9587. size_t i, n, space;
  9588. int truncated = 0;
  9589. char *added;
  9590. va_list ap;
  9591. if ((env->varlen - env->varused) < 2) {
  9592. mg_cry_internal(env->conn,
  9593. "%s: Cannot register CGI variable [%s]",
  9594. __func__,
  9595. fmt);
  9596. return;
  9597. }
  9598. /* Calculate how much space is left in the buffer */
  9599. space = (env->buflen - env->bufused);
  9600. do {
  9601. /* Space for "\0\0" is always needed. */
  9602. if (space <= 2) {
  9603. /* Allocate new buffer */
  9604. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9605. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9606. if (!added) {
  9607. /* Out of memory */
  9608. mg_cry_internal(
  9609. env->conn,
  9610. "%s: Cannot allocate memory for CGI variable [%s]",
  9611. __func__,
  9612. fmt);
  9613. return;
  9614. }
  9615. /* Retarget pointers */
  9616. env->buf = added;
  9617. env->buflen = n;
  9618. for (i = 0, n = 0; i < env->varused; i++) {
  9619. env->var[i] = added + n;
  9620. n += strlen(added + n) + 1;
  9621. }
  9622. space = (env->buflen - env->bufused);
  9623. }
  9624. /* Make a pointer to the free space int the buffer */
  9625. added = env->buf + env->bufused;
  9626. /* Copy VARIABLE=VALUE\0 string into the free space */
  9627. va_start(ap, fmt);
  9628. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9629. va_end(ap);
  9630. /* Do not add truncated strings to the environment */
  9631. if (truncated) {
  9632. /* Reallocate the buffer */
  9633. space = 0;
  9634. }
  9635. } while (truncated);
  9636. /* Calculate number of bytes added to the environment */
  9637. n = strlen(added) + 1;
  9638. env->bufused += n;
  9639. /* Append a pointer to the added string into the envp array */
  9640. env->var[env->varused] = added;
  9641. env->varused++;
  9642. }
  9643. /* Return 0 on success, non-zero if an error occurs. */
  9644. static int
  9645. prepare_cgi_environment(struct mg_connection *conn,
  9646. const char *prog,
  9647. struct cgi_environment *env)
  9648. {
  9649. const char *s;
  9650. struct vec var_vec;
  9651. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9652. int i, truncated, uri_len;
  9653. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9654. return -1;
  9655. }
  9656. env->conn = conn;
  9657. env->buflen = CGI_ENVIRONMENT_SIZE;
  9658. env->bufused = 0;
  9659. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9660. if (env->buf == NULL) {
  9661. mg_cry_internal(conn,
  9662. "%s: Not enough memory for environmental buffer",
  9663. __func__);
  9664. return -1;
  9665. }
  9666. env->varlen = MAX_CGI_ENVIR_VARS;
  9667. env->varused = 0;
  9668. env->var =
  9669. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9670. if (env->var == NULL) {
  9671. mg_cry_internal(conn,
  9672. "%s: Not enough memory for environmental variables",
  9673. __func__);
  9674. mg_free(env->buf);
  9675. return -1;
  9676. }
  9677. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9678. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9679. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9680. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9681. /* Prepare the environment block */
  9682. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9683. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9684. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9685. #if defined(USE_IPV6)
  9686. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9687. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9688. } else
  9689. #endif
  9690. {
  9691. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9692. }
  9693. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9694. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9695. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9696. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9697. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9698. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9699. /* SCRIPT_NAME */
  9700. uri_len = (int)strlen(conn->request_info.local_uri);
  9701. if (conn->path_info == NULL) {
  9702. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9703. /* URI: /path_to_script/script.cgi */
  9704. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9705. } else {
  9706. /* URI: /path_to_script/ ... using index.cgi */
  9707. const char *index_file = strrchr(prog, '/');
  9708. if (index_file) {
  9709. addenv(env,
  9710. "SCRIPT_NAME=%s%s",
  9711. conn->request_info.local_uri,
  9712. index_file + 1);
  9713. }
  9714. }
  9715. } else {
  9716. /* URI: /path_to_script/script.cgi/path_info */
  9717. addenv(env,
  9718. "SCRIPT_NAME=%.*s",
  9719. uri_len - (int)strlen(conn->path_info),
  9720. conn->request_info.local_uri);
  9721. }
  9722. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9723. if (conn->path_info == NULL) {
  9724. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9725. } else {
  9726. addenv(env,
  9727. "PATH_TRANSLATED=%s%s",
  9728. conn->dom_ctx->config[DOCUMENT_ROOT],
  9729. conn->path_info);
  9730. }
  9731. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9732. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9733. addenv(env, "CONTENT_TYPE=%s", s);
  9734. }
  9735. if (conn->request_info.query_string != NULL) {
  9736. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9737. }
  9738. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9739. addenv(env, "CONTENT_LENGTH=%s", s);
  9740. }
  9741. if ((s = getenv("PATH")) != NULL) {
  9742. addenv(env, "PATH=%s", s);
  9743. }
  9744. if (conn->path_info != NULL) {
  9745. addenv(env, "PATH_INFO=%s", conn->path_info);
  9746. }
  9747. if (conn->status_code > 0) {
  9748. /* CGI error handler should show the status code */
  9749. addenv(env, "STATUS=%d", conn->status_code);
  9750. }
  9751. #if defined(_WIN32)
  9752. if ((s = getenv("COMSPEC")) != NULL) {
  9753. addenv(env, "COMSPEC=%s", s);
  9754. }
  9755. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9756. addenv(env, "SYSTEMROOT=%s", s);
  9757. }
  9758. if ((s = getenv("SystemDrive")) != NULL) {
  9759. addenv(env, "SystemDrive=%s", s);
  9760. }
  9761. if ((s = getenv("ProgramFiles")) != NULL) {
  9762. addenv(env, "ProgramFiles=%s", s);
  9763. }
  9764. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9765. addenv(env, "ProgramFiles(x86)=%s", s);
  9766. }
  9767. #else
  9768. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9769. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9770. }
  9771. #endif /* _WIN32 */
  9772. if ((s = getenv("PERLLIB")) != NULL) {
  9773. addenv(env, "PERLLIB=%s", s);
  9774. }
  9775. if (conn->request_info.remote_user != NULL) {
  9776. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9777. addenv(env, "%s", "AUTH_TYPE=Digest");
  9778. }
  9779. /* Add all headers as HTTP_* variables */
  9780. for (i = 0; i < conn->request_info.num_headers; i++) {
  9781. (void)mg_snprintf(conn,
  9782. &truncated,
  9783. http_var_name,
  9784. sizeof(http_var_name),
  9785. "HTTP_%s",
  9786. conn->request_info.http_headers[i].name);
  9787. if (truncated) {
  9788. mg_cry_internal(conn,
  9789. "%s: HTTP header variable too long [%s]",
  9790. __func__,
  9791. conn->request_info.http_headers[i].name);
  9792. continue;
  9793. }
  9794. /* Convert variable name into uppercase, and change - to _ */
  9795. for (p = http_var_name; *p != '\0'; p++) {
  9796. if (*p == '-') {
  9797. *p = '_';
  9798. }
  9799. *p = (char)toupper((unsigned char)*p);
  9800. }
  9801. addenv(env,
  9802. "%s=%s",
  9803. http_var_name,
  9804. conn->request_info.http_headers[i].value);
  9805. }
  9806. /* Add user-specified variables */
  9807. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9808. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9809. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9810. }
  9811. env->var[env->varused] = NULL;
  9812. env->buf[env->bufused] = '\0';
  9813. return 0;
  9814. }
  9815. /* Data for CGI process control: PID and number of references */
  9816. struct process_control_data {
  9817. pid_t pid;
  9818. int references;
  9819. };
  9820. static int
  9821. abort_process(void *data)
  9822. {
  9823. /* Waitpid checks for child status and won't work for a pid that does
  9824. * not identify a child of the current process. Thus, if the pid is
  9825. * reused, we will not affect a different process. */
  9826. struct process_control_data *proc = (struct process_control_data *)data;
  9827. int status = 0;
  9828. int refs;
  9829. pid_t ret_pid;
  9830. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9831. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9832. /* Stop child process */
  9833. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9834. kill(proc->pid, SIGABRT);
  9835. /* Wait until process is terminated (don't leave zombies) */
  9836. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9837. ;
  9838. } else {
  9839. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9840. }
  9841. /* Dec reference counter */
  9842. refs = mg_atomic_dec(&proc->references);
  9843. if (refs == 0) {
  9844. /* no more references - free data */
  9845. mg_free(data);
  9846. }
  9847. return 0;
  9848. }
  9849. /* Local (static) function assumes all arguments are valid. */
  9850. static void
  9851. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9852. {
  9853. char *buf;
  9854. size_t buflen;
  9855. int headers_len, data_len, i, truncated;
  9856. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9857. const char *status, *status_text, *connection_state;
  9858. char *pbuf, dir[PATH_MAX], *p;
  9859. struct mg_request_info ri;
  9860. struct cgi_environment blk;
  9861. FILE *in = NULL, *out = NULL, *err = NULL;
  9862. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9863. pid_t pid = (pid_t)-1;
  9864. struct process_control_data *proc = NULL;
  9865. #if defined(USE_TIMERS)
  9866. double cgi_timeout = -1.0;
  9867. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9868. /* Get timeout in seconds */
  9869. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9870. }
  9871. #endif
  9872. buf = NULL;
  9873. buflen = conn->phys_ctx->max_request_size;
  9874. i = prepare_cgi_environment(conn, prog, &blk);
  9875. if (i != 0) {
  9876. blk.buf = NULL;
  9877. blk.var = NULL;
  9878. goto done;
  9879. }
  9880. /* CGI must be executed in its own directory. 'dir' must point to the
  9881. * directory containing executable program, 'p' must point to the
  9882. * executable program name relative to 'dir'. */
  9883. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9884. if (truncated) {
  9885. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9886. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9887. goto done;
  9888. }
  9889. if ((p = strrchr(dir, '/')) != NULL) {
  9890. *p++ = '\0';
  9891. } else {
  9892. dir[0] = '.';
  9893. dir[1] = '\0';
  9894. p = (char *)prog;
  9895. }
  9896. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9897. status = strerror(ERRNO);
  9898. mg_cry_internal(
  9899. conn,
  9900. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9901. prog,
  9902. status);
  9903. mg_send_http_error(conn,
  9904. 500,
  9905. "Error: Cannot create CGI pipe: %s",
  9906. status);
  9907. goto done;
  9908. }
  9909. proc = (struct process_control_data *)
  9910. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9911. if (proc == NULL) {
  9912. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9913. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9914. goto done;
  9915. }
  9916. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9917. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9918. if (pid == (pid_t)-1) {
  9919. status = strerror(ERRNO);
  9920. mg_cry_internal(
  9921. conn,
  9922. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9923. prog,
  9924. status);
  9925. mg_send_http_error(conn,
  9926. 500,
  9927. "Error: Cannot spawn CGI process [%s]: %s",
  9928. prog,
  9929. status);
  9930. mg_free(proc);
  9931. proc = NULL;
  9932. goto done;
  9933. }
  9934. /* Store data in shared process_control_data */
  9935. proc->pid = pid;
  9936. proc->references = 1;
  9937. #if defined(USE_TIMERS)
  9938. if (cgi_timeout > 0.0) {
  9939. proc->references = 2;
  9940. // Start a timer for CGI
  9941. timer_add(conn->phys_ctx,
  9942. cgi_timeout /* in seconds */,
  9943. 0.0,
  9944. 1,
  9945. abort_process,
  9946. (void *)proc);
  9947. }
  9948. #endif
  9949. /* Parent closes only one side of the pipes.
  9950. * If we don't mark them as closed, close() attempt before
  9951. * return from this function throws an exception on Windows.
  9952. * Windows does not like when closed descriptor is closed again. */
  9953. (void)close(fdin[0]);
  9954. (void)close(fdout[1]);
  9955. (void)close(fderr[1]);
  9956. fdin[0] = fdout[1] = fderr[1] = -1;
  9957. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9958. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9959. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9960. status = strerror(ERRNO);
  9961. mg_cry_internal(conn,
  9962. "Error: CGI program \"%s\": Can not open fd: %s",
  9963. prog,
  9964. status);
  9965. mg_send_http_error(conn,
  9966. 500,
  9967. "Error: CGI can not open fd\nfdopen: %s",
  9968. status);
  9969. goto done;
  9970. }
  9971. setbuf(in, NULL);
  9972. setbuf(out, NULL);
  9973. setbuf(err, NULL);
  9974. fout.access.fp = out;
  9975. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9976. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9977. conn->content_len);
  9978. /* This is a POST/PUT request, or another request with body data. */
  9979. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9980. /* Error sending the body data */
  9981. mg_cry_internal(
  9982. conn,
  9983. "Error: CGI program \"%s\": Forward body data failed",
  9984. prog);
  9985. goto done;
  9986. }
  9987. }
  9988. /* Close so child gets an EOF. */
  9989. fclose(in);
  9990. in = NULL;
  9991. fdin[1] = -1;
  9992. /* Now read CGI reply into a buffer. We need to set correct
  9993. * status code, thus we need to see all HTTP headers first.
  9994. * Do not send anything back to client, until we buffer in all
  9995. * HTTP headers. */
  9996. data_len = 0;
  9997. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9998. if (buf == NULL) {
  9999. mg_send_http_error(conn,
  10000. 500,
  10001. "Error: Not enough memory for CGI buffer (%u bytes)",
  10002. (unsigned int)buflen);
  10003. mg_cry_internal(
  10004. conn,
  10005. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10006. "bytes)",
  10007. prog,
  10008. (unsigned int)buflen);
  10009. goto done;
  10010. }
  10011. DEBUG_TRACE("CGI: %s", "wait for response");
  10012. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10013. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10014. if (headers_len <= 0) {
  10015. /* Could not parse the CGI response. Check if some error message on
  10016. * stderr. */
  10017. i = pull_all(err, conn, buf, (int)buflen);
  10018. if (i > 0) {
  10019. /* CGI program explicitly sent an error */
  10020. /* Write the error message to the internal log */
  10021. mg_cry_internal(conn,
  10022. "Error: CGI program \"%s\" sent error "
  10023. "message: [%.*s]",
  10024. prog,
  10025. i,
  10026. buf);
  10027. /* Don't send the error message back to the client */
  10028. mg_send_http_error(conn,
  10029. 500,
  10030. "Error: CGI program \"%s\" failed.",
  10031. prog);
  10032. } else {
  10033. /* CGI program did not explicitly send an error, but a broken
  10034. * respon header */
  10035. mg_cry_internal(conn,
  10036. "Error: CGI program sent malformed or too big "
  10037. "(>%u bytes) HTTP headers: [%.*s]",
  10038. (unsigned)buflen,
  10039. data_len,
  10040. buf);
  10041. mg_send_http_error(conn,
  10042. 500,
  10043. "Error: CGI program sent malformed or too big "
  10044. "(>%u bytes) HTTP headers: [%.*s]",
  10045. (unsigned)buflen,
  10046. data_len,
  10047. buf);
  10048. }
  10049. /* in both cases, abort processing CGI */
  10050. goto done;
  10051. }
  10052. pbuf = buf;
  10053. buf[headers_len - 1] = '\0';
  10054. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10055. /* Make up and send the status line */
  10056. status_text = "OK";
  10057. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10058. != NULL) {
  10059. conn->status_code = atoi(status);
  10060. status_text = status;
  10061. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10062. status_text++;
  10063. }
  10064. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10065. != NULL) {
  10066. conn->status_code = 307;
  10067. } else {
  10068. conn->status_code = 200;
  10069. }
  10070. connection_state =
  10071. get_header(ri.http_headers, ri.num_headers, "Connection");
  10072. if (!header_has_option(connection_state, "keep-alive")) {
  10073. conn->must_close = 1;
  10074. }
  10075. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10076. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10077. /* Send headers */
  10078. for (i = 0; i < ri.num_headers; i++) {
  10079. DEBUG_TRACE("CGI header: %s: %s",
  10080. ri.http_headers[i].name,
  10081. ri.http_headers[i].value);
  10082. mg_printf(conn,
  10083. "%s: %s\r\n",
  10084. ri.http_headers[i].name,
  10085. ri.http_headers[i].value);
  10086. }
  10087. mg_write(conn, "\r\n", 2);
  10088. /* Send chunk of data that may have been read after the headers */
  10089. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10090. /* Read the rest of CGI output and send to the client */
  10091. DEBUG_TRACE("CGI: %s", "forward all data");
  10092. send_file_data(conn, &fout, 0, INT64_MAX);
  10093. DEBUG_TRACE("CGI: %s", "all data sent");
  10094. done:
  10095. mg_free(blk.var);
  10096. mg_free(blk.buf);
  10097. if (pid != (pid_t)-1) {
  10098. abort_process((void *)proc);
  10099. }
  10100. if (fdin[0] != -1) {
  10101. close(fdin[0]);
  10102. }
  10103. if (fdout[1] != -1) {
  10104. close(fdout[1]);
  10105. }
  10106. if (fderr[1] != -1) {
  10107. close(fderr[1]);
  10108. }
  10109. if (in != NULL) {
  10110. fclose(in);
  10111. } else if (fdin[1] != -1) {
  10112. close(fdin[1]);
  10113. }
  10114. if (out != NULL) {
  10115. fclose(out);
  10116. } else if (fdout[0] != -1) {
  10117. close(fdout[0]);
  10118. }
  10119. if (err != NULL) {
  10120. fclose(err);
  10121. } else if (fderr[0] != -1) {
  10122. close(fderr[0]);
  10123. }
  10124. mg_free(buf);
  10125. }
  10126. #endif /* !NO_CGI */
  10127. #if !defined(NO_FILES)
  10128. static void
  10129. mkcol(struct mg_connection *conn, const char *path)
  10130. {
  10131. int rc, body_len;
  10132. struct de de;
  10133. char date[64];
  10134. time_t curtime = time(NULL);
  10135. if (conn == NULL) {
  10136. return;
  10137. }
  10138. /* TODO (mid): Check the mg_send_http_error situations in this function
  10139. */
  10140. memset(&de.file, 0, sizeof(de.file));
  10141. if (!mg_stat(conn, path, &de.file)) {
  10142. mg_cry_internal(conn,
  10143. "%s: mg_stat(%s) failed: %s",
  10144. __func__,
  10145. path,
  10146. strerror(ERRNO));
  10147. }
  10148. if (de.file.last_modified) {
  10149. /* TODO (mid): This check does not seem to make any sense ! */
  10150. /* TODO (mid): Add a webdav unit test first, before changing
  10151. * anything here. */
  10152. mg_send_http_error(
  10153. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10154. return;
  10155. }
  10156. body_len = conn->data_len - conn->request_len;
  10157. if (body_len > 0) {
  10158. mg_send_http_error(
  10159. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10160. return;
  10161. }
  10162. rc = mg_mkdir(conn, path, 0755);
  10163. if (rc == 0) {
  10164. conn->status_code = 201;
  10165. gmt_time_string(date, sizeof(date), &curtime);
  10166. mg_printf(conn,
  10167. "HTTP/1.1 %d Created\r\n"
  10168. "Date: %s\r\n",
  10169. conn->status_code,
  10170. date);
  10171. send_static_cache_header(conn);
  10172. send_additional_header(conn);
  10173. mg_printf(conn,
  10174. "Content-Length: 0\r\n"
  10175. "Connection: %s\r\n\r\n",
  10176. suggest_connection_header(conn));
  10177. } else {
  10178. if (errno == EEXIST) {
  10179. mg_send_http_error(
  10180. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10181. } else if (errno == EACCES) {
  10182. mg_send_http_error(
  10183. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10184. } else if (errno == ENOENT) {
  10185. mg_send_http_error(
  10186. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10187. } else {
  10188. mg_send_http_error(
  10189. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10190. }
  10191. }
  10192. }
  10193. static void
  10194. put_file(struct mg_connection *conn, const char *path)
  10195. {
  10196. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10197. const char *range;
  10198. int64_t r1, r2;
  10199. int rc;
  10200. char date[64];
  10201. time_t curtime = time(NULL);
  10202. if (conn == NULL) {
  10203. return;
  10204. }
  10205. if (mg_stat(conn, path, &file.stat)) {
  10206. /* File already exists */
  10207. conn->status_code = 200;
  10208. if (file.stat.is_directory) {
  10209. /* This is an already existing directory,
  10210. * so there is nothing to do for the server. */
  10211. rc = 0;
  10212. } else {
  10213. /* File exists and is not a directory. */
  10214. /* Can it be replaced? */
  10215. #if defined(MG_USE_OPEN_FILE)
  10216. if (file.access.membuf != NULL) {
  10217. /* This is an "in-memory" file, that can not be replaced */
  10218. mg_send_http_error(conn,
  10219. 405,
  10220. "Error: Put not possible\nReplacing %s "
  10221. "is not supported",
  10222. path);
  10223. return;
  10224. }
  10225. #endif
  10226. /* Check if the server may write this file */
  10227. if (access(path, W_OK) == 0) {
  10228. /* Access granted */
  10229. rc = 1;
  10230. } else {
  10231. mg_send_http_error(
  10232. conn,
  10233. 403,
  10234. "Error: Put not possible\nReplacing %s is not allowed",
  10235. path);
  10236. return;
  10237. }
  10238. }
  10239. } else {
  10240. /* File should be created */
  10241. conn->status_code = 201;
  10242. rc = put_dir(conn, path);
  10243. }
  10244. if (rc == 0) {
  10245. /* put_dir returns 0 if path is a directory */
  10246. gmt_time_string(date, sizeof(date), &curtime);
  10247. mg_printf(conn,
  10248. "HTTP/1.1 %d %s\r\n",
  10249. conn->status_code,
  10250. mg_get_response_code_text(NULL, conn->status_code));
  10251. send_no_cache_header(conn);
  10252. send_additional_header(conn);
  10253. mg_printf(conn,
  10254. "Date: %s\r\n"
  10255. "Content-Length: 0\r\n"
  10256. "Connection: %s\r\n\r\n",
  10257. date,
  10258. suggest_connection_header(conn));
  10259. /* Request to create a directory has been fulfilled successfully.
  10260. * No need to put a file. */
  10261. return;
  10262. }
  10263. if (rc == -1) {
  10264. /* put_dir returns -1 if the path is too long */
  10265. mg_send_http_error(conn,
  10266. 414,
  10267. "Error: Path too long\nput_dir(%s): %s",
  10268. path,
  10269. strerror(ERRNO));
  10270. return;
  10271. }
  10272. if (rc == -2) {
  10273. /* put_dir returns -2 if the directory can not be created */
  10274. mg_send_http_error(conn,
  10275. 500,
  10276. "Error: Can not create directory\nput_dir(%s): %s",
  10277. path,
  10278. strerror(ERRNO));
  10279. return;
  10280. }
  10281. /* A file should be created or overwritten. */
  10282. /* Currently CivetWeb does not nead read+write access. */
  10283. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10284. || file.access.fp == NULL) {
  10285. (void)mg_fclose(&file.access);
  10286. mg_send_http_error(conn,
  10287. 500,
  10288. "Error: Can not create file\nfopen(%s): %s",
  10289. path,
  10290. strerror(ERRNO));
  10291. return;
  10292. }
  10293. fclose_on_exec(&file.access, conn);
  10294. range = mg_get_header(conn, "Content-Range");
  10295. r1 = r2 = 0;
  10296. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10297. conn->status_code = 206; /* Partial content */
  10298. fseeko(file.access.fp, r1, SEEK_SET);
  10299. }
  10300. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10301. /* forward_body_data failed.
  10302. * The error code has already been sent to the client,
  10303. * and conn->status_code is already set. */
  10304. (void)mg_fclose(&file.access);
  10305. return;
  10306. }
  10307. if (mg_fclose(&file.access) != 0) {
  10308. /* fclose failed. This might have different reasons, but a likely
  10309. * one is "no space on disk", http 507. */
  10310. conn->status_code = 507;
  10311. }
  10312. gmt_time_string(date, sizeof(date), &curtime);
  10313. mg_printf(conn,
  10314. "HTTP/1.1 %d %s\r\n",
  10315. conn->status_code,
  10316. mg_get_response_code_text(NULL, conn->status_code));
  10317. send_no_cache_header(conn);
  10318. send_additional_header(conn);
  10319. mg_printf(conn,
  10320. "Date: %s\r\n"
  10321. "Content-Length: 0\r\n"
  10322. "Connection: %s\r\n\r\n",
  10323. date,
  10324. suggest_connection_header(conn));
  10325. }
  10326. static void
  10327. delete_file(struct mg_connection *conn, const char *path)
  10328. {
  10329. struct de de;
  10330. memset(&de.file, 0, sizeof(de.file));
  10331. if (!mg_stat(conn, path, &de.file)) {
  10332. /* mg_stat returns 0 if the file does not exist */
  10333. mg_send_http_error(conn,
  10334. 404,
  10335. "Error: Cannot delete file\nFile %s not found",
  10336. path);
  10337. return;
  10338. }
  10339. #if 0 /* Ignore if a file in memory is inside a folder */
  10340. if (de.access.membuf != NULL) {
  10341. /* the file is cached in memory */
  10342. mg_send_http_error(
  10343. conn,
  10344. 405,
  10345. "Error: Delete not possible\nDeleting %s is not supported",
  10346. path);
  10347. return;
  10348. }
  10349. #endif
  10350. if (de.file.is_directory) {
  10351. if (remove_directory(conn, path)) {
  10352. /* Delete is successful: Return 204 without content. */
  10353. mg_send_http_error(conn, 204, "%s", "");
  10354. } else {
  10355. /* Delete is not successful: Return 500 (Server error). */
  10356. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10357. }
  10358. return;
  10359. }
  10360. /* This is an existing file (not a directory).
  10361. * Check if write permission is granted. */
  10362. if (access(path, W_OK) != 0) {
  10363. /* File is read only */
  10364. mg_send_http_error(
  10365. conn,
  10366. 403,
  10367. "Error: Delete not possible\nDeleting %s is not allowed",
  10368. path);
  10369. return;
  10370. }
  10371. /* Try to delete it. */
  10372. if (mg_remove(conn, path) == 0) {
  10373. /* Delete was successful: Return 204 without content. */
  10374. mg_send_http_error(conn, 204, "%s", "");
  10375. } else {
  10376. /* Delete not successful (file locked). */
  10377. mg_send_http_error(conn,
  10378. 423,
  10379. "Error: Cannot delete file\nremove(%s): %s",
  10380. path,
  10381. strerror(ERRNO));
  10382. }
  10383. }
  10384. #endif /* !NO_FILES */
  10385. #if !defined(NO_FILESYSTEMS)
  10386. static void
  10387. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10388. static void
  10389. do_ssi_include(struct mg_connection *conn,
  10390. const char *ssi,
  10391. char *tag,
  10392. int include_level)
  10393. {
  10394. char file_name[MG_BUF_LEN], path[512], *p;
  10395. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10396. size_t len;
  10397. int truncated = 0;
  10398. if (conn == NULL) {
  10399. return;
  10400. }
  10401. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10402. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10403. * always < MG_BUF_LEN. */
  10404. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10405. /* File name is relative to the webserver root */
  10406. file_name[511] = 0;
  10407. (void)mg_snprintf(conn,
  10408. &truncated,
  10409. path,
  10410. sizeof(path),
  10411. "%s/%s",
  10412. conn->dom_ctx->config[DOCUMENT_ROOT],
  10413. file_name);
  10414. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10415. /* File name is relative to the webserver working directory
  10416. * or it is absolute system path */
  10417. file_name[511] = 0;
  10418. (void)
  10419. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10420. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10421. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10422. /* File name is relative to the currect document */
  10423. file_name[511] = 0;
  10424. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10425. if (!truncated) {
  10426. if ((p = strrchr(path, '/')) != NULL) {
  10427. p[1] = '\0';
  10428. }
  10429. len = strlen(path);
  10430. (void)mg_snprintf(conn,
  10431. &truncated,
  10432. path + len,
  10433. sizeof(path) - len,
  10434. "%s",
  10435. file_name);
  10436. }
  10437. } else {
  10438. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10439. return;
  10440. }
  10441. if (truncated) {
  10442. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10443. return;
  10444. }
  10445. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10446. mg_cry_internal(conn,
  10447. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10448. tag,
  10449. path,
  10450. strerror(ERRNO));
  10451. } else {
  10452. fclose_on_exec(&file.access, conn);
  10453. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10454. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10455. path)
  10456. > 0) {
  10457. send_ssi_file(conn, path, &file, include_level + 1);
  10458. } else {
  10459. send_file_data(conn, &file, 0, INT64_MAX);
  10460. }
  10461. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10462. }
  10463. }
  10464. #if !defined(NO_POPEN)
  10465. static void
  10466. do_ssi_exec(struct mg_connection *conn, char *tag)
  10467. {
  10468. char cmd[1024] = "";
  10469. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10470. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10471. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10472. } else {
  10473. cmd[1023] = 0;
  10474. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10475. mg_cry_internal(conn,
  10476. "Cannot SSI #exec: [%s]: %s",
  10477. cmd,
  10478. strerror(ERRNO));
  10479. } else {
  10480. send_file_data(conn, &file, 0, INT64_MAX);
  10481. pclose(file.access.fp);
  10482. }
  10483. }
  10484. }
  10485. #endif /* !NO_POPEN */
  10486. static int
  10487. mg_fgetc(struct mg_file *filep, int offset)
  10488. {
  10489. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10490. if (filep == NULL) {
  10491. return EOF;
  10492. }
  10493. #if defined(MG_USE_OPEN_FILE)
  10494. if ((filep->access.membuf != NULL) && (offset >= 0)
  10495. && (((unsigned int)(offset)) < filep->stat.size)) {
  10496. return ((const unsigned char *)filep->access.membuf)[offset];
  10497. } else /* else block below */
  10498. #endif
  10499. if (filep->access.fp != NULL) {
  10500. return fgetc(filep->access.fp);
  10501. } else {
  10502. return EOF;
  10503. }
  10504. }
  10505. static void
  10506. send_ssi_file(struct mg_connection *conn,
  10507. const char *path,
  10508. struct mg_file *filep,
  10509. int include_level)
  10510. {
  10511. char buf[MG_BUF_LEN];
  10512. int ch, offset, len, in_tag, in_ssi_tag;
  10513. if (include_level > 10) {
  10514. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10515. return;
  10516. }
  10517. in_tag = in_ssi_tag = len = offset = 0;
  10518. /* Read file, byte by byte, and look for SSI include tags */
  10519. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10520. if (in_tag) {
  10521. /* We are in a tag, either SSI tag or html tag */
  10522. if (ch == '>') {
  10523. /* Tag is closing */
  10524. buf[len++] = '>';
  10525. if (in_ssi_tag) {
  10526. /* Handle SSI tag */
  10527. buf[len] = 0;
  10528. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10529. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10530. #if !defined(NO_POPEN)
  10531. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10532. do_ssi_exec(conn, buf + 9);
  10533. #endif /* !NO_POPEN */
  10534. } else {
  10535. mg_cry_internal(conn,
  10536. "%s: unknown SSI "
  10537. "command: \"%s\"",
  10538. path,
  10539. buf);
  10540. }
  10541. len = 0;
  10542. in_ssi_tag = in_tag = 0;
  10543. } else {
  10544. /* Not an SSI tag */
  10545. /* Flush buffer */
  10546. (void)mg_write(conn, buf, (size_t)len);
  10547. len = 0;
  10548. in_tag = 0;
  10549. }
  10550. } else {
  10551. /* Tag is still open */
  10552. buf[len++] = (char)(ch & 0xff);
  10553. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10554. /* All SSI tags start with <!--# */
  10555. in_ssi_tag = 1;
  10556. }
  10557. if ((len + 2) > (int)sizeof(buf)) {
  10558. /* Tag to long for buffer */
  10559. mg_cry_internal(conn, "%s: tag is too large", path);
  10560. return;
  10561. }
  10562. }
  10563. } else {
  10564. /* We are not in a tag yet. */
  10565. if (ch == '<') {
  10566. /* Tag is opening */
  10567. in_tag = 1;
  10568. if (len > 0) {
  10569. /* Flush current buffer.
  10570. * Buffer is filled with "len" bytes. */
  10571. (void)mg_write(conn, buf, (size_t)len);
  10572. }
  10573. /* Store the < */
  10574. len = 1;
  10575. buf[0] = '<';
  10576. } else {
  10577. /* No Tag */
  10578. /* Add data to buffer */
  10579. buf[len++] = (char)(ch & 0xff);
  10580. /* Flush if buffer is full */
  10581. if (len == (int)sizeof(buf)) {
  10582. mg_write(conn, buf, (size_t)len);
  10583. len = 0;
  10584. }
  10585. }
  10586. }
  10587. }
  10588. /* Send the rest of buffered data */
  10589. if (len > 0) {
  10590. mg_write(conn, buf, (size_t)len);
  10591. }
  10592. }
  10593. static void
  10594. handle_ssi_file_request(struct mg_connection *conn,
  10595. const char *path,
  10596. struct mg_file *filep)
  10597. {
  10598. char date[64];
  10599. time_t curtime = time(NULL);
  10600. const char *cors_orig_cfg;
  10601. const char *cors1, *cors2, *cors3;
  10602. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10603. return;
  10604. }
  10605. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10606. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10607. /* Cross-origin resource sharing (CORS). */
  10608. cors1 = "Access-Control-Allow-Origin: ";
  10609. cors2 = cors_orig_cfg;
  10610. cors3 = "\r\n";
  10611. } else {
  10612. cors1 = cors2 = cors3 = "";
  10613. }
  10614. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10615. /* File exists (precondition for calling this function),
  10616. * but can not be opened by the server. */
  10617. mg_send_http_error(conn,
  10618. 500,
  10619. "Error: Cannot read file\nfopen(%s): %s",
  10620. path,
  10621. strerror(ERRNO));
  10622. } else {
  10623. conn->must_close = 1;
  10624. gmt_time_string(date, sizeof(date), &curtime);
  10625. fclose_on_exec(&filep->access, conn);
  10626. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10627. send_no_cache_header(conn);
  10628. send_additional_header(conn);
  10629. mg_printf(conn,
  10630. "%s%s%s"
  10631. "Date: %s\r\n"
  10632. "Content-Type: text/html\r\n"
  10633. "Connection: %s\r\n\r\n",
  10634. cors1,
  10635. cors2,
  10636. cors3,
  10637. date,
  10638. suggest_connection_header(conn));
  10639. send_ssi_file(conn, path, filep, 0);
  10640. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10641. }
  10642. }
  10643. #endif /* NO_FILESYSTEMS */
  10644. #if !defined(NO_FILES)
  10645. static void
  10646. send_options(struct mg_connection *conn)
  10647. {
  10648. char date[64];
  10649. time_t curtime = time(NULL);
  10650. if (!conn) {
  10651. return;
  10652. }
  10653. conn->status_code = 200;
  10654. conn->must_close = 1;
  10655. gmt_time_string(date, sizeof(date), &curtime);
  10656. /* We do not set a "Cache-Control" header here, but leave the default.
  10657. * Since browsers do not send an OPTIONS request, we can not test the
  10658. * effect anyway. */
  10659. mg_printf(conn,
  10660. "HTTP/1.1 200 OK\r\n"
  10661. "Date: %s\r\n"
  10662. "Connection: %s\r\n"
  10663. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10664. "PROPFIND, MKCOL\r\n"
  10665. "DAV: 1\r\n",
  10666. date,
  10667. suggest_connection_header(conn));
  10668. send_additional_header(conn);
  10669. mg_printf(conn, "\r\n");
  10670. }
  10671. /* Writes PROPFIND properties for a collection element */
  10672. static int
  10673. print_props(struct mg_connection *conn,
  10674. const char *uri,
  10675. const char *name,
  10676. struct mg_file_stat *filep)
  10677. {
  10678. size_t href_size, i, j;
  10679. int len;
  10680. char *href, mtime[64];
  10681. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10682. return 0;
  10683. }
  10684. /* Estimate worst case size for encoding */
  10685. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10686. href = (char *)mg_malloc(href_size);
  10687. if (href == NULL) {
  10688. return 0;
  10689. }
  10690. len = mg_url_encode(uri, href, href_size);
  10691. if (len >= 0) {
  10692. /* Append an extra string */
  10693. mg_url_encode(name, href + len, href_size - (size_t)len);
  10694. }
  10695. /* Directory separator should be preserved. */
  10696. for (i = j = 0; href[i]; j++) {
  10697. if (!strncmp(href + i, "%2f", 3)) {
  10698. href[j] = '/';
  10699. i += 3;
  10700. } else {
  10701. href[j] = href[i++];
  10702. }
  10703. }
  10704. href[j] = '\0';
  10705. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10706. mg_printf(conn,
  10707. "<d:response>"
  10708. "<d:href>%s</d:href>"
  10709. "<d:propstat>"
  10710. "<d:prop>"
  10711. "<d:resourcetype>%s</d:resourcetype>"
  10712. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10713. "<d:getlastmodified>%s</d:getlastmodified>"
  10714. "</d:prop>"
  10715. "<d:status>HTTP/1.1 200 OK</d:status>"
  10716. "</d:propstat>"
  10717. "</d:response>\n",
  10718. href,
  10719. filep->is_directory ? "<d:collection/>" : "",
  10720. filep->size,
  10721. mtime);
  10722. mg_free(href);
  10723. return 1;
  10724. }
  10725. static int
  10726. print_dav_dir_entry(struct de *de, void *data)
  10727. {
  10728. struct mg_connection *conn = (struct mg_connection *)data;
  10729. if (!de || !conn
  10730. || !print_props(
  10731. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10732. return -1;
  10733. }
  10734. return 0;
  10735. }
  10736. static void
  10737. handle_propfind(struct mg_connection *conn,
  10738. const char *path,
  10739. struct mg_file_stat *filep)
  10740. {
  10741. const char *depth = mg_get_header(conn, "Depth");
  10742. char date[64];
  10743. time_t curtime = time(NULL);
  10744. gmt_time_string(date, sizeof(date), &curtime);
  10745. if (!conn || !path || !filep || !conn->dom_ctx) {
  10746. return;
  10747. }
  10748. conn->must_close = 1;
  10749. conn->status_code = 207;
  10750. mg_printf(conn,
  10751. "HTTP/1.1 207 Multi-Status\r\n"
  10752. "Date: %s\r\n",
  10753. date);
  10754. send_static_cache_header(conn);
  10755. send_additional_header(conn);
  10756. mg_printf(conn,
  10757. "Connection: %s\r\n"
  10758. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10759. suggest_connection_header(conn));
  10760. mg_printf(conn,
  10761. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10762. "<d:multistatus xmlns:d='DAV:'>\n");
  10763. /* Print properties for the requested resource itself */
  10764. print_props(conn, conn->request_info.local_uri, "", filep);
  10765. /* If it is a directory, print directory entries too if Depth is not 0
  10766. */
  10767. if (filep->is_directory
  10768. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10769. "yes")
  10770. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10771. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10772. }
  10773. mg_printf(conn, "%s\n", "</d:multistatus>");
  10774. }
  10775. #endif
  10776. void
  10777. mg_lock_connection(struct mg_connection *conn)
  10778. {
  10779. if (conn) {
  10780. (void)pthread_mutex_lock(&conn->mutex);
  10781. }
  10782. }
  10783. void
  10784. mg_unlock_connection(struct mg_connection *conn)
  10785. {
  10786. if (conn) {
  10787. (void)pthread_mutex_unlock(&conn->mutex);
  10788. }
  10789. }
  10790. void
  10791. mg_lock_context(struct mg_context *ctx)
  10792. {
  10793. if (ctx) {
  10794. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10795. }
  10796. }
  10797. void
  10798. mg_unlock_context(struct mg_context *ctx)
  10799. {
  10800. if (ctx) {
  10801. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10802. }
  10803. }
  10804. #if defined(USE_LUA)
  10805. #include "mod_lua.inl"
  10806. #endif /* USE_LUA */
  10807. #if defined(USE_DUKTAPE)
  10808. #include "mod_duktape.inl"
  10809. #endif /* USE_DUKTAPE */
  10810. #if defined(USE_WEBSOCKET)
  10811. #if !defined(NO_SSL_DL)
  10812. #define SHA_API static
  10813. #include "sha1.inl"
  10814. #endif
  10815. static int
  10816. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10817. {
  10818. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10819. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10820. SHA_CTX sha_ctx;
  10821. int truncated;
  10822. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10823. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10824. if (truncated) {
  10825. conn->must_close = 1;
  10826. return 0;
  10827. }
  10828. DEBUG_TRACE("%s", "Send websocket handshake");
  10829. SHA1_Init(&sha_ctx);
  10830. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10831. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10832. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10833. mg_printf(conn,
  10834. "HTTP/1.1 101 Switching Protocols\r\n"
  10835. "Upgrade: websocket\r\n"
  10836. "Connection: Upgrade\r\n"
  10837. "Sec-WebSocket-Accept: %s\r\n",
  10838. b64_sha);
  10839. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10840. mg_printf(conn,
  10841. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10842. conn->request_info.acceptedWebSocketSubprotocol);
  10843. } else {
  10844. mg_printf(conn, "%s", "\r\n");
  10845. }
  10846. return 1;
  10847. }
  10848. #if !defined(MG_MAX_UNANSWERED_PING)
  10849. /* Configuration of the maximum number of websocket PINGs that might
  10850. * stay unanswered before the connection is considered broken.
  10851. * Note: The name of this define may still change (until it is
  10852. * defined as a compile parameter in a documentation).
  10853. */
  10854. #define MG_MAX_UNANSWERED_PING (5)
  10855. #endif
  10856. static void
  10857. read_websocket(struct mg_connection *conn,
  10858. mg_websocket_data_handler ws_data_handler,
  10859. void *callback_data)
  10860. {
  10861. /* Pointer to the beginning of the portion of the incoming websocket
  10862. * message queue.
  10863. * The original websocket upgrade request is never removed, so the queue
  10864. * begins after it. */
  10865. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10866. int n, error, exit_by_callback;
  10867. int ret;
  10868. /* body_len is the length of the entire queue in bytes
  10869. * len is the length of the current message
  10870. * data_len is the length of the current message's data payload
  10871. * header_len is the length of the current message's header */
  10872. size_t i, len, mask_len = 0, header_len, body_len;
  10873. uint64_t data_len = 0;
  10874. /* "The masking key is a 32-bit value chosen at random by the client."
  10875. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10876. */
  10877. unsigned char mask[4];
  10878. /* data points to the place where the message is stored when passed to
  10879. * the websocket_data callback. This is either mem on the stack, or a
  10880. * dynamically allocated buffer if it is too large. */
  10881. unsigned char mem[4096];
  10882. unsigned char mop; /* mask flag and opcode */
  10883. /* Variables used for connection monitoring */
  10884. double timeout = -1.0;
  10885. int enable_ping_pong = 0;
  10886. int ping_count = 0;
  10887. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10888. enable_ping_pong =
  10889. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10890. "yes");
  10891. }
  10892. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10893. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10894. }
  10895. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10896. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10897. }
  10898. /* Enter data processing loop */
  10899. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10900. conn->request_info.remote_addr,
  10901. conn->request_info.remote_port);
  10902. conn->in_websocket_handling = 1;
  10903. mg_set_thread_name("wsock");
  10904. /* Loop continuously, reading messages from the socket, invoking the
  10905. * callback, and waiting repeatedly until an error occurs. */
  10906. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10907. header_len = 0;
  10908. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10909. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10910. len = buf[1] & 127;
  10911. mask_len = (buf[1] & 128) ? 4 : 0;
  10912. if ((len < 126) && (body_len >= mask_len)) {
  10913. /* inline 7-bit length field */
  10914. data_len = len;
  10915. header_len = 2 + mask_len;
  10916. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10917. /* 16-bit length field */
  10918. header_len = 4 + mask_len;
  10919. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10920. } else if (body_len >= (10 + mask_len)) {
  10921. /* 64-bit length field */
  10922. uint32_t l1, l2;
  10923. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10924. memcpy(&l2, &buf[6], 4);
  10925. header_len = 10 + mask_len;
  10926. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10927. if (data_len > (uint64_t)0x7FFF0000ul) {
  10928. /* no can do */
  10929. mg_cry_internal(
  10930. conn,
  10931. "%s",
  10932. "websocket out of memory; closing connection");
  10933. break;
  10934. }
  10935. }
  10936. }
  10937. if ((header_len > 0) && (body_len >= header_len)) {
  10938. /* Allocate space to hold websocket payload */
  10939. unsigned char *data = mem;
  10940. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10941. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10942. conn->phys_ctx);
  10943. if (data == NULL) {
  10944. /* Allocation failed, exit the loop and then close the
  10945. * connection */
  10946. mg_cry_internal(
  10947. conn,
  10948. "%s",
  10949. "websocket out of memory; closing connection");
  10950. break;
  10951. }
  10952. }
  10953. /* Copy the mask before we shift the queue and destroy it */
  10954. if (mask_len > 0) {
  10955. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10956. } else {
  10957. memset(mask, 0, sizeof(mask));
  10958. }
  10959. /* Read frame payload from the first message in the queue into
  10960. * data and advance the queue by moving the memory in place. */
  10961. DEBUG_ASSERT(body_len >= header_len);
  10962. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10963. mop = buf[0]; /* current mask and opcode */
  10964. /* Overflow case */
  10965. len = body_len - header_len;
  10966. memcpy(data, buf + header_len, len);
  10967. error = 0;
  10968. while ((uint64_t)len < data_len) {
  10969. n = pull_inner(NULL,
  10970. conn,
  10971. (char *)(data + len),
  10972. (int)(data_len - len),
  10973. timeout);
  10974. if (n <= -2) {
  10975. error = 1;
  10976. break;
  10977. } else if (n > 0) {
  10978. len += (size_t)n;
  10979. } else {
  10980. /* Timeout: should retry */
  10981. /* TODO: retry condition */
  10982. }
  10983. }
  10984. if (error) {
  10985. mg_cry_internal(
  10986. conn,
  10987. "%s",
  10988. "Websocket pull failed; closing connection");
  10989. if (data != mem) {
  10990. mg_free(data);
  10991. }
  10992. break;
  10993. }
  10994. conn->data_len = conn->request_len;
  10995. } else {
  10996. mop = buf[0]; /* current mask and opcode, overwritten by
  10997. * memmove() */
  10998. /* Length of the message being read at the front of the
  10999. * queue. Cast to 31 bit is OK, since we limited
  11000. * data_len before. */
  11001. len = (size_t)data_len + header_len;
  11002. /* Copy the data payload into the data pointer for the
  11003. * callback. Cast to 31 bit is OK, since we
  11004. * limited data_len */
  11005. memcpy(data, buf + header_len, (size_t)data_len);
  11006. /* Move the queue forward len bytes */
  11007. memmove(buf, buf + len, body_len - len);
  11008. /* Mark the queue as advanced */
  11009. conn->data_len -= (int)len;
  11010. }
  11011. /* Apply mask if necessary */
  11012. if (mask_len > 0) {
  11013. for (i = 0; i < (size_t)data_len; i++) {
  11014. data[i] ^= mask[i & 3];
  11015. }
  11016. }
  11017. exit_by_callback = 0;
  11018. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11019. /* filter PONG messages */
  11020. DEBUG_TRACE("PONG from %s:%u",
  11021. conn->request_info.remote_addr,
  11022. conn->request_info.remote_port);
  11023. /* No unanwered PINGs left */
  11024. ping_count = 0;
  11025. } else if (enable_ping_pong
  11026. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11027. /* reply PING messages */
  11028. DEBUG_TRACE("Reply PING from %s:%u",
  11029. conn->request_info.remote_addr,
  11030. conn->request_info.remote_port);
  11031. ret = mg_websocket_write(conn,
  11032. MG_WEBSOCKET_OPCODE_PONG,
  11033. (char *)data,
  11034. (size_t)data_len);
  11035. if (ret <= 0) {
  11036. /* Error: send failed */
  11037. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11038. break;
  11039. }
  11040. } else {
  11041. /* Exit the loop if callback signals to exit (server side),
  11042. * or "connection close" opcode received (client side). */
  11043. if ((ws_data_handler != NULL)
  11044. && !ws_data_handler(conn,
  11045. mop,
  11046. (char *)data,
  11047. (size_t)data_len,
  11048. callback_data)) {
  11049. exit_by_callback = 1;
  11050. }
  11051. }
  11052. /* It a buffer has been allocated, free it again */
  11053. if (data != mem) {
  11054. mg_free(data);
  11055. }
  11056. if (exit_by_callback) {
  11057. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11058. conn->request_info.remote_addr,
  11059. conn->request_info.remote_port);
  11060. break;
  11061. }
  11062. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11063. /* Opcode == 8, connection close */
  11064. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11065. conn->request_info.remote_addr,
  11066. conn->request_info.remote_port);
  11067. break;
  11068. }
  11069. /* Not breaking the loop, process next websocket frame. */
  11070. } else {
  11071. /* Read from the socket into the next available location in the
  11072. * message queue. */
  11073. n = pull_inner(NULL,
  11074. conn,
  11075. conn->buf + conn->data_len,
  11076. conn->buf_size - conn->data_len,
  11077. timeout);
  11078. if (n <= -2) {
  11079. /* Error, no bytes read */
  11080. DEBUG_TRACE("PULL from %s:%u failed",
  11081. conn->request_info.remote_addr,
  11082. conn->request_info.remote_port);
  11083. break;
  11084. }
  11085. if (n > 0) {
  11086. conn->data_len += n;
  11087. /* Reset open PING count */
  11088. ping_count = 0;
  11089. } else {
  11090. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  11091. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11092. /* Stop sending PING */
  11093. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11094. "- closing connection",
  11095. ping_count,
  11096. conn->request_info.remote_addr,
  11097. conn->request_info.remote_port);
  11098. break;
  11099. }
  11100. if (enable_ping_pong) {
  11101. /* Send Websocket PING message */
  11102. DEBUG_TRACE("PING to %s:%u",
  11103. conn->request_info.remote_addr,
  11104. conn->request_info.remote_port);
  11105. ret = mg_websocket_write(conn,
  11106. MG_WEBSOCKET_OPCODE_PING,
  11107. NULL,
  11108. 0);
  11109. if (ret <= 0) {
  11110. /* Error: send failed */
  11111. DEBUG_TRACE("Send PING failed (%i)", ret);
  11112. break;
  11113. }
  11114. ping_count++;
  11115. }
  11116. }
  11117. /* Timeout: should retry */
  11118. /* TODO: get timeout def */
  11119. }
  11120. }
  11121. }
  11122. /* Leave data processing loop */
  11123. mg_set_thread_name("worker");
  11124. conn->in_websocket_handling = 0;
  11125. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11126. conn->request_info.remote_addr,
  11127. conn->request_info.remote_port);
  11128. }
  11129. static int
  11130. mg_websocket_write_exec(struct mg_connection *conn,
  11131. int opcode,
  11132. const char *data,
  11133. size_t dataLen,
  11134. uint32_t masking_key)
  11135. {
  11136. unsigned char header[14];
  11137. size_t headerLen;
  11138. int retval;
  11139. #if defined(GCC_DIAGNOSTIC)
  11140. /* Disable spurious conversion warning for GCC */
  11141. #pragma GCC diagnostic push
  11142. #pragma GCC diagnostic ignored "-Wconversion"
  11143. #endif
  11144. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11145. #if defined(GCC_DIAGNOSTIC)
  11146. #pragma GCC diagnostic pop
  11147. #endif
  11148. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11149. if (dataLen < 126) {
  11150. /* inline 7-bit length field */
  11151. header[1] = (unsigned char)dataLen;
  11152. headerLen = 2;
  11153. } else if (dataLen <= 0xFFFF) {
  11154. /* 16-bit length field */
  11155. uint16_t len = htons((uint16_t)dataLen);
  11156. header[1] = 126;
  11157. memcpy(header + 2, &len, 2);
  11158. headerLen = 4;
  11159. } else {
  11160. /* 64-bit length field */
  11161. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11162. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11163. header[1] = 127;
  11164. memcpy(header + 2, &len1, 4);
  11165. memcpy(header + 6, &len2, 4);
  11166. headerLen = 10;
  11167. }
  11168. if (masking_key) {
  11169. /* add mask */
  11170. header[1] |= 0x80;
  11171. memcpy(header + headerLen, &masking_key, 4);
  11172. headerLen += 4;
  11173. }
  11174. /* Note that POSIX/Winsock's send() is threadsafe
  11175. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11176. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11177. * push(), although that is only a problem if the packet is large or
  11178. * outgoing buffer is full). */
  11179. /* TODO: Check if this lock should be moved to user land.
  11180. * Currently the server sets this lock for websockets, but
  11181. * not for any other connection. It must be set for every
  11182. * conn read/written by more than one thread, no matter if
  11183. * it is a websocket or regular connection. */
  11184. (void)mg_lock_connection(conn);
  11185. retval = mg_write(conn, header, headerLen);
  11186. if (retval != (int)headerLen) {
  11187. /* Did not send complete header */
  11188. retval = -1;
  11189. } else {
  11190. if (dataLen > 0) {
  11191. retval = mg_write(conn, data, dataLen);
  11192. }
  11193. /* if dataLen == 0, the header length (2) is returned */
  11194. }
  11195. /* TODO: Remove this unlock as well, when lock is removed. */
  11196. mg_unlock_connection(conn);
  11197. return retval;
  11198. }
  11199. int
  11200. mg_websocket_write(struct mg_connection *conn,
  11201. int opcode,
  11202. const char *data,
  11203. size_t dataLen)
  11204. {
  11205. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11206. }
  11207. static void
  11208. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11209. {
  11210. size_t i = 0;
  11211. i = 0;
  11212. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11213. /* Convert in 32 bit words, if data is 4 byte aligned */
  11214. while (i < (in_len - 3)) {
  11215. *(uint32_t *)(void *)(out + i) =
  11216. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11217. i += 4;
  11218. }
  11219. }
  11220. if (i != in_len) {
  11221. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11222. while (i < in_len) {
  11223. *(uint8_t *)(void *)(out + i) =
  11224. *(uint8_t *)(void *)(in + i)
  11225. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11226. i++;
  11227. }
  11228. }
  11229. }
  11230. int
  11231. mg_websocket_client_write(struct mg_connection *conn,
  11232. int opcode,
  11233. const char *data,
  11234. size_t dataLen)
  11235. {
  11236. int retval = -1;
  11237. char *masked_data =
  11238. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11239. uint32_t masking_key = 0;
  11240. if (masked_data == NULL) {
  11241. /* Return -1 in an error case */
  11242. mg_cry_internal(conn,
  11243. "%s",
  11244. "Cannot allocate buffer for masked websocket response: "
  11245. "Out of memory");
  11246. return -1;
  11247. }
  11248. do {
  11249. /* Get a masking key - but not 0 */
  11250. masking_key = (uint32_t)get_random();
  11251. } while (masking_key == 0);
  11252. mask_data(data, dataLen, masking_key, masked_data);
  11253. retval = mg_websocket_write_exec(
  11254. conn, opcode, masked_data, dataLen, masking_key);
  11255. mg_free(masked_data);
  11256. return retval;
  11257. }
  11258. static void
  11259. handle_websocket_request(struct mg_connection *conn,
  11260. const char *path,
  11261. int is_callback_resource,
  11262. struct mg_websocket_subprotocols *subprotocols,
  11263. mg_websocket_connect_handler ws_connect_handler,
  11264. mg_websocket_ready_handler ws_ready_handler,
  11265. mg_websocket_data_handler ws_data_handler,
  11266. mg_websocket_close_handler ws_close_handler,
  11267. void *cbData)
  11268. {
  11269. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11270. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11271. ptrdiff_t lua_websock = 0;
  11272. #if !defined(USE_LUA)
  11273. (void)path;
  11274. #endif
  11275. /* Step 1: Check websocket protocol version. */
  11276. /* Step 1.1: Check Sec-WebSocket-Key. */
  11277. if (!websock_key) {
  11278. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11279. * requires a Sec-WebSocket-Key header.
  11280. */
  11281. /* It could be the hixie draft version
  11282. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11283. */
  11284. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11285. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11286. char key3[8];
  11287. if ((key1 != NULL) && (key2 != NULL)) {
  11288. /* This version uses 8 byte body data in a GET request */
  11289. conn->content_len = 8;
  11290. if (8 == mg_read(conn, key3, 8)) {
  11291. /* This is the hixie version */
  11292. mg_send_http_error(conn,
  11293. 426,
  11294. "%s",
  11295. "Protocol upgrade to RFC 6455 required");
  11296. return;
  11297. }
  11298. }
  11299. /* This is an unknown version */
  11300. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11301. return;
  11302. }
  11303. /* Step 1.2: Check websocket protocol version. */
  11304. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11305. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11306. /* Reject wrong versions */
  11307. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11308. return;
  11309. }
  11310. /* Step 1.3: Could check for "Host", but we do not really nead this
  11311. * value for anything, so just ignore it. */
  11312. /* Step 2: If a callback is responsible, call it. */
  11313. if (is_callback_resource) {
  11314. /* Step 2.1 check and select subprotocol */
  11315. const char *protocols[64]; // max 64 headers
  11316. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11317. "Sec-WebSocket-Protocol",
  11318. protocols,
  11319. 64);
  11320. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11321. int cnt = 0;
  11322. int idx;
  11323. unsigned long len;
  11324. const char *sep, *curSubProtocol,
  11325. *acceptedWebSocketSubprotocol = NULL;
  11326. /* look for matching subprotocol */
  11327. do {
  11328. const char *protocol = protocols[cnt];
  11329. do {
  11330. sep = strchr(protocol, ',');
  11331. curSubProtocol = protocol;
  11332. len = sep ? (unsigned long)(sep - protocol)
  11333. : (unsigned long)strlen(protocol);
  11334. while (sep && isspace((unsigned char)*++sep))
  11335. ; // ignore leading whitespaces
  11336. protocol = sep;
  11337. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11338. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11339. && (strncmp(curSubProtocol,
  11340. subprotocols->subprotocols[idx],
  11341. len)
  11342. == 0)) {
  11343. acceptedWebSocketSubprotocol =
  11344. subprotocols->subprotocols[idx];
  11345. break;
  11346. }
  11347. }
  11348. } while (sep && !acceptedWebSocketSubprotocol);
  11349. } while (++cnt < nbSubprotocolHeader
  11350. && !acceptedWebSocketSubprotocol);
  11351. conn->request_info.acceptedWebSocketSubprotocol =
  11352. acceptedWebSocketSubprotocol;
  11353. } else if (nbSubprotocolHeader > 0) {
  11354. /* keep legacy behavior */
  11355. const char *protocol = protocols[0];
  11356. /* The protocol is a comma separated list of names. */
  11357. /* The server must only return one value from this list. */
  11358. /* First check if it is a list or just a single value. */
  11359. const char *sep = strrchr(protocol, ',');
  11360. if (sep == NULL) {
  11361. /* Just a single protocol -> accept it. */
  11362. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11363. } else {
  11364. /* Multiple protocols -> accept the last one. */
  11365. /* This is just a quick fix if the client offers multiple
  11366. * protocols. The handler should have a list of accepted
  11367. * protocols on his own
  11368. * and use it to select one protocol among those the client
  11369. * has
  11370. * offered.
  11371. */
  11372. while (isspace((unsigned char)*++sep)) {
  11373. ; /* ignore leading whitespaces */
  11374. }
  11375. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11376. }
  11377. }
  11378. if ((ws_connect_handler != NULL)
  11379. && (ws_connect_handler(conn, cbData) != 0)) {
  11380. /* C callback has returned non-zero, do not proceed with
  11381. * handshake.
  11382. */
  11383. /* Note that C callbacks are no longer called when Lua is
  11384. * responsible, so C can no longer filter callbacks for Lua. */
  11385. return;
  11386. }
  11387. }
  11388. #if defined(USE_LUA)
  11389. /* Step 3: No callback. Check if Lua is responsible. */
  11390. else {
  11391. /* Step 3.1: Check if Lua is responsible. */
  11392. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11393. lua_websock = match_prefix(
  11394. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11395. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11396. path);
  11397. }
  11398. if (lua_websock) {
  11399. /* Step 3.2: Lua is responsible: call it. */
  11400. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11401. if (!conn->lua_websocket_state) {
  11402. /* Lua rejected the new client */
  11403. return;
  11404. }
  11405. }
  11406. }
  11407. #endif
  11408. /* Step 4: Check if there is a responsible websocket handler. */
  11409. if (!is_callback_resource && !lua_websock) {
  11410. /* There is no callback, and Lua is not responsible either. */
  11411. /* Reply with a 404 Not Found. We are still at a standard
  11412. * HTTP request here, before the websocket handshake, so
  11413. * we can still send standard HTTP error replies. */
  11414. mg_send_http_error(conn, 404, "%s", "Not found");
  11415. return;
  11416. }
  11417. /* Step 5: The websocket connection has been accepted */
  11418. if (!send_websocket_handshake(conn, websock_key)) {
  11419. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11420. return;
  11421. }
  11422. /* Step 6: Call the ready handler */
  11423. if (is_callback_resource) {
  11424. if (ws_ready_handler != NULL) {
  11425. ws_ready_handler(conn, cbData);
  11426. }
  11427. #if defined(USE_LUA)
  11428. } else if (lua_websock) {
  11429. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11430. /* the ready handler returned false */
  11431. return;
  11432. }
  11433. #endif
  11434. }
  11435. /* Step 7: Enter the read loop */
  11436. if (is_callback_resource) {
  11437. read_websocket(conn, ws_data_handler, cbData);
  11438. #if defined(USE_LUA)
  11439. } else if (lua_websock) {
  11440. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11441. #endif
  11442. }
  11443. /* Step 8: Call the close handler */
  11444. if (ws_close_handler) {
  11445. ws_close_handler(conn, cbData);
  11446. }
  11447. }
  11448. static int
  11449. is_websocket_protocol(const struct mg_connection *conn)
  11450. {
  11451. const char *upgrade, *connection;
  11452. /* A websocket protocoll has the following HTTP headers:
  11453. *
  11454. * Connection: Upgrade
  11455. * Upgrade: Websocket
  11456. */
  11457. upgrade = mg_get_header(conn, "Upgrade");
  11458. if (upgrade == NULL) {
  11459. return 0; /* fail early, don't waste time checking other header
  11460. * fields
  11461. */
  11462. }
  11463. DEBUG_TRACE("Upgrade: %s", upgrade);
  11464. if (!mg_strcasestr(upgrade, "websocket")) {
  11465. return 0;
  11466. }
  11467. connection = mg_get_header(conn, "Connection");
  11468. if (connection == NULL) {
  11469. return 0;
  11470. }
  11471. if (!mg_strcasestr(connection, "upgrade")) {
  11472. return 0;
  11473. }
  11474. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11475. * "Sec-WebSocket-Version" are also required.
  11476. * Don't check them here, since even an unsupported websocket protocol
  11477. * request still IS a websocket request (in contrast to a standard HTTP
  11478. * request). It will fail later in handle_websocket_request.
  11479. */
  11480. return 1;
  11481. }
  11482. #endif /* !USE_WEBSOCKET */
  11483. static int
  11484. isbyte(int n)
  11485. {
  11486. return (n >= 0) && (n <= 255);
  11487. }
  11488. static int
  11489. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11490. {
  11491. int n, a, b, c, d, slash = 32, len = 0;
  11492. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11493. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11494. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11495. && (slash < 33)) {
  11496. len = n;
  11497. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11498. | (uint32_t)d;
  11499. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11500. }
  11501. return len;
  11502. }
  11503. static int
  11504. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11505. {
  11506. int throttle = 0;
  11507. struct vec vec, val;
  11508. uint32_t net, mask;
  11509. char mult;
  11510. double v;
  11511. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11512. mult = ',';
  11513. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11514. || (v < 0)
  11515. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11516. && (mult != ','))) {
  11517. continue;
  11518. }
  11519. v *= (lowercase(&mult) == 'k')
  11520. ? 1024
  11521. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11522. if (vec.len == 1 && vec.ptr[0] == '*') {
  11523. throttle = (int)v;
  11524. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11525. if ((remote_ip & mask) == net) {
  11526. throttle = (int)v;
  11527. }
  11528. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11529. throttle = (int)v;
  11530. }
  11531. }
  11532. return throttle;
  11533. }
  11534. static uint32_t
  11535. get_remote_ip(const struct mg_connection *conn)
  11536. {
  11537. if (!conn) {
  11538. return 0;
  11539. }
  11540. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11541. }
  11542. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11543. #include "handle_form.inl"
  11544. #if defined(MG_LEGACY_INTERFACE)
  11545. /* Implement the deprecated mg_upload function by calling the new
  11546. * mg_handle_form_request function. While mg_upload could only handle
  11547. * HTML forms sent as POST request in multipart/form-data format
  11548. * containing only file input elements, mg_handle_form_request can
  11549. * handle all form input elements and all standard request methods. */
  11550. struct mg_upload_user_data {
  11551. struct mg_connection *conn;
  11552. const char *destination_dir;
  11553. int num_uploaded_files;
  11554. };
  11555. /* Helper function for deprecated mg_upload. */
  11556. static int
  11557. mg_upload_field_found(const char *key,
  11558. const char *filename,
  11559. char *path,
  11560. size_t pathlen,
  11561. void *user_data)
  11562. {
  11563. int truncated = 0;
  11564. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11565. (void)key;
  11566. if (!filename) {
  11567. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11568. return FORM_FIELD_STORAGE_ABORT;
  11569. }
  11570. mg_snprintf(fud->conn,
  11571. &truncated,
  11572. path,
  11573. pathlen - 1,
  11574. "%s/%s",
  11575. fud->destination_dir,
  11576. filename);
  11577. if (truncated) {
  11578. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11579. return FORM_FIELD_STORAGE_ABORT;
  11580. }
  11581. return FORM_FIELD_STORAGE_STORE;
  11582. }
  11583. /* Helper function for deprecated mg_upload. */
  11584. static int
  11585. mg_upload_field_get(const char *key,
  11586. const char *value,
  11587. size_t value_size,
  11588. void *user_data)
  11589. {
  11590. /* Function should never be called */
  11591. (void)key;
  11592. (void)value;
  11593. (void)value_size;
  11594. (void)user_data;
  11595. return 0;
  11596. }
  11597. /* Helper function for deprecated mg_upload. */
  11598. static int
  11599. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11600. {
  11601. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11602. (void)file_size;
  11603. fud->num_uploaded_files++;
  11604. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11605. return 0;
  11606. }
  11607. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11608. int
  11609. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11610. {
  11611. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11612. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11613. mg_upload_field_get,
  11614. mg_upload_field_stored,
  11615. 0};
  11616. int ret;
  11617. fdh.user_data = (void *)&fud;
  11618. ret = mg_handle_form_request(conn, &fdh);
  11619. if (ret < 0) {
  11620. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11621. }
  11622. return fud.num_uploaded_files;
  11623. }
  11624. #endif
  11625. static int
  11626. get_first_ssl_listener_index(const struct mg_context *ctx)
  11627. {
  11628. unsigned int i;
  11629. int idx = -1;
  11630. if (ctx) {
  11631. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11632. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11633. }
  11634. }
  11635. return idx;
  11636. }
  11637. /* Return host (without port) */
  11638. /* Use mg_free to free the result */
  11639. static const char *
  11640. alloc_get_host(struct mg_connection *conn)
  11641. {
  11642. char buf[1025];
  11643. size_t buflen = sizeof(buf);
  11644. const char *host_header = get_header(conn->request_info.http_headers,
  11645. conn->request_info.num_headers,
  11646. "Host");
  11647. char *host;
  11648. if (host_header != NULL) {
  11649. char *pos;
  11650. /* Create a local copy of the "Host" header, since it might be
  11651. * modified here. */
  11652. mg_strlcpy(buf, host_header, buflen);
  11653. buf[buflen - 1] = '\0';
  11654. host = buf;
  11655. while (isspace((unsigned char)*host)) {
  11656. host++;
  11657. }
  11658. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11659. * is found. */
  11660. if (*host == '[') {
  11661. pos = strchr(host, ']');
  11662. if (!pos) {
  11663. /* Malformed hostname starts with '[', but no ']' found */
  11664. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11665. return NULL;
  11666. }
  11667. /* terminate after ']' */
  11668. pos[1] = 0;
  11669. } else {
  11670. /* Otherwise, a ':' separates hostname and port number */
  11671. pos = strchr(host, ':');
  11672. if (pos != NULL) {
  11673. *pos = '\0';
  11674. }
  11675. }
  11676. if (conn->ssl) {
  11677. /* This is a HTTPS connection, maybe we have a hostname
  11678. * from SNI (set in ssl_servername_callback). */
  11679. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11680. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11681. /* We are not using the default domain */
  11682. if (mg_strcasecmp(host, sslhost)) {
  11683. /* Mismatch between SNI domain and HTTP domain */
  11684. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11685. sslhost,
  11686. host);
  11687. return NULL;
  11688. }
  11689. }
  11690. DEBUG_TRACE("HTTPS Host: %s", host);
  11691. } else {
  11692. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11693. while (dom) {
  11694. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11695. /* Found matching domain */
  11696. DEBUG_TRACE("HTTP domain %s found",
  11697. dom->config[AUTHENTICATION_DOMAIN]);
  11698. /* TODO: Check if this is a HTTP or HTTPS domain */
  11699. conn->dom_ctx = dom;
  11700. break;
  11701. }
  11702. dom = dom->next;
  11703. }
  11704. DEBUG_TRACE("HTTP Host: %s", host);
  11705. }
  11706. } else {
  11707. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11708. host = buf;
  11709. DEBUG_TRACE("IP: %s", host);
  11710. }
  11711. return mg_strdup_ctx(host, conn->phys_ctx);
  11712. }
  11713. static void
  11714. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11715. {
  11716. char target_url[MG_BUF_LEN];
  11717. int truncated = 0;
  11718. conn->must_close = 1;
  11719. /* Send host, port, uri and (if it exists) ?query_string */
  11720. if (conn->host) {
  11721. /* Use "308 Permanent Redirect" */
  11722. int redirect_code = 308;
  11723. /* Create target URL */
  11724. mg_snprintf(
  11725. conn,
  11726. &truncated,
  11727. target_url,
  11728. sizeof(target_url),
  11729. "https://%s:%d%s%s%s",
  11730. conn->host,
  11731. #if defined(USE_IPV6)
  11732. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11733. == AF_INET6)
  11734. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11735. .lsa.sin6.sin6_port)
  11736. :
  11737. #endif
  11738. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11739. .lsa.sin.sin_port),
  11740. conn->request_info.local_uri,
  11741. (conn->request_info.query_string == NULL) ? "" : "?",
  11742. (conn->request_info.query_string == NULL)
  11743. ? ""
  11744. : conn->request_info.query_string);
  11745. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11746. * is used as buffer size) */
  11747. if (truncated) {
  11748. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11749. return;
  11750. }
  11751. /* Use redirect helper function */
  11752. mg_send_http_redirect(conn, target_url, redirect_code);
  11753. }
  11754. }
  11755. static void
  11756. handler_info_acquire(struct mg_handler_info *handler_info)
  11757. {
  11758. pthread_mutex_lock(&handler_info->refcount_mutex);
  11759. handler_info->refcount++;
  11760. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11761. }
  11762. static void
  11763. handler_info_release(struct mg_handler_info *handler_info)
  11764. {
  11765. pthread_mutex_lock(&handler_info->refcount_mutex);
  11766. handler_info->refcount--;
  11767. pthread_cond_signal(&handler_info->refcount_cond);
  11768. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11769. }
  11770. static void
  11771. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11772. {
  11773. pthread_mutex_lock(&handler_info->refcount_mutex);
  11774. while (handler_info->refcount) {
  11775. pthread_cond_wait(&handler_info->refcount_cond,
  11776. &handler_info->refcount_mutex);
  11777. }
  11778. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11779. }
  11780. static void
  11781. mg_set_handler_type(struct mg_context *phys_ctx,
  11782. struct mg_domain_context *dom_ctx,
  11783. const char *uri,
  11784. int handler_type,
  11785. int is_delete_request,
  11786. mg_request_handler handler,
  11787. struct mg_websocket_subprotocols *subprotocols,
  11788. mg_websocket_connect_handler connect_handler,
  11789. mg_websocket_ready_handler ready_handler,
  11790. mg_websocket_data_handler data_handler,
  11791. mg_websocket_close_handler close_handler,
  11792. mg_authorization_handler auth_handler,
  11793. void *cbdata)
  11794. {
  11795. struct mg_handler_info *tmp_rh, **lastref;
  11796. size_t urilen = strlen(uri);
  11797. struct mg_workerTLS tls;
  11798. int is_tls_set = 0;
  11799. if (handler_type == WEBSOCKET_HANDLER) {
  11800. DEBUG_ASSERT(handler == NULL);
  11801. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11802. || ready_handler != NULL || data_handler != NULL
  11803. || close_handler != NULL);
  11804. DEBUG_ASSERT(auth_handler == NULL);
  11805. if (handler != NULL) {
  11806. return;
  11807. }
  11808. if (!is_delete_request && (connect_handler == NULL)
  11809. && (ready_handler == NULL) && (data_handler == NULL)
  11810. && (close_handler == NULL)) {
  11811. return;
  11812. }
  11813. if (auth_handler != NULL) {
  11814. return;
  11815. }
  11816. } else if (handler_type == REQUEST_HANDLER) {
  11817. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11818. && data_handler == NULL && close_handler == NULL);
  11819. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11820. DEBUG_ASSERT(auth_handler == NULL);
  11821. if ((connect_handler != NULL) || (ready_handler != NULL)
  11822. || (data_handler != NULL) || (close_handler != NULL)) {
  11823. return;
  11824. }
  11825. if (!is_delete_request && (handler == NULL)) {
  11826. return;
  11827. }
  11828. if (auth_handler != NULL) {
  11829. return;
  11830. }
  11831. } else { /* AUTH_HANDLER */
  11832. DEBUG_ASSERT(handler == NULL);
  11833. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11834. && data_handler == NULL && close_handler == NULL);
  11835. DEBUG_ASSERT(auth_handler != NULL);
  11836. if (handler != NULL) {
  11837. return;
  11838. }
  11839. if ((connect_handler != NULL) || (ready_handler != NULL)
  11840. || (data_handler != NULL) || (close_handler != NULL)) {
  11841. return;
  11842. }
  11843. if (!is_delete_request && (auth_handler == NULL)) {
  11844. return;
  11845. }
  11846. }
  11847. if (!phys_ctx || !dom_ctx) {
  11848. return;
  11849. }
  11850. /* Internal callbacks have their contexts set
  11851. * if called from non-related thread, context must be set
  11852. * since internal function assumes it exists.
  11853. * For an example see how handler_info_wait_unused()
  11854. * waits for reference to become zero
  11855. */
  11856. if (NULL == pthread_getspecific(sTlsKey)) {
  11857. is_tls_set = 1;
  11858. tls.is_master = -1;
  11859. tls.thread_idx = phys_ctx->starter_thread_idx;
  11860. #if defined(_WIN32)
  11861. tls.pthread_cond_helper_mutex = NULL;
  11862. #endif
  11863. pthread_setspecific(sTlsKey, &tls);
  11864. }
  11865. mg_lock_context(phys_ctx);
  11866. /* first try to find an existing handler */
  11867. lastref = &(dom_ctx->handlers);
  11868. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; 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 (!is_delete_request) {
  11872. /* update existing handler */
  11873. if (handler_type == REQUEST_HANDLER) {
  11874. /* Wait for end of use before updating */
  11875. handler_info_wait_unused(tmp_rh);
  11876. /* Ok, the handler is no more use -> Update it */
  11877. tmp_rh->handler = handler;
  11878. } else if (handler_type == WEBSOCKET_HANDLER) {
  11879. tmp_rh->subprotocols = subprotocols;
  11880. tmp_rh->connect_handler = connect_handler;
  11881. tmp_rh->ready_handler = ready_handler;
  11882. tmp_rh->data_handler = data_handler;
  11883. tmp_rh->close_handler = close_handler;
  11884. } else { /* AUTH_HANDLER */
  11885. tmp_rh->auth_handler = auth_handler;
  11886. }
  11887. tmp_rh->cbdata = cbdata;
  11888. } else {
  11889. /* remove existing handler */
  11890. if (handler_type == REQUEST_HANDLER) {
  11891. /* Wait for end of use before removing */
  11892. handler_info_wait_unused(tmp_rh);
  11893. /* Ok, the handler is no more used -> Destroy
  11894. * resources
  11895. */
  11896. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11897. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11898. }
  11899. *lastref = tmp_rh->next;
  11900. mg_free(tmp_rh->uri);
  11901. mg_free(tmp_rh);
  11902. }
  11903. mg_unlock_context(phys_ctx);
  11904. if (is_tls_set) {
  11905. pthread_setspecific(sTlsKey, NULL);
  11906. }
  11907. return;
  11908. }
  11909. }
  11910. lastref = &(tmp_rh->next);
  11911. }
  11912. if (is_delete_request) {
  11913. /* no handler to set, this was a remove request to a non-existing
  11914. * handler */
  11915. mg_unlock_context(phys_ctx);
  11916. if (is_tls_set) {
  11917. pthread_setspecific(sTlsKey, NULL);
  11918. }
  11919. return;
  11920. }
  11921. tmp_rh =
  11922. (struct mg_handler_info *)mg_calloc_ctx(1,
  11923. sizeof(struct mg_handler_info),
  11924. phys_ctx);
  11925. if (tmp_rh == NULL) {
  11926. mg_unlock_context(phys_ctx);
  11927. mg_cry_ctx_internal(phys_ctx,
  11928. "%s",
  11929. "Cannot create new request handler struct, OOM");
  11930. if (is_tls_set) {
  11931. pthread_setspecific(sTlsKey, NULL);
  11932. }
  11933. return;
  11934. }
  11935. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11936. if (!tmp_rh->uri) {
  11937. mg_unlock_context(phys_ctx);
  11938. mg_free(tmp_rh);
  11939. mg_cry_ctx_internal(phys_ctx,
  11940. "%s",
  11941. "Cannot create new request handler struct, OOM");
  11942. if (is_tls_set) {
  11943. pthread_setspecific(sTlsKey, NULL);
  11944. }
  11945. return;
  11946. }
  11947. tmp_rh->uri_len = urilen;
  11948. if (handler_type == REQUEST_HANDLER) {
  11949. /* Init refcount mutex and condition */
  11950. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11951. mg_unlock_context(phys_ctx);
  11952. mg_free(tmp_rh);
  11953. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11954. if (is_tls_set) {
  11955. pthread_setspecific(sTlsKey, NULL);
  11956. }
  11957. return;
  11958. }
  11959. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11960. mg_unlock_context(phys_ctx);
  11961. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11962. mg_free(tmp_rh);
  11963. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11964. if (is_tls_set) {
  11965. pthread_setspecific(sTlsKey, NULL);
  11966. }
  11967. return;
  11968. }
  11969. tmp_rh->refcount = 0;
  11970. tmp_rh->handler = handler;
  11971. } else if (handler_type == WEBSOCKET_HANDLER) {
  11972. tmp_rh->subprotocols = subprotocols;
  11973. tmp_rh->connect_handler = connect_handler;
  11974. tmp_rh->ready_handler = ready_handler;
  11975. tmp_rh->data_handler = data_handler;
  11976. tmp_rh->close_handler = close_handler;
  11977. } else { /* AUTH_HANDLER */
  11978. tmp_rh->auth_handler = auth_handler;
  11979. }
  11980. tmp_rh->cbdata = cbdata;
  11981. tmp_rh->handler_type = handler_type;
  11982. tmp_rh->next = NULL;
  11983. *lastref = tmp_rh;
  11984. mg_unlock_context(phys_ctx);
  11985. if (is_tls_set) {
  11986. pthread_setspecific(sTlsKey, NULL);
  11987. }
  11988. }
  11989. void
  11990. mg_set_request_handler(struct mg_context *ctx,
  11991. const char *uri,
  11992. mg_request_handler handler,
  11993. void *cbdata)
  11994. {
  11995. mg_set_handler_type(ctx,
  11996. &(ctx->dd),
  11997. uri,
  11998. REQUEST_HANDLER,
  11999. handler == NULL,
  12000. handler,
  12001. NULL,
  12002. NULL,
  12003. NULL,
  12004. NULL,
  12005. NULL,
  12006. NULL,
  12007. cbdata);
  12008. }
  12009. void
  12010. mg_set_websocket_handler(struct mg_context *ctx,
  12011. const char *uri,
  12012. mg_websocket_connect_handler connect_handler,
  12013. mg_websocket_ready_handler ready_handler,
  12014. mg_websocket_data_handler data_handler,
  12015. mg_websocket_close_handler close_handler,
  12016. void *cbdata)
  12017. {
  12018. mg_set_websocket_handler_with_subprotocols(ctx,
  12019. uri,
  12020. NULL,
  12021. connect_handler,
  12022. ready_handler,
  12023. data_handler,
  12024. close_handler,
  12025. cbdata);
  12026. }
  12027. void
  12028. mg_set_websocket_handler_with_subprotocols(
  12029. struct mg_context *ctx,
  12030. const char *uri,
  12031. struct mg_websocket_subprotocols *subprotocols,
  12032. mg_websocket_connect_handler connect_handler,
  12033. mg_websocket_ready_handler ready_handler,
  12034. mg_websocket_data_handler data_handler,
  12035. mg_websocket_close_handler close_handler,
  12036. void *cbdata)
  12037. {
  12038. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12039. && (data_handler == NULL)
  12040. && (close_handler == NULL);
  12041. mg_set_handler_type(ctx,
  12042. &(ctx->dd),
  12043. uri,
  12044. WEBSOCKET_HANDLER,
  12045. is_delete_request,
  12046. NULL,
  12047. subprotocols,
  12048. connect_handler,
  12049. ready_handler,
  12050. data_handler,
  12051. close_handler,
  12052. NULL,
  12053. cbdata);
  12054. }
  12055. void
  12056. mg_set_auth_handler(struct mg_context *ctx,
  12057. const char *uri,
  12058. mg_authorization_handler handler,
  12059. void *cbdata)
  12060. {
  12061. mg_set_handler_type(ctx,
  12062. &(ctx->dd),
  12063. uri,
  12064. AUTH_HANDLER,
  12065. handler == NULL,
  12066. NULL,
  12067. NULL,
  12068. NULL,
  12069. NULL,
  12070. NULL,
  12071. NULL,
  12072. handler,
  12073. cbdata);
  12074. }
  12075. static int
  12076. get_request_handler(struct mg_connection *conn,
  12077. int handler_type,
  12078. mg_request_handler *handler,
  12079. struct mg_websocket_subprotocols **subprotocols,
  12080. mg_websocket_connect_handler *connect_handler,
  12081. mg_websocket_ready_handler *ready_handler,
  12082. mg_websocket_data_handler *data_handler,
  12083. mg_websocket_close_handler *close_handler,
  12084. mg_authorization_handler *auth_handler,
  12085. void **cbdata,
  12086. struct mg_handler_info **handler_info)
  12087. {
  12088. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12089. if (request_info) {
  12090. const char *uri = request_info->local_uri;
  12091. size_t urilen = strlen(uri);
  12092. struct mg_handler_info *tmp_rh;
  12093. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12094. return 0;
  12095. }
  12096. mg_lock_context(conn->phys_ctx);
  12097. /* first try for an exact match */
  12098. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12099. tmp_rh = tmp_rh->next) {
  12100. if (tmp_rh->handler_type == handler_type) {
  12101. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12102. if (handler_type == WEBSOCKET_HANDLER) {
  12103. *subprotocols = tmp_rh->subprotocols;
  12104. *connect_handler = tmp_rh->connect_handler;
  12105. *ready_handler = tmp_rh->ready_handler;
  12106. *data_handler = tmp_rh->data_handler;
  12107. *close_handler = tmp_rh->close_handler;
  12108. } else if (handler_type == REQUEST_HANDLER) {
  12109. *handler = tmp_rh->handler;
  12110. /* Acquire handler and give it back */
  12111. handler_info_acquire(tmp_rh);
  12112. *handler_info = tmp_rh;
  12113. } else { /* AUTH_HANDLER */
  12114. *auth_handler = tmp_rh->auth_handler;
  12115. }
  12116. *cbdata = tmp_rh->cbdata;
  12117. mg_unlock_context(conn->phys_ctx);
  12118. return 1;
  12119. }
  12120. }
  12121. }
  12122. /* next try for a partial match, we will accept uri/something */
  12123. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12124. tmp_rh = tmp_rh->next) {
  12125. if (tmp_rh->handler_type == handler_type) {
  12126. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  12127. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  12128. if (handler_type == WEBSOCKET_HANDLER) {
  12129. *subprotocols = tmp_rh->subprotocols;
  12130. *connect_handler = tmp_rh->connect_handler;
  12131. *ready_handler = tmp_rh->ready_handler;
  12132. *data_handler = tmp_rh->data_handler;
  12133. *close_handler = tmp_rh->close_handler;
  12134. } else if (handler_type == REQUEST_HANDLER) {
  12135. *handler = tmp_rh->handler;
  12136. /* Acquire handler and give it back */
  12137. handler_info_acquire(tmp_rh);
  12138. *handler_info = tmp_rh;
  12139. } else { /* AUTH_HANDLER */
  12140. *auth_handler = tmp_rh->auth_handler;
  12141. }
  12142. *cbdata = tmp_rh->cbdata;
  12143. mg_unlock_context(conn->phys_ctx);
  12144. return 1;
  12145. }
  12146. }
  12147. }
  12148. /* finally try for pattern match */
  12149. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12150. tmp_rh = tmp_rh->next) {
  12151. if (tmp_rh->handler_type == handler_type) {
  12152. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  12153. if (handler_type == WEBSOCKET_HANDLER) {
  12154. *subprotocols = tmp_rh->subprotocols;
  12155. *connect_handler = tmp_rh->connect_handler;
  12156. *ready_handler = tmp_rh->ready_handler;
  12157. *data_handler = tmp_rh->data_handler;
  12158. *close_handler = tmp_rh->close_handler;
  12159. } else if (handler_type == REQUEST_HANDLER) {
  12160. *handler = tmp_rh->handler;
  12161. /* Acquire handler and give it back */
  12162. handler_info_acquire(tmp_rh);
  12163. *handler_info = tmp_rh;
  12164. } else { /* AUTH_HANDLER */
  12165. *auth_handler = tmp_rh->auth_handler;
  12166. }
  12167. *cbdata = tmp_rh->cbdata;
  12168. mg_unlock_context(conn->phys_ctx);
  12169. return 1;
  12170. }
  12171. }
  12172. }
  12173. mg_unlock_context(conn->phys_ctx);
  12174. }
  12175. return 0; /* none found */
  12176. }
  12177. /* Check if the script file is in a path, allowed for script files.
  12178. * This can be used if uploading files is possible not only for the server
  12179. * admin, and the upload mechanism does not check the file extension.
  12180. */
  12181. static int
  12182. is_in_script_path(const struct mg_connection *conn, const char *path)
  12183. {
  12184. /* TODO (Feature): Add config value for allowed script path.
  12185. * Default: All allowed. */
  12186. (void)conn;
  12187. (void)path;
  12188. return 1;
  12189. }
  12190. #if defined(USE_WEBSOCKET) \
  12191. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12192. static int
  12193. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12194. void *cbdata)
  12195. {
  12196. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12197. if (pcallbacks->websocket_connect) {
  12198. return pcallbacks->websocket_connect(conn);
  12199. }
  12200. /* No handler set - assume "OK" */
  12201. return 0;
  12202. }
  12203. static void
  12204. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12205. {
  12206. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12207. if (pcallbacks->websocket_ready) {
  12208. pcallbacks->websocket_ready(conn);
  12209. }
  12210. }
  12211. static int
  12212. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12213. int bits,
  12214. char *data,
  12215. size_t len,
  12216. void *cbdata)
  12217. {
  12218. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12219. if (pcallbacks->websocket_data) {
  12220. return pcallbacks->websocket_data(conn, bits, data, len);
  12221. }
  12222. /* No handler set - assume "OK" */
  12223. return 1;
  12224. }
  12225. static void
  12226. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12227. void *cbdata)
  12228. {
  12229. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12230. if (pcallbacks->connection_close) {
  12231. pcallbacks->connection_close(conn);
  12232. }
  12233. }
  12234. #endif
  12235. /* This is the heart of the Civetweb's logic.
  12236. * This function is called when the request is read, parsed and validated,
  12237. * and Civetweb must decide what action to take: serve a file, or
  12238. * a directory, or call embedded function, etcetera. */
  12239. static void
  12240. handle_request(struct mg_connection *conn)
  12241. {
  12242. struct mg_request_info *ri = &conn->request_info;
  12243. char path[PATH_MAX];
  12244. int uri_len, ssl_index;
  12245. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12246. is_put_or_delete_request = 0, is_callback_resource = 0;
  12247. int i;
  12248. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12249. mg_request_handler callback_handler = NULL;
  12250. struct mg_handler_info *handler_info = NULL;
  12251. struct mg_websocket_subprotocols *subprotocols;
  12252. mg_websocket_connect_handler ws_connect_handler = NULL;
  12253. mg_websocket_ready_handler ws_ready_handler = NULL;
  12254. mg_websocket_data_handler ws_data_handler = NULL;
  12255. mg_websocket_close_handler ws_close_handler = NULL;
  12256. void *callback_data = NULL;
  12257. mg_authorization_handler auth_handler = NULL;
  12258. void *auth_callback_data = NULL;
  12259. int handler_type;
  12260. time_t curtime = time(NULL);
  12261. char date[64];
  12262. path[0] = 0;
  12263. /* 1. get the request url */
  12264. /* 1.1. split into url and query string */
  12265. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12266. != NULL) {
  12267. *((char *)conn->request_info.query_string++) = '\0';
  12268. }
  12269. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12270. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12271. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12272. if (ssl_index >= 0) {
  12273. redirect_to_https_port(conn, ssl_index);
  12274. } else {
  12275. /* A http to https forward port has been specified,
  12276. * but no https port to forward to. */
  12277. mg_send_http_error(conn,
  12278. 503,
  12279. "%s",
  12280. "Error: SSL forward not configured properly");
  12281. mg_cry_internal(conn,
  12282. "%s",
  12283. "Can not redirect to SSL, no SSL port available");
  12284. }
  12285. return;
  12286. }
  12287. uri_len = (int)strlen(ri->local_uri);
  12288. /* 1.3. decode url (if config says so) */
  12289. if (should_decode_url(conn)) {
  12290. mg_url_decode(
  12291. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12292. }
  12293. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12294. * not possible */
  12295. remove_dot_segments((char *)ri->local_uri);
  12296. /* step 1. completed, the url is known now */
  12297. uri_len = (int)strlen(ri->local_uri);
  12298. DEBUG_TRACE("URL: %s", ri->local_uri);
  12299. /* 2. if this ip has limited speed, set it for this connection */
  12300. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12301. get_remote_ip(conn),
  12302. ri->local_uri);
  12303. /* 3. call a "handle everything" callback, if registered */
  12304. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12305. /* Note that since V1.7 the "begin_request" function is called
  12306. * before an authorization check. If an authorization check is
  12307. * required, use a request_handler instead. */
  12308. i = conn->phys_ctx->callbacks.begin_request(conn);
  12309. if (i > 0) {
  12310. /* callback already processed the request. Store the
  12311. return value as a status code for the access log. */
  12312. conn->status_code = i;
  12313. if (!conn->must_close) {
  12314. discard_unread_request_data(conn);
  12315. }
  12316. return;
  12317. } else if (i == 0) {
  12318. /* civetweb should process the request */
  12319. } else {
  12320. /* unspecified - may change with the next version */
  12321. return;
  12322. }
  12323. }
  12324. /* request not yet handled by a handler or redirect, so the request
  12325. * is processed here */
  12326. /* 4. Check for CORS preflight requests and handle them (if configured).
  12327. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12328. */
  12329. if (!strcmp(ri->request_method, "OPTIONS")) {
  12330. /* Send a response to CORS preflights only if
  12331. * access_control_allow_methods is not NULL and not an empty string.
  12332. * In this case, scripts can still handle CORS. */
  12333. const char *cors_meth_cfg =
  12334. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12335. const char *cors_orig_cfg =
  12336. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12337. const char *cors_origin =
  12338. get_header(ri->http_headers, ri->num_headers, "Origin");
  12339. const char *cors_acrm = get_header(ri->http_headers,
  12340. ri->num_headers,
  12341. "Access-Control-Request-Method");
  12342. /* Todo: check if cors_origin is in cors_orig_cfg.
  12343. * Or, let the client check this. */
  12344. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12345. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12346. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12347. /* This is a valid CORS preflight, and the server is configured
  12348. * to
  12349. * handle it automatically. */
  12350. const char *cors_acrh =
  12351. get_header(ri->http_headers,
  12352. ri->num_headers,
  12353. "Access-Control-Request-Headers");
  12354. gmt_time_string(date, sizeof(date), &curtime);
  12355. mg_printf(conn,
  12356. "HTTP/1.1 200 OK\r\n"
  12357. "Date: %s\r\n"
  12358. "Access-Control-Allow-Origin: %s\r\n"
  12359. "Access-Control-Allow-Methods: %s\r\n"
  12360. "Content-Length: 0\r\n"
  12361. "Connection: %s\r\n",
  12362. date,
  12363. cors_orig_cfg,
  12364. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12365. suggest_connection_header(conn));
  12366. if (cors_acrh != NULL) {
  12367. /* CORS request is asking for additional headers */
  12368. const char *cors_hdr_cfg =
  12369. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12370. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12371. /* Allow only if access_control_allow_headers is
  12372. * not NULL and not an empty string. If this
  12373. * configuration is set to *, allow everything.
  12374. * Otherwise this configuration must be a list
  12375. * of allowed HTTP header names. */
  12376. mg_printf(conn,
  12377. "Access-Control-Allow-Headers: %s\r\n",
  12378. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12379. : cors_hdr_cfg));
  12380. }
  12381. }
  12382. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12383. mg_printf(conn, "\r\n");
  12384. return;
  12385. }
  12386. }
  12387. /* 5. interpret the url to find out how the request must be handled
  12388. */
  12389. /* 5.1. first test, if the request targets the regular http(s)://
  12390. * protocol namespace or the websocket ws(s):// protocol namespace.
  12391. */
  12392. is_websocket_request = is_websocket_protocol(conn);
  12393. #if defined(USE_WEBSOCKET)
  12394. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12395. #else
  12396. handler_type = REQUEST_HANDLER;
  12397. #endif /* defined(USE_WEBSOCKET) */
  12398. /* 5.2. check if the request will be handled by a callback */
  12399. if (get_request_handler(conn,
  12400. handler_type,
  12401. &callback_handler,
  12402. &subprotocols,
  12403. &ws_connect_handler,
  12404. &ws_ready_handler,
  12405. &ws_data_handler,
  12406. &ws_close_handler,
  12407. NULL,
  12408. &callback_data,
  12409. &handler_info)) {
  12410. /* 5.2.1. A callback will handle this request. All requests
  12411. * handled
  12412. * by a callback have to be considered as requests to a script
  12413. * resource. */
  12414. is_callback_resource = 1;
  12415. is_script_resource = 1;
  12416. is_put_or_delete_request = is_put_or_delete_method(conn);
  12417. } else {
  12418. no_callback_resource:
  12419. /* 5.2.2. No callback is responsible for this request. The URI
  12420. * addresses a file based resource (static content or Lua/cgi
  12421. * scripts in the file system). */
  12422. is_callback_resource = 0;
  12423. interpret_uri(conn,
  12424. path,
  12425. sizeof(path),
  12426. &file.stat,
  12427. &is_found,
  12428. &is_script_resource,
  12429. &is_websocket_request,
  12430. &is_put_or_delete_request);
  12431. }
  12432. /* 6. authorization check */
  12433. /* 6.1. a custom authorization handler is installed */
  12434. if (get_request_handler(conn,
  12435. AUTH_HANDLER,
  12436. NULL,
  12437. NULL,
  12438. NULL,
  12439. NULL,
  12440. NULL,
  12441. NULL,
  12442. &auth_handler,
  12443. &auth_callback_data,
  12444. NULL)) {
  12445. if (!auth_handler(conn, auth_callback_data)) {
  12446. return;
  12447. }
  12448. } else if (is_put_or_delete_request && !is_script_resource
  12449. && !is_callback_resource) {
  12450. /* 6.2. this request is a PUT/DELETE to a real file */
  12451. /* 6.2.1. thus, the server must have real files */
  12452. #if defined(NO_FILES)
  12453. if (1) {
  12454. #else
  12455. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12456. #endif
  12457. /* This server does not have any real files, thus the
  12458. * PUT/DELETE methods are not valid. */
  12459. mg_send_http_error(conn,
  12460. 405,
  12461. "%s method not allowed",
  12462. conn->request_info.request_method);
  12463. return;
  12464. }
  12465. #if !defined(NO_FILES)
  12466. /* 6.2.2. Check if put authorization for static files is
  12467. * available.
  12468. */
  12469. if (!is_authorized_for_put(conn)) {
  12470. send_authorization_request(conn, NULL);
  12471. return;
  12472. }
  12473. #endif
  12474. } else {
  12475. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12476. * or it is a PUT or DELETE request to a resource that does not
  12477. * correspond to a file. Check authorization. */
  12478. if (!check_authorization(conn, path)) {
  12479. send_authorization_request(conn, NULL);
  12480. return;
  12481. }
  12482. }
  12483. /* request is authorized or does not need authorization */
  12484. /* 7. check if there are request handlers for this uri */
  12485. if (is_callback_resource) {
  12486. if (!is_websocket_request) {
  12487. i = callback_handler(conn, callback_data);
  12488. /* Callback handler will not be used anymore. Release it */
  12489. handler_info_release(handler_info);
  12490. if (i > 0) {
  12491. /* Do nothing, callback has served the request. Store
  12492. * then return value as status code for the log and discard
  12493. * all data from the client not used by the callback. */
  12494. conn->status_code = i;
  12495. if (!conn->must_close) {
  12496. discard_unread_request_data(conn);
  12497. }
  12498. } else {
  12499. /* The handler did NOT handle the request. */
  12500. /* Some proper reactions would be:
  12501. * a) close the connections without sending anything
  12502. * b) send a 404 not found
  12503. * c) try if there is a file matching the URI
  12504. * It would be possible to do a, b or c in the callback
  12505. * implementation, and return 1 - we cannot do anything
  12506. * here, that is not possible in the callback.
  12507. *
  12508. * TODO: What would be the best reaction here?
  12509. * (Note: The reaction may change, if there is a better
  12510. *idea.)
  12511. */
  12512. /* For the moment, use option c: We look for a proper file,
  12513. * but since a file request is not always a script resource,
  12514. * the authorization check might be different. */
  12515. interpret_uri(conn,
  12516. path,
  12517. sizeof(path),
  12518. &file.stat,
  12519. &is_found,
  12520. &is_script_resource,
  12521. &is_websocket_request,
  12522. &is_put_or_delete_request);
  12523. callback_handler = NULL;
  12524. /* Here we are at a dead end:
  12525. * According to URI matching, a callback should be
  12526. * responsible for handling the request,
  12527. * we called it, but the callback declared itself
  12528. * not responsible.
  12529. * We use a goto here, to get out of this dead end,
  12530. * and continue with the default handling.
  12531. * A goto here is simpler and better to understand
  12532. * than some curious loop. */
  12533. goto no_callback_resource;
  12534. }
  12535. } else {
  12536. #if defined(USE_WEBSOCKET)
  12537. handle_websocket_request(conn,
  12538. path,
  12539. is_callback_resource,
  12540. subprotocols,
  12541. ws_connect_handler,
  12542. ws_ready_handler,
  12543. ws_data_handler,
  12544. ws_close_handler,
  12545. callback_data);
  12546. #endif
  12547. }
  12548. return;
  12549. }
  12550. /* 8. handle websocket requests */
  12551. #if defined(USE_WEBSOCKET)
  12552. if (is_websocket_request) {
  12553. if (is_script_resource) {
  12554. if (is_in_script_path(conn, path)) {
  12555. /* Websocket Lua script */
  12556. handle_websocket_request(conn,
  12557. path,
  12558. 0 /* Lua Script */,
  12559. NULL,
  12560. NULL,
  12561. NULL,
  12562. NULL,
  12563. NULL,
  12564. conn->phys_ctx->user_data);
  12565. } else {
  12566. /* Script was in an illegal path */
  12567. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12568. }
  12569. } else {
  12570. #if defined(MG_LEGACY_INTERFACE)
  12571. handle_websocket_request(
  12572. conn,
  12573. path,
  12574. !is_script_resource /* could be deprecated global callback
  12575. */
  12576. ,
  12577. NULL,
  12578. deprecated_websocket_connect_wrapper,
  12579. deprecated_websocket_ready_wrapper,
  12580. deprecated_websocket_data_wrapper,
  12581. NULL,
  12582. conn->phys_ctx->callbacks);
  12583. #else
  12584. mg_send_http_error(conn, 404, "%s", "Not found");
  12585. #endif
  12586. }
  12587. return;
  12588. } else
  12589. #endif
  12590. #if defined(NO_FILES)
  12591. /* 9a. In case the server uses only callbacks, this uri is
  12592. * unknown.
  12593. * Then, all request handling ends here. */
  12594. mg_send_http_error(conn, 404, "%s", "Not Found");
  12595. #else
  12596. /* 9b. This request is either for a static file or resource handled
  12597. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12598. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12599. mg_send_http_error(conn, 404, "%s", "Not Found");
  12600. return;
  12601. }
  12602. /* 10. Request is handled by a script */
  12603. if (is_script_resource) {
  12604. handle_file_based_request(conn, path, &file);
  12605. return;
  12606. }
  12607. /* 11. Handle put/delete/mkcol requests */
  12608. if (is_put_or_delete_request) {
  12609. /* 11.1. PUT method */
  12610. if (!strcmp(ri->request_method, "PUT")) {
  12611. put_file(conn, path);
  12612. return;
  12613. }
  12614. /* 11.2. DELETE method */
  12615. if (!strcmp(ri->request_method, "DELETE")) {
  12616. delete_file(conn, path);
  12617. return;
  12618. }
  12619. /* 11.3. MKCOL method */
  12620. if (!strcmp(ri->request_method, "MKCOL")) {
  12621. mkcol(conn, path);
  12622. return;
  12623. }
  12624. /* 11.4. PATCH method
  12625. * This method is not supported for static resources,
  12626. * only for scripts (Lua, CGI) and callbacks. */
  12627. mg_send_http_error(conn,
  12628. 405,
  12629. "%s method not allowed",
  12630. conn->request_info.request_method);
  12631. return;
  12632. }
  12633. /* 11. File does not exist, or it was configured that it should be
  12634. * hidden */
  12635. if (!is_found || (must_hide_file(conn, path))) {
  12636. mg_send_http_error(conn, 404, "%s", "Not found");
  12637. return;
  12638. }
  12639. /* 12. Directory uris should end with a slash */
  12640. if (file.stat.is_directory && (uri_len > 0)
  12641. && (ri->local_uri[uri_len - 1] != '/')) {
  12642. gmt_time_string(date, sizeof(date), &curtime);
  12643. mg_printf(conn,
  12644. "HTTP/1.1 301 Moved Permanently\r\n"
  12645. "Location: %s/\r\n"
  12646. "Date: %s\r\n"
  12647. /* "Cache-Control: private\r\n" (= default) */
  12648. "Content-Length: 0\r\n"
  12649. "Connection: %s\r\n",
  12650. ri->request_uri,
  12651. date,
  12652. suggest_connection_header(conn));
  12653. send_additional_header(conn);
  12654. mg_printf(conn, "\r\n");
  12655. return;
  12656. }
  12657. /* 13. Handle other methods than GET/HEAD */
  12658. /* 13.1. Handle PROPFIND */
  12659. if (!strcmp(ri->request_method, "PROPFIND")) {
  12660. handle_propfind(conn, path, &file.stat);
  12661. return;
  12662. }
  12663. /* 13.2. Handle OPTIONS for files */
  12664. if (!strcmp(ri->request_method, "OPTIONS")) {
  12665. /* This standard handler is only used for real files.
  12666. * Scripts should support the OPTIONS method themselves, to allow a
  12667. * maximum flexibility.
  12668. * Lua and CGI scripts may fully support CORS this way (including
  12669. * preflights). */
  12670. send_options(conn);
  12671. return;
  12672. }
  12673. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12674. if ((0 != strcmp(ri->request_method, "GET"))
  12675. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12676. mg_send_http_error(conn,
  12677. 405,
  12678. "%s method not allowed",
  12679. conn->request_info.request_method);
  12680. return;
  12681. }
  12682. /* 14. directories */
  12683. if (file.stat.is_directory) {
  12684. /* Substitute files have already been handled above. */
  12685. /* Here we can either generate and send a directory listing,
  12686. * or send an "access denied" error. */
  12687. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12688. "yes")) {
  12689. handle_directory_request(conn, path);
  12690. } else {
  12691. mg_send_http_error(conn,
  12692. 403,
  12693. "%s",
  12694. "Error: Directory listing denied");
  12695. }
  12696. return;
  12697. }
  12698. /* 15. read a normal file with GET or HEAD */
  12699. handle_file_based_request(conn, path, &file);
  12700. #endif /* !defined(NO_FILES) */
  12701. }
  12702. #ifdef USE_HTTP2
  12703. #include "mod_http2.inl"
  12704. #endif
  12705. #if !defined(NO_FILESYSTEMS)
  12706. static void
  12707. handle_file_based_request(struct mg_connection *conn,
  12708. const char *path,
  12709. struct mg_file *file)
  12710. {
  12711. if (!conn || !conn->dom_ctx) {
  12712. return;
  12713. }
  12714. if (0) {
  12715. #if defined(USE_LUA)
  12716. } else if (match_prefix(
  12717. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12718. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12719. path)
  12720. > 0) {
  12721. if (is_in_script_path(conn, path)) {
  12722. /* Lua server page: an SSI like page containing mostly plain
  12723. * html
  12724. * code
  12725. * plus some tags with server generated contents. */
  12726. handle_lsp_request(conn, path, file, NULL);
  12727. } else {
  12728. /* Script was in an illegal path */
  12729. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12730. }
  12731. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12732. strlen(
  12733. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12734. path)
  12735. > 0) {
  12736. if (is_in_script_path(conn, path)) {
  12737. /* Lua in-server module script: a CGI like script used to
  12738. * generate
  12739. * the
  12740. * entire reply. */
  12741. mg_exec_lua_script(conn, path, NULL);
  12742. } else {
  12743. /* Script was in an illegal path */
  12744. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12745. }
  12746. #endif
  12747. #if defined(USE_DUKTAPE)
  12748. } else if (match_prefix(
  12749. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12750. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12751. path)
  12752. > 0) {
  12753. if (is_in_script_path(conn, path)) {
  12754. /* Call duktape to generate the page */
  12755. mg_exec_duktape_script(conn, path);
  12756. } else {
  12757. /* Script was in an illegal path */
  12758. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12759. }
  12760. #endif
  12761. #if !defined(NO_CGI)
  12762. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12763. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12764. path)
  12765. > 0) {
  12766. if (is_in_script_path(conn, path)) {
  12767. /* CGI scripts may support all HTTP methods */
  12768. handle_cgi_request(conn, path);
  12769. } else {
  12770. /* Script was in an illegal path */
  12771. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12772. }
  12773. #endif /* !NO_CGI */
  12774. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12775. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12776. path)
  12777. > 0) {
  12778. if (is_in_script_path(conn, path)) {
  12779. handle_ssi_file_request(conn, path, file);
  12780. } else {
  12781. /* Script was in an illegal path */
  12782. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12783. }
  12784. #if !defined(NO_CACHING)
  12785. } else if ((!conn->in_error_handler)
  12786. && is_not_modified(conn, &file->stat)) {
  12787. /* Send 304 "Not Modified" - this must not send any body data */
  12788. handle_not_modified_static_file_request(conn, file);
  12789. #endif /* !NO_CACHING */
  12790. } else {
  12791. handle_static_file_request(conn, path, file, NULL, NULL);
  12792. }
  12793. }
  12794. #endif /* NO_FILESYSTEMS */
  12795. static void
  12796. close_all_listening_sockets(struct mg_context *ctx)
  12797. {
  12798. unsigned int i;
  12799. if (!ctx) {
  12800. return;
  12801. }
  12802. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12803. closesocket(ctx->listening_sockets[i].sock);
  12804. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12805. }
  12806. mg_free(ctx->listening_sockets);
  12807. ctx->listening_sockets = NULL;
  12808. mg_free(ctx->listening_socket_fds);
  12809. ctx->listening_socket_fds = NULL;
  12810. }
  12811. /* Valid listening port specification is: [ip_address:]port[s]
  12812. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12813. * Examples for IPv6: [::]:80, [::1]:80,
  12814. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12815. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12816. * In order to bind to both, IPv4 and IPv6, you can either add
  12817. * both ports using 8080,[::]:8080, or the short form +8080.
  12818. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12819. * one only accepting IPv4 the other only IPv6. +8080 creates
  12820. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12821. * environment, they might work differently, or might not work
  12822. * at all - it must be tested what options work best in the
  12823. * relevant network environment.
  12824. */
  12825. static int
  12826. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12827. {
  12828. unsigned int a, b, c, d;
  12829. unsigned port;
  12830. unsigned long portUL;
  12831. int ch, len;
  12832. const char *cb;
  12833. char *endptr;
  12834. #if defined(USE_IPV6)
  12835. char buf[100] = {0};
  12836. #endif
  12837. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12838. * Also, all-zeroes in the socket address means binding to all addresses
  12839. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12840. memset(so, 0, sizeof(*so));
  12841. so->lsa.sin.sin_family = AF_INET;
  12842. *ip_version = 0;
  12843. /* Initialize port and len as invalid. */
  12844. port = 0;
  12845. len = 0;
  12846. /* Test for different ways to format this string */
  12847. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12848. == 5) {
  12849. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12850. so->lsa.sin.sin_addr.s_addr =
  12851. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12852. so->lsa.sin.sin_port = htons((uint16_t)port);
  12853. *ip_version = 4;
  12854. #if defined(USE_IPV6)
  12855. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12856. && mg_inet_pton(
  12857. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12858. /* IPv6 address, examples: see above */
  12859. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12860. */
  12861. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12862. *ip_version = 6;
  12863. #endif
  12864. } else if ((vec->ptr[0] == '+')
  12865. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12866. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12867. /* Add 1 to len for the + character we skipped before */
  12868. len++;
  12869. #if defined(USE_IPV6)
  12870. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12871. so->lsa.sin6.sin6_family = AF_INET6;
  12872. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12873. *ip_version = 4 + 6;
  12874. #else
  12875. /* Bind to IPv4 only, since IPv6 is not built in. */
  12876. so->lsa.sin.sin_port = htons((uint16_t)port);
  12877. *ip_version = 4;
  12878. #endif
  12879. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12880. && (vec->ptr != endptr)) {
  12881. len = (int)(endptr - vec->ptr);
  12882. port = (uint16_t)portUL;
  12883. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12884. so->lsa.sin.sin_port = htons((uint16_t)port);
  12885. *ip_version = 4;
  12886. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12887. /* String could be a hostname. This check algotithm
  12888. * will only work for RFC 952 compliant hostnames,
  12889. * starting with a letter, containing only letters,
  12890. * digits and hyphen ('-'). Newer specs may allow
  12891. * more, but this is not guaranteed here, since it
  12892. * may interfere with rules for port option lists. */
  12893. /* According to RFC 1035, hostnames are restricted to 255 characters
  12894. * in total (63 between two dots). */
  12895. char hostname[256];
  12896. size_t hostnlen = (size_t)(cb - vec->ptr);
  12897. if (hostnlen >= sizeof(hostname)) {
  12898. /* This would be invalid in any case */
  12899. *ip_version = 0;
  12900. return 0;
  12901. }
  12902. memcpy(hostname, vec->ptr, hostnlen);
  12903. hostname[hostnlen] = 0;
  12904. if (mg_inet_pton(
  12905. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12906. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12907. *ip_version = 4;
  12908. so->lsa.sin.sin_family = AF_INET;
  12909. so->lsa.sin.sin_port = htons((uint16_t)port);
  12910. len += (int)(hostnlen + 1);
  12911. } else {
  12912. port = 0;
  12913. len = 0;
  12914. }
  12915. #if defined(USE_IPV6)
  12916. } else if (mg_inet_pton(AF_INET6,
  12917. hostname,
  12918. &so->lsa.sin6,
  12919. sizeof(so->lsa.sin6))) {
  12920. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12921. *ip_version = 6;
  12922. so->lsa.sin6.sin6_family = AF_INET6;
  12923. so->lsa.sin.sin_port = htons((uint16_t)port);
  12924. len += (int)(hostnlen + 1);
  12925. } else {
  12926. port = 0;
  12927. len = 0;
  12928. }
  12929. #endif
  12930. }
  12931. } else {
  12932. /* Parsing failure. */
  12933. }
  12934. /* sscanf and the option splitting code ensure the following condition
  12935. */
  12936. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12937. *ip_version = 0;
  12938. return 0;
  12939. }
  12940. ch = vec->ptr[len]; /* Next character after the port number */
  12941. so->is_ssl = (ch == 's');
  12942. so->ssl_redir = (ch == 'r');
  12943. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12944. if (is_valid_port(port)
  12945. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12946. return 1;
  12947. }
  12948. /* Reset ip_version to 0 if there is an error */
  12949. *ip_version = 0;
  12950. return 0;
  12951. }
  12952. /* Is there any SSL port in use? */
  12953. static int
  12954. is_ssl_port_used(const char *ports)
  12955. {
  12956. if (ports) {
  12957. /* There are several different allowed syntax variants:
  12958. * - "80" for a single port using every network interface
  12959. * - "localhost:80" for a single port using only localhost
  12960. * - "80,localhost:8080" for two ports, one bound to localhost
  12961. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12962. * to IPv4 localhost, one to IPv6 localhost
  12963. * - "+80" use port 80 for IPv4 and IPv6
  12964. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12965. * for both: IPv4 and IPv4
  12966. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12967. * additionally port 8080 bound to localhost connections
  12968. *
  12969. * If we just look for 's' anywhere in the string, "localhost:80"
  12970. * will be detected as SSL (false positive).
  12971. * Looking for 's' after a digit may cause false positives in
  12972. * "my24service:8080".
  12973. * Looking from 's' backward if there are only ':' and numbers
  12974. * before will not work for "24service:8080" (non SSL, port 8080)
  12975. * or "24s" (SSL, port 24).
  12976. *
  12977. * Remark: Initially hostnames were not allowed to start with a
  12978. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12979. * Section 2.1).
  12980. *
  12981. * To get this correct, the entire string must be parsed as a whole,
  12982. * reading it as a list element for element and parsing with an
  12983. * algorithm equivalent to parse_port_string.
  12984. *
  12985. * In fact, we use local interface names here, not arbitrary
  12986. * hostnames, so in most cases the only name will be "localhost".
  12987. *
  12988. * So, for now, we use this simple algorithm, that may still return
  12989. * a false positive in bizarre cases.
  12990. */
  12991. int i;
  12992. int portslen = (int)strlen(ports);
  12993. char prevIsNumber = 0;
  12994. for (i = 0; i < portslen; i++) {
  12995. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12996. return 1;
  12997. }
  12998. if (ports[i] >= '0' && ports[i] <= '9') {
  12999. prevIsNumber = 1;
  13000. } else {
  13001. prevIsNumber = 0;
  13002. }
  13003. }
  13004. }
  13005. return 0;
  13006. }
  13007. static int
  13008. set_ports_option(struct mg_context *phys_ctx)
  13009. {
  13010. const char *list;
  13011. int on = 1;
  13012. #if defined(USE_IPV6)
  13013. int off = 0;
  13014. #endif
  13015. struct vec vec;
  13016. struct socket so, *ptr;
  13017. struct mg_pollfd *pfd;
  13018. union usa usa;
  13019. socklen_t len;
  13020. int ip_version;
  13021. int portsTotal = 0;
  13022. int portsOk = 0;
  13023. const char *opt_txt;
  13024. long opt_listen_backlog;
  13025. if (!phys_ctx) {
  13026. return 0;
  13027. }
  13028. memset(&so, 0, sizeof(so));
  13029. memset(&usa, 0, sizeof(usa));
  13030. len = sizeof(usa);
  13031. list = phys_ctx->dd.config[LISTENING_PORTS];
  13032. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13033. portsTotal++;
  13034. if (!parse_port_string(&vec, &so, &ip_version)) {
  13035. mg_cry_ctx_internal(
  13036. phys_ctx,
  13037. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13038. (int)vec.len,
  13039. vec.ptr,
  13040. portsTotal,
  13041. "[IP_ADDRESS:]PORT[s|r]");
  13042. continue;
  13043. }
  13044. #if !defined(NO_SSL)
  13045. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13046. mg_cry_ctx_internal(phys_ctx,
  13047. "Cannot add SSL socket (entry %i)",
  13048. portsTotal);
  13049. continue;
  13050. }
  13051. #endif
  13052. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13053. == INVALID_SOCKET) {
  13054. mg_cry_ctx_internal(phys_ctx,
  13055. "cannot create socket (entry %i)",
  13056. portsTotal);
  13057. continue;
  13058. }
  13059. #if defined(_WIN32)
  13060. /* Windows SO_REUSEADDR lets many procs binds to a
  13061. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13062. * if someone already has the socket -- DTL */
  13063. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13064. * Windows might need a few seconds before
  13065. * the same port can be used again in the
  13066. * same process, so a short Sleep may be
  13067. * required between mg_stop and mg_start.
  13068. */
  13069. if (setsockopt(so.sock,
  13070. SOL_SOCKET,
  13071. SO_EXCLUSIVEADDRUSE,
  13072. (SOCK_OPT_TYPE)&on,
  13073. sizeof(on))
  13074. != 0) {
  13075. /* Set reuse option, but don't abort on errors. */
  13076. mg_cry_ctx_internal(
  13077. phys_ctx,
  13078. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13079. portsTotal);
  13080. }
  13081. #else
  13082. if (setsockopt(so.sock,
  13083. SOL_SOCKET,
  13084. SO_REUSEADDR,
  13085. (SOCK_OPT_TYPE)&on,
  13086. sizeof(on))
  13087. != 0) {
  13088. /* Set reuse option, but don't abort on errors. */
  13089. mg_cry_ctx_internal(
  13090. phys_ctx,
  13091. "cannot set socket option SO_REUSEADDR (entry %i)",
  13092. portsTotal);
  13093. }
  13094. #endif
  13095. if (ip_version > 4) {
  13096. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13097. #if defined(USE_IPV6)
  13098. if (ip_version > 6) {
  13099. if (so.lsa.sa.sa_family == AF_INET6
  13100. && setsockopt(so.sock,
  13101. IPPROTO_IPV6,
  13102. IPV6_V6ONLY,
  13103. (void *)&off,
  13104. sizeof(off))
  13105. != 0) {
  13106. /* Set IPv6 only option, but don't abort on errors. */
  13107. mg_cry_ctx_internal(phys_ctx,
  13108. "cannot set socket option "
  13109. "IPV6_V6ONLY=off (entry %i)",
  13110. portsTotal);
  13111. }
  13112. } else {
  13113. if (so.lsa.sa.sa_family == AF_INET6
  13114. && setsockopt(so.sock,
  13115. IPPROTO_IPV6,
  13116. IPV6_V6ONLY,
  13117. (void *)&on,
  13118. sizeof(on))
  13119. != 0) {
  13120. /* Set IPv6 only option, but don't abort on errors. */
  13121. mg_cry_ctx_internal(phys_ctx,
  13122. "cannot set socket option "
  13123. "IPV6_V6ONLY=on (entry %i)",
  13124. portsTotal);
  13125. }
  13126. }
  13127. #else
  13128. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13129. closesocket(so.sock);
  13130. so.sock = INVALID_SOCKET;
  13131. continue;
  13132. #endif
  13133. }
  13134. if (so.lsa.sa.sa_family == AF_INET) {
  13135. len = sizeof(so.lsa.sin);
  13136. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13137. mg_cry_ctx_internal(phys_ctx,
  13138. "cannot bind to %.*s: %d (%s)",
  13139. (int)vec.len,
  13140. vec.ptr,
  13141. (int)ERRNO,
  13142. strerror(errno));
  13143. closesocket(so.sock);
  13144. so.sock = INVALID_SOCKET;
  13145. continue;
  13146. }
  13147. }
  13148. #if defined(USE_IPV6)
  13149. else if (so.lsa.sa.sa_family == AF_INET6) {
  13150. len = sizeof(so.lsa.sin6);
  13151. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13152. mg_cry_ctx_internal(phys_ctx,
  13153. "cannot bind to IPv6 %.*s: %d (%s)",
  13154. (int)vec.len,
  13155. vec.ptr,
  13156. (int)ERRNO,
  13157. strerror(errno));
  13158. closesocket(so.sock);
  13159. so.sock = INVALID_SOCKET;
  13160. continue;
  13161. }
  13162. }
  13163. #endif
  13164. else {
  13165. mg_cry_ctx_internal(
  13166. phys_ctx,
  13167. "cannot bind: address family not supported (entry %i)",
  13168. portsTotal);
  13169. closesocket(so.sock);
  13170. so.sock = INVALID_SOCKET;
  13171. continue;
  13172. }
  13173. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13174. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13175. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13176. mg_cry_ctx_internal(phys_ctx,
  13177. "%s value \"%s\" is invalid",
  13178. config_options[LISTEN_BACKLOG_SIZE].name,
  13179. opt_txt);
  13180. continue;
  13181. }
  13182. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13183. mg_cry_ctx_internal(phys_ctx,
  13184. "cannot listen to %.*s: %d (%s)",
  13185. (int)vec.len,
  13186. vec.ptr,
  13187. (int)ERRNO,
  13188. strerror(errno));
  13189. closesocket(so.sock);
  13190. so.sock = INVALID_SOCKET;
  13191. continue;
  13192. }
  13193. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13194. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13195. int err = (int)ERRNO;
  13196. mg_cry_ctx_internal(phys_ctx,
  13197. "call to getsockname failed %.*s: %d (%s)",
  13198. (int)vec.len,
  13199. vec.ptr,
  13200. err,
  13201. strerror(errno));
  13202. closesocket(so.sock);
  13203. so.sock = INVALID_SOCKET;
  13204. continue;
  13205. }
  13206. /* Update lsa port in case of random free ports */
  13207. #if defined(USE_IPV6)
  13208. if (so.lsa.sa.sa_family == AF_INET6) {
  13209. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13210. } else
  13211. #endif
  13212. {
  13213. so.lsa.sin.sin_port = usa.sin.sin_port;
  13214. }
  13215. if ((ptr = (struct socket *)
  13216. mg_realloc_ctx(phys_ctx->listening_sockets,
  13217. (phys_ctx->num_listening_sockets + 1)
  13218. * sizeof(phys_ctx->listening_sockets[0]),
  13219. phys_ctx))
  13220. == NULL) {
  13221. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13222. closesocket(so.sock);
  13223. so.sock = INVALID_SOCKET;
  13224. continue;
  13225. }
  13226. if ((pfd = (struct mg_pollfd *)
  13227. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13228. (phys_ctx->num_listening_sockets + 1)
  13229. * sizeof(phys_ctx->listening_socket_fds[0]),
  13230. phys_ctx))
  13231. == NULL) {
  13232. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13233. closesocket(so.sock);
  13234. so.sock = INVALID_SOCKET;
  13235. mg_free(ptr);
  13236. continue;
  13237. }
  13238. set_close_on_exec(so.sock, NULL, phys_ctx);
  13239. phys_ctx->listening_sockets = ptr;
  13240. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13241. phys_ctx->listening_socket_fds = pfd;
  13242. phys_ctx->num_listening_sockets++;
  13243. portsOk++;
  13244. }
  13245. if (portsOk != portsTotal) {
  13246. close_all_listening_sockets(phys_ctx);
  13247. portsOk = 0;
  13248. }
  13249. return portsOk;
  13250. }
  13251. static const char *
  13252. header_val(const struct mg_connection *conn, const char *header)
  13253. {
  13254. const char *header_value;
  13255. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13256. return "-";
  13257. } else {
  13258. return header_value;
  13259. }
  13260. }
  13261. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13262. static void log_access(const struct mg_connection *conn);
  13263. #include "external_log_access.inl"
  13264. #elif !defined(NO_FILESYSTEMS)
  13265. static void
  13266. log_access(const struct mg_connection *conn)
  13267. {
  13268. const struct mg_request_info *ri;
  13269. struct mg_file fi;
  13270. char date[64], src_addr[IP_ADDR_STR_LEN];
  13271. struct tm *tm;
  13272. const char *referer;
  13273. const char *user_agent;
  13274. char buf[4096];
  13275. if (!conn || !conn->dom_ctx) {
  13276. return;
  13277. }
  13278. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13279. if (mg_fopen(conn,
  13280. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13281. MG_FOPEN_MODE_APPEND,
  13282. &fi)
  13283. == 0) {
  13284. fi.access.fp = NULL;
  13285. }
  13286. } else {
  13287. fi.access.fp = NULL;
  13288. }
  13289. /* Log is written to a file and/or a callback. If both are not set,
  13290. * executing the rest of the function is pointless. */
  13291. if ((fi.access.fp == NULL)
  13292. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13293. return;
  13294. }
  13295. tm = localtime(&conn->conn_birth_time);
  13296. if (tm != NULL) {
  13297. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13298. } else {
  13299. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13300. date[sizeof(date) - 1] = '\0';
  13301. }
  13302. ri = &conn->request_info;
  13303. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13304. referer = header_val(conn, "Referer");
  13305. user_agent = header_val(conn, "User-Agent");
  13306. mg_snprintf(conn,
  13307. NULL, /* Ignore truncation in access log */
  13308. buf,
  13309. sizeof(buf),
  13310. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13311. src_addr,
  13312. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13313. date,
  13314. ri->request_method ? ri->request_method : "-",
  13315. ri->request_uri ? ri->request_uri : "-",
  13316. ri->query_string ? "?" : "",
  13317. ri->query_string ? ri->query_string : "",
  13318. ri->http_version,
  13319. conn->status_code,
  13320. conn->num_bytes_sent,
  13321. referer,
  13322. user_agent);
  13323. if (conn->phys_ctx->callbacks.log_access) {
  13324. conn->phys_ctx->callbacks.log_access(conn, buf);
  13325. }
  13326. if (fi.access.fp) {
  13327. int ok = 1;
  13328. flockfile(fi.access.fp);
  13329. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13330. ok = 0;
  13331. }
  13332. if (fflush(fi.access.fp) != 0) {
  13333. ok = 0;
  13334. }
  13335. funlockfile(fi.access.fp);
  13336. if (mg_fclose(&fi.access) != 0) {
  13337. ok = 0;
  13338. }
  13339. if (!ok) {
  13340. mg_cry_internal(conn,
  13341. "Error writing log file %s",
  13342. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13343. }
  13344. }
  13345. }
  13346. #else
  13347. #error Must either enable filesystems or provide a custom log_access implementation
  13348. #endif /* Externally provided function */
  13349. /* Verify given socket address against the ACL.
  13350. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13351. */
  13352. static int
  13353. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13354. {
  13355. int allowed, flag;
  13356. uint32_t net, mask;
  13357. struct vec vec;
  13358. if (phys_ctx) {
  13359. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13360. /* If any ACL is set, deny by default */
  13361. allowed = (list == NULL) ? '+' : '-';
  13362. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13363. flag = vec.ptr[0];
  13364. if ((flag != '+' && flag != '-')
  13365. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13366. mg_cry_ctx_internal(phys_ctx,
  13367. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13368. __func__);
  13369. return -1;
  13370. }
  13371. if (net == (remote_ip & mask)) {
  13372. allowed = flag;
  13373. }
  13374. }
  13375. return allowed == '+';
  13376. }
  13377. return -1;
  13378. }
  13379. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13380. static int
  13381. set_uid_option(struct mg_context *phys_ctx)
  13382. {
  13383. int success = 0;
  13384. if (phys_ctx) {
  13385. /* We are currently running as curr_uid. */
  13386. const uid_t curr_uid = getuid();
  13387. /* If set, we want to run as run_as_user. */
  13388. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13389. const struct passwd *to_pw = NULL;
  13390. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13391. /* run_as_user does not exist on the system. We can't proceed
  13392. * further. */
  13393. mg_cry_ctx_internal(phys_ctx,
  13394. "%s: unknown user [%s]",
  13395. __func__,
  13396. run_as_user);
  13397. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13398. /* There was either no request to change user, or we're already
  13399. * running as run_as_user. Nothing else to do.
  13400. */
  13401. success = 1;
  13402. } else {
  13403. /* Valid change request. */
  13404. if (setgid(to_pw->pw_gid) == -1) {
  13405. mg_cry_ctx_internal(phys_ctx,
  13406. "%s: setgid(%s): %s",
  13407. __func__,
  13408. run_as_user,
  13409. strerror(errno));
  13410. } else if (setgroups(0, NULL) == -1) {
  13411. mg_cry_ctx_internal(phys_ctx,
  13412. "%s: setgroups(): %s",
  13413. __func__,
  13414. strerror(errno));
  13415. } else if (setuid(to_pw->pw_uid) == -1) {
  13416. mg_cry_ctx_internal(phys_ctx,
  13417. "%s: setuid(%s): %s",
  13418. __func__,
  13419. run_as_user,
  13420. strerror(errno));
  13421. } else {
  13422. success = 1;
  13423. }
  13424. }
  13425. }
  13426. return success;
  13427. }
  13428. #endif /* !_WIN32 */
  13429. static void
  13430. tls_dtor(void *key)
  13431. {
  13432. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13433. /* key == pthread_getspecific(sTlsKey); */
  13434. if (tls) {
  13435. if (tls->is_master == 2) {
  13436. tls->is_master = -3; /* Mark memory as dead */
  13437. mg_free(tls);
  13438. }
  13439. }
  13440. pthread_setspecific(sTlsKey, NULL);
  13441. }
  13442. #if !defined(NO_SSL)
  13443. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13444. struct mg_domain_context *dom_ctx,
  13445. const char *pem,
  13446. const char *chain);
  13447. static const char *ssl_error(void);
  13448. static int
  13449. refresh_trust(struct mg_connection *conn)
  13450. {
  13451. static int reload_lock = 0;
  13452. static long int data_check = 0;
  13453. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  13454. struct stat cert_buf;
  13455. long int t;
  13456. const char *pem;
  13457. const char *chain;
  13458. int should_verify_peer;
  13459. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13460. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13461. * refresh_trust still can not work. */
  13462. return 0;
  13463. }
  13464. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13465. if (chain == NULL) {
  13466. /* pem is not NULL here */
  13467. chain = pem;
  13468. }
  13469. if (*chain == 0) {
  13470. chain = NULL;
  13471. }
  13472. t = data_check;
  13473. if (stat(pem, &cert_buf) != -1) {
  13474. t = (long int)cert_buf.st_mtime;
  13475. }
  13476. if (data_check != t) {
  13477. data_check = t;
  13478. should_verify_peer = 0;
  13479. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13480. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13481. == 0) {
  13482. should_verify_peer = 1;
  13483. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13484. "optional")
  13485. == 0) {
  13486. should_verify_peer = 1;
  13487. }
  13488. }
  13489. if (should_verify_peer) {
  13490. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13491. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13492. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13493. ca_file,
  13494. ca_path)
  13495. != 1) {
  13496. mg_cry_ctx_internal(
  13497. conn->phys_ctx,
  13498. "SSL_CTX_load_verify_locations error: %s "
  13499. "ssl_verify_peer requires setting "
  13500. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13501. "present in "
  13502. "the .conf file?",
  13503. ssl_error());
  13504. return 0;
  13505. }
  13506. }
  13507. if (1 == mg_atomic_inc(p_reload_lock)) {
  13508. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13509. == 0) {
  13510. return 0;
  13511. }
  13512. *p_reload_lock = 0;
  13513. }
  13514. }
  13515. /* lock while cert is reloading */
  13516. while (*p_reload_lock) {
  13517. sleep(1);
  13518. }
  13519. return 1;
  13520. }
  13521. #if defined(OPENSSL_API_1_1)
  13522. #else
  13523. static pthread_mutex_t *ssl_mutexes;
  13524. #endif /* OPENSSL_API_1_1 */
  13525. static int
  13526. sslize(struct mg_connection *conn,
  13527. SSL_CTX *s,
  13528. int (*func)(SSL *),
  13529. volatile int *stop_server,
  13530. const struct mg_client_options *client_options)
  13531. {
  13532. int ret, err;
  13533. int short_trust;
  13534. unsigned timeout = 1024;
  13535. unsigned i;
  13536. if (!conn) {
  13537. return 0;
  13538. }
  13539. short_trust =
  13540. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13541. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13542. if (short_trust) {
  13543. int trust_ret = refresh_trust(conn);
  13544. if (!trust_ret) {
  13545. return trust_ret;
  13546. }
  13547. }
  13548. conn->ssl = SSL_new(s);
  13549. if (conn->ssl == NULL) {
  13550. return 0;
  13551. }
  13552. SSL_set_app_data(conn->ssl, (char *)conn);
  13553. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13554. if (ret != 1) {
  13555. err = SSL_get_error(conn->ssl, ret);
  13556. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13557. SSL_free(conn->ssl);
  13558. conn->ssl = NULL;
  13559. OPENSSL_REMOVE_THREAD_STATE();
  13560. return 0;
  13561. }
  13562. if (client_options) {
  13563. if (client_options->host_name) {
  13564. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13565. }
  13566. }
  13567. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13568. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13569. /* NOTE: The loop below acts as a back-off, so we can end
  13570. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13571. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13572. if (to >= 0) {
  13573. timeout = (unsigned)to;
  13574. }
  13575. }
  13576. /* SSL functions may fail and require to be called again:
  13577. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13578. * Here "func" could be SSL_connect or SSL_accept. */
  13579. for (i = 0; i <= timeout; i += 50) {
  13580. ret = func(conn->ssl);
  13581. if (ret != 1) {
  13582. err = SSL_get_error(conn->ssl, ret);
  13583. if ((err == SSL_ERROR_WANT_CONNECT)
  13584. || (err == SSL_ERROR_WANT_ACCEPT)
  13585. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13586. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13587. if (*stop_server) {
  13588. /* Don't wait if the server is going to be stopped. */
  13589. break;
  13590. }
  13591. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13592. /* Simply retry the function call. */
  13593. mg_sleep(50);
  13594. } else {
  13595. /* Need to retry the function call "later".
  13596. * See https://linux.die.net/man/3/ssl_get_error
  13597. * This is typical for non-blocking sockets. */
  13598. struct mg_pollfd pfd;
  13599. int pollres;
  13600. pfd.fd = conn->client.sock;
  13601. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13602. || (err == SSL_ERROR_WANT_WRITE))
  13603. ? POLLOUT
  13604. : POLLIN;
  13605. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13606. if (pollres < 0) {
  13607. /* Break if error occured (-1)
  13608. * or server shutdown (-2) */
  13609. break;
  13610. }
  13611. }
  13612. } else if (err == SSL_ERROR_SYSCALL) {
  13613. /* This is an IO error. Look at errno. */
  13614. err = errno;
  13615. mg_cry_internal(conn, "SSL syscall error %i", err);
  13616. break;
  13617. } else {
  13618. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13619. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13620. break;
  13621. }
  13622. ERR_clear_error();
  13623. } else {
  13624. /* success */
  13625. break;
  13626. }
  13627. }
  13628. if (ret != 1) {
  13629. SSL_free(conn->ssl);
  13630. conn->ssl = NULL;
  13631. OPENSSL_REMOVE_THREAD_STATE();
  13632. return 0;
  13633. }
  13634. return 1;
  13635. }
  13636. /* Return OpenSSL error message (from CRYPTO lib) */
  13637. static const char *
  13638. ssl_error(void)
  13639. {
  13640. unsigned long err;
  13641. err = ERR_get_error();
  13642. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13643. }
  13644. static int
  13645. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13646. {
  13647. int i;
  13648. const char hexdigit[] = "0123456789abcdef";
  13649. if ((memlen <= 0) || (buflen <= 0)) {
  13650. return 0;
  13651. }
  13652. if (buflen < (3 * memlen)) {
  13653. return 0;
  13654. }
  13655. for (i = 0; i < memlen; i++) {
  13656. if (i > 0) {
  13657. buf[3 * i - 1] = ' ';
  13658. }
  13659. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13660. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13661. }
  13662. buf[3 * memlen - 1] = 0;
  13663. return 1;
  13664. }
  13665. static void
  13666. ssl_get_client_cert_info(struct mg_connection *conn)
  13667. {
  13668. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13669. if (cert) {
  13670. char str_subject[1024];
  13671. char str_issuer[1024];
  13672. char str_finger[1024];
  13673. unsigned char buf[256];
  13674. char *str_serial = NULL;
  13675. unsigned int ulen;
  13676. int ilen;
  13677. unsigned char *tmp_buf;
  13678. unsigned char *tmp_p;
  13679. /* Handle to algorithm used for fingerprint */
  13680. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13681. /* Get Subject and issuer */
  13682. X509_NAME *subj = X509_get_subject_name(cert);
  13683. X509_NAME *iss = X509_get_issuer_name(cert);
  13684. /* Get serial number */
  13685. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13686. /* Translate serial number to a hex string */
  13687. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13688. str_serial = BN_bn2hex(serial_bn);
  13689. BN_free(serial_bn);
  13690. /* Translate subject and issuer to a string */
  13691. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13692. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13693. /* Calculate SHA1 fingerprint and store as a hex string */
  13694. ulen = 0;
  13695. /* ASN1_digest is deprecated. Do the calculation manually,
  13696. * using EVP_Digest. */
  13697. ilen = i2d_X509(cert, NULL);
  13698. tmp_buf = (ilen > 0)
  13699. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13700. conn->phys_ctx)
  13701. : NULL;
  13702. if (tmp_buf) {
  13703. tmp_p = tmp_buf;
  13704. (void)i2d_X509(cert, &tmp_p);
  13705. if (!EVP_Digest(
  13706. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13707. ulen = 0;
  13708. }
  13709. mg_free(tmp_buf);
  13710. }
  13711. if (!hexdump2string(
  13712. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13713. *str_finger = 0;
  13714. }
  13715. conn->request_info.client_cert = (struct mg_client_cert *)
  13716. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13717. if (conn->request_info.client_cert) {
  13718. conn->request_info.client_cert->peer_cert = (void *)cert;
  13719. conn->request_info.client_cert->subject =
  13720. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13721. conn->request_info.client_cert->issuer =
  13722. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13723. conn->request_info.client_cert->serial =
  13724. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13725. conn->request_info.client_cert->finger =
  13726. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13727. } else {
  13728. mg_cry_internal(conn,
  13729. "%s",
  13730. "Out of memory: Cannot allocate memory for client "
  13731. "certificate");
  13732. }
  13733. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13734. * see https://linux.die.net/man/3/bn_bn2hex */
  13735. OPENSSL_free(str_serial);
  13736. }
  13737. }
  13738. #if defined(OPENSSL_API_1_1)
  13739. #else
  13740. static void
  13741. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13742. {
  13743. (void)line;
  13744. (void)file;
  13745. if (mode & 1) {
  13746. /* 1 is CRYPTO_LOCK */
  13747. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13748. } else {
  13749. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13750. }
  13751. }
  13752. #endif /* OPENSSL_API_1_1 */
  13753. #if !defined(NO_SSL_DL)
  13754. static void *
  13755. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13756. {
  13757. union {
  13758. void *p;
  13759. void (*fp)(void);
  13760. } u;
  13761. void *dll_handle;
  13762. struct ssl_func *fp;
  13763. int ok;
  13764. int truncated = 0;
  13765. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13766. mg_snprintf(NULL,
  13767. NULL, /* No truncation check for ebuf */
  13768. ebuf,
  13769. ebuf_len,
  13770. "%s: cannot load %s",
  13771. __func__,
  13772. dll_name);
  13773. return NULL;
  13774. }
  13775. ok = 1;
  13776. for (fp = sw; fp->name != NULL; fp++) {
  13777. #if defined(_WIN32)
  13778. /* GetProcAddress() returns pointer to function */
  13779. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13780. #else
  13781. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13782. * pointers to function pointers. We need to use a union to make a
  13783. * cast. */
  13784. u.p = dlsym(dll_handle, fp->name);
  13785. #endif /* _WIN32 */
  13786. if (u.fp == NULL) {
  13787. if (ok) {
  13788. mg_snprintf(NULL,
  13789. &truncated,
  13790. ebuf,
  13791. ebuf_len,
  13792. "%s: %s: cannot find %s",
  13793. __func__,
  13794. dll_name,
  13795. fp->name);
  13796. ok = 0;
  13797. } else {
  13798. size_t cur_len = strlen(ebuf);
  13799. if (!truncated) {
  13800. mg_snprintf(NULL,
  13801. &truncated,
  13802. ebuf + cur_len,
  13803. ebuf_len - cur_len - 3,
  13804. ", %s",
  13805. fp->name);
  13806. if (truncated) {
  13807. /* If truncated, add "..." */
  13808. strcat(ebuf, "...");
  13809. }
  13810. }
  13811. }
  13812. /* Debug:
  13813. * printf("Missing function: %s\n", fp->name); */
  13814. } else {
  13815. fp->ptr = u.fp;
  13816. }
  13817. }
  13818. if (!ok) {
  13819. (void)dlclose(dll_handle);
  13820. return NULL;
  13821. }
  13822. return dll_handle;
  13823. }
  13824. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13825. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13826. #endif /* NO_SSL_DL */
  13827. #if defined(SSL_ALREADY_INITIALIZED)
  13828. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13829. #else
  13830. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13831. #endif
  13832. static int
  13833. initialize_ssl(char *ebuf, size_t ebuf_len)
  13834. {
  13835. #if defined(OPENSSL_API_1_1)
  13836. if (ebuf_len > 0) {
  13837. ebuf[0] = 0;
  13838. }
  13839. #if !defined(NO_SSL_DL)
  13840. if (!cryptolib_dll_handle) {
  13841. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13842. if (!cryptolib_dll_handle) {
  13843. mg_snprintf(NULL,
  13844. NULL, /* No truncation check for ebuf */
  13845. ebuf,
  13846. ebuf_len,
  13847. "%s: error loading library %s",
  13848. __func__,
  13849. CRYPTO_LIB);
  13850. DEBUG_TRACE("%s", ebuf);
  13851. return 0;
  13852. }
  13853. }
  13854. #endif /* NO_SSL_DL */
  13855. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13856. return 1;
  13857. }
  13858. #else /* not OPENSSL_API_1_1 */
  13859. int i, num_locks;
  13860. size_t size;
  13861. if (ebuf_len > 0) {
  13862. ebuf[0] = 0;
  13863. }
  13864. #if !defined(NO_SSL_DL)
  13865. if (!cryptolib_dll_handle) {
  13866. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13867. if (!cryptolib_dll_handle) {
  13868. mg_snprintf(NULL,
  13869. NULL, /* No truncation check for ebuf */
  13870. ebuf,
  13871. ebuf_len,
  13872. "%s: error loading library %s",
  13873. __func__,
  13874. CRYPTO_LIB);
  13875. DEBUG_TRACE("%s", ebuf);
  13876. return 0;
  13877. }
  13878. }
  13879. #endif /* NO_SSL_DL */
  13880. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13881. return 1;
  13882. }
  13883. /* Initialize locking callbacks, needed for thread safety.
  13884. * http://www.openssl.org/support/faq.html#PROG1
  13885. */
  13886. num_locks = CRYPTO_num_locks();
  13887. if (num_locks < 0) {
  13888. num_locks = 0;
  13889. }
  13890. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13891. /* allocate mutex array, if required */
  13892. if (num_locks == 0) {
  13893. /* No mutex array required */
  13894. ssl_mutexes = NULL;
  13895. } else {
  13896. /* Mutex array required - allocate it */
  13897. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13898. /* Check OOM */
  13899. if (ssl_mutexes == NULL) {
  13900. mg_snprintf(NULL,
  13901. NULL, /* No truncation check for ebuf */
  13902. ebuf,
  13903. ebuf_len,
  13904. "%s: cannot allocate mutexes: %s",
  13905. __func__,
  13906. ssl_error());
  13907. DEBUG_TRACE("%s", ebuf);
  13908. return 0;
  13909. }
  13910. /* initialize mutex array */
  13911. for (i = 0; i < num_locks; i++) {
  13912. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13913. mg_snprintf(NULL,
  13914. NULL, /* No truncation check for ebuf */
  13915. ebuf,
  13916. ebuf_len,
  13917. "%s: error initializing mutex %i of %i",
  13918. __func__,
  13919. i,
  13920. num_locks);
  13921. DEBUG_TRACE("%s", ebuf);
  13922. mg_free(ssl_mutexes);
  13923. return 0;
  13924. }
  13925. }
  13926. }
  13927. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13928. CRYPTO_set_id_callback(&mg_current_thread_id);
  13929. #endif /* OPENSSL_API_1_1 */
  13930. #if !defined(NO_SSL_DL)
  13931. if (!ssllib_dll_handle) {
  13932. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13933. if (!ssllib_dll_handle) {
  13934. #if !defined(OPENSSL_API_1_1)
  13935. mg_free(ssl_mutexes);
  13936. #endif
  13937. DEBUG_TRACE("%s", ebuf);
  13938. return 0;
  13939. }
  13940. }
  13941. #endif /* NO_SSL_DL */
  13942. #if defined(OPENSSL_API_1_1)
  13943. /* Initialize SSL library */
  13944. OPENSSL_init_ssl(0, NULL);
  13945. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13946. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13947. NULL);
  13948. #else
  13949. /* Initialize SSL library */
  13950. SSL_library_init();
  13951. SSL_load_error_strings();
  13952. #endif
  13953. return 1;
  13954. }
  13955. static int
  13956. ssl_use_pem_file(struct mg_context *phys_ctx,
  13957. struct mg_domain_context *dom_ctx,
  13958. const char *pem,
  13959. const char *chain)
  13960. {
  13961. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13962. mg_cry_ctx_internal(phys_ctx,
  13963. "%s: cannot open certificate file %s: %s",
  13964. __func__,
  13965. pem,
  13966. ssl_error());
  13967. return 0;
  13968. }
  13969. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13970. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13971. mg_cry_ctx_internal(phys_ctx,
  13972. "%s: cannot open private key file %s: %s",
  13973. __func__,
  13974. pem,
  13975. ssl_error());
  13976. return 0;
  13977. }
  13978. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13979. mg_cry_ctx_internal(phys_ctx,
  13980. "%s: certificate and private key do not match: %s",
  13981. __func__,
  13982. pem);
  13983. return 0;
  13984. }
  13985. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13986. * chain files that contain private keys and certificates in
  13987. * SSL_CTX_use_certificate_chain_file.
  13988. * The CivetWeb-Server used pem-Files that contained both information.
  13989. * In order to make wolfSSL work, it is split in two files.
  13990. * One file that contains key and certificate used by the server and
  13991. * an optional chain file for the ssl stack.
  13992. */
  13993. if (chain) {
  13994. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13995. mg_cry_ctx_internal(phys_ctx,
  13996. "%s: cannot use certificate chain file %s: %s",
  13997. __func__,
  13998. chain,
  13999. ssl_error());
  14000. return 0;
  14001. }
  14002. }
  14003. return 1;
  14004. }
  14005. #if defined(OPENSSL_API_1_1)
  14006. static unsigned long
  14007. ssl_get_protocol(int version_id)
  14008. {
  14009. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14010. if (version_id > 0)
  14011. ret |= SSL_OP_NO_SSLv2;
  14012. if (version_id > 1)
  14013. ret |= SSL_OP_NO_SSLv3;
  14014. if (version_id > 2)
  14015. ret |= SSL_OP_NO_TLSv1;
  14016. if (version_id > 3)
  14017. ret |= SSL_OP_NO_TLSv1_1;
  14018. if (version_id > 4)
  14019. ret |= SSL_OP_NO_TLSv1_2;
  14020. #if defined(SSL_OP_NO_TLSv1_3)
  14021. if (version_id > 5)
  14022. ret |= SSL_OP_NO_TLSv1_3;
  14023. #endif
  14024. return ret;
  14025. }
  14026. #else
  14027. static long
  14028. ssl_get_protocol(int version_id)
  14029. {
  14030. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14031. if (version_id > 0)
  14032. ret |= SSL_OP_NO_SSLv2;
  14033. if (version_id > 1)
  14034. ret |= SSL_OP_NO_SSLv3;
  14035. if (version_id > 2)
  14036. ret |= SSL_OP_NO_TLSv1;
  14037. if (version_id > 3)
  14038. ret |= SSL_OP_NO_TLSv1_1;
  14039. if (version_id > 4)
  14040. ret |= SSL_OP_NO_TLSv1_2;
  14041. #if defined(SSL_OP_NO_TLSv1_3)
  14042. if (version_id > 5)
  14043. ret |= SSL_OP_NO_TLSv1_3;
  14044. #endif
  14045. return (long)ret;
  14046. }
  14047. #endif /* OPENSSL_API_1_1 */
  14048. /* SSL callback documentation:
  14049. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14050. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14051. * https://linux.die.net/man/3/ssl_set_info_callback */
  14052. /* Note: There is no "const" for the first argument in the documentation
  14053. * examples, however some (maybe most, but not all) headers of OpenSSL
  14054. * versions / OpenSSL compatibility layers have it. Having a different
  14055. * definition will cause a warning in C and an error in C++. Use "const SSL
  14056. * *", while automatical conversion from "SSL *" works for all compilers,
  14057. * but not other way around */
  14058. static void
  14059. ssl_info_callback(const SSL *ssl, int what, int ret)
  14060. {
  14061. (void)ret;
  14062. if (what & SSL_CB_HANDSHAKE_START) {
  14063. SSL_get_app_data(ssl);
  14064. }
  14065. if (what & SSL_CB_HANDSHAKE_DONE) {
  14066. /* TODO: check for openSSL 1.1 */
  14067. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14068. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14069. }
  14070. }
  14071. static int
  14072. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14073. {
  14074. struct mg_context *ctx = (struct mg_context *)arg;
  14075. struct mg_domain_context *dom = ((ctx != NULL) ? &(ctx->dd) : NULL);
  14076. #if defined(GCC_DIAGNOSTIC)
  14077. #pragma GCC diagnostic push
  14078. #pragma GCC diagnostic ignored "-Wcast-align"
  14079. #endif /* defined(GCC_DIAGNOSTIC) */
  14080. /* We used an aligned pointer in SSL_set_app_data */
  14081. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14082. #if defined(GCC_DIAGNOSTIC)
  14083. #pragma GCC diagnostic pop
  14084. #endif /* defined(GCC_DIAGNOSTIC) */
  14085. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14086. (void)ad;
  14087. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  14088. DEBUG_TRACE("%s", "internal error - assertion failed");
  14089. return SSL_TLSEXT_ERR_NOACK;
  14090. }
  14091. /* Old clients (Win XP) will not support SNI. Then, there
  14092. * is no server name available in the request - we can
  14093. * only work with the default certificate.
  14094. * Multiple HTTPS hosts on one IP+port are only possible
  14095. * with a certificate containing all alternative names.
  14096. */
  14097. if ((servername == NULL) || (*servername == 0)) {
  14098. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14099. conn->dom_ctx = &(ctx->dd);
  14100. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14101. return SSL_TLSEXT_ERR_NOACK;
  14102. }
  14103. DEBUG_TRACE("TLS connection to host %s", servername);
  14104. while (dom) {
  14105. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  14106. /* Found matching domain */
  14107. DEBUG_TRACE("TLS domain %s found",
  14108. dom->config[AUTHENTICATION_DOMAIN]);
  14109. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  14110. conn->dom_ctx = dom;
  14111. return SSL_TLSEXT_ERR_OK;
  14112. }
  14113. dom = dom->next;
  14114. }
  14115. /* Default domain */
  14116. DEBUG_TRACE("TLS default domain %s used",
  14117. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14118. conn->dom_ctx = &(ctx->dd);
  14119. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14120. return SSL_TLSEXT_ERR_OK;
  14121. }
  14122. #if defined(USE_HTTP2)
  14123. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14124. static const char *alpn_proto_order[] = {alpn_proto_list,
  14125. alpn_proto_list + 3,
  14126. alpn_proto_list + 3 + 8,
  14127. NULL};
  14128. #else
  14129. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14130. static const char *alpn_proto_order[] = {alpn_proto_list,
  14131. alpn_proto_list + 8,
  14132. NULL};
  14133. #endif
  14134. static int
  14135. alpn_select_cb(SSL *ssl,
  14136. const unsigned char **out,
  14137. unsigned char *outlen,
  14138. const unsigned char *in,
  14139. unsigned int inlen,
  14140. void *arg)
  14141. {
  14142. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14143. unsigned int i, j;
  14144. (void)ssl;
  14145. (void)dom_ctx;
  14146. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14147. /* check all accepted protocols in this order */
  14148. const char *alpn_proto = alpn_proto_order[j];
  14149. /* search input for matching protocol */
  14150. for (i = 0; i < inlen; i++) {
  14151. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14152. *out = in + i + 1;
  14153. *outlen = in[i];
  14154. return SSL_TLSEXT_ERR_OK;
  14155. }
  14156. }
  14157. }
  14158. /* Nothing found */
  14159. return SSL_TLSEXT_ERR_NOACK;
  14160. }
  14161. static int
  14162. next_protos_advertised_cb(SSL *ssl,
  14163. const unsigned char **data,
  14164. unsigned int *len,
  14165. void *arg)
  14166. {
  14167. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14168. *data = (const unsigned char *)alpn_proto_list;
  14169. *len = (unsigned int)strlen((const char *)data);
  14170. (void)ssl;
  14171. (void)dom_ctx;
  14172. return SSL_TLSEXT_ERR_OK;
  14173. }
  14174. static int
  14175. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14176. {
  14177. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14178. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14179. (const unsigned char *)alpn_proto_list,
  14180. alpn_len);
  14181. if (ret != 0) {
  14182. mg_cry_ctx_internal(phys_ctx,
  14183. "SSL_CTX_set_alpn_protos error: %s",
  14184. ssl_error());
  14185. }
  14186. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14187. alpn_select_cb,
  14188. (void *)dom_ctx);
  14189. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14190. next_protos_advertised_cb,
  14191. (void *)dom_ctx);
  14192. return ret;
  14193. }
  14194. /* Setup SSL CTX as required by CivetWeb */
  14195. static int
  14196. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14197. struct mg_domain_context *dom_ctx,
  14198. const char *pem,
  14199. const char *chain)
  14200. {
  14201. int callback_ret;
  14202. int should_verify_peer;
  14203. int peer_certificate_optional;
  14204. const char *ca_path;
  14205. const char *ca_file;
  14206. int use_default_verify_paths;
  14207. int verify_depth;
  14208. struct timespec now_mt;
  14209. md5_byte_t ssl_context_id[16];
  14210. md5_state_t md5state;
  14211. int protocol_ver;
  14212. #if defined(OPENSSL_API_1_1)
  14213. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14214. mg_cry_ctx_internal(phys_ctx,
  14215. "SSL_CTX_new (server) error: %s",
  14216. ssl_error());
  14217. return 0;
  14218. }
  14219. #else
  14220. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14221. mg_cry_ctx_internal(phys_ctx,
  14222. "SSL_CTX_new (server) error: %s",
  14223. ssl_error());
  14224. return 0;
  14225. }
  14226. #endif /* OPENSSL_API_1_1 */
  14227. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14228. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14229. | SSL_OP_NO_TLSv1_1);
  14230. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14231. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14232. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14233. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14234. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14235. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14236. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14237. #if defined(SSL_OP_NO_RENEGOTIATION)
  14238. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14239. #endif
  14240. #if !defined(NO_SSL_DL)
  14241. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14242. #endif /* NO_SSL_DL */
  14243. /* In SSL documentation examples callback defined without const
  14244. * specifier 'void (*)(SSL *, int, int)' See:
  14245. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14246. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14247. * But in the source code const SSL is used:
  14248. * 'void (*)(const SSL *, int, int)' See:
  14249. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14250. * Problem about wrong documentation described, but not resolved:
  14251. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14252. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14253. * But when compiled with modern C++ compiler, correct const should be
  14254. * provided
  14255. */
  14256. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14257. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14258. ssl_servername_callback);
  14259. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  14260. /* If a callback has been specified, call it. */
  14261. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14262. ? 0
  14263. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14264. phys_ctx->user_data));
  14265. /* If callback returns 0, civetweb sets up the SSL certificate.
  14266. * If it returns 1, civetweb assumes the calback already did this.
  14267. * If it returns -1, initializing ssl fails. */
  14268. if (callback_ret < 0) {
  14269. mg_cry_ctx_internal(phys_ctx,
  14270. "SSL callback returned error: %i",
  14271. callback_ret);
  14272. return 0;
  14273. }
  14274. if (callback_ret > 0) {
  14275. /* Callback did everything. */
  14276. return 1;
  14277. }
  14278. /* If a domain callback has been specified, call it. */
  14279. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14280. ? 0
  14281. : (phys_ctx->callbacks.init_ssl_domain(
  14282. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14283. dom_ctx->ssl_ctx,
  14284. phys_ctx->user_data));
  14285. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14286. * If it returns 1, civetweb assumes the calback already did this.
  14287. * If it returns -1, initializing ssl fails. */
  14288. if (callback_ret < 0) {
  14289. mg_cry_ctx_internal(phys_ctx,
  14290. "Domain SSL callback returned error: %i",
  14291. callback_ret);
  14292. return 0;
  14293. }
  14294. if (callback_ret > 0) {
  14295. /* Domain callback did everything. */
  14296. return 1;
  14297. }
  14298. /* Use some combination of start time, domain and port as a SSL
  14299. * context ID. This should be unique on the current machine. */
  14300. md5_init(&md5state);
  14301. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14302. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14303. md5_append(&md5state,
  14304. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14305. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14306. md5_append(&md5state,
  14307. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14308. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14309. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14310. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14311. md5_finish(&md5state, ssl_context_id);
  14312. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14313. (unsigned char *)ssl_context_id,
  14314. sizeof(ssl_context_id));
  14315. if (pem != NULL) {
  14316. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14317. return 0;
  14318. }
  14319. }
  14320. /* Should we support client certificates? */
  14321. /* Default is "no". */
  14322. should_verify_peer = 0;
  14323. peer_certificate_optional = 0;
  14324. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14325. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14326. /* Yes, they are mandatory */
  14327. should_verify_peer = 1;
  14328. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14329. "optional")
  14330. == 0) {
  14331. /* Yes, they are optional */
  14332. should_verify_peer = 1;
  14333. peer_certificate_optional = 1;
  14334. }
  14335. }
  14336. use_default_verify_paths =
  14337. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14338. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14339. == 0);
  14340. if (should_verify_peer) {
  14341. ca_path = dom_ctx->config[SSL_CA_PATH];
  14342. ca_file = dom_ctx->config[SSL_CA_FILE];
  14343. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14344. != 1) {
  14345. mg_cry_ctx_internal(phys_ctx,
  14346. "SSL_CTX_load_verify_locations error: %s "
  14347. "ssl_verify_peer requires setting "
  14348. "either ssl_ca_path or ssl_ca_file. "
  14349. "Is any of them present in the "
  14350. ".conf file?",
  14351. ssl_error());
  14352. return 0;
  14353. }
  14354. if (peer_certificate_optional) {
  14355. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14356. } else {
  14357. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14358. SSL_VERIFY_PEER
  14359. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14360. NULL);
  14361. }
  14362. if (use_default_verify_paths
  14363. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14364. mg_cry_ctx_internal(phys_ctx,
  14365. "SSL_CTX_set_default_verify_paths error: %s",
  14366. ssl_error());
  14367. return 0;
  14368. }
  14369. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14370. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14371. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14372. }
  14373. }
  14374. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14375. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14376. dom_ctx->config[SSL_CIPHER_LIST])
  14377. != 1) {
  14378. mg_cry_ctx_internal(phys_ctx,
  14379. "SSL_CTX_set_cipher_list error: %s",
  14380. ssl_error());
  14381. }
  14382. }
  14383. if (1 /* TODO */) {
  14384. init_alpn(phys_ctx, dom_ctx);
  14385. }
  14386. return 1;
  14387. }
  14388. /* Check if SSL is required.
  14389. * If so, dynamically load SSL library
  14390. * and set up ctx->ssl_ctx pointer. */
  14391. static int
  14392. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14393. {
  14394. void *ssl_ctx = 0;
  14395. int callback_ret;
  14396. const char *pem;
  14397. const char *chain;
  14398. char ebuf[128];
  14399. if (!phys_ctx) {
  14400. return 0;
  14401. }
  14402. if (!dom_ctx) {
  14403. dom_ctx = &(phys_ctx->dd);
  14404. }
  14405. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14406. /* No SSL port is set. No need to setup SSL. */
  14407. return 1;
  14408. }
  14409. /* Check for external SSL_CTX */
  14410. callback_ret =
  14411. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14412. ? 0
  14413. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14414. phys_ctx->user_data));
  14415. if (callback_ret < 0) {
  14416. mg_cry_ctx_internal(phys_ctx,
  14417. "external_ssl_ctx callback returned error: %i",
  14418. callback_ret);
  14419. return 0;
  14420. } else if (callback_ret > 0) {
  14421. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14422. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14423. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14424. return 0;
  14425. }
  14426. return 1;
  14427. }
  14428. /* Check for external domain SSL_CTX */
  14429. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14430. ? 0
  14431. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14432. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14433. &ssl_ctx,
  14434. phys_ctx->user_data));
  14435. if (callback_ret < 0) {
  14436. mg_cry_ctx_internal(
  14437. phys_ctx,
  14438. "external_ssl_ctx_domain callback returned error: %i",
  14439. callback_ret);
  14440. return 0;
  14441. } else if (callback_ret > 0) {
  14442. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14443. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14444. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14445. return 0;
  14446. }
  14447. return 1;
  14448. }
  14449. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14450. * 0, CivetWeb should continue initializing SSL */
  14451. /* If PEM file is not specified and the init_ssl callbacks
  14452. * are not specified, setup will fail. */
  14453. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14454. && (phys_ctx->callbacks.init_ssl == NULL)
  14455. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14456. /* No certificate and no init_ssl callbacks:
  14457. * Essential data to set up TLS is missing.
  14458. */
  14459. mg_cry_ctx_internal(phys_ctx,
  14460. "Initializing SSL failed: -%s is not set",
  14461. config_options[SSL_CERTIFICATE].name);
  14462. return 0;
  14463. }
  14464. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14465. if (chain == NULL) {
  14466. chain = pem;
  14467. }
  14468. if ((chain != NULL) && (*chain == 0)) {
  14469. chain = NULL;
  14470. }
  14471. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14472. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14473. return 0;
  14474. }
  14475. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14476. }
  14477. static void
  14478. uninitialize_ssl(void)
  14479. {
  14480. #if defined(OPENSSL_API_1_1)
  14481. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14482. /* Shutdown according to
  14483. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14484. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14485. */
  14486. CONF_modules_unload(1);
  14487. #else
  14488. int i;
  14489. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14490. /* Shutdown according to
  14491. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14492. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14493. */
  14494. CRYPTO_set_locking_callback(NULL);
  14495. CRYPTO_set_id_callback(NULL);
  14496. ENGINE_cleanup();
  14497. CONF_modules_unload(1);
  14498. ERR_free_strings();
  14499. EVP_cleanup();
  14500. CRYPTO_cleanup_all_ex_data();
  14501. OPENSSL_REMOVE_THREAD_STATE();
  14502. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14503. pthread_mutex_destroy(&ssl_mutexes[i]);
  14504. }
  14505. mg_free(ssl_mutexes);
  14506. ssl_mutexes = NULL;
  14507. #endif /* OPENSSL_API_1_1 */
  14508. }
  14509. }
  14510. #endif /* !NO_SSL */
  14511. #if !defined(NO_FILESYSTEMS)
  14512. static int
  14513. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14514. {
  14515. if (phys_ctx) {
  14516. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14517. const char *path;
  14518. struct mg_connection fc;
  14519. if (!dom_ctx) {
  14520. dom_ctx = &(phys_ctx->dd);
  14521. }
  14522. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14523. if ((path != NULL)
  14524. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14525. mg_cry_ctx_internal(phys_ctx,
  14526. "Cannot open %s: %s",
  14527. path,
  14528. strerror(ERRNO));
  14529. return 0;
  14530. }
  14531. return 1;
  14532. }
  14533. return 0;
  14534. }
  14535. #endif /* NO_FILESYSTEMS */
  14536. static int
  14537. set_acl_option(struct mg_context *phys_ctx)
  14538. {
  14539. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14540. }
  14541. static void
  14542. reset_per_request_attributes(struct mg_connection *conn)
  14543. {
  14544. if (!conn) {
  14545. return;
  14546. }
  14547. conn->connection_type =
  14548. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14549. conn->num_bytes_sent = conn->consumed_content = 0;
  14550. conn->path_info = NULL;
  14551. conn->status_code = -1;
  14552. conn->content_len = -1;
  14553. conn->is_chunked = 0;
  14554. conn->must_close = 0;
  14555. conn->request_len = 0;
  14556. conn->throttle = 0;
  14557. conn->accept_gzip = 0;
  14558. conn->response_info.content_length = conn->request_info.content_length = -1;
  14559. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14560. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14561. conn->response_info.status_text = NULL;
  14562. conn->response_info.status_code = 0;
  14563. conn->request_info.remote_user = NULL;
  14564. conn->request_info.request_method = NULL;
  14565. conn->request_info.request_uri = NULL;
  14566. conn->request_info.local_uri = NULL;
  14567. #if defined(MG_LEGACY_INTERFACE)
  14568. /* Legacy before split into local_uri and request_uri */
  14569. conn->request_info.uri = NULL;
  14570. #endif
  14571. }
  14572. static int
  14573. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14574. {
  14575. if (setsockopt(sock,
  14576. IPPROTO_TCP,
  14577. TCP_NODELAY,
  14578. (SOCK_OPT_TYPE)&nodelay_on,
  14579. sizeof(nodelay_on))
  14580. != 0) {
  14581. /* Error */
  14582. return 1;
  14583. }
  14584. /* OK */
  14585. return 0;
  14586. }
  14587. #if !defined(__ZEPHYR__)
  14588. static void
  14589. close_socket_gracefully(struct mg_connection *conn)
  14590. {
  14591. #if defined(_WIN32)
  14592. char buf[MG_BUF_LEN];
  14593. int n;
  14594. #endif
  14595. struct linger linger;
  14596. int error_code = 0;
  14597. int linger_timeout = -2;
  14598. socklen_t opt_len = sizeof(error_code);
  14599. if (!conn) {
  14600. return;
  14601. }
  14602. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14603. * "Note that enabling a nonzero timeout on a nonblocking socket
  14604. * is not recommended.", so set it to blocking now */
  14605. set_blocking_mode(conn->client.sock);
  14606. /* Send FIN to the client */
  14607. shutdown(conn->client.sock, SHUTDOWN_WR);
  14608. #if defined(_WIN32)
  14609. /* Read and discard pending incoming data. If we do not do that and
  14610. * close
  14611. * the socket, the data in the send buffer may be discarded. This
  14612. * behaviour is seen on Windows, when client keeps sending data
  14613. * when server decides to close the connection; then when client
  14614. * does recv() it gets no data back. */
  14615. do {
  14616. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14617. } while (n > 0);
  14618. #endif
  14619. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14620. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14621. }
  14622. /* Set linger option according to configuration */
  14623. if (linger_timeout >= 0) {
  14624. /* Set linger option to avoid socket hanging out after close. This
  14625. * prevent ephemeral port exhaust problem under high QPS. */
  14626. linger.l_onoff = 1;
  14627. #if defined(_MSC_VER)
  14628. #pragma warning(push)
  14629. #pragma warning(disable : 4244)
  14630. #endif
  14631. #if defined(GCC_DIAGNOSTIC)
  14632. #pragma GCC diagnostic push
  14633. #pragma GCC diagnostic ignored "-Wconversion"
  14634. #endif
  14635. /* Data type of linger structure elements may differ,
  14636. * so we don't know what cast we need here.
  14637. * Disable type conversion warnings. */
  14638. linger.l_linger = (linger_timeout + 999) / 1000;
  14639. #if defined(GCC_DIAGNOSTIC)
  14640. #pragma GCC diagnostic pop
  14641. #endif
  14642. #if defined(_MSC_VER)
  14643. #pragma warning(pop)
  14644. #endif
  14645. } else {
  14646. linger.l_onoff = 0;
  14647. linger.l_linger = 0;
  14648. }
  14649. if (linger_timeout < -1) {
  14650. /* Default: don't configure any linger */
  14651. } else if (getsockopt(conn->client.sock,
  14652. SOL_SOCKET,
  14653. SO_ERROR,
  14654. #if defined(_WIN32) /* WinSock uses different data type here */
  14655. (char *)&error_code,
  14656. #else
  14657. &error_code,
  14658. #endif
  14659. &opt_len)
  14660. != 0) {
  14661. /* Cannot determine if socket is already closed. This should
  14662. * not occur and never did in a test. Log an error message
  14663. * and continue. */
  14664. mg_cry_internal(conn,
  14665. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14666. __func__,
  14667. strerror(ERRNO));
  14668. #if defined(_WIN32)
  14669. } else if (error_code == WSAECONNRESET) {
  14670. #else
  14671. } else if (error_code == ECONNRESET) {
  14672. #endif
  14673. /* Socket already closed by client/peer, close socket without linger
  14674. */
  14675. } else {
  14676. /* Set linger timeout */
  14677. if (setsockopt(conn->client.sock,
  14678. SOL_SOCKET,
  14679. SO_LINGER,
  14680. (char *)&linger,
  14681. sizeof(linger))
  14682. != 0) {
  14683. mg_cry_internal(
  14684. conn,
  14685. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14686. __func__,
  14687. linger.l_onoff,
  14688. linger.l_linger,
  14689. strerror(ERRNO));
  14690. }
  14691. }
  14692. /* Now we know that our FIN is ACK-ed, safe to close */
  14693. closesocket(conn->client.sock);
  14694. conn->client.sock = INVALID_SOCKET;
  14695. }
  14696. #endif
  14697. static void
  14698. close_connection(struct mg_connection *conn)
  14699. {
  14700. #if defined(USE_SERVER_STATS)
  14701. conn->conn_state = 6; /* to close */
  14702. #endif
  14703. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14704. if (conn->lua_websocket_state) {
  14705. lua_websocket_close(conn, conn->lua_websocket_state);
  14706. conn->lua_websocket_state = NULL;
  14707. }
  14708. #endif
  14709. mg_lock_connection(conn);
  14710. /* Set close flag, so keep-alive loops will stop */
  14711. conn->must_close = 1;
  14712. /* call the connection_close callback if assigned */
  14713. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14714. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14715. conn->phys_ctx->callbacks.connection_close(conn);
  14716. }
  14717. }
  14718. /* Reset user data, after close callback is called.
  14719. * Do not reuse it. If the user needs a destructor,
  14720. * it must be done in the connection_close callback. */
  14721. mg_set_user_connection_data(conn, NULL);
  14722. #if defined(USE_SERVER_STATS)
  14723. conn->conn_state = 7; /* closing */
  14724. #endif
  14725. #if !defined(NO_SSL)
  14726. if (conn->ssl != NULL) {
  14727. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14728. */
  14729. SSL_shutdown(conn->ssl);
  14730. SSL_free(conn->ssl);
  14731. OPENSSL_REMOVE_THREAD_STATE();
  14732. conn->ssl = NULL;
  14733. }
  14734. #endif
  14735. if (conn->client.sock != INVALID_SOCKET) {
  14736. #if defined(__ZEPHYR__)
  14737. closesocket(conn->client.sock);
  14738. #else
  14739. close_socket_gracefully(conn);
  14740. #endif
  14741. conn->client.sock = INVALID_SOCKET;
  14742. }
  14743. if (conn->host) {
  14744. mg_free((void *)conn->host);
  14745. conn->host = NULL;
  14746. }
  14747. mg_unlock_connection(conn);
  14748. #if defined(USE_SERVER_STATS)
  14749. conn->conn_state = 8; /* closed */
  14750. #endif
  14751. }
  14752. void
  14753. mg_close_connection(struct mg_connection *conn)
  14754. {
  14755. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14756. return;
  14757. }
  14758. #if defined(USE_WEBSOCKET)
  14759. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14760. if (conn->in_websocket_handling) {
  14761. /* Set close flag, so the server thread can exit. */
  14762. conn->must_close = 1;
  14763. return;
  14764. }
  14765. }
  14766. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14767. unsigned int i;
  14768. /* client context: loops must end */
  14769. conn->phys_ctx->stop_flag = 1;
  14770. conn->must_close = 1;
  14771. /* We need to get the client thread out of the select/recv call
  14772. * here. */
  14773. /* Since we use a sleep quantum of some seconds to check for recv
  14774. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14775. /* join worker thread */
  14776. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14777. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14778. }
  14779. }
  14780. #endif /* defined(USE_WEBSOCKET) */
  14781. close_connection(conn);
  14782. #if !defined(NO_SSL)
  14783. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14784. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14785. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14786. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14787. }
  14788. #endif
  14789. #if defined(USE_WEBSOCKET)
  14790. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14791. mg_free(conn->phys_ctx->worker_threadids);
  14792. (void)pthread_mutex_destroy(&conn->mutex);
  14793. mg_free(conn);
  14794. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14795. mg_free(conn);
  14796. }
  14797. #else
  14798. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14799. mg_free(conn);
  14800. }
  14801. #endif /* defined(USE_WEBSOCKET) */
  14802. }
  14803. static struct mg_connection *
  14804. mg_connect_client_impl(const struct mg_client_options *client_options,
  14805. int use_ssl,
  14806. char *ebuf,
  14807. size_t ebuf_len)
  14808. {
  14809. struct mg_connection *conn = NULL;
  14810. SOCKET sock;
  14811. union usa sa;
  14812. struct sockaddr *psa;
  14813. socklen_t len;
  14814. unsigned max_req_size =
  14815. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14816. /* Size of structures, aligned to 8 bytes */
  14817. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14818. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14819. conn =
  14820. (struct mg_connection *)mg_calloc(1,
  14821. conn_size + ctx_size + max_req_size);
  14822. if (conn == NULL) {
  14823. mg_snprintf(NULL,
  14824. NULL, /* No truncation check for ebuf */
  14825. ebuf,
  14826. ebuf_len,
  14827. "calloc(): %s",
  14828. strerror(ERRNO));
  14829. return NULL;
  14830. }
  14831. #if defined(GCC_DIAGNOSTIC)
  14832. #pragma GCC diagnostic push
  14833. #pragma GCC diagnostic ignored "-Wcast-align"
  14834. #endif /* defined(GCC_DIAGNOSTIC) */
  14835. /* conn_size is aligned to 8 bytes */
  14836. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14837. #if defined(GCC_DIAGNOSTIC)
  14838. #pragma GCC diagnostic pop
  14839. #endif /* defined(GCC_DIAGNOSTIC) */
  14840. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14841. conn->buf_size = (int)max_req_size;
  14842. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14843. conn->dom_ctx = &(conn->phys_ctx->dd);
  14844. if (!connect_socket(conn->phys_ctx,
  14845. client_options->host,
  14846. client_options->port,
  14847. use_ssl,
  14848. ebuf,
  14849. ebuf_len,
  14850. &sock,
  14851. &sa)) {
  14852. /* ebuf is set by connect_socket,
  14853. * free all memory and return NULL; */
  14854. mg_free(conn);
  14855. return NULL;
  14856. }
  14857. #if !defined(NO_SSL)
  14858. #if defined(OPENSSL_API_1_1)
  14859. if (use_ssl
  14860. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14861. == NULL) {
  14862. mg_snprintf(NULL,
  14863. NULL, /* No truncation check for ebuf */
  14864. ebuf,
  14865. ebuf_len,
  14866. "SSL_CTX_new error: %s",
  14867. ssl_error());
  14868. closesocket(sock);
  14869. mg_free(conn);
  14870. return NULL;
  14871. }
  14872. #else
  14873. if (use_ssl
  14874. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14875. == NULL) {
  14876. mg_snprintf(NULL,
  14877. NULL, /* No truncation check for ebuf */
  14878. ebuf,
  14879. ebuf_len,
  14880. "SSL_CTX_new error: %s",
  14881. ssl_error());
  14882. closesocket(sock);
  14883. mg_free(conn);
  14884. return NULL;
  14885. }
  14886. #endif /* OPENSSL_API_1_1 */
  14887. #endif /* NO_SSL */
  14888. #if defined(USE_IPV6)
  14889. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14890. : sizeof(conn->client.rsa.sin6);
  14891. psa = (sa.sa.sa_family == AF_INET)
  14892. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14893. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14894. #else
  14895. len = sizeof(conn->client.rsa.sin);
  14896. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14897. #endif
  14898. conn->client.sock = sock;
  14899. conn->client.lsa = sa;
  14900. if (getsockname(sock, psa, &len) != 0) {
  14901. mg_cry_internal(conn,
  14902. "%s: getsockname() failed: %s",
  14903. __func__,
  14904. strerror(ERRNO));
  14905. }
  14906. conn->client.is_ssl = use_ssl ? 1 : 0;
  14907. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14908. mg_snprintf(NULL,
  14909. NULL, /* No truncation check for ebuf */
  14910. ebuf,
  14911. ebuf_len,
  14912. "Can not create mutex");
  14913. #if !defined(NO_SSL)
  14914. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14915. #endif
  14916. closesocket(sock);
  14917. mg_free(conn);
  14918. return NULL;
  14919. }
  14920. #if !defined(NO_SSL)
  14921. if (use_ssl) {
  14922. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14923. * SSL_CTX_set_verify call is needed to switch off server
  14924. * certificate checking, which is off by default in OpenSSL and
  14925. * on in yaSSL. */
  14926. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14927. * SSL_VERIFY_PEER, verify_ssl_server); */
  14928. if (client_options->client_cert) {
  14929. if (!ssl_use_pem_file(conn->phys_ctx,
  14930. conn->dom_ctx,
  14931. client_options->client_cert,
  14932. NULL)) {
  14933. mg_snprintf(NULL,
  14934. NULL, /* No truncation check for ebuf */
  14935. ebuf,
  14936. ebuf_len,
  14937. "Can not use SSL client certificate");
  14938. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14939. closesocket(sock);
  14940. mg_free(conn);
  14941. return NULL;
  14942. }
  14943. }
  14944. if (client_options->server_cert) {
  14945. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14946. client_options->server_cert,
  14947. NULL)
  14948. != 1) {
  14949. mg_cry_internal(conn,
  14950. "SSL_CTX_load_verify_locations error: %s ",
  14951. ssl_error());
  14952. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14953. closesocket(sock);
  14954. mg_free(conn);
  14955. return NULL;
  14956. }
  14957. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14958. } else {
  14959. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14960. }
  14961. if (!sslize(conn,
  14962. conn->dom_ctx->ssl_ctx,
  14963. SSL_connect,
  14964. &(conn->phys_ctx->stop_flag),
  14965. client_options)) {
  14966. mg_snprintf(NULL,
  14967. NULL, /* No truncation check for ebuf */
  14968. ebuf,
  14969. ebuf_len,
  14970. "SSL connection error");
  14971. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14972. closesocket(sock);
  14973. mg_free(conn);
  14974. return NULL;
  14975. }
  14976. }
  14977. #endif
  14978. return conn;
  14979. }
  14980. CIVETWEB_API struct mg_connection *
  14981. mg_connect_client_secure(const struct mg_client_options *client_options,
  14982. char *error_buffer,
  14983. size_t error_buffer_size)
  14984. {
  14985. return mg_connect_client_impl(client_options,
  14986. 1,
  14987. error_buffer,
  14988. error_buffer_size);
  14989. }
  14990. struct mg_connection *
  14991. mg_connect_client(const char *host,
  14992. int port,
  14993. int use_ssl,
  14994. char *error_buffer,
  14995. size_t error_buffer_size)
  14996. {
  14997. struct mg_client_options opts;
  14998. memset(&opts, 0, sizeof(opts));
  14999. opts.host = host;
  15000. opts.port = port;
  15001. return mg_connect_client_impl(&opts,
  15002. use_ssl,
  15003. error_buffer,
  15004. error_buffer_size);
  15005. }
  15006. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15007. struct mg_connection *
  15008. mg_connect_client2(const char *host,
  15009. const char *protocol,
  15010. int port,
  15011. const char *path,
  15012. struct mg_init_data *init,
  15013. struct mg_error_data *error)
  15014. {
  15015. int is_ssl, is_ws;
  15016. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15017. if (error != NULL) {
  15018. error->code = 0;
  15019. if (error->text_buffer_size > 0) {
  15020. *error->text = 0;
  15021. }
  15022. }
  15023. if ((host == NULL) || (protocol == NULL)) {
  15024. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15025. mg_snprintf(NULL,
  15026. NULL, /* No truncation check for error buffers */
  15027. error->text,
  15028. error->text_buffer_size,
  15029. "%s",
  15030. "Invalid parameters");
  15031. }
  15032. return NULL;
  15033. }
  15034. /* check all known protocolls */
  15035. if (!mg_strcasecmp(protocol, "http")) {
  15036. is_ssl = 0;
  15037. is_ws = 0;
  15038. } else if (!mg_strcasecmp(protocol, "https")) {
  15039. is_ssl = 1;
  15040. is_ws = 0;
  15041. #if defined(USE_WEBSOCKET)
  15042. } else if (!mg_strcasecmp(protocol, "ws")) {
  15043. is_ssl = 0;
  15044. is_ws = 1;
  15045. } else if (!mg_strcasecmp(protocol, "wss")) {
  15046. is_ssl = 1;
  15047. is_ws = 1;
  15048. #endif
  15049. } else {
  15050. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15051. mg_snprintf(NULL,
  15052. NULL, /* No truncation check for error buffers */
  15053. error->text,
  15054. error->text_buffer_size,
  15055. "Protocol %s not supported",
  15056. protocol);
  15057. }
  15058. return NULL;
  15059. }
  15060. /* TODO: The current implementation here just calls the old
  15061. * implementations, without using any new options. This is just a first
  15062. * step to test the new interfaces. */
  15063. #if defined(USE_WEBSOCKET)
  15064. if (is_ws) {
  15065. /* TODO: implement all options */
  15066. return mg_connect_websocket_client(
  15067. host,
  15068. port,
  15069. is_ssl,
  15070. ((error != NULL) ? error->text : NULL),
  15071. ((error != NULL) ? error->text_buffer_size : 0),
  15072. (path ? path : ""),
  15073. NULL /* TODO: origin */,
  15074. deprecated_websocket_data_wrapper,
  15075. deprecated_websocket_close_wrapper,
  15076. (void *)init->callbacks);
  15077. }
  15078. #endif
  15079. /* TODO: all additional options */
  15080. struct mg_client_options opts;
  15081. memset(&opts, 0, sizeof(opts));
  15082. opts.host = host;
  15083. opts.port = port;
  15084. return mg_connect_client_impl(&opts,
  15085. is_ssl,
  15086. ((error != NULL) ? error->text : NULL),
  15087. ((error != NULL) ? error->text_buffer_size
  15088. : 0));
  15089. }
  15090. #endif
  15091. static const struct {
  15092. const char *proto;
  15093. size_t proto_len;
  15094. unsigned default_port;
  15095. } abs_uri_protocols[] = {{"http://", 7, 80},
  15096. {"https://", 8, 443},
  15097. {"ws://", 5, 80},
  15098. {"wss://", 6, 443},
  15099. {NULL, 0, 0}};
  15100. /* Check if the uri is valid.
  15101. * return 0 for invalid uri,
  15102. * return 1 for *,
  15103. * return 2 for relative uri,
  15104. * return 3 for absolute uri without port,
  15105. * return 4 for absolute uri with port */
  15106. static int
  15107. get_uri_type(const char *uri)
  15108. {
  15109. int i;
  15110. const char *hostend, *portbegin;
  15111. char *portend;
  15112. unsigned long port;
  15113. /* According to the HTTP standard
  15114. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15115. * URI can be an asterisk (*) or should start with slash (relative uri),
  15116. * or it should start with the protocol (absolute uri). */
  15117. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15118. /* asterisk */
  15119. return 1;
  15120. }
  15121. /* Valid URIs according to RFC 3986
  15122. * (https://www.ietf.org/rfc/rfc3986.txt)
  15123. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15124. * and unreserved characters A-Z a-z 0-9 and -._~
  15125. * and % encoded symbols.
  15126. */
  15127. for (i = 0; uri[i] != 0; i++) {
  15128. if (uri[i] < 33) {
  15129. /* control characters and spaces are invalid */
  15130. return 0;
  15131. }
  15132. if (uri[i] > 126) {
  15133. /* non-ascii characters must be % encoded */
  15134. return 0;
  15135. } else {
  15136. switch (uri[i]) {
  15137. case '"': /* 34 */
  15138. case '<': /* 60 */
  15139. case '>': /* 62 */
  15140. case '\\': /* 92 */
  15141. case '^': /* 94 */
  15142. case '`': /* 96 */
  15143. case '{': /* 123 */
  15144. case '|': /* 124 */
  15145. case '}': /* 125 */
  15146. return 0;
  15147. default:
  15148. /* character is ok */
  15149. break;
  15150. }
  15151. }
  15152. }
  15153. /* A relative uri starts with a / character */
  15154. if (uri[0] == '/') {
  15155. /* relative uri */
  15156. return 2;
  15157. }
  15158. /* It could be an absolute uri: */
  15159. /* This function only checks if the uri is valid, not if it is
  15160. * addressing the current server. So civetweb can also be used
  15161. * as a proxy server. */
  15162. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15163. if (mg_strncasecmp(uri,
  15164. abs_uri_protocols[i].proto,
  15165. abs_uri_protocols[i].proto_len)
  15166. == 0) {
  15167. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15168. if (!hostend) {
  15169. return 0;
  15170. }
  15171. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15172. if (!portbegin) {
  15173. return 3;
  15174. }
  15175. port = strtoul(portbegin + 1, &portend, 10);
  15176. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15177. return 0;
  15178. }
  15179. return 4;
  15180. }
  15181. }
  15182. return 0;
  15183. }
  15184. /* Return NULL or the relative uri at the current server */
  15185. static const char *
  15186. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15187. {
  15188. const char *server_domain;
  15189. size_t server_domain_len;
  15190. size_t request_domain_len = 0;
  15191. unsigned long port = 0;
  15192. int i, auth_domain_check_enabled;
  15193. const char *hostbegin = NULL;
  15194. const char *hostend = NULL;
  15195. const char *portbegin;
  15196. char *portend;
  15197. auth_domain_check_enabled =
  15198. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15199. /* DNS is case insensitive, so use case insensitive string compare here
  15200. */
  15201. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15202. if (mg_strncasecmp(uri,
  15203. abs_uri_protocols[i].proto,
  15204. abs_uri_protocols[i].proto_len)
  15205. == 0) {
  15206. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15207. hostend = strchr(hostbegin, '/');
  15208. if (!hostend) {
  15209. return 0;
  15210. }
  15211. portbegin = strchr(hostbegin, ':');
  15212. if ((!portbegin) || (portbegin > hostend)) {
  15213. port = abs_uri_protocols[i].default_port;
  15214. request_domain_len = (size_t)(hostend - hostbegin);
  15215. } else {
  15216. port = strtoul(portbegin + 1, &portend, 10);
  15217. if ((portend != hostend) || (port <= 0)
  15218. || !is_valid_port(port)) {
  15219. return 0;
  15220. }
  15221. request_domain_len = (size_t)(portbegin - hostbegin);
  15222. }
  15223. /* protocol found, port set */
  15224. break;
  15225. }
  15226. }
  15227. if (!port) {
  15228. /* port remains 0 if the protocol is not found */
  15229. return 0;
  15230. }
  15231. /* Check if the request is directed to a different server. */
  15232. /* First check if the port is the same (IPv4 and IPv6). */
  15233. #if defined(USE_IPV6)
  15234. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15235. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15236. /* Request is directed to a different port */
  15237. return 0;
  15238. }
  15239. } else
  15240. #endif
  15241. {
  15242. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15243. /* Request is directed to a different port */
  15244. return 0;
  15245. }
  15246. }
  15247. /* Finally check if the server corresponds to the authentication
  15248. * domain of the server (the server domain).
  15249. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15250. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15251. * but do not allow substrings (like
  15252. * http://notmydomain.com/path/file.ext
  15253. * or http://mydomain.com.fake/path/file.ext).
  15254. */
  15255. if (auth_domain_check_enabled) {
  15256. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15257. server_domain_len = strlen(server_domain);
  15258. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15259. return 0;
  15260. }
  15261. if ((request_domain_len == server_domain_len)
  15262. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15263. /* Request is directed to this server - full name match. */
  15264. } else {
  15265. if (request_domain_len < (server_domain_len + 2)) {
  15266. /* Request is directed to another server: The server name
  15267. * is longer than the request name.
  15268. * Drop this case here to avoid overflows in the
  15269. * following checks. */
  15270. return 0;
  15271. }
  15272. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15273. /* Request is directed to another server: It could be a
  15274. * substring
  15275. * like notmyserver.com */
  15276. return 0;
  15277. }
  15278. if (0
  15279. != memcmp(server_domain,
  15280. hostbegin + request_domain_len - server_domain_len,
  15281. server_domain_len)) {
  15282. /* Request is directed to another server:
  15283. * The server name is different. */
  15284. return 0;
  15285. }
  15286. }
  15287. }
  15288. return hostend;
  15289. }
  15290. static int
  15291. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15292. {
  15293. if (ebuf_len > 0) {
  15294. ebuf[0] = '\0';
  15295. }
  15296. *err = 0;
  15297. reset_per_request_attributes(conn);
  15298. if (!conn) {
  15299. mg_snprintf(conn,
  15300. NULL, /* No truncation check for ebuf */
  15301. ebuf,
  15302. ebuf_len,
  15303. "%s",
  15304. "Internal error");
  15305. *err = 500;
  15306. return 0;
  15307. }
  15308. /* Set the time the request was received. This value should be used for
  15309. * timeouts. */
  15310. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15311. conn->request_len =
  15312. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15313. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15314. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15315. mg_snprintf(conn,
  15316. NULL, /* No truncation check for ebuf */
  15317. ebuf,
  15318. ebuf_len,
  15319. "%s",
  15320. "Invalid message size");
  15321. *err = 500;
  15322. return 0;
  15323. }
  15324. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15325. mg_snprintf(conn,
  15326. NULL, /* No truncation check for ebuf */
  15327. ebuf,
  15328. ebuf_len,
  15329. "%s",
  15330. "Message too large");
  15331. *err = 413;
  15332. return 0;
  15333. }
  15334. if (conn->request_len <= 0) {
  15335. if (conn->data_len > 0) {
  15336. mg_snprintf(conn,
  15337. NULL, /* No truncation check for ebuf */
  15338. ebuf,
  15339. ebuf_len,
  15340. "%s",
  15341. "Malformed message");
  15342. *err = 400;
  15343. } else {
  15344. /* Server did not recv anything -> just close the connection */
  15345. conn->must_close = 1;
  15346. mg_snprintf(conn,
  15347. NULL, /* No truncation check for ebuf */
  15348. ebuf,
  15349. ebuf_len,
  15350. "%s",
  15351. "No data received");
  15352. *err = 0;
  15353. }
  15354. return 0;
  15355. }
  15356. return 1;
  15357. }
  15358. static int
  15359. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15360. {
  15361. const char *cl;
  15362. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15363. return 0;
  15364. }
  15365. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15366. <= 0) {
  15367. mg_snprintf(conn,
  15368. NULL, /* No truncation check for ebuf */
  15369. ebuf,
  15370. ebuf_len,
  15371. "%s",
  15372. "Bad request");
  15373. *err = 400;
  15374. return 0;
  15375. }
  15376. /* Message is a valid request */
  15377. /* Is there a "host" ? */
  15378. if (conn->host != NULL) {
  15379. mg_free((void *)conn->host);
  15380. }
  15381. conn->host = alloc_get_host(conn);
  15382. if (!conn->host) {
  15383. mg_snprintf(conn,
  15384. NULL, /* No truncation check for ebuf */
  15385. ebuf,
  15386. ebuf_len,
  15387. "%s",
  15388. "Bad request: Host mismatch");
  15389. *err = 400;
  15390. return 0;
  15391. }
  15392. if (((cl = get_header(conn->request_info.http_headers,
  15393. conn->request_info.num_headers,
  15394. "Transfer-Encoding"))
  15395. != NULL)
  15396. && mg_strcasecmp(cl, "identity")) {
  15397. if (mg_strcasecmp(cl, "chunked")) {
  15398. mg_snprintf(conn,
  15399. NULL, /* No truncation check for ebuf */
  15400. ebuf,
  15401. ebuf_len,
  15402. "%s",
  15403. "Bad request");
  15404. *err = 400;
  15405. return 0;
  15406. }
  15407. conn->is_chunked = 1;
  15408. conn->content_len = 0; /* not yet read */
  15409. } else if ((cl = get_header(conn->request_info.http_headers,
  15410. conn->request_info.num_headers,
  15411. "Content-Length"))
  15412. != NULL) {
  15413. /* Request has content length set */
  15414. char *endptr = NULL;
  15415. conn->content_len = strtoll(cl, &endptr, 10);
  15416. if ((endptr == cl) || (conn->content_len < 0)) {
  15417. mg_snprintf(conn,
  15418. NULL, /* No truncation check for ebuf */
  15419. ebuf,
  15420. ebuf_len,
  15421. "%s",
  15422. "Bad request");
  15423. *err = 411;
  15424. return 0;
  15425. }
  15426. /* Publish the content length back to the request info. */
  15427. conn->request_info.content_length = conn->content_len;
  15428. } else {
  15429. /* There is no exception, see RFC7230. */
  15430. conn->content_len = 0;
  15431. }
  15432. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15433. return 1;
  15434. }
  15435. /* conn is assumed to be valid in this internal function */
  15436. static int
  15437. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15438. {
  15439. const char *cl;
  15440. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15441. return 0;
  15442. }
  15443. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15444. <= 0) {
  15445. mg_snprintf(conn,
  15446. NULL, /* No truncation check for ebuf */
  15447. ebuf,
  15448. ebuf_len,
  15449. "%s",
  15450. "Bad response");
  15451. *err = 400;
  15452. return 0;
  15453. }
  15454. /* Message is a valid response */
  15455. if (((cl = get_header(conn->response_info.http_headers,
  15456. conn->response_info.num_headers,
  15457. "Transfer-Encoding"))
  15458. != NULL)
  15459. && mg_strcasecmp(cl, "identity")) {
  15460. if (mg_strcasecmp(cl, "chunked")) {
  15461. mg_snprintf(conn,
  15462. NULL, /* No truncation check for ebuf */
  15463. ebuf,
  15464. ebuf_len,
  15465. "%s",
  15466. "Bad request");
  15467. *err = 400;
  15468. return 0;
  15469. }
  15470. conn->is_chunked = 1;
  15471. conn->content_len = 0; /* not yet read */
  15472. } else if ((cl = get_header(conn->response_info.http_headers,
  15473. conn->response_info.num_headers,
  15474. "Content-Length"))
  15475. != NULL) {
  15476. char *endptr = NULL;
  15477. conn->content_len = strtoll(cl, &endptr, 10);
  15478. if ((endptr == cl) || (conn->content_len < 0)) {
  15479. mg_snprintf(conn,
  15480. NULL, /* No truncation check for ebuf */
  15481. ebuf,
  15482. ebuf_len,
  15483. "%s",
  15484. "Bad request");
  15485. *err = 411;
  15486. return 0;
  15487. }
  15488. /* Publish the content length back to the response info. */
  15489. conn->response_info.content_length = conn->content_len;
  15490. /* TODO: check if it is still used in response_info */
  15491. conn->request_info.content_length = conn->content_len;
  15492. /* TODO: we should also consider HEAD method */
  15493. if (conn->response_info.status_code == 304) {
  15494. conn->content_len = 0;
  15495. }
  15496. } else {
  15497. /* TODO: we should also consider HEAD method */
  15498. if (((conn->response_info.status_code >= 100)
  15499. && (conn->response_info.status_code <= 199))
  15500. || (conn->response_info.status_code == 204)
  15501. || (conn->response_info.status_code == 304)) {
  15502. conn->content_len = 0;
  15503. } else {
  15504. conn->content_len = -1; /* unknown content length */
  15505. }
  15506. }
  15507. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15508. return 1;
  15509. }
  15510. int
  15511. mg_get_response(struct mg_connection *conn,
  15512. char *ebuf,
  15513. size_t ebuf_len,
  15514. int timeout)
  15515. {
  15516. int err, ret;
  15517. char txt[32]; /* will not overflow */
  15518. char *save_timeout;
  15519. char *new_timeout;
  15520. if (ebuf_len > 0) {
  15521. ebuf[0] = '\0';
  15522. }
  15523. if (!conn) {
  15524. mg_snprintf(conn,
  15525. NULL, /* No truncation check for ebuf */
  15526. ebuf,
  15527. ebuf_len,
  15528. "%s",
  15529. "Parameter error");
  15530. return -1;
  15531. }
  15532. /* Reset the previous responses */
  15533. conn->data_len = 0;
  15534. /* Implementation of API function for HTTP clients */
  15535. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15536. if (timeout >= 0) {
  15537. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15538. new_timeout = txt;
  15539. } else {
  15540. new_timeout = NULL;
  15541. }
  15542. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15543. ret = get_response(conn, ebuf, ebuf_len, &err);
  15544. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15545. #if defined(MG_LEGACY_INTERFACE)
  15546. /* TODO: 1) uri is deprecated;
  15547. * 2) here, ri.uri is the http response code */
  15548. conn->request_info.uri = conn->request_info.request_uri;
  15549. #endif
  15550. conn->request_info.local_uri = conn->request_info.request_uri;
  15551. /* TODO (mid): Define proper return values - maybe return length?
  15552. * For the first test use <0 for error and >0 for OK */
  15553. return (ret == 0) ? -1 : +1;
  15554. }
  15555. struct mg_connection *
  15556. mg_download(const char *host,
  15557. int port,
  15558. int use_ssl,
  15559. char *ebuf,
  15560. size_t ebuf_len,
  15561. const char *fmt,
  15562. ...)
  15563. {
  15564. struct mg_connection *conn;
  15565. va_list ap;
  15566. int i;
  15567. int reqerr;
  15568. if (ebuf_len > 0) {
  15569. ebuf[0] = '\0';
  15570. }
  15571. va_start(ap, fmt);
  15572. /* open a connection */
  15573. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15574. if (conn != NULL) {
  15575. i = mg_vprintf(conn, fmt, ap);
  15576. if (i <= 0) {
  15577. mg_snprintf(conn,
  15578. NULL, /* No truncation check for ebuf */
  15579. ebuf,
  15580. ebuf_len,
  15581. "%s",
  15582. "Error sending request");
  15583. } else {
  15584. /* make sure the buffer is clear */
  15585. conn->data_len = 0;
  15586. get_response(conn, ebuf, ebuf_len, &reqerr);
  15587. #if defined(MG_LEGACY_INTERFACE)
  15588. /* TODO: 1) uri is deprecated;
  15589. * 2) here, ri.uri is the http response code */
  15590. conn->request_info.uri = conn->request_info.request_uri;
  15591. #endif
  15592. conn->request_info.local_uri = conn->request_info.request_uri;
  15593. }
  15594. }
  15595. /* if an error occurred, close the connection */
  15596. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15597. mg_close_connection(conn);
  15598. conn = NULL;
  15599. }
  15600. va_end(ap);
  15601. return conn;
  15602. }
  15603. struct websocket_client_thread_data {
  15604. struct mg_connection *conn;
  15605. mg_websocket_data_handler data_handler;
  15606. mg_websocket_close_handler close_handler;
  15607. void *callback_data;
  15608. };
  15609. #if defined(USE_WEBSOCKET)
  15610. #if defined(_WIN32)
  15611. static unsigned __stdcall websocket_client_thread(void *data)
  15612. #else
  15613. static void *
  15614. websocket_client_thread(void *data)
  15615. #endif
  15616. {
  15617. struct websocket_client_thread_data *cdata =
  15618. (struct websocket_client_thread_data *)data;
  15619. void *user_thread_ptr = NULL;
  15620. #if !defined(_WIN32)
  15621. struct sigaction sa;
  15622. /* Ignore SIGPIPE */
  15623. memset(&sa, 0, sizeof(sa));
  15624. sa.sa_handler = SIG_IGN;
  15625. sigaction(SIGPIPE, &sa, NULL);
  15626. #endif
  15627. mg_set_thread_name("ws-clnt");
  15628. if (cdata->conn->phys_ctx) {
  15629. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15630. /* 3 indicates a websocket client thread */
  15631. /* TODO: check if conn->phys_ctx can be set */
  15632. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15633. cdata->conn->phys_ctx, 3);
  15634. }
  15635. }
  15636. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15637. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15638. if (cdata->close_handler != NULL) {
  15639. cdata->close_handler(cdata->conn, cdata->callback_data);
  15640. }
  15641. /* The websocket_client context has only this thread. If it runs out,
  15642. set the stop_flag to 2 (= "stopped"). */
  15643. cdata->conn->phys_ctx->stop_flag = 2;
  15644. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15645. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15646. 3,
  15647. user_thread_ptr);
  15648. }
  15649. mg_free((void *)cdata);
  15650. #if defined(_WIN32)
  15651. return 0;
  15652. #else
  15653. return NULL;
  15654. #endif
  15655. }
  15656. #endif
  15657. static struct mg_connection *
  15658. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15659. int use_ssl,
  15660. char *error_buffer,
  15661. size_t error_buffer_size,
  15662. const char *path,
  15663. const char *origin,
  15664. mg_websocket_data_handler data_func,
  15665. mg_websocket_close_handler close_func,
  15666. void *user_data)
  15667. {
  15668. struct mg_connection *conn = NULL;
  15669. #if defined(USE_WEBSOCKET)
  15670. struct websocket_client_thread_data *thread_data;
  15671. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15672. static const char *handshake_req;
  15673. int port = client_options->port;
  15674. const char *host = client_options->host;
  15675. int i;
  15676. if (origin != NULL) {
  15677. handshake_req = "GET %s HTTP/1.1\r\n"
  15678. "Host: %s\r\n"
  15679. "Upgrade: websocket\r\n"
  15680. "Connection: Upgrade\r\n"
  15681. "Sec-WebSocket-Key: %s\r\n"
  15682. "Sec-WebSocket-Version: 13\r\n"
  15683. "Origin: %s\r\n"
  15684. "\r\n";
  15685. } else {
  15686. handshake_req = "GET %s HTTP/1.1\r\n"
  15687. "Host: %s\r\n"
  15688. "Upgrade: websocket\r\n"
  15689. "Connection: Upgrade\r\n"
  15690. "Sec-WebSocket-Key: %s\r\n"
  15691. "Sec-WebSocket-Version: 13\r\n"
  15692. "\r\n";
  15693. }
  15694. #if defined(__clang__)
  15695. #pragma clang diagnostic push
  15696. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15697. #endif
  15698. /* Establish the client connection and request upgrade */
  15699. conn =
  15700. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15701. if (conn == NULL) {
  15702. /* error_buffer already filled */
  15703. return NULL;
  15704. }
  15705. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15706. if (i <= 0) {
  15707. mg_snprintf(conn,
  15708. NULL, /* No truncation check for ebuf */
  15709. error_buffer,
  15710. error_buffer_size,
  15711. "%s",
  15712. "Error sending request");
  15713. mg_close_connection(conn);
  15714. return NULL;
  15715. }
  15716. conn->data_len = 0;
  15717. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15718. mg_close_connection(conn);
  15719. return NULL;
  15720. }
  15721. conn->request_info.local_uri = conn->request_info.request_uri;
  15722. #if defined(__clang__)
  15723. #pragma clang diagnostic pop
  15724. #endif
  15725. /* Connection object will be null if something goes wrong */
  15726. if (conn == NULL) {
  15727. if (!*error_buffer) {
  15728. /* There should be already an error message */
  15729. mg_snprintf(conn,
  15730. NULL, /* No truncation check for ebuf */
  15731. error_buffer,
  15732. error_buffer_size,
  15733. "Unexpected error");
  15734. }
  15735. return NULL;
  15736. }
  15737. if (conn->response_info.status_code != 101) {
  15738. /* We sent an "upgrade" request. For a correct websocket
  15739. * protocol handshake, we expect a "101 Continue" response.
  15740. * Otherwise it is a protocol violation. Maybe the HTTP
  15741. * Server does not know websockets. */
  15742. if (!*error_buffer) {
  15743. /* set an error, if not yet set */
  15744. mg_snprintf(conn,
  15745. NULL, /* No truncation check for ebuf */
  15746. error_buffer,
  15747. error_buffer_size,
  15748. "Unexpected server reply");
  15749. }
  15750. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15751. mg_close_connection(conn);
  15752. return NULL;
  15753. }
  15754. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15755. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15756. if (!thread_data) {
  15757. DEBUG_TRACE("%s\r\n", "Out of memory");
  15758. mg_close_connection(conn);
  15759. return NULL;
  15760. }
  15761. thread_data->conn = conn;
  15762. thread_data->data_handler = data_func;
  15763. thread_data->close_handler = close_func;
  15764. thread_data->callback_data = user_data;
  15765. conn->phys_ctx->worker_threadids =
  15766. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15767. if (!conn->phys_ctx->worker_threadids) {
  15768. DEBUG_TRACE("%s\r\n", "Out of memory");
  15769. mg_free(thread_data);
  15770. mg_close_connection(conn);
  15771. return NULL;
  15772. }
  15773. /* Now upgrade to ws/wss client context */
  15774. conn->phys_ctx->user_data = user_data;
  15775. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15776. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15777. /* Start a thread to read the websocket client connection
  15778. * This thread will automatically stop when mg_disconnect is
  15779. * called on the client connection */
  15780. if (mg_start_thread_with_id(websocket_client_thread,
  15781. thread_data,
  15782. conn->phys_ctx->worker_threadids)
  15783. != 0) {
  15784. conn->phys_ctx->cfg_worker_threads = 0;
  15785. mg_free(thread_data);
  15786. mg_close_connection(conn);
  15787. conn = NULL;
  15788. DEBUG_TRACE("%s",
  15789. "Websocket client connect thread could not be started\r\n");
  15790. }
  15791. #else
  15792. /* Appease "unused parameter" warnings */
  15793. (void)client_options;
  15794. (void)use_ssl;
  15795. (void)error_buffer;
  15796. (void)error_buffer_size;
  15797. (void)path;
  15798. (void)origin;
  15799. (void)user_data;
  15800. (void)data_func;
  15801. (void)close_func;
  15802. #endif
  15803. return conn;
  15804. }
  15805. struct mg_connection *
  15806. mg_connect_websocket_client(const char *host,
  15807. int port,
  15808. int use_ssl,
  15809. char *error_buffer,
  15810. size_t error_buffer_size,
  15811. const char *path,
  15812. const char *origin,
  15813. mg_websocket_data_handler data_func,
  15814. mg_websocket_close_handler close_func,
  15815. void *user_data)
  15816. {
  15817. struct mg_client_options client_options;
  15818. memset(&client_options, 0, sizeof(client_options));
  15819. client_options.host = host;
  15820. client_options.port = port;
  15821. return mg_connect_websocket_client_impl(&client_options,
  15822. use_ssl,
  15823. error_buffer,
  15824. error_buffer_size,
  15825. path,
  15826. origin,
  15827. data_func,
  15828. close_func,
  15829. user_data);
  15830. }
  15831. struct mg_connection *
  15832. mg_connect_websocket_client_secure(
  15833. const struct mg_client_options *client_options,
  15834. char *error_buffer,
  15835. size_t error_buffer_size,
  15836. const char *path,
  15837. const char *origin,
  15838. mg_websocket_data_handler data_func,
  15839. mg_websocket_close_handler close_func,
  15840. void *user_data)
  15841. {
  15842. if (!client_options) {
  15843. return NULL;
  15844. }
  15845. return mg_connect_websocket_client_impl(client_options,
  15846. 1,
  15847. error_buffer,
  15848. error_buffer_size,
  15849. path,
  15850. origin,
  15851. data_func,
  15852. close_func,
  15853. user_data);
  15854. }
  15855. /* Prepare connection data structure */
  15856. static void
  15857. init_connection(struct mg_connection *conn)
  15858. {
  15859. /* Is keep alive allowed by the server */
  15860. int keep_alive_enabled =
  15861. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15862. if (!keep_alive_enabled) {
  15863. conn->must_close = 1;
  15864. }
  15865. /* Important: on new connection, reset the receiving buffer. Credit
  15866. * goes to crule42. */
  15867. conn->data_len = 0;
  15868. conn->handled_requests = 0;
  15869. mg_set_user_connection_data(conn, NULL);
  15870. #if defined(USE_SERVER_STATS)
  15871. conn->conn_state = 2; /* init */
  15872. #endif
  15873. /* call the init_connection callback if assigned */
  15874. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15875. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15876. void *conn_data = NULL;
  15877. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15878. mg_set_user_connection_data(conn, conn_data);
  15879. }
  15880. }
  15881. }
  15882. /* Process a connection - may handle multiple requests
  15883. * using the same connection.
  15884. * Must be called with a valid connection (conn and
  15885. * conn->phys_ctx must be valid).
  15886. */
  15887. static void
  15888. process_new_connection(struct mg_connection *conn)
  15889. {
  15890. struct mg_request_info *ri = &conn->request_info;
  15891. int keep_alive, discard_len;
  15892. char ebuf[100];
  15893. const char *hostend;
  15894. int reqerr, uri_type;
  15895. int is_http2 = 0;
  15896. #if defined(USE_SERVER_STATS)
  15897. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15898. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15899. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15900. /* could use atomic compare exchange, but this
  15901. * seems overkill for statistics data */
  15902. conn->phys_ctx->max_active_connections = mcon;
  15903. }
  15904. #endif
  15905. init_connection(conn);
  15906. DEBUG_TRACE("Start processing connection from %s",
  15907. conn->request_info.remote_addr);
  15908. /* Loop over multiple requests sent using the same connection
  15909. * (while "keep alive"). */
  15910. do {
  15911. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15912. conn->handled_requests + 1);
  15913. #if defined(USE_SERVER_STATS)
  15914. conn->conn_state = 3; /* ready */
  15915. #endif
  15916. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15917. /* The request sent by the client could not be understood by
  15918. * the server, or it was incomplete or a timeout. Send an
  15919. * error message and close the connection. */
  15920. if (reqerr > 0) {
  15921. DEBUG_ASSERT(ebuf[0] != '\0');
  15922. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15923. }
  15924. #if defined(USE_HTTP2)
  15925. } else if ((0 == strcmp(ri->http_version, "2.0"))
  15926. && (conn->handled_requests == 0)) {
  15927. /* Initialize */
  15928. is_http2 = 1;
  15929. conn->content_len = -1; /* content len is unknown */
  15930. #endif
  15931. } else if (strcmp(ri->http_version, "1.0")
  15932. && strcmp(ri->http_version, "1.1")) {
  15933. mg_snprintf(conn,
  15934. NULL, /* No truncation check for ebuf */
  15935. ebuf,
  15936. sizeof(ebuf),
  15937. "Bad HTTP version: [%s]",
  15938. ri->http_version);
  15939. mg_send_http_error(conn, 505, "%s", ebuf);
  15940. }
  15941. if ((ebuf[0] == '\0') && (!is_http2)) {
  15942. uri_type = get_uri_type(conn->request_info.request_uri);
  15943. switch (uri_type) {
  15944. case 1:
  15945. /* Asterisk */
  15946. conn->request_info.local_uri = 0;
  15947. /* TODO: Deal with '*'. */
  15948. break;
  15949. case 2:
  15950. /* relative uri */
  15951. conn->request_info.local_uri = conn->request_info.request_uri;
  15952. break;
  15953. case 3:
  15954. case 4:
  15955. /* absolute uri (with/without port) */
  15956. hostend = get_rel_url_at_current_server(
  15957. conn->request_info.request_uri, conn);
  15958. if (hostend) {
  15959. conn->request_info.local_uri = hostend;
  15960. } else {
  15961. conn->request_info.local_uri = NULL;
  15962. }
  15963. break;
  15964. default:
  15965. mg_snprintf(conn,
  15966. NULL, /* No truncation check for ebuf */
  15967. ebuf,
  15968. sizeof(ebuf),
  15969. "Invalid URI");
  15970. mg_send_http_error(conn, 400, "%s", ebuf);
  15971. conn->request_info.local_uri = NULL;
  15972. break;
  15973. }
  15974. #if defined(MG_LEGACY_INTERFACE)
  15975. /* Legacy before split into local_uri and request_uri */
  15976. conn->request_info.uri = conn->request_info.local_uri;
  15977. #endif
  15978. }
  15979. DEBUG_TRACE("http: %s, error: %s",
  15980. (ri->http_version ? ri->http_version : "none"),
  15981. (ebuf[0] ? ebuf : "none"));
  15982. #if defined(USE_HTTP2)
  15983. if (is_http2) {
  15984. if (!is_valid_http2_primer(conn)) {
  15985. /* Primer does not match expectation from RFC.
  15986. * See https://tools.ietf.org/html/rfc7540#section-3.5 */
  15987. mg_snprintf(conn,
  15988. NULL, /* No truncation check for ebuf */
  15989. ebuf,
  15990. sizeof(ebuf),
  15991. "Invalid HTTP/2 primer");
  15992. mg_send_http_error(conn, 400, "%s", ebuf);
  15993. } else {
  15994. /* Valid HTTP/2 primer received */
  15995. handle_http2(conn);
  15996. }
  15997. } else
  15998. #endif
  15999. if (ebuf[0] == '\0') {
  16000. if (conn->request_info.local_uri) {
  16001. /* handle request to local server */
  16002. #if defined(USE_SERVER_STATS)
  16003. conn->conn_state = 4; /* processing */
  16004. #endif
  16005. handle_request(conn);
  16006. #if defined(USE_SERVER_STATS)
  16007. conn->conn_state = 5; /* processed */
  16008. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  16009. conn->consumed_content);
  16010. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  16011. conn->num_bytes_sent);
  16012. #endif
  16013. DEBUG_TRACE("%s", "handle_request done");
  16014. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16015. conn->phys_ctx->callbacks.end_request(conn,
  16016. conn->status_code);
  16017. DEBUG_TRACE("%s", "end_request callback done");
  16018. }
  16019. log_access(conn);
  16020. } else {
  16021. /* TODO: handle non-local request (PROXY) */
  16022. conn->must_close = 1;
  16023. }
  16024. } else {
  16025. conn->must_close = 1;
  16026. }
  16027. if (ri->remote_user != NULL) {
  16028. mg_free((void *)ri->remote_user);
  16029. /* Important! When having connections with and without auth
  16030. * would cause double free and then crash */
  16031. ri->remote_user = NULL;
  16032. }
  16033. /* NOTE(lsm): order is important here. should_keep_alive() call
  16034. * is using parsed request, which will be invalid after
  16035. * memmove's below.
  16036. * Therefore, memorize should_keep_alive() result now for later
  16037. * use in loop exit condition. */
  16038. /* Enable it only if this request is completely discardable. */
  16039. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  16040. && (conn->content_len >= 0) && (conn->request_len > 0)
  16041. && ((conn->is_chunked == 4)
  16042. || (!conn->is_chunked
  16043. && ((conn->consumed_content == conn->content_len)
  16044. || ((conn->request_len + conn->content_len)
  16045. <= conn->data_len))))
  16046. && (!is_http2);
  16047. if (keep_alive) {
  16048. /* Discard all buffered data for this request */
  16049. discard_len =
  16050. ((conn->request_len + conn->content_len) < conn->data_len)
  16051. ? (int)(conn->request_len + conn->content_len)
  16052. : conn->data_len;
  16053. conn->data_len -= discard_len;
  16054. if (conn->data_len > 0) {
  16055. DEBUG_TRACE("discard_len = %d", discard_len);
  16056. memmove(conn->buf,
  16057. conn->buf + discard_len,
  16058. (size_t)conn->data_len);
  16059. }
  16060. }
  16061. DEBUG_ASSERT(conn->data_len >= 0);
  16062. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16063. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16064. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16065. (long int)conn->data_len,
  16066. (long int)conn->buf_size);
  16067. break;
  16068. }
  16069. conn->handled_requests++;
  16070. } while (keep_alive);
  16071. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16072. conn->request_info.remote_addr,
  16073. difftime(time(NULL), conn->conn_birth_time));
  16074. close_connection(conn);
  16075. #if defined(USE_SERVER_STATS)
  16076. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16077. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16078. #endif
  16079. }
  16080. #if defined(ALTERNATIVE_QUEUE)
  16081. static void
  16082. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16083. {
  16084. unsigned int i;
  16085. while (!ctx->stop_flag) {
  16086. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16087. /* find a free worker slot and signal it */
  16088. if (ctx->client_socks[i].in_use == 2) {
  16089. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16090. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16091. ctx->client_socks[i] = *sp;
  16092. ctx->client_socks[i].in_use = 1;
  16093. /* socket has been moved to the consumer */
  16094. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16095. (void)event_signal(ctx->client_wait_events[i]);
  16096. return;
  16097. }
  16098. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16099. }
  16100. }
  16101. /* queue is full */
  16102. mg_sleep(1);
  16103. }
  16104. /* must consume */
  16105. set_blocking_mode(sp->sock);
  16106. closesocket(sp->sock);
  16107. }
  16108. static int
  16109. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16110. {
  16111. DEBUG_TRACE("%s", "going idle");
  16112. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16113. ctx->client_socks[thread_index].in_use = 2;
  16114. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16115. event_wait(ctx->client_wait_events[thread_index]);
  16116. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16117. *sp = ctx->client_socks[thread_index];
  16118. if (ctx->stop_flag) {
  16119. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16120. if (sp->in_use == 1) {
  16121. /* must consume */
  16122. set_blocking_mode(sp->sock);
  16123. closesocket(sp->sock);
  16124. }
  16125. return 0;
  16126. }
  16127. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16128. if (sp->in_use == 1) {
  16129. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16130. return 1;
  16131. }
  16132. /* must not reach here */
  16133. DEBUG_ASSERT(0);
  16134. return 0;
  16135. }
  16136. #else /* ALTERNATIVE_QUEUE */
  16137. /* Worker threads take accepted socket from the queue */
  16138. static int
  16139. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16140. {
  16141. (void)thread_index;
  16142. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16143. DEBUG_TRACE("%s", "going idle");
  16144. /* If the queue is empty, wait. We're idle at this point. */
  16145. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  16146. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16147. }
  16148. /* If we're stopping, sq_head may be equal to sq_tail. */
  16149. if (ctx->sq_head > ctx->sq_tail) {
  16150. /* Copy socket from the queue and increment tail */
  16151. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16152. ctx->sq_tail++;
  16153. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16154. /* Wrap pointers if needed */
  16155. while (ctx->sq_tail > ctx->sq_size) {
  16156. ctx->sq_tail -= ctx->sq_size;
  16157. ctx->sq_head -= ctx->sq_size;
  16158. }
  16159. }
  16160. (void)pthread_cond_signal(&ctx->sq_empty);
  16161. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16162. return !ctx->stop_flag;
  16163. }
  16164. /* Master thread adds accepted socket to a queue */
  16165. static void
  16166. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16167. {
  16168. int queue_filled;
  16169. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16170. queue_filled = ctx->sq_head - ctx->sq_tail;
  16171. /* If the queue is full, wait */
  16172. while ((ctx->stop_flag == 0) && (queue_filled >= ctx->sq_size)) {
  16173. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16174. #if defined(USE_SERVER_STATS)
  16175. if (queue_filled > ctx->sq_max_fill) {
  16176. ctx->sq_max_fill = queue_filled;
  16177. }
  16178. #endif
  16179. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16180. ctx->sq_blocked = 0; /* Not blocked now */
  16181. queue_filled = ctx->sq_head - ctx->sq_tail;
  16182. }
  16183. if (queue_filled < ctx->sq_size) {
  16184. /* Copy socket to the queue and increment head */
  16185. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16186. ctx->sq_head++;
  16187. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16188. }
  16189. queue_filled = ctx->sq_head - ctx->sq_tail;
  16190. #if defined(USE_SERVER_STATS)
  16191. if (queue_filled > ctx->sq_max_fill) {
  16192. ctx->sq_max_fill = queue_filled;
  16193. }
  16194. #endif
  16195. (void)pthread_cond_signal(&ctx->sq_full);
  16196. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16197. }
  16198. #endif /* ALTERNATIVE_QUEUE */
  16199. static void
  16200. worker_thread_run(struct mg_connection *conn)
  16201. {
  16202. struct mg_context *ctx = conn->phys_ctx;
  16203. int thread_index;
  16204. struct mg_workerTLS tls;
  16205. #if defined(MG_LEGACY_INTERFACE)
  16206. uint32_t addr;
  16207. #endif
  16208. mg_set_thread_name("worker");
  16209. tls.is_master = 0;
  16210. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16211. #if defined(_WIN32)
  16212. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16213. #endif
  16214. /* Initialize thread local storage before calling any callback */
  16215. pthread_setspecific(sTlsKey, &tls);
  16216. /* Check if there is a user callback */
  16217. if (ctx->callbacks.init_thread) {
  16218. /* call init_thread for a worker thread (type 1), and store the
  16219. * return value */
  16220. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16221. } else {
  16222. /* No callback: set user pointer to NULL */
  16223. tls.user_ptr = NULL;
  16224. }
  16225. /* Connection structure has been pre-allocated */
  16226. thread_index = (int)(conn - ctx->worker_connections);
  16227. if ((thread_index < 0)
  16228. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16229. mg_cry_ctx_internal(ctx,
  16230. "Internal error: Invalid worker index %i",
  16231. thread_index);
  16232. return;
  16233. }
  16234. /* Request buffers are not pre-allocated. They are private to the
  16235. * request and do not contain any state information that might be
  16236. * of interest to anyone observing a server status. */
  16237. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16238. if (conn->buf == NULL) {
  16239. mg_cry_ctx_internal(
  16240. ctx,
  16241. "Out of memory: Cannot allocate buffer for worker %i",
  16242. thread_index);
  16243. return;
  16244. }
  16245. conn->buf_size = (int)ctx->max_request_size;
  16246. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16247. conn->host = NULL; /* until we have more information. */
  16248. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16249. conn->request_info.user_data = ctx->user_data;
  16250. /* Allocate a mutex for this connection to allow communication both
  16251. * within the request handler and from elsewhere in the application
  16252. */
  16253. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16254. mg_free(conn->buf);
  16255. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16256. return;
  16257. }
  16258. #if defined(USE_SERVER_STATS)
  16259. conn->conn_state = 1; /* not consumed */
  16260. #endif
  16261. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16262. * signal sq_empty condvar to wake up the master waiting in
  16263. * produce_socket() */
  16264. while (consume_socket(ctx, &conn->client, thread_index)) {
  16265. #if defined(USE_SERVER_STATS)
  16266. conn->conn_close_time = 0;
  16267. #endif
  16268. conn->conn_birth_time = time(NULL);
  16269. /* Fill in IP, port info early so even if SSL setup below fails,
  16270. * error handler would have the corresponding info.
  16271. * Thanks to Johannes Winkelmann for the patch.
  16272. */
  16273. #if defined(USE_IPV6)
  16274. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16275. conn->request_info.remote_port =
  16276. ntohs(conn->client.rsa.sin6.sin6_port);
  16277. } else
  16278. #endif
  16279. {
  16280. conn->request_info.remote_port =
  16281. ntohs(conn->client.rsa.sin.sin_port);
  16282. }
  16283. sockaddr_to_string(conn->request_info.remote_addr,
  16284. sizeof(conn->request_info.remote_addr),
  16285. &conn->client.rsa);
  16286. DEBUG_TRACE("Start processing connection from %s",
  16287. conn->request_info.remote_addr);
  16288. conn->request_info.is_ssl = conn->client.is_ssl;
  16289. if (conn->client.is_ssl) {
  16290. #if !defined(NO_SSL)
  16291. /* HTTPS connection */
  16292. if (sslize(conn,
  16293. conn->dom_ctx->ssl_ctx,
  16294. SSL_accept,
  16295. &(conn->phys_ctx->stop_flag),
  16296. NULL)) {
  16297. /* conn->dom_ctx is set in get_request */
  16298. /* Get SSL client certificate information (if set) */
  16299. ssl_get_client_cert_info(conn);
  16300. /* process HTTPS connection */
  16301. process_new_connection(conn);
  16302. /* Free client certificate info */
  16303. if (conn->request_info.client_cert) {
  16304. mg_free((void *)(conn->request_info.client_cert->subject));
  16305. mg_free((void *)(conn->request_info.client_cert->issuer));
  16306. mg_free((void *)(conn->request_info.client_cert->serial));
  16307. mg_free((void *)(conn->request_info.client_cert->finger));
  16308. /* Free certificate memory */
  16309. X509_free(
  16310. (X509 *)conn->request_info.client_cert->peer_cert);
  16311. conn->request_info.client_cert->peer_cert = 0;
  16312. conn->request_info.client_cert->subject = 0;
  16313. conn->request_info.client_cert->issuer = 0;
  16314. conn->request_info.client_cert->serial = 0;
  16315. conn->request_info.client_cert->finger = 0;
  16316. mg_free(conn->request_info.client_cert);
  16317. conn->request_info.client_cert = 0;
  16318. }
  16319. } else {
  16320. /* make sure the connection is cleaned up on SSL failure */
  16321. close_connection(conn);
  16322. }
  16323. #endif
  16324. } else {
  16325. /* process HTTP connection */
  16326. process_new_connection(conn);
  16327. }
  16328. DEBUG_TRACE("%s", "Connection closed");
  16329. #if defined(USE_SERVER_STATS)
  16330. conn->conn_close_time = time(NULL);
  16331. #endif
  16332. }
  16333. /* Call exit thread user callback */
  16334. if (ctx->callbacks.exit_thread) {
  16335. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16336. }
  16337. /* delete thread local storage objects */
  16338. pthread_setspecific(sTlsKey, NULL);
  16339. #if defined(_WIN32)
  16340. CloseHandle(tls.pthread_cond_helper_mutex);
  16341. #endif
  16342. pthread_mutex_destroy(&conn->mutex);
  16343. /* Free the request buffer. */
  16344. conn->buf_size = 0;
  16345. mg_free(conn->buf);
  16346. conn->buf = NULL;
  16347. #if defined(USE_SERVER_STATS)
  16348. conn->conn_state = 9; /* done */
  16349. #endif
  16350. DEBUG_TRACE("%s", "exiting");
  16351. }
  16352. /* Threads have different return types on Windows and Unix. */
  16353. #if defined(_WIN32)
  16354. static unsigned __stdcall worker_thread(void *thread_func_param)
  16355. {
  16356. worker_thread_run((struct mg_connection *)thread_func_param);
  16357. return 0;
  16358. }
  16359. #else
  16360. static void *
  16361. worker_thread(void *thread_func_param)
  16362. {
  16363. #if !defined(__ZEPHYR__)
  16364. struct sigaction sa;
  16365. /* Ignore SIGPIPE */
  16366. memset(&sa, 0, sizeof(sa));
  16367. sa.sa_handler = SIG_IGN;
  16368. sigaction(SIGPIPE, &sa, NULL);
  16369. #endif
  16370. worker_thread_run((struct mg_connection *)thread_func_param);
  16371. return NULL;
  16372. }
  16373. #endif /* _WIN32 */
  16374. /* This is an internal function, thus all arguments are expected to be
  16375. * valid - a NULL check is not required. */
  16376. static void
  16377. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16378. {
  16379. struct socket so;
  16380. char src_addr[IP_ADDR_STR_LEN];
  16381. socklen_t len = sizeof(so.rsa);
  16382. #if !defined(__ZEPHYR__)
  16383. int on = 1;
  16384. #endif
  16385. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16386. == INVALID_SOCKET) {
  16387. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16388. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16389. mg_cry_ctx_internal(ctx,
  16390. "%s: %s is not allowed to connect",
  16391. __func__,
  16392. src_addr);
  16393. closesocket(so.sock);
  16394. } else {
  16395. /* Put so socket structure into the queue */
  16396. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16397. set_close_on_exec(so.sock, NULL, ctx);
  16398. so.is_ssl = listener->is_ssl;
  16399. so.ssl_redir = listener->ssl_redir;
  16400. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16401. mg_cry_ctx_internal(ctx,
  16402. "%s: getsockname() failed: %s",
  16403. __func__,
  16404. strerror(ERRNO));
  16405. }
  16406. #if !defined(__ZEPHYR__)
  16407. /* Set TCP keep-alive. This is needed because if HTTP-level
  16408. * keep-alive
  16409. * is enabled, and client resets the connection, server won't get
  16410. * TCP FIN or RST and will keep the connection open forever. With
  16411. * TCP keep-alive, next keep-alive handshake will figure out that
  16412. * the client is down and will close the server end.
  16413. * Thanks to Igor Klopov who suggested the patch. */
  16414. if (setsockopt(so.sock,
  16415. SOL_SOCKET,
  16416. SO_KEEPALIVE,
  16417. (SOCK_OPT_TYPE)&on,
  16418. sizeof(on))
  16419. != 0) {
  16420. mg_cry_ctx_internal(
  16421. ctx,
  16422. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16423. __func__,
  16424. strerror(ERRNO));
  16425. }
  16426. #endif
  16427. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16428. * to effectively fill up the underlying IP packet payload and
  16429. * reduce the overhead of sending lots of small buffers. However
  16430. * this hurts the server's throughput (ie. operations per second)
  16431. * when HTTP 1.1 persistent connections are used and the responses
  16432. * are relatively small (eg. less than 1400 bytes).
  16433. */
  16434. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16435. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16436. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16437. mg_cry_ctx_internal(
  16438. ctx,
  16439. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16440. __func__,
  16441. strerror(ERRNO));
  16442. }
  16443. }
  16444. /* The "non blocking" property should already be
  16445. * inherited from the parent socket. Set it for
  16446. * non-compliant socket implementations. */
  16447. set_non_blocking_mode(so.sock);
  16448. so.in_use = 0;
  16449. produce_socket(ctx, &so);
  16450. }
  16451. }
  16452. static void
  16453. master_thread_run(struct mg_context *ctx)
  16454. {
  16455. struct mg_workerTLS tls;
  16456. struct mg_pollfd *pfd;
  16457. unsigned int i;
  16458. unsigned int workerthreadcount;
  16459. if (!ctx) {
  16460. return;
  16461. }
  16462. mg_set_thread_name("master");
  16463. /* Increase priority of the master thread */
  16464. #if defined(_WIN32)
  16465. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16466. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16467. int min_prio = sched_get_priority_min(SCHED_RR);
  16468. int max_prio = sched_get_priority_max(SCHED_RR);
  16469. if ((min_prio >= 0) && (max_prio >= 0)
  16470. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16471. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16472. struct sched_param sched_param = {0};
  16473. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16474. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16475. }
  16476. #endif
  16477. /* Initialize thread local storage */
  16478. #if defined(_WIN32)
  16479. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16480. #endif
  16481. tls.is_master = 1;
  16482. pthread_setspecific(sTlsKey, &tls);
  16483. if (ctx->callbacks.init_thread) {
  16484. /* Callback for the master thread (type 0) */
  16485. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16486. } else {
  16487. tls.user_ptr = NULL;
  16488. }
  16489. /* Server starts *now* */
  16490. ctx->start_time = time(NULL);
  16491. /* Start the server */
  16492. pfd = ctx->listening_socket_fds;
  16493. while (ctx->stop_flag == 0) {
  16494. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16495. pfd[i].fd = ctx->listening_sockets[i].sock;
  16496. pfd[i].events = POLLIN;
  16497. }
  16498. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16499. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16500. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16501. * successful poll, and POLLIN is defined as
  16502. * (POLLRDNORM | POLLRDBAND)
  16503. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16504. * pfd[i].revents == POLLIN. */
  16505. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  16506. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16507. }
  16508. }
  16509. }
  16510. }
  16511. /* Here stop_flag is 1 - Initiate shutdown. */
  16512. DEBUG_TRACE("%s", "stopping workers");
  16513. /* Stop signal received: somebody called mg_stop. Quit. */
  16514. close_all_listening_sockets(ctx);
  16515. /* Wakeup workers that are waiting for connections to handle. */
  16516. #if defined(ALTERNATIVE_QUEUE)
  16517. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16518. event_signal(ctx->client_wait_events[i]);
  16519. }
  16520. #else
  16521. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16522. pthread_cond_broadcast(&ctx->sq_full);
  16523. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16524. #endif
  16525. /* Join all worker threads to avoid leaking threads. */
  16526. workerthreadcount = ctx->cfg_worker_threads;
  16527. for (i = 0; i < workerthreadcount; i++) {
  16528. if (ctx->worker_threadids[i] != 0) {
  16529. mg_join_thread(ctx->worker_threadids[i]);
  16530. }
  16531. }
  16532. #if defined(USE_LUA)
  16533. /* Free Lua state of lua background task */
  16534. if (ctx->lua_background_state) {
  16535. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16536. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16537. if (lua_istable(lstate, -1)) {
  16538. reg_boolean(lstate, "shutdown", 1);
  16539. lua_pop(lstate, 1);
  16540. mg_sleep(2);
  16541. }
  16542. lua_close(lstate);
  16543. ctx->lua_background_state = 0;
  16544. }
  16545. #endif
  16546. DEBUG_TRACE("%s", "exiting");
  16547. /* call exit thread callback */
  16548. if (ctx->callbacks.exit_thread) {
  16549. /* Callback for the master thread (type 0) */
  16550. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16551. }
  16552. #if defined(_WIN32)
  16553. CloseHandle(tls.pthread_cond_helper_mutex);
  16554. #endif
  16555. pthread_setspecific(sTlsKey, NULL);
  16556. /* Signal mg_stop() that we're done.
  16557. * WARNING: This must be the very last thing this
  16558. * thread does, as ctx becomes invalid after this line. */
  16559. ctx->stop_flag = 2;
  16560. }
  16561. /* Threads have different return types on Windows and Unix. */
  16562. #if defined(_WIN32)
  16563. static unsigned __stdcall master_thread(void *thread_func_param)
  16564. {
  16565. master_thread_run((struct mg_context *)thread_func_param);
  16566. return 0;
  16567. }
  16568. #else
  16569. static void *
  16570. master_thread(void *thread_func_param)
  16571. {
  16572. #if !defined(__ZEPHYR__)
  16573. struct sigaction sa;
  16574. /* Ignore SIGPIPE */
  16575. memset(&sa, 0, sizeof(sa));
  16576. sa.sa_handler = SIG_IGN;
  16577. sigaction(SIGPIPE, &sa, NULL);
  16578. #endif
  16579. master_thread_run((struct mg_context *)thread_func_param);
  16580. return NULL;
  16581. }
  16582. #endif /* _WIN32 */
  16583. static void
  16584. free_context(struct mg_context *ctx)
  16585. {
  16586. int i;
  16587. struct mg_handler_info *tmp_rh;
  16588. if (ctx == NULL) {
  16589. return;
  16590. }
  16591. if (ctx->callbacks.exit_context) {
  16592. ctx->callbacks.exit_context(ctx);
  16593. }
  16594. /* All threads exited, no sync is needed. Destroy thread mutex and
  16595. * condvars
  16596. */
  16597. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16598. #if defined(ALTERNATIVE_QUEUE)
  16599. mg_free(ctx->client_socks);
  16600. if (ctx->client_wait_events != NULL) {
  16601. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16602. event_destroy(ctx->client_wait_events[i]);
  16603. }
  16604. mg_free(ctx->client_wait_events);
  16605. }
  16606. #else
  16607. (void)pthread_cond_destroy(&ctx->sq_empty);
  16608. (void)pthread_cond_destroy(&ctx->sq_full);
  16609. mg_free(ctx->squeue);
  16610. #endif
  16611. /* Destroy other context global data structures mutex */
  16612. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16613. #if defined(USE_TIMERS)
  16614. timers_exit(ctx);
  16615. #endif
  16616. /* Deallocate config parameters */
  16617. for (i = 0; i < NUM_OPTIONS; i++) {
  16618. if (ctx->dd.config[i] != NULL) {
  16619. #if defined(_MSC_VER)
  16620. #pragma warning(suppress : 6001)
  16621. #endif
  16622. mg_free(ctx->dd.config[i]);
  16623. }
  16624. }
  16625. /* Deallocate request handlers */
  16626. while (ctx->dd.handlers) {
  16627. tmp_rh = ctx->dd.handlers;
  16628. ctx->dd.handlers = tmp_rh->next;
  16629. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  16630. pthread_cond_destroy(&tmp_rh->refcount_cond);
  16631. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  16632. }
  16633. mg_free(tmp_rh->uri);
  16634. mg_free(tmp_rh);
  16635. }
  16636. #if !defined(NO_SSL)
  16637. /* Deallocate SSL context */
  16638. if (ctx->dd.ssl_ctx != NULL) {
  16639. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16640. int callback_ret =
  16641. (ctx->callbacks.external_ssl_ctx == NULL)
  16642. ? 0
  16643. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16644. if (callback_ret == 0) {
  16645. SSL_CTX_free(ctx->dd.ssl_ctx);
  16646. }
  16647. /* else: ignore error and ommit SSL_CTX_free in case
  16648. * callback_ret is 1 */
  16649. }
  16650. #endif /* !NO_SSL */
  16651. /* Deallocate worker thread ID array */
  16652. mg_free(ctx->worker_threadids);
  16653. /* Deallocate worker thread ID array */
  16654. mg_free(ctx->worker_connections);
  16655. /* deallocate system name string */
  16656. mg_free(ctx->systemName);
  16657. /* Deallocate context itself */
  16658. mg_free(ctx);
  16659. }
  16660. void
  16661. mg_stop(struct mg_context *ctx)
  16662. {
  16663. pthread_t mt;
  16664. if (!ctx) {
  16665. return;
  16666. }
  16667. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16668. * two threads is not allowed. */
  16669. mt = ctx->masterthreadid;
  16670. if (mt == 0) {
  16671. return;
  16672. }
  16673. ctx->masterthreadid = 0;
  16674. /* Set stop flag, so all threads know they have to exit. */
  16675. ctx->stop_flag = 1;
  16676. /* Wait until everything has stopped. */
  16677. while (ctx->stop_flag != 2) {
  16678. (void)mg_sleep(10);
  16679. }
  16680. mg_join_thread(mt);
  16681. free_context(ctx);
  16682. #if defined(_WIN32)
  16683. (void)WSACleanup();
  16684. #endif /* _WIN32 */
  16685. }
  16686. static void
  16687. get_system_name(char **sysName)
  16688. {
  16689. #if defined(_WIN32)
  16690. #if defined(_WIN32_WCE)
  16691. *sysName = mg_strdup("WinCE");
  16692. #else
  16693. char name[128];
  16694. DWORD dwVersion = 0;
  16695. DWORD dwMajorVersion = 0;
  16696. DWORD dwMinorVersion = 0;
  16697. DWORD dwBuild = 0;
  16698. BOOL wowRet, isWoW = FALSE;
  16699. #if defined(_MSC_VER)
  16700. #pragma warning(push)
  16701. /* GetVersion was declared deprecated */
  16702. #pragma warning(disable : 4996)
  16703. #endif
  16704. dwVersion = GetVersion();
  16705. #if defined(_MSC_VER)
  16706. #pragma warning(pop)
  16707. #endif
  16708. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16709. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16710. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16711. (void)dwBuild;
  16712. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16713. sprintf(name,
  16714. "Windows %u.%u%s",
  16715. (unsigned)dwMajorVersion,
  16716. (unsigned)dwMinorVersion,
  16717. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16718. *sysName = mg_strdup(name);
  16719. #endif
  16720. #elif defined(__ZEPHYR__)
  16721. *sysName = mg_strdup("Zephyr OS");
  16722. #else
  16723. struct utsname name;
  16724. memset(&name, 0, sizeof(name));
  16725. uname(&name);
  16726. *sysName = mg_strdup(name.sysname);
  16727. #endif
  16728. }
  16729. static void
  16730. legacy_init(const char **options)
  16731. {
  16732. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16733. if (options) {
  16734. const char **run_options = options;
  16735. const char *optname = config_options[LISTENING_PORTS].name;
  16736. /* Try to find the "listening_ports" option */
  16737. while (*run_options) {
  16738. if (!strcmp(*run_options, optname)) {
  16739. ports_option = run_options[1];
  16740. }
  16741. run_options += 2;
  16742. }
  16743. }
  16744. if (is_ssl_port_used(ports_option)) {
  16745. /* Initialize with SSL support */
  16746. mg_init_library(MG_FEATURES_TLS);
  16747. } else {
  16748. /* Initialize without SSL support */
  16749. mg_init_library(MG_FEATURES_DEFAULT);
  16750. }
  16751. }
  16752. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16753. static
  16754. #endif
  16755. struct mg_context *
  16756. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16757. {
  16758. struct mg_context *ctx;
  16759. const char *name, *value, *default_value;
  16760. int idx, ok, workerthreadcount;
  16761. unsigned int i;
  16762. int itmp;
  16763. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16764. const char **options =
  16765. ((init != NULL) ? (init->configuration_options) : (NULL));
  16766. struct mg_workerTLS tls;
  16767. #if defined(_WIN32)
  16768. WSADATA data;
  16769. WSAStartup(MAKEWORD(2, 2), &data);
  16770. #endif /* _WIN32 */
  16771. if (error != NULL) {
  16772. error->code = 0;
  16773. if (error->text_buffer_size > 0) {
  16774. *error->text = 0;
  16775. }
  16776. }
  16777. if (mg_init_library_called == 0) {
  16778. /* Legacy INIT, if mg_start is called without mg_init_library.
  16779. * Note: This will cause a memory leak when unloading the library.
  16780. */
  16781. legacy_init(options);
  16782. }
  16783. /* Allocate context and initialize reasonable general case defaults. */
  16784. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16785. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16786. mg_snprintf(NULL,
  16787. NULL, /* No truncation check for error buffers */
  16788. error->text,
  16789. error->text_buffer_size,
  16790. "%s",
  16791. "Out of memory");
  16792. }
  16793. return NULL;
  16794. }
  16795. /* Random number generator will initialize at the first call */
  16796. ctx->dd.auth_nonce_mask =
  16797. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16798. /* Save started thread index to reuse in other external API calls
  16799. * For the sake of thread synchronization all non-civetweb threads
  16800. * can be considered as single external thread */
  16801. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16802. tls.is_master = -1; /* Thread calling mg_start */
  16803. tls.thread_idx = ctx->starter_thread_idx;
  16804. #if defined(_WIN32)
  16805. tls.pthread_cond_helper_mutex = NULL;
  16806. #endif
  16807. pthread_setspecific(sTlsKey, &tls);
  16808. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16809. #if !defined(ALTERNATIVE_QUEUE)
  16810. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16811. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16812. ctx->sq_blocked = 0;
  16813. #endif
  16814. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16815. if (!ok) {
  16816. const char *err_msg =
  16817. "Cannot initialize thread synchronization objects";
  16818. /* Fatal error - abort start. However, this situation should never
  16819. * occur in practice. */
  16820. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16821. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16822. mg_snprintf(NULL,
  16823. NULL, /* No truncation check for error buffers */
  16824. error->text,
  16825. error->text_buffer_size,
  16826. "%s",
  16827. err_msg);
  16828. }
  16829. mg_free(ctx);
  16830. pthread_setspecific(sTlsKey, NULL);
  16831. return NULL;
  16832. }
  16833. if ((init != NULL) && (init->callbacks != NULL)) {
  16834. /* Set all callbacks except exit_context. */
  16835. ctx->callbacks = *init->callbacks;
  16836. exit_callback = init->callbacks->exit_context;
  16837. /* The exit callback is activated once the context is successfully
  16838. * created. It should not be called, if an incomplete context object
  16839. * is deleted during a failed initialization. */
  16840. ctx->callbacks.exit_context = 0;
  16841. }
  16842. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16843. ctx->dd.handlers = NULL;
  16844. ctx->dd.next = NULL;
  16845. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16846. ctx->dd.shared_lua_websockets = NULL;
  16847. #endif
  16848. /* Store options */
  16849. while (options && (name = *options++) != NULL) {
  16850. if ((idx = get_option_index(name)) == -1) {
  16851. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16852. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16853. mg_snprintf(NULL,
  16854. NULL, /* No truncation check for error buffers */
  16855. error->text,
  16856. error->text_buffer_size,
  16857. "Invalid configuration option: %s",
  16858. name);
  16859. }
  16860. free_context(ctx);
  16861. pthread_setspecific(sTlsKey, NULL);
  16862. return NULL;
  16863. } else if ((value = *options++) == NULL) {
  16864. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16865. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16866. mg_snprintf(NULL,
  16867. NULL, /* No truncation check for error buffers */
  16868. error->text,
  16869. error->text_buffer_size,
  16870. "Invalid configuration option value: %s",
  16871. name);
  16872. }
  16873. free_context(ctx);
  16874. pthread_setspecific(sTlsKey, NULL);
  16875. return NULL;
  16876. }
  16877. if (ctx->dd.config[idx] != NULL) {
  16878. /* A duplicate configuration option is not an error - the last
  16879. * option value will be used. */
  16880. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16881. mg_free(ctx->dd.config[idx]);
  16882. }
  16883. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16884. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16885. }
  16886. /* Set default value if needed */
  16887. for (i = 0; config_options[i].name != NULL; i++) {
  16888. default_value = config_options[i].default_value;
  16889. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16890. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16891. }
  16892. }
  16893. /* Request size option */
  16894. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16895. if (itmp < 1024) {
  16896. mg_cry_ctx_internal(ctx,
  16897. "%s too small",
  16898. config_options[MAX_REQUEST_SIZE].name);
  16899. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16900. mg_snprintf(NULL,
  16901. NULL, /* No truncation check for error buffers */
  16902. error->text,
  16903. error->text_buffer_size,
  16904. "Invalid configuration option value: %s",
  16905. config_options[MAX_REQUEST_SIZE].name);
  16906. }
  16907. free_context(ctx);
  16908. pthread_setspecific(sTlsKey, NULL);
  16909. return NULL;
  16910. }
  16911. ctx->max_request_size = (unsigned)itmp;
  16912. /* Queue length */
  16913. #if !defined(ALTERNATIVE_QUEUE)
  16914. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16915. if (itmp < 1) {
  16916. mg_cry_ctx_internal(ctx,
  16917. "%s too small",
  16918. config_options[CONNECTION_QUEUE_SIZE].name);
  16919. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16920. mg_snprintf(NULL,
  16921. NULL, /* No truncation check for error buffers */
  16922. error->text,
  16923. error->text_buffer_size,
  16924. "Invalid configuration option value: %s",
  16925. config_options[CONNECTION_QUEUE_SIZE].name);
  16926. }
  16927. free_context(ctx);
  16928. pthread_setspecific(sTlsKey, NULL);
  16929. return NULL;
  16930. }
  16931. ctx->squeue =
  16932. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16933. if (ctx->squeue == NULL) {
  16934. mg_cry_ctx_internal(ctx,
  16935. "Out of memory: Cannot allocate %s",
  16936. config_options[CONNECTION_QUEUE_SIZE].name);
  16937. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16938. mg_snprintf(NULL,
  16939. NULL, /* No truncation check for error buffers */
  16940. error->text,
  16941. error->text_buffer_size,
  16942. "Out of memory: Cannot allocate %s",
  16943. config_options[CONNECTION_QUEUE_SIZE].name);
  16944. }
  16945. free_context(ctx);
  16946. pthread_setspecific(sTlsKey, NULL);
  16947. return NULL;
  16948. }
  16949. ctx->sq_size = itmp;
  16950. #endif
  16951. /* Worker thread count option */
  16952. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16953. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16954. if (workerthreadcount <= 0) {
  16955. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16956. } else {
  16957. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16958. }
  16959. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16960. mg_snprintf(NULL,
  16961. NULL, /* No truncation check for error buffers */
  16962. error->text,
  16963. error->text_buffer_size,
  16964. "Invalid configuration option value: %s",
  16965. config_options[NUM_THREADS].name);
  16966. }
  16967. free_context(ctx);
  16968. pthread_setspecific(sTlsKey, NULL);
  16969. return NULL;
  16970. }
  16971. /* Document root */
  16972. #if defined(NO_FILES)
  16973. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16974. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16975. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16976. mg_snprintf(NULL,
  16977. NULL, /* No truncation check for error buffers */
  16978. error->text,
  16979. error->text_buffer_size,
  16980. "Invalid configuration option value: %s",
  16981. config_options[DOCUMENT_ROOT].name);
  16982. }
  16983. free_context(ctx);
  16984. pthread_setspecific(sTlsKey, NULL);
  16985. return NULL;
  16986. }
  16987. #endif
  16988. get_system_name(&ctx->systemName);
  16989. #if defined(USE_LUA)
  16990. /* If a Lua background script has been configured, start it. */
  16991. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16992. char ebuf[256];
  16993. struct vec opt_vec;
  16994. struct vec eq_vec;
  16995. const char *sparams;
  16996. lua_State *state = mg_prepare_lua_context_script(
  16997. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16998. if (!state) {
  16999. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  17000. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17001. mg_snprintf(NULL,
  17002. NULL, /* No truncation check for error buffers */
  17003. error->text,
  17004. error->text_buffer_size,
  17005. "Error in script %s: %s",
  17006. config_options[DOCUMENT_ROOT].name,
  17007. ebuf);
  17008. }
  17009. free_context(ctx);
  17010. pthread_setspecific(sTlsKey, NULL);
  17011. return NULL;
  17012. }
  17013. ctx->lua_background_state = (void *)state;
  17014. lua_newtable(state);
  17015. reg_boolean(state, "shutdown", 0);
  17016. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17017. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17018. reg_llstring(
  17019. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17020. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17021. break;
  17022. }
  17023. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17024. } else {
  17025. ctx->lua_background_state = 0;
  17026. }
  17027. #endif
  17028. /* Step by step initialization of ctx - depending on build options */
  17029. #if !defined(NO_FILESYSTEMS)
  17030. if (!set_gpass_option(ctx, NULL)) {
  17031. const char *err_msg = "Invalid global password file";
  17032. /* Fatal error - abort start. */
  17033. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17034. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17035. mg_snprintf(NULL,
  17036. NULL, /* No truncation check for error buffers */
  17037. error->text,
  17038. error->text_buffer_size,
  17039. "%s",
  17040. err_msg);
  17041. }
  17042. free_context(ctx);
  17043. pthread_setspecific(sTlsKey, NULL);
  17044. return NULL;
  17045. }
  17046. #endif
  17047. #if !defined(NO_SSL)
  17048. if (!init_ssl_ctx(ctx, NULL)) {
  17049. const char *err_msg = "Error initializing SSL context";
  17050. /* Fatal error - abort start. */
  17051. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17052. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17053. mg_snprintf(NULL,
  17054. NULL, /* No truncation check for error buffers */
  17055. error->text,
  17056. error->text_buffer_size,
  17057. "%s",
  17058. err_msg);
  17059. }
  17060. free_context(ctx);
  17061. pthread_setspecific(sTlsKey, NULL);
  17062. return NULL;
  17063. }
  17064. #endif
  17065. if (!set_ports_option(ctx)) {
  17066. const char *err_msg = "Failed to setup server ports";
  17067. /* Fatal error - abort start. */
  17068. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17069. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17070. mg_snprintf(NULL,
  17071. NULL, /* No truncation check for error buffers */
  17072. error->text,
  17073. error->text_buffer_size,
  17074. "%s",
  17075. err_msg);
  17076. }
  17077. free_context(ctx);
  17078. pthread_setspecific(sTlsKey, NULL);
  17079. return NULL;
  17080. }
  17081. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17082. if (!set_uid_option(ctx)) {
  17083. const char *err_msg = "Failed to run as configured user";
  17084. /* Fatal error - abort start. */
  17085. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17086. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17087. mg_snprintf(NULL,
  17088. NULL, /* No truncation check for error buffers */
  17089. error->text,
  17090. error->text_buffer_size,
  17091. "%s",
  17092. err_msg);
  17093. }
  17094. free_context(ctx);
  17095. pthread_setspecific(sTlsKey, NULL);
  17096. return NULL;
  17097. }
  17098. #endif
  17099. if (!set_acl_option(ctx)) {
  17100. const char *err_msg = "Failed to setup access control list";
  17101. /* Fatal error - abort start. */
  17102. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17103. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17104. mg_snprintf(NULL,
  17105. NULL, /* No truncation check for error buffers */
  17106. error->text,
  17107. error->text_buffer_size,
  17108. "%s",
  17109. err_msg);
  17110. }
  17111. free_context(ctx);
  17112. pthread_setspecific(sTlsKey, NULL);
  17113. return NULL;
  17114. }
  17115. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17116. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17117. sizeof(pthread_t),
  17118. ctx);
  17119. if (ctx->worker_threadids == NULL) {
  17120. const char *err_msg = "Not enough memory for worker thread ID array";
  17121. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17122. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17123. mg_snprintf(NULL,
  17124. NULL, /* No truncation check for error buffers */
  17125. error->text,
  17126. error->text_buffer_size,
  17127. "%s",
  17128. err_msg);
  17129. }
  17130. free_context(ctx);
  17131. pthread_setspecific(sTlsKey, NULL);
  17132. return NULL;
  17133. }
  17134. ctx->worker_connections =
  17135. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17136. sizeof(struct mg_connection),
  17137. ctx);
  17138. if (ctx->worker_connections == NULL) {
  17139. const char *err_msg =
  17140. "Not enough memory for worker thread connection array";
  17141. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17142. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17143. mg_snprintf(NULL,
  17144. NULL, /* No truncation check for error buffers */
  17145. error->text,
  17146. error->text_buffer_size,
  17147. "%s",
  17148. err_msg);
  17149. }
  17150. free_context(ctx);
  17151. pthread_setspecific(sTlsKey, NULL);
  17152. return NULL;
  17153. }
  17154. #if defined(ALTERNATIVE_QUEUE)
  17155. ctx->client_wait_events =
  17156. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17157. sizeof(ctx->client_wait_events[0]),
  17158. ctx);
  17159. if (ctx->client_wait_events == NULL) {
  17160. const char *err_msg = "Not enough memory for worker event array";
  17161. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17162. mg_free(ctx->worker_threadids);
  17163. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17164. mg_snprintf(NULL,
  17165. NULL, /* No truncation check for error buffers */
  17166. error->text,
  17167. error->text_buffer_size,
  17168. "%s",
  17169. err_msg);
  17170. }
  17171. free_context(ctx);
  17172. pthread_setspecific(sTlsKey, NULL);
  17173. return NULL;
  17174. }
  17175. ctx->client_socks =
  17176. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17177. sizeof(ctx->client_socks[0]),
  17178. ctx);
  17179. if (ctx->client_socks == NULL) {
  17180. const char *err_msg = "Not enough memory for worker socket array";
  17181. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17182. mg_free(ctx->client_wait_events);
  17183. mg_free(ctx->worker_threadids);
  17184. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17185. mg_snprintf(NULL,
  17186. NULL, /* No truncation check for error buffers */
  17187. error->text,
  17188. error->text_buffer_size,
  17189. "%s",
  17190. err_msg);
  17191. }
  17192. free_context(ctx);
  17193. pthread_setspecific(sTlsKey, NULL);
  17194. return NULL;
  17195. }
  17196. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17197. ctx->client_wait_events[i] = event_create();
  17198. if (ctx->client_wait_events[i] == 0) {
  17199. const char *err_msg = "Error creating worker event %i";
  17200. mg_cry_ctx_internal(ctx, err_msg, i);
  17201. while (i > 0) {
  17202. i--;
  17203. event_destroy(ctx->client_wait_events[i]);
  17204. }
  17205. mg_free(ctx->client_socks);
  17206. mg_free(ctx->client_wait_events);
  17207. mg_free(ctx->worker_threadids);
  17208. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17209. mg_snprintf(NULL,
  17210. NULL, /* No truncation check for error buffers */
  17211. error->text,
  17212. error->text_buffer_size,
  17213. err_msg,
  17214. i);
  17215. }
  17216. free_context(ctx);
  17217. pthread_setspecific(sTlsKey, NULL);
  17218. return NULL;
  17219. }
  17220. }
  17221. #endif
  17222. #if defined(USE_TIMERS)
  17223. if (timers_init(ctx) != 0) {
  17224. const char *err_msg = "Error creating timers";
  17225. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17226. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17227. mg_snprintf(NULL,
  17228. NULL, /* No truncation check for error buffers */
  17229. error->text,
  17230. error->text_buffer_size,
  17231. "%s",
  17232. err_msg);
  17233. }
  17234. free_context(ctx);
  17235. pthread_setspecific(sTlsKey, NULL);
  17236. return NULL;
  17237. }
  17238. #endif
  17239. /* Context has been created - init user libraries */
  17240. if (ctx->callbacks.init_context) {
  17241. ctx->callbacks.init_context(ctx);
  17242. }
  17243. /* From now, the context is successfully created.
  17244. * When it is destroyed, the exit callback should be called. */
  17245. ctx->callbacks.exit_context = exit_callback;
  17246. ctx->context_type = CONTEXT_SERVER; /* server context */
  17247. /* Start worker threads */
  17248. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17249. /* worker_thread sets up the other fields */
  17250. ctx->worker_connections[i].phys_ctx = ctx;
  17251. if (mg_start_thread_with_id(worker_thread,
  17252. &ctx->worker_connections[i],
  17253. &ctx->worker_threadids[i])
  17254. != 0) {
  17255. long error_no = (long)ERRNO;
  17256. /* thread was not created */
  17257. if (i > 0) {
  17258. /* If the second, third, ... thread cannot be created, set a
  17259. * warning, but keep running. */
  17260. mg_cry_ctx_internal(ctx,
  17261. "Cannot start worker thread %i: error %ld",
  17262. i + 1,
  17263. error_no);
  17264. /* If the server initialization should stop here, all
  17265. * threads that have already been created must be stopped
  17266. * first, before any free_context(ctx) call.
  17267. */
  17268. } else {
  17269. /* If the first worker thread cannot be created, stop
  17270. * initialization and free the entire server context. */
  17271. mg_cry_ctx_internal(ctx,
  17272. "Cannot create threads: error %ld",
  17273. error_no);
  17274. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17275. mg_snprintf(
  17276. NULL,
  17277. NULL, /* No truncation check for error buffers */
  17278. error->text,
  17279. error->text_buffer_size,
  17280. "Cannot create first worker thread: error %ld",
  17281. error_no);
  17282. }
  17283. free_context(ctx);
  17284. pthread_setspecific(sTlsKey, NULL);
  17285. return NULL;
  17286. }
  17287. break;
  17288. }
  17289. }
  17290. /* Start master (listening) thread */
  17291. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17292. pthread_setspecific(sTlsKey, NULL);
  17293. return ctx;
  17294. }
  17295. struct mg_context *
  17296. mg_start(const struct mg_callbacks *callbacks,
  17297. void *user_data,
  17298. const char **options)
  17299. {
  17300. struct mg_init_data init = {0};
  17301. init.callbacks = callbacks;
  17302. init.user_data = user_data;
  17303. init.configuration_options = options;
  17304. return mg_start2(&init, NULL);
  17305. }
  17306. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17307. /* Add an additional domain to an already running web server. */
  17308. int
  17309. mg_start_domain2(struct mg_context *ctx,
  17310. const char **options,
  17311. struct mg_error_data *error)
  17312. {
  17313. const char *name;
  17314. const char *value;
  17315. const char *default_value;
  17316. struct mg_domain_context *new_dom;
  17317. struct mg_domain_context *dom;
  17318. int idx, i;
  17319. if (error != NULL) {
  17320. error->code = 0;
  17321. if (error->text_buffer_size > 0) {
  17322. *error->text = 0;
  17323. }
  17324. }
  17325. if ((ctx == NULL) || (options == NULL)) {
  17326. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17327. mg_snprintf(NULL,
  17328. NULL, /* No truncation check for error buffers */
  17329. error->text,
  17330. error->text_buffer_size,
  17331. "%s",
  17332. "Invalid parameters");
  17333. }
  17334. return -1;
  17335. }
  17336. if (ctx->stop_flag != 0) {
  17337. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17338. mg_snprintf(NULL,
  17339. NULL, /* No truncation check for error buffers */
  17340. error->text,
  17341. error->text_buffer_size,
  17342. "%s",
  17343. "Server already stopped");
  17344. }
  17345. return -1;
  17346. }
  17347. new_dom = (struct mg_domain_context *)
  17348. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17349. if (!new_dom) {
  17350. /* Out of memory */
  17351. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17352. mg_snprintf(NULL,
  17353. NULL, /* No truncation check for error buffers */
  17354. error->text,
  17355. error->text_buffer_size,
  17356. "%s",
  17357. "Out or memory");
  17358. }
  17359. return -6;
  17360. }
  17361. /* Store options - TODO: unite duplicate code */
  17362. while (options && (name = *options++) != NULL) {
  17363. if ((idx = get_option_index(name)) == -1) {
  17364. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17365. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17366. mg_snprintf(NULL,
  17367. NULL, /* No truncation check for error buffers */
  17368. error->text,
  17369. error->text_buffer_size,
  17370. "Invalid option: %s",
  17371. name);
  17372. }
  17373. mg_free(new_dom);
  17374. return -2;
  17375. } else if ((value = *options++) == NULL) {
  17376. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17377. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17378. mg_snprintf(NULL,
  17379. NULL, /* No truncation check for error buffers */
  17380. error->text,
  17381. error->text_buffer_size,
  17382. "Invalid option value: %s",
  17383. name);
  17384. }
  17385. mg_free(new_dom);
  17386. return -2;
  17387. }
  17388. if (new_dom->config[idx] != NULL) {
  17389. /* Duplicate option: Later values overwrite earlier ones. */
  17390. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17391. mg_free(new_dom->config[idx]);
  17392. }
  17393. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17394. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17395. }
  17396. /* Authentication domain is mandatory */
  17397. /* TODO: Maybe use a new option hostname? */
  17398. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17399. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17400. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17401. mg_snprintf(NULL,
  17402. NULL, /* No truncation check for error buffers */
  17403. error->text,
  17404. error->text_buffer_size,
  17405. "Mandatory option %s missing",
  17406. config_options[AUTHENTICATION_DOMAIN].name);
  17407. }
  17408. mg_free(new_dom);
  17409. return -4;
  17410. }
  17411. /* Set default value if needed. Take the config value from
  17412. * ctx as a default value. */
  17413. for (i = 0; config_options[i].name != NULL; i++) {
  17414. default_value = ctx->dd.config[i];
  17415. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17416. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17417. }
  17418. }
  17419. new_dom->handlers = NULL;
  17420. new_dom->next = NULL;
  17421. new_dom->nonce_count = 0;
  17422. new_dom->auth_nonce_mask =
  17423. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17424. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17425. new_dom->shared_lua_websockets = NULL;
  17426. #endif
  17427. if (!init_ssl_ctx(ctx, new_dom)) {
  17428. /* Init SSL failed */
  17429. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17430. mg_snprintf(NULL,
  17431. NULL, /* No truncation check for error buffers */
  17432. error->text,
  17433. error->text_buffer_size,
  17434. "%s",
  17435. "Initializing SSL context failed");
  17436. }
  17437. mg_free(new_dom);
  17438. return -3;
  17439. }
  17440. /* Add element to linked list. */
  17441. mg_lock_context(ctx);
  17442. idx = 0;
  17443. dom = &(ctx->dd);
  17444. for (;;) {
  17445. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17446. dom->config[AUTHENTICATION_DOMAIN])) {
  17447. /* Domain collision */
  17448. mg_cry_ctx_internal(ctx,
  17449. "domain %s already in use",
  17450. new_dom->config[AUTHENTICATION_DOMAIN]);
  17451. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17452. mg_snprintf(NULL,
  17453. NULL, /* No truncation check for error buffers */
  17454. error->text,
  17455. error->text_buffer_size,
  17456. "Domain %s specified by %s is already in use",
  17457. new_dom->config[AUTHENTICATION_DOMAIN],
  17458. config_options[AUTHENTICATION_DOMAIN].name);
  17459. }
  17460. mg_free(new_dom);
  17461. mg_unlock_context(ctx);
  17462. return -5;
  17463. }
  17464. /* Count number of domains */
  17465. idx++;
  17466. if (dom->next == NULL) {
  17467. dom->next = new_dom;
  17468. break;
  17469. }
  17470. dom = dom->next;
  17471. }
  17472. mg_unlock_context(ctx);
  17473. /* Return domain number */
  17474. return idx;
  17475. }
  17476. int
  17477. mg_start_domain(struct mg_context *ctx, const char **options)
  17478. {
  17479. return mg_start_domain2(ctx, options, NULL);
  17480. }
  17481. #endif
  17482. /* Feature check API function */
  17483. unsigned
  17484. mg_check_feature(unsigned feature)
  17485. {
  17486. static const unsigned feature_set = 0
  17487. /* Set bits for available features according to API documentation.
  17488. * This bit mask is created at compile time, according to the active
  17489. * preprocessor defines. It is a single const value at runtime. */
  17490. #if !defined(NO_FILES)
  17491. | MG_FEATURES_FILES
  17492. #endif
  17493. #if !defined(NO_SSL)
  17494. | MG_FEATURES_SSL
  17495. #endif
  17496. #if !defined(NO_CGI)
  17497. | MG_FEATURES_CGI
  17498. #endif
  17499. #if defined(USE_IPV6)
  17500. | MG_FEATURES_IPV6
  17501. #endif
  17502. #if defined(USE_WEBSOCKET)
  17503. | MG_FEATURES_WEBSOCKET
  17504. #endif
  17505. #if defined(USE_LUA)
  17506. | MG_FEATURES_LUA
  17507. #endif
  17508. #if defined(USE_DUKTAPE)
  17509. | MG_FEATURES_SSJS
  17510. #endif
  17511. #if !defined(NO_CACHING)
  17512. | MG_FEATURES_CACHE
  17513. #endif
  17514. #if defined(USE_SERVER_STATS)
  17515. | MG_FEATURES_STATS
  17516. #endif
  17517. #if defined(USE_ZLIB)
  17518. | MG_FEATURES_COMPRESSION
  17519. #endif
  17520. /* Set some extra bits not defined in the API documentation.
  17521. * These bits may change without further notice. */
  17522. #if defined(MG_LEGACY_INTERFACE)
  17523. | 0x00008000u
  17524. #endif
  17525. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17526. | 0x00004000u
  17527. #endif
  17528. #if defined(MEMORY_DEBUGGING)
  17529. | 0x00001000u
  17530. #endif
  17531. #if defined(USE_TIMERS)
  17532. | 0x00020000u
  17533. #endif
  17534. #if !defined(NO_NONCE_CHECK)
  17535. | 0x00040000u
  17536. #endif
  17537. #if !defined(NO_POPEN)
  17538. | 0x00080000u
  17539. #endif
  17540. ;
  17541. return (feature & feature_set);
  17542. }
  17543. static size_t
  17544. mg_str_append(char **dst, char *end, const char *src)
  17545. {
  17546. size_t len = strlen(src);
  17547. if (*dst != end) {
  17548. /* Append src if enough space, or close dst. */
  17549. if ((size_t)(end - *dst) > len) {
  17550. strcpy(*dst, src);
  17551. *dst += len;
  17552. } else {
  17553. *dst = end;
  17554. }
  17555. }
  17556. return len;
  17557. }
  17558. /* Get system information. It can be printed or stored by the caller.
  17559. * Return the size of available information. */
  17560. int
  17561. mg_get_system_info(char *buffer, int buflen)
  17562. {
  17563. char *end, *append_eoobj = NULL, block[256];
  17564. size_t system_info_length = 0;
  17565. #if defined(_WIN32)
  17566. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17567. #else
  17568. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17569. #endif
  17570. if ((buffer == NULL) || (buflen < 1)) {
  17571. buflen = 0;
  17572. end = buffer;
  17573. } else {
  17574. *buffer = 0;
  17575. end = buffer + buflen;
  17576. }
  17577. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17578. /* has enough space to append eoobj */
  17579. append_eoobj = buffer;
  17580. if (end) {
  17581. end -= sizeof(eoobj) - 1;
  17582. }
  17583. }
  17584. system_info_length += mg_str_append(&buffer, end, "{");
  17585. /* Server version */
  17586. {
  17587. const char *version = mg_version();
  17588. mg_snprintf(NULL,
  17589. NULL,
  17590. block,
  17591. sizeof(block),
  17592. "%s\"version\" : \"%s\"",
  17593. eol,
  17594. version);
  17595. system_info_length += mg_str_append(&buffer, end, block);
  17596. }
  17597. /* System info */
  17598. {
  17599. #if defined(_WIN32)
  17600. DWORD dwVersion = 0;
  17601. DWORD dwMajorVersion = 0;
  17602. DWORD dwMinorVersion = 0;
  17603. SYSTEM_INFO si;
  17604. GetSystemInfo(&si);
  17605. #if defined(_MSC_VER)
  17606. #pragma warning(push)
  17607. /* GetVersion was declared deprecated */
  17608. #pragma warning(disable : 4996)
  17609. #endif
  17610. dwVersion = GetVersion();
  17611. #if defined(_MSC_VER)
  17612. #pragma warning(pop)
  17613. #endif
  17614. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17615. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17616. mg_snprintf(NULL,
  17617. NULL,
  17618. block,
  17619. sizeof(block),
  17620. ",%s\"os\" : \"Windows %u.%u\"",
  17621. eol,
  17622. (unsigned)dwMajorVersion,
  17623. (unsigned)dwMinorVersion);
  17624. system_info_length += mg_str_append(&buffer, end, block);
  17625. mg_snprintf(NULL,
  17626. NULL,
  17627. block,
  17628. sizeof(block),
  17629. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17630. eol,
  17631. (unsigned)si.wProcessorArchitecture,
  17632. (unsigned)si.dwNumberOfProcessors,
  17633. (unsigned)si.dwActiveProcessorMask);
  17634. system_info_length += mg_str_append(&buffer, end, block);
  17635. #elif defined(__ZEPHYR__)
  17636. mg_snprintf(NULL,
  17637. NULL,
  17638. block,
  17639. sizeof(block),
  17640. ",%s\"os\" : \"%s %s\"",
  17641. eol,
  17642. "Zephyr OS",
  17643. ZEPHYR_VERSION);
  17644. system_info_length += mg_str_append(&buffer, end, block);
  17645. #else
  17646. struct utsname name;
  17647. memset(&name, 0, sizeof(name));
  17648. uname(&name);
  17649. mg_snprintf(NULL,
  17650. NULL,
  17651. block,
  17652. sizeof(block),
  17653. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17654. eol,
  17655. name.sysname,
  17656. name.version,
  17657. name.release,
  17658. name.machine);
  17659. system_info_length += mg_str_append(&buffer, end, block);
  17660. #endif
  17661. }
  17662. /* Features */
  17663. {
  17664. mg_snprintf(NULL,
  17665. NULL,
  17666. block,
  17667. sizeof(block),
  17668. ",%s\"features\" : %lu"
  17669. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17670. eol,
  17671. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17672. eol,
  17673. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17674. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17675. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17676. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17677. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17678. : "",
  17679. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17680. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17681. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17682. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17683. system_info_length += mg_str_append(&buffer, end, block);
  17684. #if defined(USE_LUA)
  17685. mg_snprintf(NULL,
  17686. NULL,
  17687. block,
  17688. sizeof(block),
  17689. ",%s\"lua_version\" : \"%u (%s)\"",
  17690. eol,
  17691. (unsigned)LUA_VERSION_NUM,
  17692. LUA_RELEASE);
  17693. system_info_length += mg_str_append(&buffer, end, block);
  17694. #endif
  17695. #if defined(USE_DUKTAPE)
  17696. mg_snprintf(NULL,
  17697. NULL,
  17698. block,
  17699. sizeof(block),
  17700. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17701. eol,
  17702. (unsigned)DUK_VERSION / 10000,
  17703. ((unsigned)DUK_VERSION / 100) % 100,
  17704. (unsigned)DUK_VERSION % 100);
  17705. system_info_length += mg_str_append(&buffer, end, block);
  17706. #endif
  17707. }
  17708. /* Build date */
  17709. {
  17710. #if defined(GCC_DIAGNOSTIC)
  17711. #if GCC_VERSION >= 40900
  17712. #pragma GCC diagnostic push
  17713. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17714. #pragma GCC diagnostic ignored "-Wdate-time"
  17715. #endif
  17716. #endif
  17717. mg_snprintf(NULL,
  17718. NULL,
  17719. block,
  17720. sizeof(block),
  17721. ",%s\"build\" : \"%s\"",
  17722. eol,
  17723. __DATE__);
  17724. #if defined(GCC_DIAGNOSTIC)
  17725. #if GCC_VERSION >= 40900
  17726. #pragma GCC diagnostic pop
  17727. #endif
  17728. #endif
  17729. system_info_length += mg_str_append(&buffer, end, block);
  17730. }
  17731. /* Compiler information */
  17732. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17733. {
  17734. #if defined(_MSC_VER)
  17735. mg_snprintf(NULL,
  17736. NULL,
  17737. block,
  17738. sizeof(block),
  17739. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17740. eol,
  17741. (unsigned)_MSC_VER,
  17742. (unsigned)_MSC_FULL_VER);
  17743. system_info_length += mg_str_append(&buffer, end, block);
  17744. #elif defined(__MINGW64__)
  17745. mg_snprintf(NULL,
  17746. NULL,
  17747. block,
  17748. sizeof(block),
  17749. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17750. eol,
  17751. (unsigned)__MINGW64_VERSION_MAJOR,
  17752. (unsigned)__MINGW64_VERSION_MINOR);
  17753. system_info_length += mg_str_append(&buffer, end, block);
  17754. mg_snprintf(NULL,
  17755. NULL,
  17756. block,
  17757. sizeof(block),
  17758. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17759. eol,
  17760. (unsigned)__MINGW32_MAJOR_VERSION,
  17761. (unsigned)__MINGW32_MINOR_VERSION);
  17762. system_info_length += mg_str_append(&buffer, end, block);
  17763. #elif defined(__MINGW32__)
  17764. mg_snprintf(NULL,
  17765. NULL,
  17766. block,
  17767. sizeof(block),
  17768. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17769. eol,
  17770. (unsigned)__MINGW32_MAJOR_VERSION,
  17771. (unsigned)__MINGW32_MINOR_VERSION);
  17772. system_info_length += mg_str_append(&buffer, end, block);
  17773. #elif defined(__clang__)
  17774. mg_snprintf(NULL,
  17775. NULL,
  17776. block,
  17777. sizeof(block),
  17778. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17779. eol,
  17780. __clang_major__,
  17781. __clang_minor__,
  17782. __clang_patchlevel__,
  17783. __clang_version__);
  17784. system_info_length += mg_str_append(&buffer, end, block);
  17785. #elif defined(__GNUC__)
  17786. mg_snprintf(NULL,
  17787. NULL,
  17788. block,
  17789. sizeof(block),
  17790. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17791. eol,
  17792. (unsigned)__GNUC__,
  17793. (unsigned)__GNUC_MINOR__,
  17794. (unsigned)__GNUC_PATCHLEVEL__);
  17795. system_info_length += mg_str_append(&buffer, end, block);
  17796. #elif defined(__INTEL_COMPILER)
  17797. mg_snprintf(NULL,
  17798. NULL,
  17799. block,
  17800. sizeof(block),
  17801. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17802. eol,
  17803. (unsigned)__INTEL_COMPILER);
  17804. system_info_length += mg_str_append(&buffer, end, block);
  17805. #elif defined(__BORLANDC__)
  17806. mg_snprintf(NULL,
  17807. NULL,
  17808. block,
  17809. sizeof(block),
  17810. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17811. eol,
  17812. (unsigned)__BORLANDC__);
  17813. system_info_length += mg_str_append(&buffer, end, block);
  17814. #elif defined(__SUNPRO_C)
  17815. mg_snprintf(NULL,
  17816. NULL,
  17817. block,
  17818. sizeof(block),
  17819. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17820. eol,
  17821. (unsigned)__SUNPRO_C);
  17822. system_info_length += mg_str_append(&buffer, end, block);
  17823. #else
  17824. mg_snprintf(NULL,
  17825. NULL,
  17826. block,
  17827. sizeof(block),
  17828. ",%s\"compiler\" : \"other\"",
  17829. eol);
  17830. system_info_length += mg_str_append(&buffer, end, block);
  17831. #endif
  17832. }
  17833. /* Determine 32/64 bit data mode.
  17834. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17835. {
  17836. mg_snprintf(NULL,
  17837. NULL,
  17838. block,
  17839. sizeof(block),
  17840. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17841. "char:%u/%u, "
  17842. "ptr:%u, size:%u, time:%u\"",
  17843. eol,
  17844. (unsigned)sizeof(short),
  17845. (unsigned)sizeof(int),
  17846. (unsigned)sizeof(long),
  17847. (unsigned)sizeof(long long),
  17848. (unsigned)sizeof(float),
  17849. (unsigned)sizeof(double),
  17850. (unsigned)sizeof(long double),
  17851. (unsigned)sizeof(char),
  17852. (unsigned)sizeof(wchar_t),
  17853. (unsigned)sizeof(void *),
  17854. (unsigned)sizeof(size_t),
  17855. (unsigned)sizeof(time_t));
  17856. system_info_length += mg_str_append(&buffer, end, block);
  17857. }
  17858. /* Terminate string */
  17859. if (append_eoobj) {
  17860. strcat(append_eoobj, eoobj);
  17861. }
  17862. system_info_length += sizeof(eoobj) - 1;
  17863. return (int)system_info_length;
  17864. }
  17865. /* Get context information. It can be printed or stored by the caller.
  17866. * Return the size of available information. */
  17867. int
  17868. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17869. {
  17870. #if defined(USE_SERVER_STATS)
  17871. char *end, *append_eoobj = NULL, block[256];
  17872. size_t context_info_length = 0;
  17873. #if defined(_WIN32)
  17874. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17875. #else
  17876. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17877. #endif
  17878. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17879. if ((buffer == NULL) || (buflen < 1)) {
  17880. buflen = 0;
  17881. end = buffer;
  17882. } else {
  17883. *buffer = 0;
  17884. end = buffer + buflen;
  17885. }
  17886. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17887. /* has enough space to append eoobj */
  17888. append_eoobj = buffer;
  17889. end -= sizeof(eoobj) - 1;
  17890. }
  17891. context_info_length += mg_str_append(&buffer, end, "{");
  17892. if (ms) { /* <-- should be always true */
  17893. /* Memory information */
  17894. mg_snprintf(NULL,
  17895. NULL,
  17896. block,
  17897. sizeof(block),
  17898. "%s\"memory\" : {%s"
  17899. "\"blocks\" : %i,%s"
  17900. "\"used\" : %" INT64_FMT ",%s"
  17901. "\"maxUsed\" : %" INT64_FMT "%s"
  17902. "}",
  17903. eol,
  17904. eol,
  17905. ms->blockCount,
  17906. eol,
  17907. ms->totalMemUsed,
  17908. eol,
  17909. ms->maxMemUsed,
  17910. eol);
  17911. context_info_length += mg_str_append(&buffer, end, block);
  17912. }
  17913. if (ctx) {
  17914. /* Declare all variables at begin of the block, to comply
  17915. * with old C standards. */
  17916. char start_time_str[64] = {0};
  17917. char now_str[64] = {0};
  17918. time_t start_time = ctx->start_time;
  17919. time_t now = time(NULL);
  17920. /* Connections information */
  17921. mg_snprintf(NULL,
  17922. NULL,
  17923. block,
  17924. sizeof(block),
  17925. ",%s\"connections\" : {%s"
  17926. "\"active\" : %i,%s"
  17927. "\"maxActive\" : %i,%s"
  17928. "\"total\" : %" INT64_FMT "%s"
  17929. "}",
  17930. eol,
  17931. eol,
  17932. ctx->active_connections,
  17933. eol,
  17934. ctx->max_active_connections,
  17935. eol,
  17936. ctx->total_connections,
  17937. eol);
  17938. context_info_length += mg_str_append(&buffer, end, block);
  17939. /* Queue information */
  17940. #if !defined(ALTERNATIVE_QUEUE)
  17941. mg_snprintf(NULL,
  17942. NULL,
  17943. block,
  17944. sizeof(block),
  17945. ",%s\"queue\" : {%s"
  17946. "\"length\" : %i,%s"
  17947. "\"filled\" : %i,%s"
  17948. "\"maxFilled\" : %i,%s"
  17949. "\"full\" : %s%s"
  17950. "}",
  17951. eol,
  17952. eol,
  17953. ctx->sq_size,
  17954. eol,
  17955. ctx->sq_head - ctx->sq_tail,
  17956. eol,
  17957. ctx->sq_max_fill,
  17958. eol,
  17959. (ctx->sq_blocked ? "true" : "false"),
  17960. eol);
  17961. context_info_length += mg_str_append(&buffer, end, block);
  17962. #endif
  17963. /* Requests information */
  17964. mg_snprintf(NULL,
  17965. NULL,
  17966. block,
  17967. sizeof(block),
  17968. ",%s\"requests\" : {%s"
  17969. "\"total\" : %" INT64_FMT "%s"
  17970. "}",
  17971. eol,
  17972. eol,
  17973. ctx->total_requests,
  17974. eol);
  17975. context_info_length += mg_str_append(&buffer, end, block);
  17976. /* Data information */
  17977. mg_snprintf(NULL,
  17978. NULL,
  17979. block,
  17980. sizeof(block),
  17981. ",%s\"data\" : {%s"
  17982. "\"read\" : %" INT64_FMT ",%s"
  17983. "\"written\" : %" INT64_FMT "%s"
  17984. "}",
  17985. eol,
  17986. eol,
  17987. ctx->total_data_read,
  17988. eol,
  17989. ctx->total_data_written,
  17990. eol);
  17991. context_info_length += mg_str_append(&buffer, end, block);
  17992. /* Execution time information */
  17993. gmt_time_string(start_time_str,
  17994. sizeof(start_time_str) - 1,
  17995. &start_time);
  17996. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17997. mg_snprintf(NULL,
  17998. NULL,
  17999. block,
  18000. sizeof(block),
  18001. ",%s\"time\" : {%s"
  18002. "\"uptime\" : %.0f,%s"
  18003. "\"start\" : \"%s\",%s"
  18004. "\"now\" : \"%s\"%s"
  18005. "}",
  18006. eol,
  18007. eol,
  18008. difftime(now, start_time),
  18009. eol,
  18010. start_time_str,
  18011. eol,
  18012. now_str,
  18013. eol);
  18014. context_info_length += mg_str_append(&buffer, end, block);
  18015. }
  18016. /* Terminate string */
  18017. if (append_eoobj) {
  18018. strcat(append_eoobj, eoobj);
  18019. }
  18020. context_info_length += sizeof(eoobj) - 1;
  18021. return (int)context_info_length;
  18022. #else
  18023. (void)ctx;
  18024. if ((buffer != NULL) && (buflen > 0)) {
  18025. *buffer = 0;
  18026. }
  18027. return 0;
  18028. #endif
  18029. }
  18030. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18031. /* Get connection information. It can be printed or stored by the caller.
  18032. * Return the size of available information. */
  18033. int
  18034. mg_get_connection_info(const struct mg_context *ctx,
  18035. int idx,
  18036. char *buffer,
  18037. int buflen)
  18038. {
  18039. const struct mg_connection *conn;
  18040. const struct mg_request_info *ri;
  18041. char *end, *append_eoobj = NULL, block[256];
  18042. size_t connection_info_length = 0;
  18043. int state = 0;
  18044. const char *state_str = "unknown";
  18045. #if defined(_WIN32)
  18046. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18047. #else
  18048. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18049. #endif
  18050. if ((buffer == NULL) || (buflen < 1)) {
  18051. buflen = 0;
  18052. end = buffer;
  18053. } else {
  18054. *buffer = 0;
  18055. end = buffer + buflen;
  18056. }
  18057. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18058. /* has enough space to append eoobj */
  18059. append_eoobj = buffer;
  18060. end -= sizeof(eoobj) - 1;
  18061. }
  18062. if ((ctx == NULL) || (idx < 0)) {
  18063. /* Parameter error */
  18064. return 0;
  18065. }
  18066. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18067. /* Out of range */
  18068. return 0;
  18069. }
  18070. /* Take connection [idx]. This connection is not locked in
  18071. * any way, so some other thread might use it. */
  18072. conn = (ctx->worker_connections) + idx;
  18073. /* Initialize output string */
  18074. connection_info_length += mg_str_append(&buffer, end, "{");
  18075. /* Init variables */
  18076. ri = &(conn->request_info);
  18077. #if defined(USE_SERVER_STATS)
  18078. state = conn->conn_state;
  18079. /* State as string */
  18080. switch (state) {
  18081. case 0:
  18082. state_str = "undefined";
  18083. break;
  18084. case 1:
  18085. state_str = "not used";
  18086. break;
  18087. case 2:
  18088. state_str = "init";
  18089. break;
  18090. case 3:
  18091. state_str = "ready";
  18092. break;
  18093. case 4:
  18094. state_str = "processing";
  18095. break;
  18096. case 5:
  18097. state_str = "processed";
  18098. break;
  18099. case 6:
  18100. state_str = "to close";
  18101. break;
  18102. case 7:
  18103. state_str = "closing";
  18104. break;
  18105. case 8:
  18106. state_str = "closed";
  18107. break;
  18108. case 9:
  18109. state_str = "done";
  18110. break;
  18111. }
  18112. #endif
  18113. /* Connection info */
  18114. if ((state >= 3) && (state < 9)) {
  18115. mg_snprintf(NULL,
  18116. NULL,
  18117. block,
  18118. sizeof(block),
  18119. "%s\"connection\" : {%s"
  18120. "\"remote\" : {%s"
  18121. "\"protocol\" : \"%s\",%s"
  18122. "\"addr\" : \"%s\",%s"
  18123. "\"port\" : %u%s"
  18124. "},%s"
  18125. "\"handled_requests\" : %u%s"
  18126. "}",
  18127. eol,
  18128. eol,
  18129. eol,
  18130. get_proto_name(conn),
  18131. eol,
  18132. ri->remote_addr,
  18133. eol,
  18134. ri->remote_port,
  18135. eol,
  18136. eol,
  18137. conn->handled_requests,
  18138. eol);
  18139. connection_info_length += mg_str_append(&buffer, end, block);
  18140. }
  18141. /* Request info */
  18142. if ((state >= 4) && (state < 6)) {
  18143. mg_snprintf(NULL,
  18144. NULL,
  18145. block,
  18146. sizeof(block),
  18147. "%s%s\"request_info\" : {%s"
  18148. "\"method\" : \"%s\",%s"
  18149. "\"uri\" : \"%s\",%s"
  18150. "\"query\" : %s%s%s%s"
  18151. "}",
  18152. (connection_info_length > 1 ? "," : ""),
  18153. eol,
  18154. eol,
  18155. ri->request_method,
  18156. eol,
  18157. ri->request_uri,
  18158. eol,
  18159. ri->query_string ? "\"" : "",
  18160. ri->query_string ? ri->query_string : "null",
  18161. ri->query_string ? "\"" : "",
  18162. eol);
  18163. connection_info_length += mg_str_append(&buffer, end, block);
  18164. }
  18165. /* Execution time information */
  18166. if ((state >= 2) && (state < 9)) {
  18167. char start_time_str[64] = {0};
  18168. char close_time_str[64] = {0};
  18169. time_t start_time = conn->conn_birth_time;
  18170. time_t close_time = conn->conn_close_time;
  18171. double time_diff;
  18172. gmt_time_string(start_time_str,
  18173. sizeof(start_time_str) - 1,
  18174. &start_time);
  18175. if (close_time != 0) {
  18176. time_diff = difftime(close_time, start_time);
  18177. gmt_time_string(close_time_str,
  18178. sizeof(close_time_str) - 1,
  18179. &close_time);
  18180. } else {
  18181. time_t now = time(NULL);
  18182. time_diff = difftime(now, start_time);
  18183. close_time_str[0] = 0; /* or use "now" ? */
  18184. }
  18185. mg_snprintf(NULL,
  18186. NULL,
  18187. block,
  18188. sizeof(block),
  18189. "%s%s\"time\" : {%s"
  18190. "\"uptime\" : %.0f,%s"
  18191. "\"start\" : \"%s\",%s"
  18192. "\"closed\" : \"%s\"%s"
  18193. "}",
  18194. (connection_info_length > 1 ? "," : ""),
  18195. eol,
  18196. eol,
  18197. time_diff,
  18198. eol,
  18199. start_time_str,
  18200. eol,
  18201. close_time_str,
  18202. eol);
  18203. connection_info_length += mg_str_append(&buffer, end, block);
  18204. }
  18205. /* Remote user name */
  18206. if ((ri->remote_user) && (state < 9)) {
  18207. mg_snprintf(NULL,
  18208. NULL,
  18209. block,
  18210. sizeof(block),
  18211. "%s%s\"user\" : {%s"
  18212. "\"name\" : \"%s\",%s"
  18213. "}",
  18214. (connection_info_length > 1 ? "," : ""),
  18215. eol,
  18216. eol,
  18217. ri->remote_user,
  18218. eol);
  18219. connection_info_length += mg_str_append(&buffer, end, block);
  18220. }
  18221. /* Data block */
  18222. if (state >= 3) {
  18223. mg_snprintf(NULL,
  18224. NULL,
  18225. block,
  18226. sizeof(block),
  18227. "%s%s\"data\" : {%s"
  18228. "\"read\" : %" INT64_FMT ",%s"
  18229. "\"written\" : %" INT64_FMT "%s"
  18230. "}",
  18231. (connection_info_length > 1 ? "," : ""),
  18232. eol,
  18233. eol,
  18234. conn->consumed_content,
  18235. eol,
  18236. conn->num_bytes_sent,
  18237. eol);
  18238. connection_info_length += mg_str_append(&buffer, end, block);
  18239. }
  18240. /* State */
  18241. mg_snprintf(NULL,
  18242. NULL,
  18243. block,
  18244. sizeof(block),
  18245. "%s%s\"state\" : \"%s\"",
  18246. (connection_info_length > 1 ? "," : ""),
  18247. eol,
  18248. state_str);
  18249. connection_info_length += mg_str_append(&buffer, end, block);
  18250. /* Terminate string */
  18251. if (append_eoobj) {
  18252. strcat(append_eoobj, eoobj);
  18253. }
  18254. connection_info_length += sizeof(eoobj) - 1;
  18255. return (int)connection_info_length;
  18256. }
  18257. #endif
  18258. /* Initialize this library. This function does not need to be thread safe.
  18259. */
  18260. unsigned
  18261. mg_init_library(unsigned features)
  18262. {
  18263. #if !defined(NO_SSL)
  18264. char ebuf[128];
  18265. #endif
  18266. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18267. unsigned features_inited = features_to_init;
  18268. if (mg_init_library_called <= 0) {
  18269. /* Not initialized yet */
  18270. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18271. return 0;
  18272. }
  18273. }
  18274. mg_global_lock();
  18275. if (mg_init_library_called <= 0) {
  18276. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  18277. /* Fatal error - abort start. However, this situation should
  18278. * never occur in practice. */
  18279. mg_global_unlock();
  18280. return 0;
  18281. }
  18282. #if defined(_WIN32)
  18283. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18284. #else
  18285. pthread_mutexattr_init(&pthread_mutex_attr);
  18286. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  18287. #endif
  18288. #if defined(USE_LUA)
  18289. lua_init_optional_libraries();
  18290. #endif
  18291. }
  18292. mg_global_unlock();
  18293. #if !defined(NO_SSL)
  18294. if (features_to_init & MG_FEATURES_SSL) {
  18295. if (!mg_ssl_initialized) {
  18296. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18297. mg_ssl_initialized = 1;
  18298. } else {
  18299. (void)ebuf;
  18300. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18301. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18302. }
  18303. } else {
  18304. /* ssl already initialized */
  18305. }
  18306. }
  18307. #endif
  18308. /* Start WinSock for Windows */
  18309. mg_global_lock();
  18310. if (mg_init_library_called <= 0) {
  18311. #if defined(_WIN32)
  18312. WSADATA data;
  18313. WSAStartup(MAKEWORD(2, 2), &data);
  18314. #endif /* _WIN32 */
  18315. mg_init_library_called = 1;
  18316. } else {
  18317. mg_init_library_called++;
  18318. }
  18319. mg_global_unlock();
  18320. return features_inited;
  18321. }
  18322. /* Un-initialize this library. */
  18323. unsigned
  18324. mg_exit_library(void)
  18325. {
  18326. if (mg_init_library_called <= 0) {
  18327. return 0;
  18328. }
  18329. mg_global_lock();
  18330. mg_init_library_called--;
  18331. if (mg_init_library_called == 0) {
  18332. #if defined(_WIN32)
  18333. (void)WSACleanup();
  18334. #endif /* _WIN32 */
  18335. #if !defined(NO_SSL)
  18336. if (mg_ssl_initialized) {
  18337. uninitialize_ssl();
  18338. mg_ssl_initialized = 0;
  18339. }
  18340. #endif
  18341. #if defined(_WIN32)
  18342. (void)pthread_mutex_destroy(&global_log_file_lock);
  18343. #else
  18344. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18345. #endif
  18346. (void)pthread_key_delete(sTlsKey);
  18347. #if defined(USE_LUA)
  18348. lua_exit_optional_libraries();
  18349. #endif
  18350. mg_global_unlock();
  18351. (void)pthread_mutex_destroy(&global_lock_mutex);
  18352. return 1;
  18353. }
  18354. mg_global_unlock();
  18355. return 1;
  18356. }
  18357. /* End of civetweb.c */