civetweb.c 566 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104
  1. /* Copyright (c) 2013-2020 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE 8096
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #ifndef DEBUG_TRACE_STREAM
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. /********************************************************************/
  369. /* CivetWeb configuration defines */
  370. /********************************************************************/
  371. /* Maximum number of threads that can be configured.
  372. * The number of threads actually created depends on the "num_threads"
  373. * configuration parameter, but this is the upper limit. */
  374. #if !defined(MAX_WORKER_THREADS)
  375. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  376. #endif
  377. /* Timeout interval for select/poll calls.
  378. * The timeouts depend on "*_timeout_ms" configuration values, but long
  379. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  380. * This reduces the time required to stop the server. */
  381. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  382. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  383. #endif
  384. /* Do not try to compress files smaller than this limit. */
  385. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  386. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  387. #endif
  388. #if !defined(PASSWORDS_FILE_NAME)
  389. #define PASSWORDS_FILE_NAME ".htpasswd"
  390. #endif
  391. /* Initial buffer size for all CGI environment variables. In case there is
  392. * not enough space, another block is allocated. */
  393. #if !defined(CGI_ENVIRONMENT_SIZE)
  394. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  395. #endif
  396. /* Maximum number of environment variables. */
  397. #if !defined(MAX_CGI_ENVIR_VARS)
  398. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  399. #endif
  400. /* General purpose buffer size. */
  401. #if !defined(MG_BUF_LEN) /* in bytes */
  402. #define MG_BUF_LEN (1024 * 8)
  403. #endif
  404. /********************************************************************/
  405. /* Helper makros */
  406. #if !defined(ARRAY_SIZE)
  407. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  408. #endif
  409. #include <stdint.h>
  410. /* Standard defines */
  411. #if !defined(INT64_MAX)
  412. #define INT64_MAX (9223372036854775807)
  413. #endif
  414. #define SHUTDOWN_RD (0)
  415. #define SHUTDOWN_WR (1)
  416. #define SHUTDOWN_BOTH (2)
  417. mg_static_assert(MAX_WORKER_THREADS >= 1,
  418. "worker threads must be a positive number");
  419. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  420. "size_t data type size check");
  421. #if defined(_WIN32) /* WINDOWS include block */
  422. #include <malloc.h> /* *alloc( */
  423. #include <stdlib.h> /* *alloc( */
  424. #include <time.h> /* struct timespec */
  425. #include <windows.h>
  426. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  427. #include <ws2tcpip.h>
  428. typedef const char *SOCK_OPT_TYPE;
  429. #if !defined(PATH_MAX)
  430. #define W_PATH_MAX (MAX_PATH)
  431. /* at most three UTF-8 chars per wchar_t */
  432. #define PATH_MAX (W_PATH_MAX * 3)
  433. #else
  434. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  435. #endif
  436. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  437. #if !defined(_IN_PORT_T)
  438. #if !defined(in_port_t)
  439. #define in_port_t u_short
  440. #endif
  441. #endif
  442. #if !defined(_WIN32_WCE)
  443. #include <direct.h>
  444. #include <io.h>
  445. #include <process.h>
  446. #else /* _WIN32_WCE */
  447. #define NO_CGI /* WinCE has no pipes */
  448. #define NO_POPEN /* WinCE has no popen */
  449. typedef long off_t;
  450. #define errno ((int)(GetLastError()))
  451. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  452. #endif /* _WIN32_WCE */
  453. #define MAKEUQUAD(lo, hi) \
  454. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  455. #define RATE_DIFF (10000000) /* 100 nsecs */
  456. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  457. #define SYS2UNIX_TIME(lo, hi) \
  458. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  459. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  460. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  461. * Also use _strtoui64 on modern M$ compilers */
  462. #if defined(_MSC_VER)
  463. #if (_MSC_VER < 1300)
  464. #define STRX(x) #x
  465. #define STR(x) STRX(x)
  466. #define __func__ __FILE__ ":" STR(__LINE__)
  467. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  468. #define strtoll(x, y, z) (_atoi64(x))
  469. #else
  470. #define __func__ __FUNCTION__
  471. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  472. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  473. #endif
  474. #endif /* _MSC_VER */
  475. #define ERRNO ((int)(GetLastError()))
  476. #define NO_SOCKLEN_T
  477. #if defined(_WIN64) || defined(__MINGW64__)
  478. #if !defined(SSL_LIB)
  479. #if defined(OPENSSL_API_1_1)
  480. #define SSL_LIB "libssl-1_1-x64.dll"
  481. #else /* OPENSSL_API_1_1 */
  482. #define SSL_LIB "ssleay64.dll"
  483. #endif /* OPENSSL_API_1_1 */
  484. #endif /* SSL_LIB */
  485. #if !defined(CRYPTO_LIB)
  486. #if defined(OPENSSL_API_1_1)
  487. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  488. #else /* OPENSSL_API_1_1 */
  489. #define CRYPTO_LIB "libeay64.dll"
  490. #endif /* OPENSSL_API_1_1 */
  491. #endif /* CRYPTO_LIB */
  492. #else /* defined(_WIN64) || defined(__MINGW64__) */
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1.dll"
  496. #else
  497. #define SSL_LIB "ssleay32.dll"
  498. #endif
  499. #endif /* SSL_LIB */
  500. #if !defined(CRYPTO_LIB)
  501. #if defined(OPENSSL_API_1_1)
  502. #define CRYPTO_LIB "libcrypto-1_1.dll"
  503. #else
  504. #define CRYPTO_LIB "libeay32.dll"
  505. #endif
  506. #endif /* CRYPTO_LIB */
  507. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  508. #define O_NONBLOCK (0)
  509. #if !defined(W_OK)
  510. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  511. #endif
  512. #define _POSIX_
  513. #define INT64_FMT "I64d"
  514. #define UINT64_FMT "I64u"
  515. #define WINCDECL __cdecl
  516. #define vsnprintf_impl _vsnprintf
  517. #define access _access
  518. #define mg_sleep(x) (Sleep(x))
  519. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  520. #if !defined(popen)
  521. #define popen(x, y) (_popen(x, y))
  522. #endif
  523. #if !defined(pclose)
  524. #define pclose(x) (_pclose(x))
  525. #endif
  526. #define close(x) (_close(x))
  527. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  528. #define RTLD_LAZY (0)
  529. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  530. #define fdopen(x, y) (_fdopen((x), (y)))
  531. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  532. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  533. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  534. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  535. #define sleep(x) (Sleep((x)*1000))
  536. #define rmdir(x) (_rmdir(x))
  537. #if defined(_WIN64) || !defined(__MINGW32__)
  538. /* Only MinGW 32 bit is missing this function */
  539. #define timegm(x) (_mkgmtime(x))
  540. #else
  541. time_t timegm(struct tm *tm);
  542. #define NEED_TIMEGM
  543. #endif
  544. #if !defined(fileno)
  545. #define fileno(x) (_fileno(x))
  546. #endif /* !fileno MINGW #defines fileno */
  547. typedef struct {
  548. CRITICAL_SECTION sec; /* Immovable */
  549. } pthread_mutex_t;
  550. typedef DWORD pthread_key_t;
  551. typedef HANDLE pthread_t;
  552. typedef struct {
  553. pthread_mutex_t threadIdSec;
  554. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  555. } pthread_cond_t;
  556. #if !defined(__clockid_t_defined)
  557. typedef DWORD clockid_t;
  558. #endif
  559. #if !defined(CLOCK_MONOTONIC)
  560. #define CLOCK_MONOTONIC (1)
  561. #endif
  562. #if !defined(CLOCK_REALTIME)
  563. #define CLOCK_REALTIME (2)
  564. #endif
  565. #if !defined(CLOCK_THREAD)
  566. #define CLOCK_THREAD (3)
  567. #endif
  568. #if !defined(CLOCK_PROCESS)
  569. #define CLOCK_PROCESS (4)
  570. #endif
  571. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  572. #define _TIMESPEC_DEFINED
  573. #endif
  574. #if !defined(_TIMESPEC_DEFINED)
  575. struct timespec {
  576. time_t tv_sec; /* seconds */
  577. long tv_nsec; /* nanoseconds */
  578. };
  579. #endif
  580. #if !defined(WIN_PTHREADS_TIME_H)
  581. #define MUST_IMPLEMENT_CLOCK_GETTIME
  582. #endif
  583. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  584. #define clock_gettime mg_clock_gettime
  585. static int
  586. clock_gettime(clockid_t clk_id, struct timespec *tp)
  587. {
  588. FILETIME ft;
  589. ULARGE_INTEGER li, li2;
  590. BOOL ok = FALSE;
  591. double d;
  592. static double perfcnt_per_sec = 0.0;
  593. static BOOL initialized = FALSE;
  594. if (!initialized) {
  595. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  596. perfcnt_per_sec = 1.0 / li.QuadPart;
  597. initialized = TRUE;
  598. }
  599. if (tp) {
  600. memset(tp, 0, sizeof(*tp));
  601. if (clk_id == CLOCK_REALTIME) {
  602. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  603. GetSystemTimeAsFileTime(&ft);
  604. li.LowPart = ft.dwLowDateTime;
  605. li.HighPart = ft.dwHighDateTime;
  606. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  607. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  608. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  609. ok = TRUE;
  610. /* END: CLOCK_REALTIME */
  611. } else if (clk_id == CLOCK_MONOTONIC) {
  612. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  613. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  614. d = li.QuadPart * perfcnt_per_sec;
  615. tp->tv_sec = (time_t)d;
  616. d -= (double)tp->tv_sec;
  617. tp->tv_nsec = (long)(d * 1.0E9);
  618. ok = TRUE;
  619. /* END: CLOCK_MONOTONIC */
  620. } else if (clk_id == CLOCK_THREAD) {
  621. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  622. FILETIME t_create, t_exit, t_kernel, t_user;
  623. if (GetThreadTimes(GetCurrentThread(),
  624. &t_create,
  625. &t_exit,
  626. &t_kernel,
  627. &t_user)) {
  628. li.LowPart = t_user.dwLowDateTime;
  629. li.HighPart = t_user.dwHighDateTime;
  630. li2.LowPart = t_kernel.dwLowDateTime;
  631. li2.HighPart = t_kernel.dwHighDateTime;
  632. li.QuadPart += li2.QuadPart;
  633. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  634. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  635. ok = TRUE;
  636. }
  637. /* END: CLOCK_THREAD */
  638. } else if (clk_id == CLOCK_PROCESS) {
  639. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetProcessTimes(GetCurrentProcess(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_PROCESS */
  656. } else {
  657. /* BEGIN: unknown clock */
  658. /* ok = FALSE; already set by init */
  659. /* END: unknown clock */
  660. }
  661. }
  662. return ok ? 0 : -1;
  663. }
  664. #endif
  665. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  666. static int pthread_mutex_lock(pthread_mutex_t *);
  667. static int pthread_mutex_unlock(pthread_mutex_t *);
  668. static void path_to_unicode(const struct mg_connection *conn,
  669. const char *path,
  670. wchar_t *wbuf,
  671. size_t wbuf_len);
  672. /* All file operations need to be rewritten to solve #246. */
  673. struct mg_file;
  674. static const char *
  675. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  676. /* POSIX dirent interface */
  677. struct dirent {
  678. char d_name[PATH_MAX];
  679. };
  680. typedef struct DIR {
  681. HANDLE handle;
  682. WIN32_FIND_DATAW info;
  683. struct dirent result;
  684. } DIR;
  685. #if defined(HAVE_POLL)
  686. #define mg_pollfd pollfd
  687. #else
  688. struct mg_pollfd {
  689. SOCKET fd;
  690. short events;
  691. short revents;
  692. };
  693. #endif
  694. /* Mark required libraries */
  695. #if defined(_MSC_VER)
  696. #pragma comment(lib, "Ws2_32.lib")
  697. #endif
  698. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  699. #include <inttypes.h>
  700. typedef const void *SOCK_OPT_TYPE;
  701. #if defined(ANDROID)
  702. typedef unsigned short int in_port_t;
  703. #endif
  704. #if !defined(__ZEPHYR__)
  705. #include <arpa/inet.h>
  706. #include <ctype.h>
  707. #include <dirent.h>
  708. #include <grp.h>
  709. #include <limits.h>
  710. #include <netdb.h>
  711. #include <netinet/in.h>
  712. #include <netinet/tcp.h>
  713. #include <pthread.h>
  714. #include <pwd.h>
  715. #include <stdarg.h>
  716. #include <stddef.h>
  717. #include <stdio.h>
  718. #include <stdlib.h>
  719. #include <string.h>
  720. #include <sys/poll.h>
  721. #include <sys/socket.h>
  722. #include <sys/time.h>
  723. #include <sys/utsname.h>
  724. #include <sys/wait.h>
  725. #include <time.h>
  726. #include <unistd.h>
  727. #endif
  728. #define vsnprintf_impl vsnprintf
  729. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  730. #include <dlfcn.h>
  731. #endif
  732. #if defined(__MACH__)
  733. #define SSL_LIB "libssl.dylib"
  734. #define CRYPTO_LIB "libcrypto.dylib"
  735. #else
  736. #if !defined(SSL_LIB)
  737. #define SSL_LIB "libssl.so"
  738. #endif
  739. #if !defined(CRYPTO_LIB)
  740. #define CRYPTO_LIB "libcrypto.so"
  741. #endif
  742. #endif
  743. #if !defined(O_BINARY)
  744. #define O_BINARY (0)
  745. #endif /* O_BINARY */
  746. #define closesocket(a) (close(a))
  747. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  748. #define mg_remove(conn, x) (remove(x))
  749. #define mg_sleep(x) (usleep((x)*1000))
  750. #define mg_opendir(conn, x) (opendir(x))
  751. #define mg_closedir(x) (closedir(x))
  752. #define mg_readdir(x) (readdir(x))
  753. #define ERRNO (errno)
  754. #define INVALID_SOCKET (-1)
  755. #define INT64_FMT PRId64
  756. #define UINT64_FMT PRIu64
  757. typedef int SOCKET;
  758. #define WINCDECL
  759. #if defined(__hpux)
  760. /* HPUX 11 does not have monotonic, fall back to realtime */
  761. #if !defined(CLOCK_MONOTONIC)
  762. #define CLOCK_MONOTONIC CLOCK_REALTIME
  763. #endif
  764. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  765. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  766. * the prototypes use int* rather than socklen_t* which matches the
  767. * actual library expectation. When called with the wrong size arg
  768. * accept() returns a zero client inet addr and check_acl() always
  769. * fails. Since socklen_t is widely used below, just force replace
  770. * their typedef with int. - DTL
  771. */
  772. #define socklen_t int
  773. #endif /* hpux */
  774. #define mg_pollfd pollfd
  775. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  776. /* In case our C library is missing "timegm", provide an implementation */
  777. #if defined(NEED_TIMEGM)
  778. static inline int
  779. is_leap(int y)
  780. {
  781. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  782. }
  783. static inline int
  784. count_leap(int y)
  785. {
  786. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  787. }
  788. time_t
  789. timegm(struct tm *tm)
  790. {
  791. static const unsigned short ydays[] = {
  792. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  793. int year = tm->tm_year + 1900;
  794. int mon = tm->tm_mon;
  795. int mday = tm->tm_mday - 1;
  796. int hour = tm->tm_hour;
  797. int min = tm->tm_min;
  798. int sec = tm->tm_sec;
  799. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  800. || (mday >= ydays[mon + 1] - ydays[mon]
  801. + (mon == 1 && is_leap(year) ? 1 : 0))
  802. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  803. return -1;
  804. time_t res = year - 1970;
  805. res *= 365;
  806. res += mday;
  807. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  808. res += count_leap(year);
  809. res *= 24;
  810. res += hour;
  811. res *= 60;
  812. res += min;
  813. res *= 60;
  814. res += sec;
  815. return res;
  816. }
  817. #endif /* NEED_TIMEGM */
  818. /* va_copy should always be a macro, C99 and C++11 - DTL */
  819. #if !defined(va_copy)
  820. #define va_copy(x, y) ((x) = (y))
  821. #endif
  822. #if defined(_WIN32)
  823. /* Create substitutes for POSIX functions in Win32. */
  824. #if defined(GCC_DIAGNOSTIC)
  825. /* Show no warning in case system functions are not used. */
  826. #pragma GCC diagnostic push
  827. #pragma GCC diagnostic ignored "-Wunused-function"
  828. #endif
  829. static pthread_mutex_t global_log_file_lock;
  830. FUNCTION_MAY_BE_UNUSED
  831. static DWORD
  832. pthread_self(void)
  833. {
  834. return GetCurrentThreadId();
  835. }
  836. FUNCTION_MAY_BE_UNUSED
  837. static int
  838. pthread_key_create(
  839. pthread_key_t *key,
  840. void (*_ignored)(void *) /* destructor not supported for Windows */
  841. )
  842. {
  843. (void)_ignored;
  844. if ((key != 0)) {
  845. *key = TlsAlloc();
  846. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  847. }
  848. return -2;
  849. }
  850. FUNCTION_MAY_BE_UNUSED
  851. static int
  852. pthread_key_delete(pthread_key_t key)
  853. {
  854. return TlsFree(key) ? 0 : 1;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. pthread_setspecific(pthread_key_t key, void *value)
  859. {
  860. return TlsSetValue(key, value) ? 0 : 1;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static void *
  864. pthread_getspecific(pthread_key_t key)
  865. {
  866. return TlsGetValue(key);
  867. }
  868. #if defined(GCC_DIAGNOSTIC)
  869. /* Enable unused function warning again */
  870. #pragma GCC diagnostic pop
  871. #endif
  872. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  873. #else
  874. static pthread_mutexattr_t pthread_mutex_attr;
  875. #endif /* _WIN32 */
  876. #if defined(_WIN32_WCE)
  877. /* Create substitutes for POSIX functions in Win32. */
  878. #if defined(GCC_DIAGNOSTIC)
  879. /* Show no warning in case system functions are not used. */
  880. #pragma GCC diagnostic push
  881. #pragma GCC diagnostic ignored "-Wunused-function"
  882. #endif
  883. FUNCTION_MAY_BE_UNUSED
  884. static time_t
  885. time(time_t *ptime)
  886. {
  887. time_t t;
  888. SYSTEMTIME st;
  889. FILETIME ft;
  890. GetSystemTime(&st);
  891. SystemTimeToFileTime(&st, &ft);
  892. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  893. if (ptime != NULL) {
  894. *ptime = t;
  895. }
  896. return t;
  897. }
  898. FUNCTION_MAY_BE_UNUSED
  899. static struct tm *
  900. localtime_s(const time_t *ptime, struct tm *ptm)
  901. {
  902. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  903. FILETIME ft, lft;
  904. SYSTEMTIME st;
  905. TIME_ZONE_INFORMATION tzinfo;
  906. if (ptm == NULL) {
  907. return NULL;
  908. }
  909. *(int64_t *)&ft = t;
  910. FileTimeToLocalFileTime(&ft, &lft);
  911. FileTimeToSystemTime(&lft, &st);
  912. ptm->tm_year = st.wYear - 1900;
  913. ptm->tm_mon = st.wMonth - 1;
  914. ptm->tm_wday = st.wDayOfWeek;
  915. ptm->tm_mday = st.wDay;
  916. ptm->tm_hour = st.wHour;
  917. ptm->tm_min = st.wMinute;
  918. ptm->tm_sec = st.wSecond;
  919. ptm->tm_yday = 0; /* hope nobody uses this */
  920. ptm->tm_isdst =
  921. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  922. return ptm;
  923. }
  924. FUNCTION_MAY_BE_UNUSED
  925. static struct tm *
  926. gmtime_s(const time_t *ptime, struct tm *ptm)
  927. {
  928. /* FIXME(lsm): fix this. */
  929. return localtime_s(ptime, ptm);
  930. }
  931. static int mg_atomic_inc(volatile int *addr);
  932. static struct tm tm_array[MAX_WORKER_THREADS];
  933. static int tm_index = 0;
  934. FUNCTION_MAY_BE_UNUSED
  935. static struct tm *
  936. localtime(const time_t *ptime)
  937. {
  938. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  939. return localtime_s(ptime, tm_array + i);
  940. }
  941. FUNCTION_MAY_BE_UNUSED
  942. static struct tm *
  943. gmtime(const time_t *ptime)
  944. {
  945. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  946. return gmtime_s(ptime, tm_array + i);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static size_t
  950. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  951. {
  952. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  953. * for WinCE"); */
  954. return 0;
  955. }
  956. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  957. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  958. #define remove(f) mg_remove(NULL, f)
  959. FUNCTION_MAY_BE_UNUSED
  960. static int
  961. rename(const char *a, const char *b)
  962. {
  963. wchar_t wa[W_PATH_MAX];
  964. wchar_t wb[W_PATH_MAX];
  965. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  966. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  967. return MoveFileW(wa, wb) ? 0 : -1;
  968. }
  969. struct stat {
  970. int64_t st_size;
  971. time_t st_mtime;
  972. };
  973. FUNCTION_MAY_BE_UNUSED
  974. static int
  975. stat(const char *name, struct stat *st)
  976. {
  977. wchar_t wbuf[W_PATH_MAX];
  978. WIN32_FILE_ATTRIBUTE_DATA attr;
  979. time_t creation_time, write_time;
  980. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  981. memset(&attr, 0, sizeof(attr));
  982. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  983. st->st_size =
  984. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  985. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  986. attr.ftLastWriteTime.dwHighDateTime);
  987. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  988. attr.ftCreationTime.dwHighDateTime);
  989. if (creation_time > write_time) {
  990. st->st_mtime = creation_time;
  991. } else {
  992. st->st_mtime = write_time;
  993. }
  994. return 0;
  995. }
  996. #define access(x, a) 1 /* not required anyway */
  997. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  998. /* Values from errno.h in Windows SDK (Visual Studio). */
  999. #define EEXIST 17
  1000. #define EACCES 13
  1001. #define ENOENT 2
  1002. #if defined(GCC_DIAGNOSTIC)
  1003. /* Enable unused function warning again */
  1004. #pragma GCC diagnostic pop
  1005. #endif
  1006. #endif /* defined(_WIN32_WCE) */
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Show no warning in case system functions are not used. */
  1009. #pragma GCC diagnostic push
  1010. #pragma GCC diagnostic ignored "-Wunused-function"
  1011. #endif /* defined(GCC_DIAGNOSTIC) */
  1012. #if defined(__clang__)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma clang diagnostic push
  1015. #pragma clang diagnostic ignored "-Wunused-function"
  1016. #endif
  1017. static pthread_mutex_t global_lock_mutex;
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static void
  1020. mg_global_lock(void)
  1021. {
  1022. (void)pthread_mutex_lock(&global_lock_mutex);
  1023. }
  1024. FUNCTION_MAY_BE_UNUSED
  1025. static void
  1026. mg_global_unlock(void)
  1027. {
  1028. (void)pthread_mutex_unlock(&global_lock_mutex);
  1029. }
  1030. FUNCTION_MAY_BE_UNUSED
  1031. static int
  1032. mg_atomic_inc(volatile int *addr)
  1033. {
  1034. int ret;
  1035. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1036. /* Depending on the SDK, this function uses either
  1037. * (volatile unsigned int *) or (volatile LONG *),
  1038. * so whatever you use, the other SDK is likely to raise a warning. */
  1039. ret = InterlockedIncrement((volatile long *)addr);
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. ret = __sync_add_and_fetch(addr, 1);
  1044. #else
  1045. mg_global_lock();
  1046. ret = (++(*addr));
  1047. mg_global_unlock();
  1048. #endif
  1049. return ret;
  1050. }
  1051. FUNCTION_MAY_BE_UNUSED
  1052. static int
  1053. mg_atomic_dec(volatile int *addr)
  1054. {
  1055. int ret;
  1056. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1057. /* Depending on the SDK, this function uses either
  1058. * (volatile unsigned int *) or (volatile LONG *),
  1059. * so whatever you use, the other SDK is likely to raise a warning. */
  1060. ret = InterlockedDecrement((volatile long *)addr);
  1061. #elif defined(__GNUC__) \
  1062. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1063. && !defined(NO_ATOMICS)
  1064. ret = __sync_sub_and_fetch(addr, 1);
  1065. #else
  1066. mg_global_lock();
  1067. ret = (--(*addr));
  1068. mg_global_unlock();
  1069. #endif
  1070. return ret;
  1071. }
  1072. #if defined(USE_SERVER_STATS)
  1073. static int64_t
  1074. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1075. {
  1076. int64_t ret;
  1077. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1078. ret = InterlockedAdd64(addr, value);
  1079. #elif defined(__GNUC__) \
  1080. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1081. && !defined(NO_ATOMICS)
  1082. ret = __sync_add_and_fetch(addr, value);
  1083. #else
  1084. mg_global_lock();
  1085. *addr += value;
  1086. ret = (*addr);
  1087. mg_global_unlock();
  1088. #endif
  1089. return ret;
  1090. }
  1091. #endif
  1092. #if defined(GCC_DIAGNOSTIC)
  1093. /* Show no warning in case system functions are not used. */
  1094. #pragma GCC diagnostic pop
  1095. #endif /* defined(GCC_DIAGNOSTIC) */
  1096. #if defined(__clang__)
  1097. /* Show no warning in case system functions are not used. */
  1098. #pragma clang diagnostic pop
  1099. #endif
  1100. #if defined(USE_SERVER_STATS)
  1101. struct mg_memory_stat {
  1102. volatile int64_t totalMemUsed;
  1103. volatile int64_t maxMemUsed;
  1104. volatile int blockCount;
  1105. };
  1106. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1107. static void *
  1108. mg_malloc_ex(size_t size,
  1109. struct mg_context *ctx,
  1110. const char *file,
  1111. unsigned line)
  1112. {
  1113. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1114. void *memory = 0;
  1115. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1116. #if defined(MEMORY_DEBUGGING)
  1117. char mallocStr[256];
  1118. #else
  1119. (void)file;
  1120. (void)line;
  1121. #endif
  1122. if (data) {
  1123. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1124. if (mmem > mstat->maxMemUsed) {
  1125. /* could use atomic compare exchange, but this
  1126. * seems overkill for statistics data */
  1127. mstat->maxMemUsed = mmem;
  1128. }
  1129. mg_atomic_inc(&mstat->blockCount);
  1130. ((uintptr_t *)data)[0] = size;
  1131. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1132. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1133. }
  1134. #if defined(MEMORY_DEBUGGING)
  1135. sprintf(mallocStr,
  1136. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1137. memory,
  1138. (unsigned long)size,
  1139. (unsigned long)mstat->totalMemUsed,
  1140. (unsigned long)mstat->blockCount,
  1141. file,
  1142. line);
  1143. #if defined(_WIN32)
  1144. OutputDebugStringA(mallocStr);
  1145. #else
  1146. DEBUG_TRACE("%s", mallocStr);
  1147. #endif
  1148. #endif
  1149. return memory;
  1150. }
  1151. static void *
  1152. mg_calloc_ex(size_t count,
  1153. size_t size,
  1154. struct mg_context *ctx,
  1155. const char *file,
  1156. unsigned line)
  1157. {
  1158. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1159. if (data) {
  1160. memset(data, 0, size * count);
  1161. }
  1162. return data;
  1163. }
  1164. static void
  1165. mg_free_ex(void *memory, const char *file, unsigned line)
  1166. {
  1167. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1168. #if defined(MEMORY_DEBUGGING)
  1169. char mallocStr[256];
  1170. #else
  1171. (void)file;
  1172. (void)line;
  1173. #endif
  1174. if (memory) {
  1175. uintptr_t size = ((uintptr_t *)data)[0];
  1176. struct mg_memory_stat *mstat =
  1177. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1178. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1179. mg_atomic_dec(&mstat->blockCount);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)size,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. #if defined(_WIN32)
  1190. OutputDebugStringA(mallocStr);
  1191. #else
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. #endif
  1195. free(data);
  1196. }
  1197. }
  1198. static void *
  1199. mg_realloc_ex(void *memory,
  1200. size_t newsize,
  1201. struct mg_context *ctx,
  1202. const char *file,
  1203. unsigned line)
  1204. {
  1205. void *data;
  1206. void *_realloc;
  1207. uintptr_t oldsize;
  1208. #if defined(MEMORY_DEBUGGING)
  1209. char mallocStr[256];
  1210. #else
  1211. (void)file;
  1212. (void)line;
  1213. #endif
  1214. if (newsize) {
  1215. if (memory) {
  1216. /* Reallocate existing block */
  1217. struct mg_memory_stat *mstat;
  1218. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1219. oldsize = ((uintptr_t *)data)[0];
  1220. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1221. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1222. if (_realloc) {
  1223. data = _realloc;
  1224. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1225. #if defined(MEMORY_DEBUGGING)
  1226. sprintf(mallocStr,
  1227. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1228. memory,
  1229. (unsigned long)oldsize,
  1230. (unsigned long)mstat->totalMemUsed,
  1231. (unsigned long)mstat->blockCount,
  1232. file,
  1233. line);
  1234. #if defined(_WIN32)
  1235. OutputDebugStringA(mallocStr);
  1236. #else
  1237. DEBUG_TRACE("%s", mallocStr);
  1238. #endif
  1239. #endif
  1240. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1241. #if defined(MEMORY_DEBUGGING)
  1242. sprintf(mallocStr,
  1243. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1244. memory,
  1245. (unsigned long)newsize,
  1246. (unsigned long)mstat->totalMemUsed,
  1247. (unsigned long)mstat->blockCount,
  1248. file,
  1249. line);
  1250. #if defined(_WIN32)
  1251. OutputDebugStringA(mallocStr);
  1252. #else
  1253. DEBUG_TRACE("%s", mallocStr);
  1254. #endif
  1255. #endif
  1256. *(uintptr_t *)data = newsize;
  1257. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1258. } else {
  1259. #if defined(MEMORY_DEBUGGING)
  1260. #if defined(_WIN32)
  1261. OutputDebugStringA("MEM: realloc failed\n");
  1262. #else
  1263. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1264. #endif
  1265. #endif
  1266. return _realloc;
  1267. }
  1268. } else {
  1269. /* Allocate new block */
  1270. data = mg_malloc_ex(newsize, ctx, file, line);
  1271. }
  1272. } else {
  1273. /* Free existing block */
  1274. data = 0;
  1275. mg_free_ex(memory, file, line);
  1276. }
  1277. return data;
  1278. }
  1279. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1280. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1281. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1282. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1283. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1284. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1285. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1286. #else /* USE_SERVER_STATS */
  1287. static __inline void *
  1288. mg_malloc(size_t a)
  1289. {
  1290. return malloc(a);
  1291. }
  1292. static __inline void *
  1293. mg_calloc(size_t a, size_t b)
  1294. {
  1295. return calloc(a, b);
  1296. }
  1297. static __inline void *
  1298. mg_realloc(void *a, size_t b)
  1299. {
  1300. return realloc(a, b);
  1301. }
  1302. static __inline void
  1303. mg_free(void *a)
  1304. {
  1305. free(a);
  1306. }
  1307. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1308. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1309. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1310. #define mg_free_ctx(a, c) mg_free(a)
  1311. #endif /* USE_SERVER_STATS */
  1312. static void mg_vsnprintf(const struct mg_connection *conn,
  1313. int *truncated,
  1314. char *buf,
  1315. size_t buflen,
  1316. const char *fmt,
  1317. va_list ap);
  1318. static void mg_snprintf(const struct mg_connection *conn,
  1319. int *truncated,
  1320. char *buf,
  1321. size_t buflen,
  1322. PRINTF_FORMAT_STRING(const char *fmt),
  1323. ...) PRINTF_ARGS(5, 6);
  1324. /* This following lines are just meant as a reminder to use the mg-functions
  1325. * for memory management */
  1326. #if defined(malloc)
  1327. #undef malloc
  1328. #endif
  1329. #if defined(calloc)
  1330. #undef calloc
  1331. #endif
  1332. #if defined(realloc)
  1333. #undef realloc
  1334. #endif
  1335. #if defined(free)
  1336. #undef free
  1337. #endif
  1338. #if defined(snprintf)
  1339. #undef snprintf
  1340. #endif
  1341. #if defined(vsnprintf)
  1342. #undef vsnprintf
  1343. #endif
  1344. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1345. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1346. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1347. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1348. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1349. #if defined(_WIN32)
  1350. /* vsnprintf must not be used in any system,
  1351. * but this define only works well for Windows. */
  1352. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1353. #endif
  1354. /* mg_init_library counter */
  1355. static int mg_init_library_called = 0;
  1356. #if !defined(NO_SSL)
  1357. static int mg_ssl_initialized = 0;
  1358. #endif
  1359. static pthread_key_t sTlsKey; /* Thread local storage index */
  1360. static int thread_idx_max = 0;
  1361. #if defined(MG_LEGACY_INTERFACE)
  1362. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1363. #endif
  1364. struct mg_workerTLS {
  1365. int is_master;
  1366. unsigned long thread_idx;
  1367. void *user_ptr;
  1368. #if defined(_WIN32)
  1369. HANDLE pthread_cond_helper_mutex;
  1370. struct mg_workerTLS *next_waiting_thread;
  1371. #endif
  1372. const char *alpn_proto;
  1373. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1374. char txtbuf[4];
  1375. #endif
  1376. };
  1377. #if defined(GCC_DIAGNOSTIC)
  1378. /* Show no warning in case system functions are not used. */
  1379. #pragma GCC diagnostic push
  1380. #pragma GCC diagnostic ignored "-Wunused-function"
  1381. #endif /* defined(GCC_DIAGNOSTIC) */
  1382. #if defined(__clang__)
  1383. /* Show no warning in case system functions are not used. */
  1384. #pragma clang diagnostic push
  1385. #pragma clang diagnostic ignored "-Wunused-function"
  1386. #endif
  1387. /* Get a unique thread ID as unsigned long, independent from the data type
  1388. * of thread IDs defined by the operating system API.
  1389. * If two calls to mg_current_thread_id return the same value, they calls
  1390. * are done from the same thread. If they return different values, they are
  1391. * done from different threads. (Provided this function is used in the same
  1392. * process context and threads are not repeatedly created and deleted, but
  1393. * CivetWeb does not do that).
  1394. * This function must match the signature required for SSL id callbacks:
  1395. * CRYPTO_set_id_callback
  1396. */
  1397. FUNCTION_MAY_BE_UNUSED
  1398. static unsigned long
  1399. mg_current_thread_id(void)
  1400. {
  1401. #if defined(_WIN32)
  1402. return GetCurrentThreadId();
  1403. #else
  1404. #if defined(__clang__)
  1405. #pragma clang diagnostic push
  1406. #pragma clang diagnostic ignored "-Wunreachable-code"
  1407. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1408. * or not, so one of the two conditions will be unreachable by construction.
  1409. * Unfortunately the C standard does not define a way to check this at
  1410. * compile time, since the #if preprocessor conditions can not use the sizeof
  1411. * operator as an argument. */
  1412. #endif
  1413. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1414. /* This is the problematic case for CRYPTO_set_id_callback:
  1415. * The OS pthread_t can not be cast to unsigned long. */
  1416. struct mg_workerTLS *tls =
  1417. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1418. if (tls == NULL) {
  1419. /* SSL called from an unknown thread: Create some thread index.
  1420. */
  1421. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1422. tls->is_master = -2; /* -2 means "3rd party thread" */
  1423. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1424. pthread_setspecific(sTlsKey, tls);
  1425. }
  1426. return tls->thread_idx;
  1427. } else {
  1428. /* pthread_t may be any data type, so a simple cast to unsigned long
  1429. * can rise a warning/error, depending on the platform.
  1430. * Here memcpy is used as an anything-to-anything cast. */
  1431. unsigned long ret = 0;
  1432. pthread_t t = pthread_self();
  1433. memcpy(&ret, &t, sizeof(pthread_t));
  1434. return ret;
  1435. }
  1436. #if defined(__clang__)
  1437. #pragma clang diagnostic pop
  1438. #endif
  1439. #endif
  1440. }
  1441. FUNCTION_MAY_BE_UNUSED
  1442. static uint64_t
  1443. mg_get_current_time_ns(void)
  1444. {
  1445. struct timespec tsnow;
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1448. }
  1449. #if defined(GCC_DIAGNOSTIC)
  1450. /* Show no warning in case system functions are not used. */
  1451. #pragma GCC diagnostic pop
  1452. #endif /* defined(GCC_DIAGNOSTIC) */
  1453. #if defined(__clang__)
  1454. /* Show no warning in case system functions are not used. */
  1455. #pragma clang diagnostic pop
  1456. #endif
  1457. #if defined(NEED_DEBUG_TRACE_FUNC)
  1458. static void
  1459. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1460. {
  1461. va_list args;
  1462. struct timespec tsnow;
  1463. /* Get some operating system independent thread id */
  1464. unsigned long thread_id = mg_current_thread_id();
  1465. clock_gettime(CLOCK_REALTIME, &tsnow);
  1466. flockfile(DEBUG_TRACE_STREAM);
  1467. fprintf(DEBUG_TRACE_STREAM,
  1468. "*** %lu.%09lu %lu %s:%u: ",
  1469. (unsigned long)tsnow.tv_sec,
  1470. (unsigned long)tsnow.tv_nsec,
  1471. thread_id,
  1472. func,
  1473. line);
  1474. va_start(args, fmt);
  1475. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1476. va_end(args);
  1477. putc('\n', DEBUG_TRACE_STREAM);
  1478. fflush(DEBUG_TRACE_STREAM);
  1479. funlockfile(DEBUG_TRACE_STREAM);
  1480. }
  1481. #endif /* NEED_DEBUG_TRACE_FUNC */
  1482. #define MD5_STATIC static
  1483. #include "md5.inl"
  1484. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1485. #if defined(NO_SOCKLEN_T)
  1486. typedef int socklen_t;
  1487. #endif /* NO_SOCKLEN_T */
  1488. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1489. #if !defined(MSG_NOSIGNAL)
  1490. #define MSG_NOSIGNAL (0)
  1491. #endif
  1492. #if defined(NO_SSL)
  1493. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1494. typedef struct SSL_CTX SSL_CTX;
  1495. #else
  1496. #if defined(NO_SSL_DL)
  1497. #include <openssl/bn.h>
  1498. #include <openssl/conf.h>
  1499. #include <openssl/crypto.h>
  1500. #include <openssl/dh.h>
  1501. #include <openssl/engine.h>
  1502. #include <openssl/err.h>
  1503. #include <openssl/opensslv.h>
  1504. #include <openssl/pem.h>
  1505. #include <openssl/ssl.h>
  1506. #include <openssl/tls1.h>
  1507. #include <openssl/x509.h>
  1508. #if defined(WOLFSSL_VERSION)
  1509. /* Additional defines for WolfSSL, see
  1510. * https://github.com/civetweb/civetweb/issues/583 */
  1511. #include "wolfssl_extras.inl"
  1512. #endif
  1513. #if defined(OPENSSL_IS_BORINGSSL)
  1514. /* From boringssl/src/include/openssl/mem.h:
  1515. *
  1516. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1517. * However, that was written in a time before Valgrind and ASAN. Since we now
  1518. * have those tools, the OpenSSL allocation functions are simply macros around
  1519. * the standard memory functions.
  1520. *
  1521. * #define OPENSSL_free free */
  1522. #define free free
  1523. // disable for boringssl
  1524. #define CONF_modules_unload(a) ((void)0)
  1525. #define ENGINE_cleanup() ((void)0)
  1526. #endif
  1527. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1528. /* If OpenSSL headers are included, automatically select the API version */
  1529. #if !defined(OPENSSL_API_1_1)
  1530. #define OPENSSL_API_1_1
  1531. #endif
  1532. #define OPENSSL_REMOVE_THREAD_STATE()
  1533. #else
  1534. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1535. #endif
  1536. #else
  1537. /* SSL loaded dynamically from DLL.
  1538. * I put the prototypes here to be independent from OpenSSL source
  1539. * installation. */
  1540. typedef struct ssl_st SSL;
  1541. typedef struct ssl_method_st SSL_METHOD;
  1542. typedef struct ssl_ctx_st SSL_CTX;
  1543. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1544. typedef struct x509_name X509_NAME;
  1545. typedef struct asn1_integer ASN1_INTEGER;
  1546. typedef struct bignum BIGNUM;
  1547. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1548. typedef struct evp_md EVP_MD;
  1549. typedef struct x509 X509;
  1550. #define SSL_CTRL_OPTIONS (32)
  1551. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1552. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1553. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1554. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1555. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1556. #define SSL_VERIFY_NONE (0)
  1557. #define SSL_VERIFY_PEER (1)
  1558. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1559. #define SSL_VERIFY_CLIENT_ONCE (4)
  1560. #define SSL_OP_ALL (0x80000BFFul)
  1561. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1562. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1563. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1564. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1565. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1566. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1567. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1568. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1569. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1570. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1571. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1572. #define SSL_CB_HANDSHAKE_START (0x10)
  1573. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1574. #define SSL_ERROR_NONE (0)
  1575. #define SSL_ERROR_SSL (1)
  1576. #define SSL_ERROR_WANT_READ (2)
  1577. #define SSL_ERROR_WANT_WRITE (3)
  1578. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1579. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1580. #define SSL_ERROR_ZERO_RETURN (6)
  1581. #define SSL_ERROR_WANT_CONNECT (7)
  1582. #define SSL_ERROR_WANT_ACCEPT (8)
  1583. #define TLSEXT_TYPE_server_name (0)
  1584. #define TLSEXT_NAMETYPE_host_name (0)
  1585. #define SSL_TLSEXT_ERR_OK (0)
  1586. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1587. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1588. #define SSL_TLSEXT_ERR_NOACK (3)
  1589. enum ssl_func_category {
  1590. TLS_Mandatory, /* required for HTTPS */
  1591. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1592. TLS_END_OF_LIST
  1593. };
  1594. /* Check if all TLS functions/features are available */
  1595. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1596. struct ssl_func {
  1597. const char *name; /* SSL function name */
  1598. enum ssl_func_category required; /* Mandatory or optional */
  1599. void (*ptr)(void); /* Function pointer */
  1600. };
  1601. #if defined(OPENSSL_API_1_1)
  1602. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1603. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1604. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1605. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1606. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1607. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1608. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1609. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1610. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1611. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1612. #define OPENSSL_init_ssl \
  1613. (*(int (*)(uint64_t opts, \
  1614. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1615. .ptr)
  1616. #define SSL_CTX_use_PrivateKey_file \
  1617. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1618. #define SSL_CTX_use_certificate_file \
  1619. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1620. #define SSL_CTX_set_default_passwd_cb \
  1621. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1622. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1623. #define SSL_CTX_use_certificate_chain_file \
  1624. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1625. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1626. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1627. #define SSL_CTX_set_verify \
  1628. (*(void (*)(SSL_CTX *, \
  1629. int, \
  1630. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1631. .ptr)
  1632. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1633. #define SSL_CTX_load_verify_locations \
  1634. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1635. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1636. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1637. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1638. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1639. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1640. #define SSL_CIPHER_get_name \
  1641. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1642. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1643. #define SSL_CTX_set_session_id_context \
  1644. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1645. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1646. #define SSL_CTX_set_cipher_list \
  1647. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1648. #define SSL_CTX_set_options \
  1649. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1650. #define SSL_CTX_set_info_callback \
  1651. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1652. ssl_sw[32] \
  1653. .ptr)
  1654. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1655. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1656. #define SSL_CTX_callback_ctrl \
  1657. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1658. #define SSL_get_servername \
  1659. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1660. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1661. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1662. #define SSL_CTX_set_alpn_protos \
  1663. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1664. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1665. const unsigned char **out,
  1666. unsigned char *outlen,
  1667. const unsigned char *in,
  1668. unsigned int inlen,
  1669. void *arg);
  1670. #define SSL_CTX_set_alpn_select_cb \
  1671. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1672. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1673. const unsigned char **out,
  1674. unsigned int *outlen,
  1675. void *arg);
  1676. #define SSL_CTX_set_next_protos_advertised_cb \
  1677. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1678. .ptr)
  1679. #define SSL_CTX_clear_options(ctx, op) \
  1680. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1681. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1682. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1683. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1684. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1685. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1686. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1687. SSL_CTX_callback_ctrl(ctx, \
  1688. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1689. (void (*)(void))cb)
  1690. #define SSL_set_tlsext_host_name(ctx, arg) \
  1691. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1692. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1693. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1694. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1695. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1696. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1697. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1698. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1699. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1700. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1701. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1702. #define X509_NAME_oneline \
  1703. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1704. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1705. #define EVP_get_digestbyname \
  1706. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1707. #define EVP_Digest \
  1708. (*(int (*)( \
  1709. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1710. crypto_sw[9] \
  1711. .ptr)
  1712. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1713. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1714. #define ASN1_INTEGER_to_BN \
  1715. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1716. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1717. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1718. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1719. #define OPENSSL_free(a) CRYPTO_free(a)
  1720. #define OPENSSL_REMOVE_THREAD_STATE()
  1721. /* init_ssl_ctx() function updates this array.
  1722. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1723. * of respective functions. The macros above (like SSL_connect()) are really
  1724. * just calling these functions indirectly via the pointer. */
  1725. static struct ssl_func ssl_sw[] = {
  1726. {"SSL_free", TLS_Mandatory, NULL},
  1727. {"SSL_accept", TLS_Mandatory, NULL},
  1728. {"SSL_connect", TLS_Mandatory, NULL},
  1729. {"SSL_read", TLS_Mandatory, NULL},
  1730. {"SSL_write", TLS_Mandatory, NULL},
  1731. {"SSL_get_error", TLS_Mandatory, NULL},
  1732. {"SSL_set_fd", TLS_Mandatory, NULL},
  1733. {"SSL_new", TLS_Mandatory, NULL},
  1734. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1735. {"TLS_server_method", TLS_Mandatory, NULL},
  1736. {"OPENSSL_init_ssl", TLS_Mandatory, NULL},
  1737. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1738. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1739. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1740. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1741. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1742. {"TLS_client_method", TLS_Mandatory, NULL},
  1743. {"SSL_pending", TLS_Mandatory, NULL},
  1744. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1745. {"SSL_shutdown", TLS_Mandatory, NULL},
  1746. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1747. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1748. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1749. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1750. {"SSL_get_version", TLS_Mandatory, NULL},
  1751. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1752. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1753. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1754. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1755. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1756. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1757. {"SSL_CTX_set_options", TLS_Mandatory, NULL},
  1758. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1759. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1760. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1761. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1762. {"SSL_get_servername", TLS_Mandatory, NULL},
  1763. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1764. {"SSL_ctrl", TLS_Mandatory, NULL},
  1765. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1766. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1767. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1768. {NULL, TLS_END_OF_LIST, NULL}};
  1769. /* Similar array as ssl_sw. These functions could be located in different
  1770. * lib. */
  1771. static struct ssl_func crypto_sw[] = {
  1772. {"ERR_get_error", TLS_Mandatory, NULL},
  1773. {"ERR_error_string", TLS_Mandatory, NULL},
  1774. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1775. {"X509_free", TLS_Mandatory, NULL},
  1776. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1777. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1778. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1779. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1780. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1781. {"EVP_Digest", TLS_Mandatory, NULL},
  1782. {"i2d_X509", TLS_Mandatory, NULL},
  1783. {"BN_bn2hex", TLS_Mandatory, NULL},
  1784. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1785. {"BN_free", TLS_Mandatory, NULL},
  1786. {"CRYPTO_free", TLS_Mandatory, NULL},
  1787. {"ERR_clear_error", TLS_Mandatory, NULL},
  1788. {NULL, TLS_END_OF_LIST, NULL}};
  1789. #else
  1790. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1791. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1792. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1793. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1794. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1795. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1796. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1797. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1798. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1799. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1800. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1801. #define SSL_CTX_use_PrivateKey_file \
  1802. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1803. #define SSL_CTX_use_certificate_file \
  1804. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1805. #define SSL_CTX_set_default_passwd_cb \
  1806. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1807. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1808. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1809. #define SSL_CTX_use_certificate_chain_file \
  1810. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1811. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1812. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1813. #define SSL_CTX_set_verify \
  1814. (*(void (*)(SSL_CTX *, \
  1815. int, \
  1816. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1817. .ptr)
  1818. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1819. #define SSL_CTX_load_verify_locations \
  1820. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1821. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1822. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1823. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1824. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1825. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1826. #define SSL_CIPHER_get_name \
  1827. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1828. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1829. #define SSL_CTX_set_session_id_context \
  1830. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1831. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1832. #define SSL_CTX_set_cipher_list \
  1833. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1834. #define SSL_CTX_set_info_callback \
  1835. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1836. .ptr)
  1837. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1838. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1839. #define SSL_CTX_callback_ctrl \
  1840. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1841. #define SSL_get_servername \
  1842. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1843. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1844. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1845. #define SSL_CTX_set_alpn_protos \
  1846. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1847. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1848. const unsigned char **out,
  1849. unsigned char *outlen,
  1850. const unsigned char *in,
  1851. unsigned int inlen,
  1852. void *arg);
  1853. #define SSL_CTX_set_alpn_select_cb \
  1854. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1855. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1856. const unsigned char **out,
  1857. unsigned int *outlen,
  1858. void *arg);
  1859. #define SSL_CTX_set_next_protos_advertised_cb \
  1860. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1861. .ptr)
  1862. #define SSL_CTX_set_options(ctx, op) \
  1863. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1864. #define SSL_CTX_clear_options(ctx, op) \
  1865. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1866. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1867. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1868. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1869. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1870. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1871. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1872. SSL_CTX_callback_ctrl(ctx, \
  1873. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1874. (void (*)(void))cb)
  1875. #define SSL_set_tlsext_host_name(ctx, arg) \
  1876. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1877. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1878. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1879. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1880. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1881. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1882. #define CRYPTO_set_locking_callback \
  1883. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1884. #define CRYPTO_set_id_callback \
  1885. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1886. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1887. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1888. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1889. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1890. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1891. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1892. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1893. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1894. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1895. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1896. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1897. #define X509_NAME_oneline \
  1898. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1899. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1900. #define i2c_ASN1_INTEGER \
  1901. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1902. #define EVP_get_digestbyname \
  1903. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1904. #define EVP_Digest \
  1905. (*(int (*)( \
  1906. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1907. crypto_sw[18] \
  1908. .ptr)
  1909. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1910. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1911. #define ASN1_INTEGER_to_BN \
  1912. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1913. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1914. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1915. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1916. #define OPENSSL_free(a) CRYPTO_free(a)
  1917. /* use here ERR_remove_state,
  1918. * while on some platforms function is not included into library due to
  1919. * deprication */
  1920. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1921. /* init_ssl_ctx() function updates this array.
  1922. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1923. * of respective functions. The macros above (like SSL_connect()) are really
  1924. * just calling these functions indirectly via the pointer. */
  1925. static struct ssl_func ssl_sw[] = {
  1926. {"SSL_free", TLS_Mandatory, NULL},
  1927. {"SSL_accept", TLS_Mandatory, NULL},
  1928. {"SSL_connect", TLS_Mandatory, NULL},
  1929. {"SSL_read", TLS_Mandatory, NULL},
  1930. {"SSL_write", TLS_Mandatory, NULL},
  1931. {"SSL_get_error", TLS_Mandatory, NULL},
  1932. {"SSL_set_fd", TLS_Mandatory, NULL},
  1933. {"SSL_new", TLS_Mandatory, NULL},
  1934. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1935. {"SSLv23_server_method", TLS_Mandatory, NULL},
  1936. {"SSL_library_init", TLS_Mandatory, NULL},
  1937. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1938. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1939. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1940. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1941. {"SSL_load_error_strings", TLS_Mandatory, NULL},
  1942. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1943. {"SSLv23_client_method", TLS_Mandatory, NULL},
  1944. {"SSL_pending", TLS_Mandatory, NULL},
  1945. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1946. {"SSL_shutdown", TLS_Mandatory, NULL},
  1947. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1948. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1949. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1950. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1951. {"SSL_get_version", TLS_Mandatory, NULL},
  1952. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1953. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1954. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1955. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1956. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1957. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1958. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1959. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1960. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1961. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1962. {"SSL_get_servername", TLS_Mandatory, NULL},
  1963. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1964. {"SSL_ctrl", TLS_Mandatory, NULL},
  1965. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1966. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1967. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1968. {NULL, TLS_END_OF_LIST, NULL}};
  1969. /* Similar array as ssl_sw. These functions could be located in different
  1970. * lib. */
  1971. static struct ssl_func crypto_sw[] = {
  1972. {"CRYPTO_num_locks", TLS_Mandatory, NULL},
  1973. {"CRYPTO_set_locking_callback", TLS_Mandatory, NULL},
  1974. {"CRYPTO_set_id_callback", TLS_Mandatory, NULL},
  1975. {"ERR_get_error", TLS_Mandatory, NULL},
  1976. {"ERR_error_string", TLS_Mandatory, NULL},
  1977. {"ERR_remove_state", TLS_Mandatory, NULL},
  1978. {"ERR_free_strings", TLS_Mandatory, NULL},
  1979. {"ENGINE_cleanup", TLS_Mandatory, NULL},
  1980. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1981. {"CRYPTO_cleanup_all_ex_data", TLS_Mandatory, NULL},
  1982. {"EVP_cleanup", TLS_Mandatory, NULL},
  1983. {"X509_free", TLS_Mandatory, NULL},
  1984. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1985. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1986. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1987. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1988. {"i2c_ASN1_INTEGER", TLS_Mandatory, NULL},
  1989. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1990. {"EVP_Digest", TLS_Mandatory, NULL},
  1991. {"i2d_X509", TLS_Mandatory, NULL},
  1992. {"BN_bn2hex", TLS_Mandatory, NULL},
  1993. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1994. {"BN_free", TLS_Mandatory, NULL},
  1995. {"CRYPTO_free", TLS_Mandatory, NULL},
  1996. {"ERR_clear_error", TLS_Mandatory, NULL},
  1997. {NULL, TLS_END_OF_LIST, NULL}};
  1998. #endif /* OPENSSL_API_1_1 */
  1999. #endif /* NO_SSL_DL */
  2000. #endif /* NO_SSL */
  2001. #if !defined(NO_CACHING)
  2002. static const char month_names[][4] = {"Jan",
  2003. "Feb",
  2004. "Mar",
  2005. "Apr",
  2006. "May",
  2007. "Jun",
  2008. "Jul",
  2009. "Aug",
  2010. "Sep",
  2011. "Oct",
  2012. "Nov",
  2013. "Dec"};
  2014. #endif /* !NO_CACHING */
  2015. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2016. * the union u. */
  2017. union usa {
  2018. struct sockaddr sa;
  2019. struct sockaddr_in sin;
  2020. #if defined(USE_IPV6)
  2021. struct sockaddr_in6 sin6;
  2022. #endif
  2023. };
  2024. /* Describes a string (chunk of memory). */
  2025. struct vec {
  2026. const char *ptr;
  2027. size_t len;
  2028. };
  2029. struct mg_file_stat {
  2030. /* File properties filled by mg_stat: */
  2031. uint64_t size;
  2032. time_t last_modified;
  2033. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2034. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2035. * case we need a "Content-Eencoding: gzip" header */
  2036. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2037. };
  2038. struct mg_file_in_memory {
  2039. char *p;
  2040. uint32_t pos;
  2041. char mode;
  2042. };
  2043. struct mg_file_access {
  2044. /* File properties filled by mg_fopen: */
  2045. FILE *fp;
  2046. #if defined(MG_USE_OPEN_FILE)
  2047. /* TODO (low): Remove obsolete "file in memory" implementation.
  2048. * In an "early 2017" discussion at Google groups
  2049. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  2050. * we decided to get rid of this feature (after some fade-out
  2051. * phase). */
  2052. const char *membuf;
  2053. #endif
  2054. };
  2055. struct mg_file {
  2056. struct mg_file_stat stat;
  2057. struct mg_file_access access;
  2058. };
  2059. #if defined(MG_USE_OPEN_FILE)
  2060. #define STRUCT_FILE_INITIALIZER \
  2061. { \
  2062. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2063. { \
  2064. (FILE *)NULL, (const char *)NULL \
  2065. } \
  2066. }
  2067. #else
  2068. #define STRUCT_FILE_INITIALIZER \
  2069. { \
  2070. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2071. { \
  2072. (FILE *)NULL \
  2073. } \
  2074. }
  2075. #endif
  2076. /* Describes listening socket, or socket which was accept()-ed by the master
  2077. * thread and queued for future handling by the worker thread. */
  2078. struct socket {
  2079. SOCKET sock; /* Listening socket */
  2080. union usa lsa; /* Local socket address */
  2081. union usa rsa; /* Remote socket address */
  2082. unsigned char is_ssl; /* Is port SSL-ed */
  2083. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2084. * port */
  2085. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2086. };
  2087. /* Enum const for all options must be in sync with
  2088. * static struct mg_option config_options[]
  2089. * This is tested in the unit test (test/private.c)
  2090. * "Private Config Options"
  2091. */
  2092. enum {
  2093. /* Once for each server */
  2094. LISTENING_PORTS,
  2095. NUM_THREADS,
  2096. RUN_AS_USER,
  2097. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2098. * socket option typedef TCP_NODELAY. */
  2099. MAX_REQUEST_SIZE,
  2100. LINGER_TIMEOUT,
  2101. CONNECTION_QUEUE_SIZE,
  2102. LISTEN_BACKLOG_SIZE,
  2103. #if defined(__linux__)
  2104. ALLOW_SENDFILE_CALL,
  2105. #endif
  2106. #if defined(_WIN32)
  2107. CASE_SENSITIVE_FILES,
  2108. #endif
  2109. THROTTLE,
  2110. ACCESS_LOG_FILE,
  2111. ERROR_LOG_FILE,
  2112. ENABLE_KEEP_ALIVE,
  2113. REQUEST_TIMEOUT,
  2114. KEEP_ALIVE_TIMEOUT,
  2115. #if defined(USE_WEBSOCKET)
  2116. WEBSOCKET_TIMEOUT,
  2117. ENABLE_WEBSOCKET_PING_PONG,
  2118. #endif
  2119. DECODE_URL,
  2120. #if defined(USE_LUA)
  2121. LUA_BACKGROUND_SCRIPT,
  2122. LUA_BACKGROUND_SCRIPT_PARAMS,
  2123. #endif
  2124. #if defined(USE_TIMERS)
  2125. CGI_TIMEOUT,
  2126. #endif
  2127. /* Once for each domain */
  2128. DOCUMENT_ROOT,
  2129. CGI_EXTENSIONS,
  2130. CGI_ENVIRONMENT,
  2131. PUT_DELETE_PASSWORDS_FILE,
  2132. CGI_INTERPRETER,
  2133. CGI_INTERPRETER_ARGS,
  2134. PROTECT_URI,
  2135. AUTHENTICATION_DOMAIN,
  2136. ENABLE_AUTH_DOMAIN_CHECK,
  2137. SSI_EXTENSIONS,
  2138. ENABLE_DIRECTORY_LISTING,
  2139. GLOBAL_PASSWORDS_FILE,
  2140. INDEX_FILES,
  2141. ACCESS_CONTROL_LIST,
  2142. EXTRA_MIME_TYPES,
  2143. SSL_CERTIFICATE,
  2144. SSL_CERTIFICATE_CHAIN,
  2145. URL_REWRITE_PATTERN,
  2146. HIDE_FILES,
  2147. SSL_DO_VERIFY_PEER,
  2148. SSL_CA_PATH,
  2149. SSL_CA_FILE,
  2150. SSL_VERIFY_DEPTH,
  2151. SSL_DEFAULT_VERIFY_PATHS,
  2152. SSL_CIPHER_LIST,
  2153. SSL_PROTOCOL_VERSION,
  2154. SSL_SHORT_TRUST,
  2155. #if defined(USE_LUA)
  2156. LUA_PRELOAD_FILE,
  2157. LUA_SCRIPT_EXTENSIONS,
  2158. LUA_SERVER_PAGE_EXTENSIONS,
  2159. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2160. LUA_DEBUG_PARAMS,
  2161. #endif
  2162. #endif
  2163. #if defined(USE_DUKTAPE)
  2164. DUKTAPE_SCRIPT_EXTENSIONS,
  2165. #endif
  2166. #if defined(USE_WEBSOCKET)
  2167. WEBSOCKET_ROOT,
  2168. #endif
  2169. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2170. LUA_WEBSOCKET_EXTENSIONS,
  2171. #endif
  2172. ACCESS_CONTROL_ALLOW_ORIGIN,
  2173. ACCESS_CONTROL_ALLOW_METHODS,
  2174. ACCESS_CONTROL_ALLOW_HEADERS,
  2175. ERROR_PAGES,
  2176. #if !defined(NO_CACHING)
  2177. STATIC_FILE_MAX_AGE,
  2178. STATIC_FILE_CACHE_CONTROL,
  2179. #endif
  2180. #if !defined(NO_SSL)
  2181. STRICT_HTTPS_MAX_AGE,
  2182. #endif
  2183. ADDITIONAL_HEADER,
  2184. ALLOW_INDEX_SCRIPT_SUB_RES,
  2185. #if defined(DAEMONIZE)
  2186. ENABLE_DAEMONIZE,
  2187. #endif
  2188. NUM_OPTIONS
  2189. };
  2190. /* Config option name, config types, default value.
  2191. * Must be in the same order as the enum const above.
  2192. */
  2193. static const struct mg_option config_options[] = {
  2194. /* Once for each server */
  2195. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2196. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2197. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2198. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2199. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2200. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2201. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2202. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2203. #if defined(__linux__)
  2204. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2205. #endif
  2206. #if defined(_WIN32)
  2207. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2208. #endif
  2209. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2210. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2211. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2212. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2213. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2214. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2215. #if defined(USE_WEBSOCKET)
  2216. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2217. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2218. #endif
  2219. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2220. #if defined(USE_LUA)
  2221. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2222. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2223. #endif
  2224. #if defined(USE_TIMERS)
  2225. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2226. #endif
  2227. /* Once for each domain */
  2228. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2229. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2230. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2231. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2232. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2233. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2234. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2235. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2236. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2237. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2238. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2239. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2240. {"index_files",
  2241. MG_CONFIG_TYPE_STRING_LIST,
  2242. #if defined(USE_LUA)
  2243. "index.xhtml,index.html,index.htm,"
  2244. "index.lp,index.lsp,index.lua,index.cgi,"
  2245. "index.shtml,index.php"},
  2246. #else
  2247. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2248. #endif
  2249. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2250. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2251. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2252. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2253. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2254. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2255. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2256. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2257. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2258. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2259. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2260. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2261. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2262. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2263. #if defined(USE_LUA)
  2264. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2265. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2266. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2267. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2268. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2269. #endif
  2270. #endif
  2271. #if defined(USE_DUKTAPE)
  2272. /* The support for duktape is still in alpha version state.
  2273. * The name of this config option might change. */
  2274. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2275. #endif
  2276. #if defined(USE_WEBSOCKET)
  2277. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2278. #endif
  2279. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2280. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2281. #endif
  2282. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2283. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2284. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2285. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2286. #if !defined(NO_CACHING)
  2287. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2288. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2289. #endif
  2290. #if !defined(NO_SSL)
  2291. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2292. #endif
  2293. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2294. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2295. #if defined(DAEMONIZE)
  2296. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2297. #endif
  2298. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2299. /* Check if the config_options and the corresponding enum have compatible
  2300. * sizes. */
  2301. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2302. == (NUM_OPTIONS + 1),
  2303. "config_options and enum not sync");
  2304. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2305. struct mg_handler_info {
  2306. /* Name/Pattern of the URI. */
  2307. char *uri;
  2308. size_t uri_len;
  2309. /* handler type */
  2310. int handler_type;
  2311. /* Handler for http/https or authorization requests. */
  2312. mg_request_handler handler;
  2313. unsigned int refcount;
  2314. int removing;
  2315. /* Handler for ws/wss (websocket) requests. */
  2316. mg_websocket_connect_handler connect_handler;
  2317. mg_websocket_ready_handler ready_handler;
  2318. mg_websocket_data_handler data_handler;
  2319. mg_websocket_close_handler close_handler;
  2320. /* accepted subprotocols for ws/wss requests. */
  2321. struct mg_websocket_subprotocols *subprotocols;
  2322. /* Handler for authorization requests */
  2323. mg_authorization_handler auth_handler;
  2324. /* User supplied argument for the handler function. */
  2325. void *cbdata;
  2326. /* next handler in a linked list */
  2327. struct mg_handler_info *next;
  2328. };
  2329. enum {
  2330. CONTEXT_INVALID,
  2331. CONTEXT_SERVER,
  2332. CONTEXT_HTTP_CLIENT,
  2333. CONTEXT_WS_CLIENT
  2334. };
  2335. struct mg_domain_context {
  2336. SSL_CTX *ssl_ctx; /* SSL context */
  2337. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2338. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2339. int64_t ssl_cert_last_mtime;
  2340. /* Server nonce */
  2341. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2342. unsigned long nonce_count; /* Used nonces, used for authentication */
  2343. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2344. /* linked list of shared lua websockets */
  2345. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2346. #endif
  2347. /* Linked list of domains */
  2348. struct mg_domain_context *next;
  2349. };
  2350. /* Stop flag can be "volatile" or require a lock */
  2351. typedef int volatile stop_flag_t;
  2352. #ifdef STOP_FLAG_NEEDS_LOCK
  2353. static int
  2354. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2355. {
  2356. int r;
  2357. mg_global_lock();
  2358. r = ((*f) == 0);
  2359. mg_global_unlock();
  2360. return r;
  2361. }
  2362. static int
  2363. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2364. {
  2365. int r;
  2366. mg_global_lock();
  2367. r = ((*f) == 2);
  2368. mg_global_unlock();
  2369. return r;
  2370. }
  2371. static void
  2372. STOP_FLAG_ASSIGN(stop_flag_t *f, int v)
  2373. {
  2374. mg_global_lock();
  2375. (*f) = v;
  2376. mg_global_unlock();
  2377. }
  2378. #else /* STOP_FLAG_NEEDS_LOCK */
  2379. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2380. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2381. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2382. #endif /* STOP_FLAG_NEEDS_LOCK */
  2383. struct mg_context {
  2384. /* Part 1 - Physical context:
  2385. * This holds threads, ports, timeouts, ...
  2386. * set for the entire server, independent from the
  2387. * addressed hostname.
  2388. */
  2389. /* Connection related */
  2390. int context_type; /* See CONTEXT_* above */
  2391. struct socket *listening_sockets;
  2392. struct mg_pollfd *listening_socket_fds;
  2393. unsigned int num_listening_sockets;
  2394. struct mg_connection *worker_connections; /* The connection struct, pre-
  2395. * allocated for each worker */
  2396. #if defined(USE_SERVER_STATS)
  2397. int active_connections;
  2398. int max_active_connections;
  2399. int64_t total_connections;
  2400. int64_t total_requests;
  2401. int64_t total_data_read;
  2402. int64_t total_data_written;
  2403. #endif
  2404. /* Thread related */
  2405. stop_flag_t stop_flag; /* Should we stop event loop */
  2406. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2407. pthread_t masterthreadid; /* The master thread ID */
  2408. unsigned int
  2409. cfg_worker_threads; /* The number of configured worker threads. */
  2410. pthread_t *worker_threadids; /* The worker thread IDs */
  2411. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2412. /* Connection to thread dispatching */
  2413. #if defined(ALTERNATIVE_QUEUE)
  2414. struct socket *client_socks;
  2415. void **client_wait_events;
  2416. #else
  2417. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2418. worker thread */
  2419. volatile int sq_head; /* Head of the socket queue */
  2420. volatile int sq_tail; /* Tail of the socket queue */
  2421. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2422. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2423. volatile int sq_blocked; /* Status information: sq is full */
  2424. int sq_size; /* No of elements in socket queue */
  2425. #if defined(USE_SERVER_STATS)
  2426. int sq_max_fill;
  2427. #endif /* USE_SERVER_STATS */
  2428. #endif /* ALTERNATIVE_QUEUE */
  2429. /* Memory related */
  2430. unsigned int max_request_size; /* The max request size */
  2431. #if defined(USE_SERVER_STATS)
  2432. struct mg_memory_stat ctx_memory;
  2433. #endif
  2434. /* Operating system related */
  2435. char *systemName; /* What operating system is running */
  2436. time_t start_time; /* Server start time, used for authentication
  2437. * and for diagnstics. */
  2438. #if defined(USE_TIMERS)
  2439. struct ttimers *timers;
  2440. #endif
  2441. /* Lua specific: Background operations and shared websockets */
  2442. #if defined(USE_LUA)
  2443. void *lua_background_state;
  2444. #endif
  2445. /* Server nonce */
  2446. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2447. * ssl_cert_last_mtime, nonce_count, and
  2448. * next (linked list) */
  2449. /* Server callbacks */
  2450. struct mg_callbacks callbacks; /* User-defined callback function */
  2451. void *user_data; /* User-defined data */
  2452. /* Part 2 - Logical domain:
  2453. * This holds hostname, TLS certificate, document root, ...
  2454. * set for a domain hosted at the server.
  2455. * There may be multiple domains hosted at one physical server.
  2456. * The default domain "dd" is the first element of a list of
  2457. * domains.
  2458. */
  2459. struct mg_domain_context dd; /* default domain */
  2460. };
  2461. #if defined(USE_SERVER_STATS)
  2462. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2463. static struct mg_memory_stat *
  2464. get_memory_stat(struct mg_context *ctx)
  2465. {
  2466. if (ctx) {
  2467. return &(ctx->ctx_memory);
  2468. }
  2469. return &mg_common_memory;
  2470. }
  2471. #endif
  2472. enum {
  2473. CONNECTION_TYPE_INVALID,
  2474. CONNECTION_TYPE_REQUEST,
  2475. CONNECTION_TYPE_RESPONSE
  2476. };
  2477. enum {
  2478. PROTOCOL_TYPE_HTTP1 = 0,
  2479. PROTOCOL_TYPE_WEBSOCKET = 1,
  2480. PROTOCOL_TYPE_HTTP2 = 2
  2481. };
  2482. struct mg_connection {
  2483. int connection_type; /* see CONNECTION_TYPE_* above */
  2484. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2485. struct mg_request_info request_info;
  2486. struct mg_response_info response_info;
  2487. struct mg_context *phys_ctx;
  2488. struct mg_domain_context *dom_ctx;
  2489. #if defined(USE_SERVER_STATS)
  2490. int conn_state; /* 0 = undef, numerical value may change in different
  2491. * versions. For the current definition, see
  2492. * mg_get_connection_info_impl */
  2493. #endif
  2494. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2495. SSL *ssl; /* SSL descriptor */
  2496. struct socket client; /* Connected client */
  2497. time_t conn_birth_time; /* Time (wall clock) when connection was
  2498. * established */
  2499. #if defined(USE_SERVER_STATS)
  2500. time_t conn_close_time; /* Time (wall clock) when connection was
  2501. * closed (or 0 if still open) */
  2502. #endif
  2503. struct timespec req_time; /* Time (since system start) when the request
  2504. * was received */
  2505. int64_t num_bytes_sent; /* Total bytes sent to client */
  2506. int64_t content_len; /* How many bytes of content can be read
  2507. * !is_chunked: Content-Length header value
  2508. * or -1 (until connection closed,
  2509. * not allowed for a request)
  2510. * is_chunked: >= 0, appended gradually
  2511. */
  2512. int64_t consumed_content; /* How many bytes of content have been read */
  2513. int is_chunked; /* Transfer-Encoding is chunked:
  2514. * 0 = not chunked,
  2515. * 1 = chunked, not yet, or some data read,
  2516. * 2 = chunked, has error,
  2517. * 3 = chunked, all data read except trailer,
  2518. * 4 = chunked, all data read
  2519. */
  2520. char *buf; /* Buffer for received data */
  2521. char *path_info; /* PATH_INFO part of the URL */
  2522. int must_close; /* 1 if connection must be closed */
  2523. int accept_gzip; /* 1 if gzip encoding is accepted */
  2524. int in_error_handler; /* 1 if in handler for user defined error
  2525. * pages */
  2526. #if defined(USE_WEBSOCKET)
  2527. int in_websocket_handling; /* 1 if in read_websocket */
  2528. #endif
  2529. int handled_requests; /* Number of requests handled by this connection
  2530. */
  2531. int buf_size; /* Buffer size */
  2532. int request_len; /* Size of the request + headers in a buffer */
  2533. int data_len; /* Total size of data in a buffer */
  2534. int status_code; /* HTTP reply status code, e.g. 200 */
  2535. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2536. * throttle */
  2537. time_t last_throttle_time; /* Last time throttled data was sent */
  2538. int last_throttle_bytes; /* Bytes sent this second */
  2539. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2540. * atomic transmissions for websockets */
  2541. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2542. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2543. #endif
  2544. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2545. * for quick access */
  2546. };
  2547. /* Directory entry */
  2548. struct de {
  2549. struct mg_connection *conn;
  2550. char *file_name;
  2551. struct mg_file_stat file;
  2552. };
  2553. #define mg_cry_internal(conn, fmt, ...) \
  2554. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2555. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2556. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2557. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2558. struct mg_context *ctx,
  2559. const char *func,
  2560. unsigned line,
  2561. const char *fmt,
  2562. ...) PRINTF_ARGS(5, 6);
  2563. #if !defined(NO_THREAD_NAME)
  2564. #if defined(_WIN32) && defined(_MSC_VER)
  2565. /* Set the thread name for debugging purposes in Visual Studio
  2566. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2567. */
  2568. #pragma pack(push, 8)
  2569. typedef struct tagTHREADNAME_INFO {
  2570. DWORD dwType; /* Must be 0x1000. */
  2571. LPCSTR szName; /* Pointer to name (in user addr space). */
  2572. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2573. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2574. } THREADNAME_INFO;
  2575. #pragma pack(pop)
  2576. #elif defined(__linux__)
  2577. #include <sys/prctl.h>
  2578. #include <sys/sendfile.h>
  2579. #if defined(ALTERNATIVE_QUEUE)
  2580. #include <sys/eventfd.h>
  2581. #endif /* ALTERNATIVE_QUEUE */
  2582. #if defined(ALTERNATIVE_QUEUE)
  2583. static void *
  2584. event_create(void)
  2585. {
  2586. int evhdl = eventfd(0, EFD_CLOEXEC);
  2587. int *ret;
  2588. if (evhdl == -1) {
  2589. /* Linux uses -1 on error, Windows NULL. */
  2590. /* However, Linux does not return 0 on success either. */
  2591. return 0;
  2592. }
  2593. ret = (int *)mg_malloc(sizeof(int));
  2594. if (ret) {
  2595. *ret = evhdl;
  2596. } else {
  2597. (void)close(evhdl);
  2598. }
  2599. return (void *)ret;
  2600. }
  2601. static int
  2602. event_wait(void *eventhdl)
  2603. {
  2604. uint64_t u;
  2605. int evhdl, s;
  2606. if (!eventhdl) {
  2607. /* error */
  2608. return 0;
  2609. }
  2610. evhdl = *(int *)eventhdl;
  2611. s = (int)read(evhdl, &u, sizeof(u));
  2612. if (s != sizeof(u)) {
  2613. /* error */
  2614. return 0;
  2615. }
  2616. (void)u; /* the value is not required */
  2617. return 1;
  2618. }
  2619. static int
  2620. event_signal(void *eventhdl)
  2621. {
  2622. uint64_t u = 1;
  2623. int evhdl, s;
  2624. if (!eventhdl) {
  2625. /* error */
  2626. return 0;
  2627. }
  2628. evhdl = *(int *)eventhdl;
  2629. s = (int)write(evhdl, &u, sizeof(u));
  2630. if (s != sizeof(u)) {
  2631. /* error */
  2632. return 0;
  2633. }
  2634. return 1;
  2635. }
  2636. static void
  2637. event_destroy(void *eventhdl)
  2638. {
  2639. int evhdl;
  2640. if (!eventhdl) {
  2641. /* error */
  2642. return;
  2643. }
  2644. evhdl = *(int *)eventhdl;
  2645. close(evhdl);
  2646. mg_free(eventhdl);
  2647. }
  2648. #endif
  2649. #endif
  2650. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2651. struct posix_event {
  2652. pthread_mutex_t mutex;
  2653. pthread_cond_t cond;
  2654. int signaled;
  2655. };
  2656. static void *
  2657. event_create(void)
  2658. {
  2659. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2660. if (ret == 0) {
  2661. /* out of memory */
  2662. return 0;
  2663. }
  2664. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2665. /* pthread mutex not available */
  2666. mg_free(ret);
  2667. return 0;
  2668. }
  2669. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2670. /* pthread cond not available */
  2671. pthread_mutex_destroy(&(ret->mutex));
  2672. mg_free(ret);
  2673. return 0;
  2674. }
  2675. ret->signaled = 0;
  2676. return (void *)ret;
  2677. }
  2678. static int
  2679. event_wait(void *eventhdl)
  2680. {
  2681. struct posix_event *ev = (struct posix_event *)eventhdl;
  2682. pthread_mutex_lock(&(ev->mutex));
  2683. while (!ev->signaled) {
  2684. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2685. }
  2686. ev->signaled = 0;
  2687. pthread_mutex_unlock(&(ev->mutex));
  2688. return 1;
  2689. }
  2690. static int
  2691. event_signal(void *eventhdl)
  2692. {
  2693. struct posix_event *ev = (struct posix_event *)eventhdl;
  2694. pthread_mutex_lock(&(ev->mutex));
  2695. pthread_cond_signal(&(ev->cond));
  2696. ev->signaled = 1;
  2697. pthread_mutex_unlock(&(ev->mutex));
  2698. return 1;
  2699. }
  2700. static void
  2701. event_destroy(void *eventhdl)
  2702. {
  2703. struct posix_event *ev = (struct posix_event *)eventhdl;
  2704. pthread_cond_destroy(&(ev->cond));
  2705. pthread_mutex_destroy(&(ev->mutex));
  2706. mg_free(ev);
  2707. }
  2708. #endif
  2709. static void
  2710. mg_set_thread_name(const char *name)
  2711. {
  2712. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2713. mg_snprintf(
  2714. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2715. #if defined(_WIN32)
  2716. #if defined(_MSC_VER)
  2717. /* Windows and Visual Studio Compiler */
  2718. __try {
  2719. THREADNAME_INFO info;
  2720. info.dwType = 0x1000;
  2721. info.szName = threadName;
  2722. info.dwThreadID = ~0U;
  2723. info.dwFlags = 0;
  2724. RaiseException(0x406D1388,
  2725. 0,
  2726. sizeof(info) / sizeof(ULONG_PTR),
  2727. (ULONG_PTR *)&info);
  2728. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2729. }
  2730. #elif defined(__MINGW32__)
  2731. /* No option known to set thread name for MinGW known */
  2732. #endif
  2733. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2734. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2735. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2736. #if defined(__MACH__)
  2737. /* OS X only current thread name can be changed */
  2738. (void)pthread_setname_np(threadName);
  2739. #else
  2740. (void)pthread_setname_np(pthread_self(), threadName);
  2741. #endif
  2742. #elif defined(__linux__)
  2743. /* On Linux we can use the prctl function.
  2744. * When building for Linux Standard Base (LSB) use
  2745. * NO_THREAD_NAME. However, thread names are a big
  2746. * help for debugging, so the stadard is to set them.
  2747. */
  2748. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2749. #endif
  2750. }
  2751. #else /* !defined(NO_THREAD_NAME) */
  2752. void
  2753. mg_set_thread_name(const char *threadName)
  2754. {
  2755. }
  2756. #endif
  2757. #if defined(MG_LEGACY_INTERFACE)
  2758. const char **
  2759. mg_get_valid_option_names(void)
  2760. {
  2761. /* This function is deprecated. Use mg_get_valid_options instead. */
  2762. static const char
  2763. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2764. int i;
  2765. for (i = 0; config_options[i].name != NULL; i++) {
  2766. data[i * 2] = config_options[i].name;
  2767. data[i * 2 + 1] = config_options[i].default_value;
  2768. }
  2769. return data;
  2770. }
  2771. #endif
  2772. const struct mg_option *
  2773. mg_get_valid_options(void)
  2774. {
  2775. return config_options;
  2776. }
  2777. /* Do not open file (used in is_file_in_memory) */
  2778. #define MG_FOPEN_MODE_NONE (0)
  2779. /* Open file for read only access */
  2780. #define MG_FOPEN_MODE_READ (1)
  2781. /* Open file for writing, create and overwrite */
  2782. #define MG_FOPEN_MODE_WRITE (2)
  2783. /* Open file for writing, create and append */
  2784. #define MG_FOPEN_MODE_APPEND (4)
  2785. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2786. * output filep and return 1, otherwise return 0 and don't modify anything.
  2787. */
  2788. static int
  2789. open_file_in_memory(const struct mg_connection *conn,
  2790. const char *path,
  2791. struct mg_file *filep,
  2792. int mode)
  2793. {
  2794. #if defined(MG_USE_OPEN_FILE)
  2795. size_t size = 0;
  2796. const char *buf = NULL;
  2797. if (!conn) {
  2798. return 0;
  2799. }
  2800. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2801. return 0;
  2802. }
  2803. if (conn->phys_ctx->callbacks.open_file) {
  2804. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2805. if (buf != NULL) {
  2806. if (filep == NULL) {
  2807. /* This is a file in memory, but we cannot store the
  2808. * properties
  2809. * now.
  2810. * Called from "is_file_in_memory" function. */
  2811. return 1;
  2812. }
  2813. /* NOTE: override filep->size only on success. Otherwise, it
  2814. * might
  2815. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2816. filep->access.membuf = buf;
  2817. filep->access.fp = NULL;
  2818. /* Size was set by the callback */
  2819. filep->stat.size = size;
  2820. /* Assume the data may change during runtime by setting
  2821. * last_modified = now */
  2822. filep->stat.last_modified = time(NULL);
  2823. filep->stat.is_directory = 0;
  2824. filep->stat.is_gzipped = 0;
  2825. }
  2826. }
  2827. return (buf != NULL);
  2828. #else
  2829. (void)conn;
  2830. (void)path;
  2831. (void)filep;
  2832. (void)mode;
  2833. return 0;
  2834. #endif
  2835. }
  2836. static int
  2837. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2838. {
  2839. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2840. }
  2841. static int
  2842. is_file_opened(const struct mg_file_access *fileacc)
  2843. {
  2844. if (!fileacc) {
  2845. return 0;
  2846. }
  2847. #if defined(MG_USE_OPEN_FILE)
  2848. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2849. #else
  2850. return (fileacc->fp != NULL);
  2851. #endif
  2852. }
  2853. #if !defined(NO_FILESYSTEMS)
  2854. static int mg_stat(const struct mg_connection *conn,
  2855. const char *path,
  2856. struct mg_file_stat *filep);
  2857. /* mg_fopen will open a file either in memory or on the disk.
  2858. * The input parameter path is a string in UTF-8 encoding.
  2859. * The input parameter mode is MG_FOPEN_MODE_*
  2860. * On success, either fp or membuf will be set in the output
  2861. * struct file. All status members will also be set.
  2862. * The function returns 1 on success, 0 on error. */
  2863. static int
  2864. mg_fopen(const struct mg_connection *conn,
  2865. const char *path,
  2866. int mode,
  2867. struct mg_file *filep)
  2868. {
  2869. int found;
  2870. if (!filep) {
  2871. return 0;
  2872. }
  2873. filep->access.fp = NULL;
  2874. #if defined(MG_USE_OPEN_FILE)
  2875. filep->access.membuf = NULL;
  2876. #endif
  2877. if (!is_file_in_memory(conn, path)) {
  2878. /* filep is initialized in mg_stat: all fields with memset to,
  2879. * some fields like size and modification date with values */
  2880. found = mg_stat(conn, path, &(filep->stat));
  2881. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2882. /* file does not exist and will not be created */
  2883. return 0;
  2884. }
  2885. #if defined(_WIN32)
  2886. {
  2887. wchar_t wbuf[W_PATH_MAX];
  2888. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2889. switch (mode) {
  2890. case MG_FOPEN_MODE_READ:
  2891. filep->access.fp = _wfopen(wbuf, L"rb");
  2892. break;
  2893. case MG_FOPEN_MODE_WRITE:
  2894. filep->access.fp = _wfopen(wbuf, L"wb");
  2895. break;
  2896. case MG_FOPEN_MODE_APPEND:
  2897. filep->access.fp = _wfopen(wbuf, L"ab");
  2898. break;
  2899. }
  2900. }
  2901. #else
  2902. /* Linux et al already use unicode. No need to convert. */
  2903. switch (mode) {
  2904. case MG_FOPEN_MODE_READ:
  2905. filep->access.fp = fopen(path, "r");
  2906. break;
  2907. case MG_FOPEN_MODE_WRITE:
  2908. filep->access.fp = fopen(path, "w");
  2909. break;
  2910. case MG_FOPEN_MODE_APPEND:
  2911. filep->access.fp = fopen(path, "a");
  2912. break;
  2913. }
  2914. #endif
  2915. if (!found) {
  2916. /* File did not exist before fopen was called.
  2917. * Maybe it has been created now. Get stat info
  2918. * like creation time now. */
  2919. found = mg_stat(conn, path, &(filep->stat));
  2920. (void)found;
  2921. }
  2922. /* file is on disk */
  2923. return (filep->access.fp != NULL);
  2924. } else {
  2925. #if defined(MG_USE_OPEN_FILE)
  2926. /* is_file_in_memory returned true */
  2927. if (open_file_in_memory(conn, path, filep, mode)) {
  2928. /* file is in memory */
  2929. return (filep->access.membuf != NULL);
  2930. }
  2931. #endif
  2932. }
  2933. /* Open failed */
  2934. return 0;
  2935. }
  2936. /* return 0 on success, just like fclose */
  2937. static int
  2938. mg_fclose(struct mg_file_access *fileacc)
  2939. {
  2940. int ret = -1;
  2941. if (fileacc != NULL) {
  2942. if (fileacc->fp != NULL) {
  2943. ret = fclose(fileacc->fp);
  2944. #if defined(MG_USE_OPEN_FILE)
  2945. } else if (fileacc->membuf != NULL) {
  2946. ret = 0;
  2947. #endif
  2948. }
  2949. /* reset all members of fileacc */
  2950. memset(fileacc, 0, sizeof(*fileacc));
  2951. }
  2952. return ret;
  2953. }
  2954. #endif /* NO_FILESYSTEMS */
  2955. static void
  2956. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2957. {
  2958. for (; *src != '\0' && n > 1; n--) {
  2959. *dst++ = *src++;
  2960. }
  2961. *dst = '\0';
  2962. }
  2963. static int
  2964. lowercase(const char *s)
  2965. {
  2966. return tolower((unsigned char)*s);
  2967. }
  2968. int
  2969. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2970. {
  2971. int diff = 0;
  2972. if (len > 0) {
  2973. do {
  2974. diff = lowercase(s1++) - lowercase(s2++);
  2975. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2976. }
  2977. return diff;
  2978. }
  2979. int
  2980. mg_strcasecmp(const char *s1, const char *s2)
  2981. {
  2982. int diff;
  2983. do {
  2984. diff = lowercase(s1++) - lowercase(s2++);
  2985. } while (diff == 0 && s1[-1] != '\0');
  2986. return diff;
  2987. }
  2988. static char *
  2989. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2990. {
  2991. char *p;
  2992. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2993. * defined */
  2994. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2995. mg_strlcpy(p, ptr, len + 1);
  2996. }
  2997. return p;
  2998. }
  2999. static char *
  3000. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3001. {
  3002. return mg_strndup_ctx(str, strlen(str), ctx);
  3003. }
  3004. static char *
  3005. mg_strdup(const char *str)
  3006. {
  3007. return mg_strndup_ctx(str, strlen(str), NULL);
  3008. }
  3009. static const char *
  3010. mg_strcasestr(const char *big_str, const char *small_str)
  3011. {
  3012. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3013. if (big_len >= small_len) {
  3014. for (i = 0; i <= (big_len - small_len); i++) {
  3015. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3016. return big_str + i;
  3017. }
  3018. }
  3019. }
  3020. return NULL;
  3021. }
  3022. /* Return null terminated string of given maximum length.
  3023. * Report errors if length is exceeded. */
  3024. static void
  3025. mg_vsnprintf(const struct mg_connection *conn,
  3026. int *truncated,
  3027. char *buf,
  3028. size_t buflen,
  3029. const char *fmt,
  3030. va_list ap)
  3031. {
  3032. int n, ok;
  3033. if (buflen == 0) {
  3034. if (truncated) {
  3035. *truncated = 1;
  3036. }
  3037. return;
  3038. }
  3039. #if defined(__clang__)
  3040. #pragma clang diagnostic push
  3041. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3042. /* Using fmt as a non-literal is intended here, since it is mostly called
  3043. * indirectly by mg_snprintf */
  3044. #endif
  3045. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3046. ok = (n >= 0) && ((size_t)n < buflen);
  3047. #if defined(__clang__)
  3048. #pragma clang diagnostic pop
  3049. #endif
  3050. if (ok) {
  3051. if (truncated) {
  3052. *truncated = 0;
  3053. }
  3054. } else {
  3055. if (truncated) {
  3056. *truncated = 1;
  3057. }
  3058. mg_cry_internal(conn,
  3059. "truncating vsnprintf buffer: [%.*s]",
  3060. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3061. buf);
  3062. n = (int)buflen - 1;
  3063. }
  3064. buf[n] = '\0';
  3065. }
  3066. static void
  3067. mg_snprintf(const struct mg_connection *conn,
  3068. int *truncated,
  3069. char *buf,
  3070. size_t buflen,
  3071. const char *fmt,
  3072. ...)
  3073. {
  3074. va_list ap;
  3075. va_start(ap, fmt);
  3076. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3077. va_end(ap);
  3078. }
  3079. static int
  3080. get_option_index(const char *name)
  3081. {
  3082. int i;
  3083. for (i = 0; config_options[i].name != NULL; i++) {
  3084. if (strcmp(config_options[i].name, name) == 0) {
  3085. return i;
  3086. }
  3087. }
  3088. return -1;
  3089. }
  3090. const char *
  3091. mg_get_option(const struct mg_context *ctx, const char *name)
  3092. {
  3093. int i;
  3094. if ((i = get_option_index(name)) == -1) {
  3095. return NULL;
  3096. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3097. return "";
  3098. } else {
  3099. return ctx->dd.config[i];
  3100. }
  3101. }
  3102. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3103. struct mg_context *
  3104. mg_get_context(const struct mg_connection *conn)
  3105. {
  3106. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3107. }
  3108. void *
  3109. mg_get_user_data(const struct mg_context *ctx)
  3110. {
  3111. return (ctx == NULL) ? NULL : ctx->user_data;
  3112. }
  3113. void *
  3114. mg_get_user_context_data(const struct mg_connection *conn)
  3115. {
  3116. return mg_get_user_data(mg_get_context(conn));
  3117. }
  3118. void *
  3119. mg_get_thread_pointer(const struct mg_connection *conn)
  3120. {
  3121. /* both methods should return the same pointer */
  3122. if (conn) {
  3123. /* quick access, in case conn is known */
  3124. return conn->tls_user_ptr;
  3125. } else {
  3126. /* otherwise get pointer from thread local storage (TLS) */
  3127. struct mg_workerTLS *tls =
  3128. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3129. return tls->user_ptr;
  3130. }
  3131. }
  3132. void
  3133. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3134. {
  3135. if (conn != NULL) {
  3136. conn->request_info.conn_data = data;
  3137. }
  3138. }
  3139. void *
  3140. mg_get_user_connection_data(const struct mg_connection *conn)
  3141. {
  3142. if (conn != NULL) {
  3143. return conn->request_info.conn_data;
  3144. }
  3145. return NULL;
  3146. }
  3147. #if defined(MG_LEGACY_INTERFACE)
  3148. /* Deprecated: Use mg_get_server_ports instead. */
  3149. size_t
  3150. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3151. {
  3152. size_t i;
  3153. if (!ctx) {
  3154. return 0;
  3155. }
  3156. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3157. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3158. ports[i] =
  3159. #if defined(USE_IPV6)
  3160. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3161. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3162. :
  3163. #endif
  3164. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3165. }
  3166. return i;
  3167. }
  3168. #endif
  3169. int
  3170. mg_get_server_ports(const struct mg_context *ctx,
  3171. int size,
  3172. struct mg_server_port *ports)
  3173. {
  3174. int i, cnt = 0;
  3175. if (size <= 0) {
  3176. return -1;
  3177. }
  3178. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3179. if (!ctx) {
  3180. return -1;
  3181. }
  3182. if (!ctx->listening_sockets) {
  3183. return -1;
  3184. }
  3185. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3186. ports[cnt].port =
  3187. #if defined(USE_IPV6)
  3188. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3189. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3190. :
  3191. #endif
  3192. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3193. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3194. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3195. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3196. /* IPv4 */
  3197. ports[cnt].protocol = 1;
  3198. cnt++;
  3199. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3200. /* IPv6 */
  3201. ports[cnt].protocol = 3;
  3202. cnt++;
  3203. }
  3204. }
  3205. return cnt;
  3206. }
  3207. static void
  3208. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3209. {
  3210. buf[0] = '\0';
  3211. if (!usa) {
  3212. return;
  3213. }
  3214. if (usa->sa.sa_family == AF_INET) {
  3215. getnameinfo(&usa->sa,
  3216. sizeof(usa->sin),
  3217. buf,
  3218. (unsigned)len,
  3219. NULL,
  3220. 0,
  3221. NI_NUMERICHOST);
  3222. }
  3223. #if defined(USE_IPV6)
  3224. else if (usa->sa.sa_family == AF_INET6) {
  3225. getnameinfo(&usa->sa,
  3226. sizeof(usa->sin6),
  3227. buf,
  3228. (unsigned)len,
  3229. NULL,
  3230. 0,
  3231. NI_NUMERICHOST);
  3232. }
  3233. #endif
  3234. }
  3235. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3236. * included in all responses other than 100, 101, 5xx. */
  3237. static void
  3238. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3239. {
  3240. #if !defined(REENTRANT_TIME)
  3241. struct tm *tm;
  3242. tm = ((t != NULL) ? gmtime(t) : NULL);
  3243. if (tm != NULL) {
  3244. #else
  3245. struct tm _tm;
  3246. struct tm *tm = &_tm;
  3247. if (t != NULL) {
  3248. gmtime_r(t, tm);
  3249. #endif
  3250. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3251. } else {
  3252. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3253. buf[buf_len - 1] = '\0';
  3254. }
  3255. }
  3256. /* difftime for struct timespec. Return value is in seconds. */
  3257. static double
  3258. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3259. {
  3260. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3261. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3262. }
  3263. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3264. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3265. const char *func,
  3266. unsigned line,
  3267. const char *fmt,
  3268. va_list ap);
  3269. #include "external_mg_cry_internal_impl.inl"
  3270. #elif !defined(NO_FILESYSTEMS)
  3271. /* Print error message to the opened error log stream. */
  3272. static void
  3273. mg_cry_internal_impl(const struct mg_connection *conn,
  3274. const char *func,
  3275. unsigned line,
  3276. const char *fmt,
  3277. va_list ap)
  3278. {
  3279. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3280. struct mg_file fi;
  3281. time_t timestamp;
  3282. /* Unused, in the RELEASE build */
  3283. (void)func;
  3284. (void)line;
  3285. #if defined(GCC_DIAGNOSTIC)
  3286. #pragma GCC diagnostic push
  3287. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3288. #endif
  3289. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3290. #if defined(GCC_DIAGNOSTIC)
  3291. #pragma GCC diagnostic pop
  3292. #endif
  3293. buf[sizeof(buf) - 1] = 0;
  3294. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3295. if (!conn) {
  3296. puts(buf);
  3297. return;
  3298. }
  3299. /* Do not lock when getting the callback value, here and below.
  3300. * I suppose this is fine, since function cannot disappear in the
  3301. * same way string option can. */
  3302. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3303. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3304. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3305. if (mg_fopen(conn,
  3306. conn->dom_ctx->config[ERROR_LOG_FILE],
  3307. MG_FOPEN_MODE_APPEND,
  3308. &fi)
  3309. == 0) {
  3310. fi.access.fp = NULL;
  3311. }
  3312. } else {
  3313. fi.access.fp = NULL;
  3314. }
  3315. if (fi.access.fp != NULL) {
  3316. flockfile(fi.access.fp);
  3317. timestamp = time(NULL);
  3318. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3319. fprintf(fi.access.fp,
  3320. "[%010lu] [error] [client %s] ",
  3321. (unsigned long)timestamp,
  3322. src_addr);
  3323. if (conn->request_info.request_method != NULL) {
  3324. fprintf(fi.access.fp,
  3325. "%s %s: ",
  3326. conn->request_info.request_method,
  3327. conn->request_info.request_uri
  3328. ? conn->request_info.request_uri
  3329. : "");
  3330. }
  3331. fprintf(fi.access.fp, "%s", buf);
  3332. fputc('\n', fi.access.fp);
  3333. fflush(fi.access.fp);
  3334. funlockfile(fi.access.fp);
  3335. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3336. * mg_cry here anyway ;-) */
  3337. }
  3338. }
  3339. }
  3340. #else
  3341. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3342. #endif /* Externally provided function */
  3343. /* Construct fake connection structure. Used for logging, if connection
  3344. * is not applicable at the moment of logging. */
  3345. static struct mg_connection *
  3346. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3347. {
  3348. static const struct mg_connection conn_zero = {0};
  3349. *fc = conn_zero;
  3350. fc->phys_ctx = ctx;
  3351. fc->dom_ctx = &(ctx->dd);
  3352. return fc;
  3353. }
  3354. static void
  3355. mg_cry_internal_wrap(const struct mg_connection *conn,
  3356. struct mg_context *ctx,
  3357. const char *func,
  3358. unsigned line,
  3359. const char *fmt,
  3360. ...)
  3361. {
  3362. va_list ap;
  3363. va_start(ap, fmt);
  3364. if (!conn && ctx) {
  3365. struct mg_connection fc;
  3366. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3367. } else {
  3368. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3369. }
  3370. va_end(ap);
  3371. }
  3372. void
  3373. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3374. {
  3375. va_list ap;
  3376. va_start(ap, fmt);
  3377. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3378. va_end(ap);
  3379. }
  3380. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3381. const char *
  3382. mg_version(void)
  3383. {
  3384. return CIVETWEB_VERSION;
  3385. }
  3386. const struct mg_request_info *
  3387. mg_get_request_info(const struct mg_connection *conn)
  3388. {
  3389. if (!conn) {
  3390. return NULL;
  3391. }
  3392. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3393. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3394. char txt[16];
  3395. struct mg_workerTLS *tls =
  3396. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3397. sprintf(txt, "%03i", conn->response_info.status_code);
  3398. if (strlen(txt) == 3) {
  3399. memcpy(tls->txtbuf, txt, 4);
  3400. } else {
  3401. strcpy(tls->txtbuf, "ERR");
  3402. }
  3403. ((struct mg_connection *)conn)->request_info.local_uri =
  3404. ((struct mg_connection *)conn)->request_info.request_uri =
  3405. tls->txtbuf; /* use thread safe buffer */
  3406. ((struct mg_connection *)conn)->request_info.num_headers =
  3407. conn->response_info.num_headers;
  3408. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3409. conn->response_info.http_headers,
  3410. sizeof(conn->response_info.http_headers));
  3411. } else
  3412. #endif
  3413. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3414. return NULL;
  3415. }
  3416. return &conn->request_info;
  3417. }
  3418. const struct mg_response_info *
  3419. mg_get_response_info(const struct mg_connection *conn)
  3420. {
  3421. if (!conn) {
  3422. return NULL;
  3423. }
  3424. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3425. return NULL;
  3426. }
  3427. return &conn->response_info;
  3428. }
  3429. static const char *
  3430. get_proto_name(const struct mg_connection *conn)
  3431. {
  3432. #if defined(__clang__)
  3433. #pragma clang diagnostic push
  3434. #pragma clang diagnostic ignored "-Wunreachable-code"
  3435. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3436. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3437. * unreachable, but splitting into four different #ifdef clauses here is more
  3438. * complicated.
  3439. */
  3440. #endif
  3441. const struct mg_request_info *ri = &conn->request_info;
  3442. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3443. ? (ri->is_ssl ? "wss" : "ws")
  3444. : (ri->is_ssl ? "https" : "http"));
  3445. return proto;
  3446. #if defined(__clang__)
  3447. #pragma clang diagnostic pop
  3448. #endif
  3449. }
  3450. int
  3451. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3452. {
  3453. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3454. return -1;
  3455. } else {
  3456. int truncated = 0;
  3457. const struct mg_request_info *ri = &conn->request_info;
  3458. const char *proto = get_proto_name(conn);
  3459. if (ri->local_uri == NULL) {
  3460. return -1;
  3461. }
  3462. if ((ri->request_uri != NULL)
  3463. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3464. /* The request uri is different from the local uri.
  3465. * This is usually if an absolute URI, including server
  3466. * name has been provided. */
  3467. mg_snprintf(conn,
  3468. &truncated,
  3469. buf,
  3470. buflen,
  3471. "%s://%s",
  3472. proto,
  3473. ri->request_uri);
  3474. if (truncated) {
  3475. return -1;
  3476. }
  3477. return 0;
  3478. } else {
  3479. /* The common case is a relative URI, so we have to
  3480. * construct an absolute URI from server name and port */
  3481. #if defined(USE_IPV6)
  3482. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3483. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3484. : htons(conn->client.lsa.sin.sin_port);
  3485. #else
  3486. int port = htons(conn->client.lsa.sin.sin_port);
  3487. #endif
  3488. int def_port = ri->is_ssl ? 443 : 80;
  3489. int auth_domain_check_enabled =
  3490. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3491. && (!mg_strcasecmp(
  3492. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3493. const char *server_domain =
  3494. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3495. char portstr[16];
  3496. char server_ip[48];
  3497. if (port != def_port) {
  3498. sprintf(portstr, ":%u", (unsigned)port);
  3499. } else {
  3500. portstr[0] = 0;
  3501. }
  3502. if (!auth_domain_check_enabled || !server_domain) {
  3503. sockaddr_to_string(server_ip,
  3504. sizeof(server_ip),
  3505. &conn->client.lsa);
  3506. server_domain = server_ip;
  3507. }
  3508. mg_snprintf(conn,
  3509. &truncated,
  3510. buf,
  3511. buflen,
  3512. "%s://%s%s%s",
  3513. proto,
  3514. server_domain,
  3515. portstr,
  3516. ri->local_uri);
  3517. if (truncated) {
  3518. return -1;
  3519. }
  3520. return 0;
  3521. }
  3522. }
  3523. }
  3524. /* Skip the characters until one of the delimiters characters found.
  3525. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3526. * Advance pointer to buffer to the next word. Return found 0-terminated
  3527. * word.
  3528. * Delimiters can be quoted with quotechar. */
  3529. static char *
  3530. skip_quoted(char **buf,
  3531. const char *delimiters,
  3532. const char *whitespace,
  3533. char quotechar)
  3534. {
  3535. char *p, *begin_word, *end_word, *end_whitespace;
  3536. begin_word = *buf;
  3537. end_word = begin_word + strcspn(begin_word, delimiters);
  3538. /* Check for quotechar */
  3539. if (end_word > begin_word) {
  3540. p = end_word - 1;
  3541. while (*p == quotechar) {
  3542. /* While the delimiter is quoted, look for the next delimiter.
  3543. */
  3544. /* This happens, e.g., in calls from parse_auth_header,
  3545. * if the user name contains a " character. */
  3546. /* If there is anything beyond end_word, copy it. */
  3547. if (*end_word != '\0') {
  3548. size_t end_off = strcspn(end_word + 1, delimiters);
  3549. memmove(p, end_word, end_off + 1);
  3550. p += end_off; /* p must correspond to end_word - 1 */
  3551. end_word += end_off + 1;
  3552. } else {
  3553. *p = '\0';
  3554. break;
  3555. }
  3556. }
  3557. for (p++; p < end_word; p++) {
  3558. *p = '\0';
  3559. }
  3560. }
  3561. if (*end_word == '\0') {
  3562. *buf = end_word;
  3563. } else {
  3564. #if defined(GCC_DIAGNOSTIC)
  3565. /* Disable spurious conversion warning for GCC */
  3566. #pragma GCC diagnostic push
  3567. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3568. #endif /* defined(GCC_DIAGNOSTIC) */
  3569. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3570. #if defined(GCC_DIAGNOSTIC)
  3571. #pragma GCC diagnostic pop
  3572. #endif /* defined(GCC_DIAGNOSTIC) */
  3573. for (p = end_word; p < end_whitespace; p++) {
  3574. *p = '\0';
  3575. }
  3576. *buf = end_whitespace;
  3577. }
  3578. return begin_word;
  3579. }
  3580. /* Return HTTP header value, or NULL if not found. */
  3581. static const char *
  3582. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3583. {
  3584. int i;
  3585. for (i = 0; i < num_hdr; i++) {
  3586. if (!mg_strcasecmp(name, hdr[i].name)) {
  3587. return hdr[i].value;
  3588. }
  3589. }
  3590. return NULL;
  3591. }
  3592. #if defined(USE_WEBSOCKET)
  3593. /* Retrieve requested HTTP header multiple values, and return the number of
  3594. * found occurrences */
  3595. static int
  3596. get_req_headers(const struct mg_request_info *ri,
  3597. const char *name,
  3598. const char **output,
  3599. int output_max_size)
  3600. {
  3601. int i;
  3602. int cnt = 0;
  3603. if (ri) {
  3604. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3605. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3606. output[cnt++] = ri->http_headers[i].value;
  3607. }
  3608. }
  3609. }
  3610. return cnt;
  3611. }
  3612. #endif
  3613. const char *
  3614. mg_get_header(const struct mg_connection *conn, const char *name)
  3615. {
  3616. if (!conn) {
  3617. return NULL;
  3618. }
  3619. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3620. return get_header(conn->request_info.http_headers,
  3621. conn->request_info.num_headers,
  3622. name);
  3623. }
  3624. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3625. return get_header(conn->response_info.http_headers,
  3626. conn->response_info.num_headers,
  3627. name);
  3628. }
  3629. return NULL;
  3630. }
  3631. static const char *
  3632. get_http_version(const struct mg_connection *conn)
  3633. {
  3634. if (!conn) {
  3635. return NULL;
  3636. }
  3637. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3638. return conn->request_info.http_version;
  3639. }
  3640. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3641. return conn->response_info.http_version;
  3642. }
  3643. return NULL;
  3644. }
  3645. /* A helper function for traversing a comma separated list of values.
  3646. * It returns a list pointer shifted to the next value, or NULL if the end
  3647. * of the list found.
  3648. * Value is stored in val vector. If value has form "x=y", then eq_val
  3649. * vector is initialized to point to the "y" part, and val vector length
  3650. * is adjusted to point only to "x". */
  3651. static const char *
  3652. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3653. {
  3654. int end;
  3655. reparse:
  3656. if (val == NULL || list == NULL || *list == '\0') {
  3657. /* End of the list */
  3658. return NULL;
  3659. }
  3660. /* Skip over leading LWS */
  3661. while (*list == ' ' || *list == '\t')
  3662. list++;
  3663. val->ptr = list;
  3664. if ((list = strchr(val->ptr, ',')) != NULL) {
  3665. /* Comma found. Store length and shift the list ptr */
  3666. val->len = ((size_t)(list - val->ptr));
  3667. list++;
  3668. } else {
  3669. /* This value is the last one */
  3670. list = val->ptr + strlen(val->ptr);
  3671. val->len = ((size_t)(list - val->ptr));
  3672. }
  3673. /* Adjust length for trailing LWS */
  3674. end = (int)val->len - 1;
  3675. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3676. end--;
  3677. val->len = (size_t)(end) + (size_t)(1);
  3678. if (val->len == 0) {
  3679. /* Ignore any empty entries. */
  3680. goto reparse;
  3681. }
  3682. if (eq_val != NULL) {
  3683. /* Value has form "x=y", adjust pointers and lengths
  3684. * so that val points to "x", and eq_val points to "y". */
  3685. eq_val->len = 0;
  3686. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3687. if (eq_val->ptr != NULL) {
  3688. eq_val->ptr++; /* Skip over '=' character */
  3689. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3690. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3691. }
  3692. }
  3693. return list;
  3694. }
  3695. /* A helper function for checking if a comma separated list of values
  3696. * contains
  3697. * the given option (case insensitvely).
  3698. * 'header' can be NULL, in which case false is returned. */
  3699. static int
  3700. header_has_option(const char *header, const char *option)
  3701. {
  3702. struct vec opt_vec;
  3703. struct vec eq_vec;
  3704. DEBUG_ASSERT(option != NULL);
  3705. DEBUG_ASSERT(option[0] != '\0');
  3706. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3707. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3708. return 1;
  3709. }
  3710. return 0;
  3711. }
  3712. /* Perform case-insensitive match of string against pattern */
  3713. static ptrdiff_t
  3714. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3715. {
  3716. const char *or_str;
  3717. ptrdiff_t i, j, len, res;
  3718. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3719. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3720. return (res > 0) ? res
  3721. : match_prefix(or_str + 1,
  3722. (size_t)((pattern + pattern_len)
  3723. - (or_str + 1)),
  3724. str);
  3725. }
  3726. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3727. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3728. continue;
  3729. } else if (pattern[i] == '$') {
  3730. return (str[j] == '\0') ? j : -1;
  3731. } else if (pattern[i] == '*') {
  3732. i++;
  3733. if (pattern[i] == '*') {
  3734. i++;
  3735. len = (ptrdiff_t)strlen(str + j);
  3736. } else {
  3737. len = (ptrdiff_t)strcspn(str + j, "/");
  3738. }
  3739. if (i == (ptrdiff_t)pattern_len) {
  3740. return j + len;
  3741. }
  3742. do {
  3743. res = match_prefix(pattern + i,
  3744. (pattern_len - (size_t)i),
  3745. str + j + len);
  3746. } while (res == -1 && len-- > 0);
  3747. return (res == -1) ? -1 : j + res + len;
  3748. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3749. return -1;
  3750. }
  3751. }
  3752. return (ptrdiff_t)j;
  3753. }
  3754. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3755. * This function must tolerate situations when connection info is not
  3756. * set up, for example if request parsing failed. */
  3757. static int
  3758. should_keep_alive(const struct mg_connection *conn)
  3759. {
  3760. const char *http_version;
  3761. const char *header;
  3762. /* First satisfy needs of the server */
  3763. if ((conn == NULL) || conn->must_close) {
  3764. /* Close, if civetweb framework needs to close */
  3765. return 0;
  3766. }
  3767. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3768. /* Close, if keep alive is not enabled */
  3769. return 0;
  3770. }
  3771. /* Check explicit wish of the client */
  3772. header = mg_get_header(conn, "Connection");
  3773. if (header) {
  3774. /* If there is a connection header from the client, obey */
  3775. if (header_has_option(header, "keep-alive")) {
  3776. return 1;
  3777. }
  3778. return 0;
  3779. }
  3780. /* Use default of the standard */
  3781. http_version = get_http_version(conn);
  3782. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3783. /* HTTP 1.1 default is keep alive */
  3784. return 1;
  3785. }
  3786. /* HTTP 1.0 (and earlier) default is to close the connection */
  3787. return 0;
  3788. }
  3789. static int
  3790. should_decode_url(const struct mg_connection *conn)
  3791. {
  3792. if (!conn || !conn->dom_ctx) {
  3793. return 0;
  3794. }
  3795. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3796. }
  3797. static const char *
  3798. suggest_connection_header(const struct mg_connection *conn)
  3799. {
  3800. return should_keep_alive(conn) ? "keep-alive" : "close";
  3801. }
  3802. static int
  3803. send_no_cache_header(struct mg_connection *conn)
  3804. {
  3805. /* Send all current and obsolete cache opt-out directives. */
  3806. return mg_printf(conn,
  3807. "Cache-Control: no-cache, no-store, "
  3808. "must-revalidate, private, max-age=0\r\n"
  3809. "Pragma: no-cache\r\n"
  3810. "Expires: 0\r\n");
  3811. }
  3812. static int
  3813. send_static_cache_header(struct mg_connection *conn)
  3814. {
  3815. #if !defined(NO_CACHING)
  3816. int max_age;
  3817. const char *cache_control =
  3818. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3819. if (cache_control != NULL) {
  3820. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3821. }
  3822. /* Read the server config to check how long a file may be cached.
  3823. * The configuration is in seconds. */
  3824. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3825. if (max_age <= 0) {
  3826. /* 0 means "do not cache". All values <0 are reserved
  3827. * and may be used differently in the future. */
  3828. /* If a file should not be cached, do not only send
  3829. * max-age=0, but also pragmas and Expires headers. */
  3830. return send_no_cache_header(conn);
  3831. }
  3832. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3833. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3834. /* See also https://www.mnot.net/cache_docs/ */
  3835. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3836. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3837. * leap
  3838. * year to 31622400 seconds. For the moment, we just send whatever has
  3839. * been configured, still the behavior for >1 year should be considered
  3840. * as undefined. */
  3841. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3842. #else /* NO_CACHING */
  3843. return send_no_cache_header(conn);
  3844. #endif /* !NO_CACHING */
  3845. }
  3846. static int
  3847. send_additional_header(struct mg_connection *conn)
  3848. {
  3849. int i = 0;
  3850. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3851. #if !defined(NO_SSL)
  3852. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3853. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3854. if (max_age >= 0) {
  3855. i += mg_printf(conn,
  3856. "Strict-Transport-Security: max-age=%u\r\n",
  3857. (unsigned)max_age);
  3858. }
  3859. }
  3860. #endif
  3861. if (header && header[0]) {
  3862. i += mg_printf(conn, "%s\r\n", header);
  3863. }
  3864. return i;
  3865. }
  3866. #if !defined(NO_FILESYSTEMS)
  3867. static void handle_file_based_request(struct mg_connection *conn,
  3868. const char *path,
  3869. struct mg_file *filep);
  3870. #endif /* NO_FILESYSTEMS */
  3871. const char *
  3872. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3873. {
  3874. /* See IANA HTTP status code assignment:
  3875. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3876. */
  3877. switch (response_code) {
  3878. /* RFC2616 Section 10.1 - Informational 1xx */
  3879. case 100:
  3880. return "Continue"; /* RFC2616 Section 10.1.1 */
  3881. case 101:
  3882. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3883. case 102:
  3884. return "Processing"; /* RFC2518 Section 10.1 */
  3885. /* RFC2616 Section 10.2 - Successful 2xx */
  3886. case 200:
  3887. return "OK"; /* RFC2616 Section 10.2.1 */
  3888. case 201:
  3889. return "Created"; /* RFC2616 Section 10.2.2 */
  3890. case 202:
  3891. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3892. case 203:
  3893. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3894. case 204:
  3895. return "No Content"; /* RFC2616 Section 10.2.5 */
  3896. case 205:
  3897. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3898. case 206:
  3899. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3900. case 207:
  3901. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3902. */
  3903. case 208:
  3904. return "Already Reported"; /* RFC5842 Section 7.1 */
  3905. case 226:
  3906. return "IM used"; /* RFC3229 Section 10.4.1 */
  3907. /* RFC2616 Section 10.3 - Redirection 3xx */
  3908. case 300:
  3909. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3910. case 301:
  3911. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3912. case 302:
  3913. return "Found"; /* RFC2616 Section 10.3.3 */
  3914. case 303:
  3915. return "See Other"; /* RFC2616 Section 10.3.4 */
  3916. case 304:
  3917. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3918. case 305:
  3919. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3920. case 307:
  3921. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3922. case 308:
  3923. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3924. /* RFC2616 Section 10.4 - Client Error 4xx */
  3925. case 400:
  3926. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3927. case 401:
  3928. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3929. case 402:
  3930. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3931. case 403:
  3932. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3933. case 404:
  3934. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3935. case 405:
  3936. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3937. case 406:
  3938. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3939. case 407:
  3940. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3941. case 408:
  3942. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3943. case 409:
  3944. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3945. case 410:
  3946. return "Gone"; /* RFC2616 Section 10.4.11 */
  3947. case 411:
  3948. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3949. case 412:
  3950. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3951. case 413:
  3952. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3953. case 414:
  3954. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3955. case 415:
  3956. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3957. case 416:
  3958. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3959. */
  3960. case 417:
  3961. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3962. case 421:
  3963. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3964. case 422:
  3965. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3966. * Section 11.2 */
  3967. case 423:
  3968. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3969. case 424:
  3970. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3971. * Section 11.4 */
  3972. case 426:
  3973. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3974. case 428:
  3975. return "Precondition Required"; /* RFC 6585, Section 3 */
  3976. case 429:
  3977. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3978. case 431:
  3979. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3980. case 451:
  3981. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3982. * Section 3 */
  3983. /* RFC2616 Section 10.5 - Server Error 5xx */
  3984. case 500:
  3985. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3986. case 501:
  3987. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3988. case 502:
  3989. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3990. case 503:
  3991. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3992. case 504:
  3993. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3994. case 505:
  3995. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3996. case 506:
  3997. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3998. case 507:
  3999. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4000. * Section 11.5 */
  4001. case 508:
  4002. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4003. case 510:
  4004. return "Not Extended"; /* RFC 2774, Section 7 */
  4005. case 511:
  4006. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4007. /* Other status codes, not shown in the IANA HTTP status code
  4008. * assignment.
  4009. * E.g., "de facto" standards due to common use, ... */
  4010. case 418:
  4011. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4012. case 419:
  4013. return "Authentication Timeout"; /* common use */
  4014. case 420:
  4015. return "Enhance Your Calm"; /* common use */
  4016. case 440:
  4017. return "Login Timeout"; /* common use */
  4018. case 509:
  4019. return "Bandwidth Limit Exceeded"; /* common use */
  4020. default:
  4021. /* This error code is unknown. This should not happen. */
  4022. if (conn) {
  4023. mg_cry_internal(conn,
  4024. "Unknown HTTP response code: %u",
  4025. response_code);
  4026. }
  4027. /* Return at least a category according to RFC 2616 Section 10. */
  4028. if (response_code >= 100 && response_code < 200) {
  4029. /* Unknown informational status code */
  4030. return "Information";
  4031. }
  4032. if (response_code >= 200 && response_code < 300) {
  4033. /* Unknown success code */
  4034. return "Success";
  4035. }
  4036. if (response_code >= 300 && response_code < 400) {
  4037. /* Unknown redirection code */
  4038. return "Redirection";
  4039. }
  4040. if (response_code >= 400 && response_code < 500) {
  4041. /* Unknown request error code */
  4042. return "Client Error";
  4043. }
  4044. if (response_code >= 500 && response_code < 600) {
  4045. /* Unknown server error code */
  4046. return "Server Error";
  4047. }
  4048. /* Response code not even within reasonable range */
  4049. return "";
  4050. }
  4051. }
  4052. static int
  4053. mg_send_http_error_impl(struct mg_connection *conn,
  4054. int status,
  4055. const char *fmt,
  4056. va_list args)
  4057. {
  4058. char errmsg_buf[MG_BUF_LEN];
  4059. va_list ap;
  4060. int has_body;
  4061. char date[64];
  4062. time_t curtime = time(NULL);
  4063. #if !defined(NO_FILESYSTEMS)
  4064. char path_buf[PATH_MAX];
  4065. int len, i, page_handler_found, scope, truncated;
  4066. const char *error_handler = NULL;
  4067. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4068. const char *error_page_file_ext, *tstr;
  4069. #endif /* NO_FILESYSTEMS */
  4070. int handled_by_callback = 0;
  4071. const char *status_text = mg_get_response_code_text(conn, status);
  4072. if ((conn == NULL) || (fmt == NULL)) {
  4073. return -2;
  4074. }
  4075. /* Set status (for log) */
  4076. conn->status_code = status;
  4077. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4078. has_body = ((status > 199) && (status != 204) && (status != 304));
  4079. /* Prepare message in buf, if required */
  4080. if (has_body
  4081. || (!conn->in_error_handler
  4082. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4083. /* Store error message in errmsg_buf */
  4084. va_copy(ap, args);
  4085. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4086. va_end(ap);
  4087. /* In a debug build, print all html errors */
  4088. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4089. }
  4090. /* If there is a http_error callback, call it.
  4091. * But don't do it recursively, if callback calls mg_send_http_error again.
  4092. */
  4093. if (!conn->in_error_handler
  4094. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4095. /* Mark in_error_handler to avoid recursion and call user callback. */
  4096. conn->in_error_handler = 1;
  4097. handled_by_callback =
  4098. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4099. == 0);
  4100. conn->in_error_handler = 0;
  4101. }
  4102. if (!handled_by_callback) {
  4103. /* Check for recursion */
  4104. if (conn->in_error_handler) {
  4105. DEBUG_TRACE(
  4106. "Recursion when handling error %u - fall back to default",
  4107. status);
  4108. #if !defined(NO_FILESYSTEMS)
  4109. } else {
  4110. /* Send user defined error pages, if defined */
  4111. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4112. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4113. page_handler_found = 0;
  4114. if (error_handler != NULL) {
  4115. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4116. switch (scope) {
  4117. case 1: /* Handler for specific error, e.g. 404 error */
  4118. mg_snprintf(conn,
  4119. &truncated,
  4120. path_buf,
  4121. sizeof(path_buf) - 32,
  4122. "%serror%03u.",
  4123. error_handler,
  4124. status);
  4125. break;
  4126. case 2: /* Handler for error group, e.g., 5xx error
  4127. * handler
  4128. * for all server errors (500-599) */
  4129. mg_snprintf(conn,
  4130. &truncated,
  4131. path_buf,
  4132. sizeof(path_buf) - 32,
  4133. "%serror%01uxx.",
  4134. error_handler,
  4135. status / 100);
  4136. break;
  4137. default: /* Handler for all errors */
  4138. mg_snprintf(conn,
  4139. &truncated,
  4140. path_buf,
  4141. sizeof(path_buf) - 32,
  4142. "%serror.",
  4143. error_handler);
  4144. break;
  4145. }
  4146. /* String truncation in buf may only occur if
  4147. * error_handler is too long. This string is
  4148. * from the config, not from a client. */
  4149. (void)truncated;
  4150. /* The following code is redundant, but it should avoid
  4151. * false positives in static source code analyzers and
  4152. * vulnerability scanners.
  4153. */
  4154. path_buf[sizeof(path_buf) - 32] = 0;
  4155. len = (int)strlen(path_buf);
  4156. if (len > (int)sizeof(path_buf) - 32) {
  4157. len = (int)sizeof(path_buf) - 32;
  4158. }
  4159. /* Start with the file extenstion from the configuration. */
  4160. tstr = strchr(error_page_file_ext, '.');
  4161. while (tstr) {
  4162. for (i = 1;
  4163. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4164. i++) {
  4165. /* buffer overrun is not possible here, since
  4166. * (i < 32) && (len < sizeof(path_buf) - 32)
  4167. * ==> (i + len) < sizeof(path_buf) */
  4168. path_buf[len + i - 1] = tstr[i];
  4169. }
  4170. /* buffer overrun is not possible here, since
  4171. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4172. * ==> (i + len) <= sizeof(path_buf) */
  4173. path_buf[len + i - 1] = 0;
  4174. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4175. DEBUG_TRACE("Check error page %s - found",
  4176. path_buf);
  4177. page_handler_found = 1;
  4178. break;
  4179. }
  4180. DEBUG_TRACE("Check error page %s - not found",
  4181. path_buf);
  4182. /* Continue with the next file extenstion from the
  4183. * configuration (if there is a next one). */
  4184. tstr = strchr(tstr + i, '.');
  4185. }
  4186. }
  4187. }
  4188. if (page_handler_found) {
  4189. conn->in_error_handler = 1;
  4190. handle_file_based_request(conn, path_buf, &error_page_file);
  4191. conn->in_error_handler = 0;
  4192. return 0;
  4193. }
  4194. #endif /* NO_FILESYSTEMS */
  4195. }
  4196. /* No custom error page. Send default error page. */
  4197. gmt_time_string(date, sizeof(date), &curtime);
  4198. conn->must_close = 1;
  4199. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4200. send_no_cache_header(conn);
  4201. send_additional_header(conn);
  4202. if (has_body) {
  4203. mg_printf(conn,
  4204. "%s",
  4205. "Content-Type: text/plain; charset=utf-8\r\n");
  4206. }
  4207. mg_printf(conn,
  4208. "Date: %s\r\n"
  4209. "Connection: close\r\n\r\n",
  4210. date);
  4211. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4212. if (has_body) {
  4213. /* For other errors, send a generic error message. */
  4214. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4215. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4216. } else {
  4217. /* No body allowed. Close the connection. */
  4218. DEBUG_TRACE("Error %i", status);
  4219. }
  4220. }
  4221. return 0;
  4222. }
  4223. int
  4224. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4225. {
  4226. va_list ap;
  4227. int ret;
  4228. va_start(ap, fmt);
  4229. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4230. va_end(ap);
  4231. return ret;
  4232. }
  4233. int
  4234. mg_send_http_ok(struct mg_connection *conn,
  4235. const char *mime_type,
  4236. long long content_length)
  4237. {
  4238. char date[64];
  4239. time_t curtime = time(NULL);
  4240. if ((mime_type == NULL) || (*mime_type == 0)) {
  4241. /* No content type defined: default to text/html */
  4242. mime_type = "text/html";
  4243. }
  4244. gmt_time_string(date, sizeof(date), &curtime);
  4245. mg_printf(conn,
  4246. "HTTP/1.1 200 OK\r\n"
  4247. "Content-Type: %s\r\n"
  4248. "Date: %s\r\n"
  4249. "Connection: %s\r\n",
  4250. mime_type,
  4251. date,
  4252. suggest_connection_header(conn));
  4253. send_no_cache_header(conn);
  4254. send_additional_header(conn);
  4255. if (content_length < 0) {
  4256. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4257. } else {
  4258. mg_printf(conn,
  4259. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4260. (uint64_t)content_length);
  4261. }
  4262. return 0;
  4263. }
  4264. int
  4265. mg_send_http_redirect(struct mg_connection *conn,
  4266. const char *target_url,
  4267. int redirect_code)
  4268. {
  4269. /* Send a 30x redirect response.
  4270. *
  4271. * Redirect types (status codes):
  4272. *
  4273. * Status | Perm/Temp | Method | Version
  4274. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4275. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4276. * 303 | temporary | always use GET | HTTP/1.1
  4277. * 307 | temporary | always keep method | HTTP/1.1
  4278. * 308 | permanent | always keep method | HTTP/1.1
  4279. */
  4280. const char *redirect_text;
  4281. int ret;
  4282. size_t content_len = 0;
  4283. char reply[MG_BUF_LEN];
  4284. /* In case redirect_code=0, use 307. */
  4285. if (redirect_code == 0) {
  4286. redirect_code = 307;
  4287. }
  4288. /* In case redirect_code is none of the above, return error. */
  4289. if ((redirect_code != 301) && (redirect_code != 302)
  4290. && (redirect_code != 303) && (redirect_code != 307)
  4291. && (redirect_code != 308)) {
  4292. /* Parameter error */
  4293. return -2;
  4294. }
  4295. /* Get proper text for response code */
  4296. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4297. /* If target_url is not defined, redirect to "/". */
  4298. if ((target_url == NULL) || (*target_url == 0)) {
  4299. target_url = "/";
  4300. }
  4301. #if defined(MG_SEND_REDIRECT_BODY)
  4302. /* TODO: condition name? */
  4303. /* Prepare a response body with a hyperlink.
  4304. *
  4305. * According to RFC2616 (and RFC1945 before):
  4306. * Unless the request method was HEAD, the entity of the
  4307. * response SHOULD contain a short hypertext note with a hyperlink to
  4308. * the new URI(s).
  4309. *
  4310. * However, this response body is not useful in M2M communication.
  4311. * Probably the original reason in the RFC was, clients not supporting
  4312. * a 30x HTTP redirect could still show the HTML page and let the user
  4313. * press the link. Since current browsers support 30x HTTP, the additional
  4314. * HTML body does not seem to make sense anymore.
  4315. *
  4316. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4317. * but it only notes:
  4318. * The server's response payload usually contains a short
  4319. * hypertext note with a hyperlink to the new URI(s).
  4320. *
  4321. * Deactivated by default. If you need the 30x body, set the define.
  4322. */
  4323. mg_snprintf(
  4324. conn,
  4325. NULL /* ignore truncation */,
  4326. reply,
  4327. sizeof(reply),
  4328. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4329. redirect_text,
  4330. target_url,
  4331. target_url);
  4332. content_len = strlen(reply);
  4333. #else
  4334. reply[0] = 0;
  4335. #endif
  4336. /* Do not send any additional header. For all other options,
  4337. * including caching, there are suitable defaults. */
  4338. ret = mg_printf(conn,
  4339. "HTTP/1.1 %i %s\r\n"
  4340. "Location: %s\r\n"
  4341. "Content-Length: %u\r\n"
  4342. "Connection: %s\r\n\r\n",
  4343. redirect_code,
  4344. redirect_text,
  4345. target_url,
  4346. (unsigned int)content_len,
  4347. suggest_connection_header(conn));
  4348. /* Send response body */
  4349. if (ret > 0) {
  4350. /* ... unless it is a HEAD request */
  4351. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4352. ret = mg_write(conn, reply, content_len);
  4353. }
  4354. }
  4355. return (ret > 0) ? ret : -1;
  4356. }
  4357. #if defined(_WIN32)
  4358. /* Create substitutes for POSIX functions in Win32. */
  4359. #if defined(GCC_DIAGNOSTIC)
  4360. /* Show no warning in case system functions are not used. */
  4361. #pragma GCC diagnostic push
  4362. #pragma GCC diagnostic ignored "-Wunused-function"
  4363. #endif
  4364. static int
  4365. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4366. {
  4367. (void)unused;
  4368. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4369. InitializeCriticalSection(&mutex->sec);
  4370. return 0;
  4371. }
  4372. static int
  4373. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4374. {
  4375. DeleteCriticalSection(&mutex->sec);
  4376. return 0;
  4377. }
  4378. static int
  4379. pthread_mutex_lock(pthread_mutex_t *mutex)
  4380. {
  4381. EnterCriticalSection(&mutex->sec);
  4382. return 0;
  4383. }
  4384. static int
  4385. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4386. {
  4387. LeaveCriticalSection(&mutex->sec);
  4388. return 0;
  4389. }
  4390. FUNCTION_MAY_BE_UNUSED
  4391. static int
  4392. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4393. {
  4394. (void)unused;
  4395. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4396. cv->waiting_thread = NULL;
  4397. return 0;
  4398. }
  4399. FUNCTION_MAY_BE_UNUSED
  4400. static int
  4401. pthread_cond_timedwait(pthread_cond_t *cv,
  4402. pthread_mutex_t *mutex,
  4403. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4404. {
  4405. struct mg_workerTLS **ptls,
  4406. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4407. int ok;
  4408. int64_t nsnow, nswaitabs, nswaitrel;
  4409. DWORD mswaitrel;
  4410. pthread_mutex_lock(&cv->threadIdSec);
  4411. /* Add this thread to cv's waiting list */
  4412. ptls = &cv->waiting_thread;
  4413. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4414. ;
  4415. tls->next_waiting_thread = NULL;
  4416. *ptls = tls;
  4417. pthread_mutex_unlock(&cv->threadIdSec);
  4418. if (abstime) {
  4419. nsnow = mg_get_current_time_ns();
  4420. nswaitabs =
  4421. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4422. nswaitrel = nswaitabs - nsnow;
  4423. if (nswaitrel < 0) {
  4424. nswaitrel = 0;
  4425. }
  4426. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4427. } else {
  4428. mswaitrel = (DWORD)INFINITE;
  4429. }
  4430. pthread_mutex_unlock(mutex);
  4431. ok = (WAIT_OBJECT_0
  4432. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4433. if (!ok) {
  4434. ok = 1;
  4435. pthread_mutex_lock(&cv->threadIdSec);
  4436. ptls = &cv->waiting_thread;
  4437. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4438. if (*ptls == tls) {
  4439. *ptls = tls->next_waiting_thread;
  4440. ok = 0;
  4441. break;
  4442. }
  4443. }
  4444. pthread_mutex_unlock(&cv->threadIdSec);
  4445. if (ok) {
  4446. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4447. (DWORD)INFINITE);
  4448. }
  4449. }
  4450. /* This thread has been removed from cv's waiting list */
  4451. pthread_mutex_lock(mutex);
  4452. return ok ? 0 : -1;
  4453. }
  4454. FUNCTION_MAY_BE_UNUSED
  4455. static int
  4456. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4457. {
  4458. return pthread_cond_timedwait(cv, mutex, NULL);
  4459. }
  4460. FUNCTION_MAY_BE_UNUSED
  4461. static int
  4462. pthread_cond_signal(pthread_cond_t *cv)
  4463. {
  4464. HANDLE wkup = NULL;
  4465. BOOL ok = FALSE;
  4466. pthread_mutex_lock(&cv->threadIdSec);
  4467. if (cv->waiting_thread) {
  4468. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4469. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4470. ok = SetEvent(wkup);
  4471. DEBUG_ASSERT(ok);
  4472. }
  4473. pthread_mutex_unlock(&cv->threadIdSec);
  4474. return ok ? 0 : 1;
  4475. }
  4476. FUNCTION_MAY_BE_UNUSED
  4477. static int
  4478. pthread_cond_broadcast(pthread_cond_t *cv)
  4479. {
  4480. pthread_mutex_lock(&cv->threadIdSec);
  4481. while (cv->waiting_thread) {
  4482. pthread_cond_signal(cv);
  4483. }
  4484. pthread_mutex_unlock(&cv->threadIdSec);
  4485. return 0;
  4486. }
  4487. FUNCTION_MAY_BE_UNUSED
  4488. static int
  4489. pthread_cond_destroy(pthread_cond_t *cv)
  4490. {
  4491. pthread_mutex_lock(&cv->threadIdSec);
  4492. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4493. pthread_mutex_unlock(&cv->threadIdSec);
  4494. pthread_mutex_destroy(&cv->threadIdSec);
  4495. return 0;
  4496. }
  4497. #if defined(ALTERNATIVE_QUEUE)
  4498. FUNCTION_MAY_BE_UNUSED
  4499. static void *
  4500. event_create(void)
  4501. {
  4502. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4503. }
  4504. FUNCTION_MAY_BE_UNUSED
  4505. static int
  4506. event_wait(void *eventhdl)
  4507. {
  4508. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4509. return (res == WAIT_OBJECT_0);
  4510. }
  4511. FUNCTION_MAY_BE_UNUSED
  4512. static int
  4513. event_signal(void *eventhdl)
  4514. {
  4515. return (int)SetEvent((HANDLE)eventhdl);
  4516. }
  4517. FUNCTION_MAY_BE_UNUSED
  4518. static void
  4519. event_destroy(void *eventhdl)
  4520. {
  4521. CloseHandle((HANDLE)eventhdl);
  4522. }
  4523. #endif
  4524. #if defined(GCC_DIAGNOSTIC)
  4525. /* Enable unused function warning again */
  4526. #pragma GCC diagnostic pop
  4527. #endif
  4528. /* For Windows, change all slashes to backslashes in path names. */
  4529. static void
  4530. change_slashes_to_backslashes(char *path)
  4531. {
  4532. int i;
  4533. for (i = 0; path[i] != '\0'; i++) {
  4534. if (path[i] == '/') {
  4535. path[i] = '\\';
  4536. }
  4537. /* remove double backslash (check i > 0 to preserve UNC paths,
  4538. * like \\server\file.txt) */
  4539. if ((i > 0) && (path[i] == '\\')) {
  4540. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4541. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4542. }
  4543. }
  4544. }
  4545. }
  4546. static int
  4547. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4548. {
  4549. int diff;
  4550. do {
  4551. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4552. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4553. s1++;
  4554. s2++;
  4555. } while ((diff == 0) && (s1[-1] != L'\0'));
  4556. return diff;
  4557. }
  4558. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4559. * wbuf and wbuf_len is a target buffer and its length. */
  4560. static void
  4561. path_to_unicode(const struct mg_connection *conn,
  4562. const char *path,
  4563. wchar_t *wbuf,
  4564. size_t wbuf_len)
  4565. {
  4566. char buf[PATH_MAX], buf2[PATH_MAX];
  4567. wchar_t wbuf2[W_PATH_MAX + 1];
  4568. DWORD long_len, err;
  4569. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4570. mg_strlcpy(buf, path, sizeof(buf));
  4571. change_slashes_to_backslashes(buf);
  4572. /* Convert to Unicode and back. If doubly-converted string does not
  4573. * match the original, something is fishy, reject. */
  4574. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4575. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4576. WideCharToMultiByte(
  4577. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4578. if (strcmp(buf, buf2) != 0) {
  4579. wbuf[0] = L'\0';
  4580. }
  4581. /* Windows file systems are not case sensitive, but you can still use
  4582. * uppercase and lowercase letters (on all modern file systems).
  4583. * The server can check if the URI uses the same upper/lowercase
  4584. * letters an the file system, effectively making Windows servers
  4585. * case sensitive (like Linux servers are). It is still not possible
  4586. * to use two files with the same name in different cases on Windows
  4587. * (like /a and /A) - this would be possible in Linux.
  4588. * As a default, Windows is not case sensitive, but the case sensitive
  4589. * file name check can be activated by an additional configuration. */
  4590. if (conn) {
  4591. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4592. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4593. "yes")) {
  4594. /* Use case sensitive compare function */
  4595. fcompare = wcscmp;
  4596. }
  4597. }
  4598. (void)conn; /* conn is currently unused */
  4599. #if !defined(_WIN32_WCE)
  4600. /* Only accept a full file path, not a Windows short (8.3) path. */
  4601. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4602. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4603. if (long_len == 0) {
  4604. err = GetLastError();
  4605. if (err == ERROR_FILE_NOT_FOUND) {
  4606. /* File does not exist. This is not always a problem here. */
  4607. return;
  4608. }
  4609. }
  4610. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4611. /* Short name is used. */
  4612. wbuf[0] = L'\0';
  4613. }
  4614. #else
  4615. (void)long_len;
  4616. (void)wbuf2;
  4617. (void)err;
  4618. if (strchr(path, '~')) {
  4619. wbuf[0] = L'\0';
  4620. }
  4621. #endif
  4622. }
  4623. #if !defined(NO_FILESYSTEMS)
  4624. static int
  4625. mg_stat(const struct mg_connection *conn,
  4626. const char *path,
  4627. struct mg_file_stat *filep)
  4628. {
  4629. wchar_t wbuf[W_PATH_MAX];
  4630. WIN32_FILE_ATTRIBUTE_DATA info;
  4631. time_t creation_time;
  4632. size_t len;
  4633. if (!filep) {
  4634. return 0;
  4635. }
  4636. memset(filep, 0, sizeof(*filep));
  4637. if (conn && is_file_in_memory(conn, path)) {
  4638. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4639. * memset */
  4640. /* Quick fix (for 1.9.x): */
  4641. /* mg_stat must fill all fields, also for files in memory */
  4642. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4643. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4644. filep->size = tmp_file.stat.size;
  4645. filep->location = 2;
  4646. /* TODO: for 1.10: restructure how files in memory are handled */
  4647. /* The "file in memory" feature is a candidate for deletion.
  4648. * Please join the discussion at
  4649. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4650. */
  4651. filep->last_modified = time(NULL); /* TODO */
  4652. /* last_modified = now ... assumes the file may change during
  4653. * runtime,
  4654. * so every mg_fopen call may return different data */
  4655. /* last_modified = conn->phys_ctx.start_time;
  4656. * May be used it the data does not change during runtime. This
  4657. * allows
  4658. * browser caching. Since we do not know, we have to assume the file
  4659. * in memory may change. */
  4660. return 1;
  4661. }
  4662. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4663. /* Windows happily opens files with some garbage at the end of file name.
  4664. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4665. * "a.cgi", despite one would expect an error back. */
  4666. len = strlen(path);
  4667. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4668. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4669. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4670. filep->last_modified =
  4671. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4672. info.ftLastWriteTime.dwHighDateTime);
  4673. /* On Windows, the file creation time can be higher than the
  4674. * modification time, e.g. when a file is copied.
  4675. * Since the Last-Modified timestamp is used for caching
  4676. * it should be based on the most recent timestamp. */
  4677. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4678. info.ftCreationTime.dwHighDateTime);
  4679. if (creation_time > filep->last_modified) {
  4680. filep->last_modified = creation_time;
  4681. }
  4682. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4683. return 1;
  4684. }
  4685. return 0;
  4686. }
  4687. #endif
  4688. static int
  4689. mg_remove(const struct mg_connection *conn, const char *path)
  4690. {
  4691. wchar_t wbuf[W_PATH_MAX];
  4692. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4693. return DeleteFileW(wbuf) ? 0 : -1;
  4694. }
  4695. static int
  4696. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4697. {
  4698. wchar_t wbuf[W_PATH_MAX];
  4699. (void)mode;
  4700. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4701. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4702. }
  4703. /* Create substitutes for POSIX functions in Win32. */
  4704. #if defined(GCC_DIAGNOSTIC)
  4705. /* Show no warning in case system functions are not used. */
  4706. #pragma GCC diagnostic push
  4707. #pragma GCC diagnostic ignored "-Wunused-function"
  4708. #endif
  4709. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4710. FUNCTION_MAY_BE_UNUSED
  4711. static DIR *
  4712. mg_opendir(const struct mg_connection *conn, const char *name)
  4713. {
  4714. DIR *dir = NULL;
  4715. wchar_t wpath[W_PATH_MAX];
  4716. DWORD attrs;
  4717. if (name == NULL) {
  4718. SetLastError(ERROR_BAD_ARGUMENTS);
  4719. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4720. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4721. } else {
  4722. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4723. attrs = GetFileAttributesW(wpath);
  4724. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4725. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4726. (void)wcscat(wpath, L"\\*");
  4727. dir->handle = FindFirstFileW(wpath, &dir->info);
  4728. dir->result.d_name[0] = '\0';
  4729. } else {
  4730. mg_free(dir);
  4731. dir = NULL;
  4732. }
  4733. }
  4734. return dir;
  4735. }
  4736. FUNCTION_MAY_BE_UNUSED
  4737. static int
  4738. mg_closedir(DIR *dir)
  4739. {
  4740. int result = 0;
  4741. if (dir != NULL) {
  4742. if (dir->handle != INVALID_HANDLE_VALUE)
  4743. result = FindClose(dir->handle) ? 0 : -1;
  4744. mg_free(dir);
  4745. } else {
  4746. result = -1;
  4747. SetLastError(ERROR_BAD_ARGUMENTS);
  4748. }
  4749. return result;
  4750. }
  4751. FUNCTION_MAY_BE_UNUSED
  4752. static struct dirent *
  4753. mg_readdir(DIR *dir)
  4754. {
  4755. struct dirent *result = 0;
  4756. if (dir) {
  4757. if (dir->handle != INVALID_HANDLE_VALUE) {
  4758. result = &dir->result;
  4759. (void)WideCharToMultiByte(CP_UTF8,
  4760. 0,
  4761. dir->info.cFileName,
  4762. -1,
  4763. result->d_name,
  4764. sizeof(result->d_name),
  4765. NULL,
  4766. NULL);
  4767. if (!FindNextFileW(dir->handle, &dir->info)) {
  4768. (void)FindClose(dir->handle);
  4769. dir->handle = INVALID_HANDLE_VALUE;
  4770. }
  4771. } else {
  4772. SetLastError(ERROR_FILE_NOT_FOUND);
  4773. }
  4774. } else {
  4775. SetLastError(ERROR_BAD_ARGUMENTS);
  4776. }
  4777. return result;
  4778. }
  4779. #if !defined(HAVE_POLL)
  4780. #undef POLLIN
  4781. #undef POLLPRI
  4782. #undef POLLOUT
  4783. #define POLLIN (1) /* Data ready - read will not block. */
  4784. #define POLLPRI (2) /* Priority data ready. */
  4785. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4786. FUNCTION_MAY_BE_UNUSED
  4787. static int
  4788. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4789. {
  4790. struct timeval tv;
  4791. fd_set rset;
  4792. fd_set wset;
  4793. unsigned int i;
  4794. int result;
  4795. SOCKET maxfd = 0;
  4796. memset(&tv, 0, sizeof(tv));
  4797. tv.tv_sec = milliseconds / 1000;
  4798. tv.tv_usec = (milliseconds % 1000) * 1000;
  4799. FD_ZERO(&rset);
  4800. FD_ZERO(&wset);
  4801. for (i = 0; i < n; i++) {
  4802. if (pfd[i].events & POLLIN) {
  4803. FD_SET(pfd[i].fd, &rset);
  4804. }
  4805. if (pfd[i].events & POLLOUT) {
  4806. FD_SET(pfd[i].fd, &wset);
  4807. }
  4808. pfd[i].revents = 0;
  4809. if (pfd[i].fd > maxfd) {
  4810. maxfd = pfd[i].fd;
  4811. }
  4812. }
  4813. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4814. for (i = 0; i < n; i++) {
  4815. if (FD_ISSET(pfd[i].fd, &rset)) {
  4816. pfd[i].revents |= POLLIN;
  4817. }
  4818. if (FD_ISSET(pfd[i].fd, &wset)) {
  4819. pfd[i].revents |= POLLOUT;
  4820. }
  4821. }
  4822. }
  4823. /* We should subtract the time used in select from remaining
  4824. * "milliseconds", in particular if called from mg_poll with a
  4825. * timeout quantum.
  4826. * Unfortunately, the remaining time is not stored in "tv" in all
  4827. * implementations, so the result in "tv" must be considered undefined.
  4828. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4829. return result;
  4830. }
  4831. #endif /* HAVE_POLL */
  4832. #if defined(GCC_DIAGNOSTIC)
  4833. /* Enable unused function warning again */
  4834. #pragma GCC diagnostic pop
  4835. #endif
  4836. static void
  4837. set_close_on_exec(SOCKET sock,
  4838. const struct mg_connection *conn /* may be null */,
  4839. struct mg_context *ctx /* may be null */)
  4840. {
  4841. (void)conn; /* Unused. */
  4842. (void)ctx;
  4843. #if defined(_WIN32_WCE)
  4844. (void)sock;
  4845. #else
  4846. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4847. #endif
  4848. }
  4849. int
  4850. mg_start_thread(mg_thread_func_t f, void *p)
  4851. {
  4852. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4853. /* Compile-time option to control stack size, e.g.
  4854. * -DUSE_STACK_SIZE=16384
  4855. */
  4856. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4857. == ((uintptr_t)(-1L)))
  4858. ? -1
  4859. : 0);
  4860. #else
  4861. return (
  4862. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4863. ? -1
  4864. : 0);
  4865. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4866. }
  4867. /* Start a thread storing the thread context. */
  4868. static int
  4869. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4870. void *p,
  4871. pthread_t *threadidptr)
  4872. {
  4873. uintptr_t uip;
  4874. HANDLE threadhandle;
  4875. int result = -1;
  4876. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4877. threadhandle = (HANDLE)uip;
  4878. if ((uip != 0) && (threadidptr != NULL)) {
  4879. *threadidptr = threadhandle;
  4880. result = 0;
  4881. }
  4882. return result;
  4883. }
  4884. /* Wait for a thread to finish. */
  4885. static int
  4886. mg_join_thread(pthread_t threadid)
  4887. {
  4888. int result;
  4889. DWORD dwevent;
  4890. result = -1;
  4891. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4892. if (dwevent == WAIT_FAILED) {
  4893. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4894. } else {
  4895. if (dwevent == WAIT_OBJECT_0) {
  4896. CloseHandle(threadid);
  4897. result = 0;
  4898. }
  4899. }
  4900. return result;
  4901. }
  4902. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4903. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4904. /* Create substitutes for POSIX functions in Win32. */
  4905. #if defined(GCC_DIAGNOSTIC)
  4906. /* Show no warning in case system functions are not used. */
  4907. #pragma GCC diagnostic push
  4908. #pragma GCC diagnostic ignored "-Wunused-function"
  4909. #endif
  4910. FUNCTION_MAY_BE_UNUSED
  4911. static HANDLE
  4912. dlopen(const char *dll_name, int flags)
  4913. {
  4914. wchar_t wbuf[W_PATH_MAX];
  4915. (void)flags;
  4916. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4917. return LoadLibraryW(wbuf);
  4918. }
  4919. FUNCTION_MAY_BE_UNUSED
  4920. static int
  4921. dlclose(void *handle)
  4922. {
  4923. int result;
  4924. if (FreeLibrary((HMODULE)handle) != 0) {
  4925. result = 0;
  4926. } else {
  4927. result = -1;
  4928. }
  4929. return result;
  4930. }
  4931. #if defined(GCC_DIAGNOSTIC)
  4932. /* Enable unused function warning again */
  4933. #pragma GCC diagnostic pop
  4934. #endif
  4935. #endif
  4936. #if !defined(NO_CGI)
  4937. #define SIGKILL (0)
  4938. static int
  4939. kill(pid_t pid, int sig_num)
  4940. {
  4941. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4942. (void)CloseHandle((HANDLE)pid);
  4943. return 0;
  4944. }
  4945. #if !defined(WNOHANG)
  4946. #define WNOHANG (1)
  4947. #endif
  4948. static pid_t
  4949. waitpid(pid_t pid, int *status, int flags)
  4950. {
  4951. DWORD timeout = INFINITE;
  4952. DWORD waitres;
  4953. (void)status; /* Currently not used by any client here */
  4954. if ((flags | WNOHANG) == WNOHANG) {
  4955. timeout = 0;
  4956. }
  4957. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4958. if (waitres == WAIT_OBJECT_0) {
  4959. return pid;
  4960. }
  4961. if (waitres == WAIT_TIMEOUT) {
  4962. return 0;
  4963. }
  4964. return (pid_t)-1;
  4965. }
  4966. static void
  4967. trim_trailing_whitespaces(char *s)
  4968. {
  4969. char *e = s + strlen(s);
  4970. while ((e > s) && isspace((unsigned char)e[-1])) {
  4971. *(--e) = '\0';
  4972. }
  4973. }
  4974. static pid_t
  4975. spawn_process(struct mg_connection *conn,
  4976. const char *prog,
  4977. char *envblk,
  4978. char *envp[],
  4979. int fdin[2],
  4980. int fdout[2],
  4981. int fderr[2],
  4982. const char *dir)
  4983. {
  4984. HANDLE me;
  4985. char *p, *interp;
  4986. char *interp_arg = 0;
  4987. char full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX],
  4988. buf[PATH_MAX];
  4989. int truncated;
  4990. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4991. STARTUPINFOA si;
  4992. PROCESS_INFORMATION pi = {0};
  4993. (void)envp;
  4994. memset(&si, 0, sizeof(si));
  4995. si.cb = sizeof(si);
  4996. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4997. si.wShowWindow = SW_HIDE;
  4998. me = GetCurrentProcess();
  4999. DuplicateHandle(me,
  5000. (HANDLE)_get_osfhandle(fdin[0]),
  5001. me,
  5002. &si.hStdInput,
  5003. 0,
  5004. TRUE,
  5005. DUPLICATE_SAME_ACCESS);
  5006. DuplicateHandle(me,
  5007. (HANDLE)_get_osfhandle(fdout[1]),
  5008. me,
  5009. &si.hStdOutput,
  5010. 0,
  5011. TRUE,
  5012. DUPLICATE_SAME_ACCESS);
  5013. DuplicateHandle(me,
  5014. (HANDLE)_get_osfhandle(fderr[1]),
  5015. me,
  5016. &si.hStdError,
  5017. 0,
  5018. TRUE,
  5019. DUPLICATE_SAME_ACCESS);
  5020. /* Mark handles that should not be inherited. See
  5021. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5022. */
  5023. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5024. HANDLE_FLAG_INHERIT,
  5025. 0);
  5026. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5027. HANDLE_FLAG_INHERIT,
  5028. 0);
  5029. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5030. HANDLE_FLAG_INHERIT,
  5031. 0);
  5032. /* First check, if there is a CGI interpreter configured for all CGI
  5033. * scripts. */
  5034. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5035. if (interp != NULL) {
  5036. /* If there is a configured interpreter, check for additional arguments
  5037. */
  5038. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5039. } else {
  5040. /* Otherwise, the interpreter must be stated in the first line of the
  5041. * CGI script file, after a #! (shebang) mark. */
  5042. buf[0] = buf[1] = '\0';
  5043. /* Get the full script path */
  5044. mg_snprintf(
  5045. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5046. if (truncated) {
  5047. pi.hProcess = (pid_t)-1;
  5048. goto spawn_cleanup;
  5049. }
  5050. /* Open the script file, to read the first line */
  5051. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5052. #if defined(MG_USE_OPEN_FILE)
  5053. p = (char *)file.access.membuf;
  5054. #else
  5055. p = (char *)NULL;
  5056. #endif
  5057. /* Read the first line of the script into the buffer */
  5058. mg_fgets(buf, sizeof(buf), &file, &p);
  5059. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5060. buf[sizeof(buf) - 1] = '\0';
  5061. }
  5062. if ((buf[0] == '#') && (buf[1] == '!')) {
  5063. trim_trailing_whitespaces(buf + 2);
  5064. } else {
  5065. buf[2] = '\0';
  5066. }
  5067. interp = buf + 2;
  5068. }
  5069. if (interp[0] != '\0') {
  5070. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  5071. interp = full_interp;
  5072. }
  5073. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5074. if (interp[0] != '\0') {
  5075. /* This is an interpreted script file. We must call the interpreter. */
  5076. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5077. mg_snprintf(conn,
  5078. &truncated,
  5079. cmdline,
  5080. sizeof(cmdline),
  5081. "\"%s\" %s \"%s\\%s\"",
  5082. interp,
  5083. interp_arg,
  5084. full_dir,
  5085. prog);
  5086. } else {
  5087. mg_snprintf(conn,
  5088. &truncated,
  5089. cmdline,
  5090. sizeof(cmdline),
  5091. "\"%s\" \"%s\\%s\"",
  5092. interp,
  5093. full_dir,
  5094. prog);
  5095. }
  5096. } else {
  5097. /* This is (probably) a compiled program. We call it directly. */
  5098. mg_snprintf(conn,
  5099. &truncated,
  5100. cmdline,
  5101. sizeof(cmdline),
  5102. "\"%s\\%s\"",
  5103. full_dir,
  5104. prog);
  5105. }
  5106. if (truncated) {
  5107. pi.hProcess = (pid_t)-1;
  5108. goto spawn_cleanup;
  5109. }
  5110. DEBUG_TRACE("Running [%s]", cmdline);
  5111. if (CreateProcessA(NULL,
  5112. cmdline,
  5113. NULL,
  5114. NULL,
  5115. TRUE,
  5116. CREATE_NEW_PROCESS_GROUP,
  5117. envblk,
  5118. NULL,
  5119. &si,
  5120. &pi)
  5121. == 0) {
  5122. mg_cry_internal(
  5123. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5124. pi.hProcess = (pid_t)-1;
  5125. /* goto spawn_cleanup; */
  5126. }
  5127. spawn_cleanup:
  5128. (void)CloseHandle(si.hStdOutput);
  5129. (void)CloseHandle(si.hStdError);
  5130. (void)CloseHandle(si.hStdInput);
  5131. if (pi.hThread != NULL) {
  5132. (void)CloseHandle(pi.hThread);
  5133. }
  5134. return (pid_t)pi.hProcess;
  5135. }
  5136. #endif /* !NO_CGI */
  5137. static int
  5138. set_blocking_mode(SOCKET sock)
  5139. {
  5140. unsigned long non_blocking = 0;
  5141. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5142. }
  5143. static int
  5144. set_non_blocking_mode(SOCKET sock)
  5145. {
  5146. unsigned long non_blocking = 1;
  5147. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5148. }
  5149. #else
  5150. #if !defined(NO_FILESYSTEMS)
  5151. static int
  5152. mg_stat(const struct mg_connection *conn,
  5153. const char *path,
  5154. struct mg_file_stat *filep)
  5155. {
  5156. struct stat st;
  5157. if (!filep) {
  5158. return 0;
  5159. }
  5160. memset(filep, 0, sizeof(*filep));
  5161. if (conn && is_file_in_memory(conn, path)) {
  5162. /* Quick fix (for 1.9.x): */
  5163. /* mg_stat must fill all fields, also for files in memory */
  5164. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5165. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5166. filep->size = tmp_file.stat.size;
  5167. filep->last_modified = time(NULL);
  5168. filep->location = 2;
  5169. /* TODO: remove legacy "files in memory" feature */
  5170. return 1;
  5171. }
  5172. if (0 == stat(path, &st)) {
  5173. filep->size = (uint64_t)(st.st_size);
  5174. filep->last_modified = st.st_mtime;
  5175. filep->is_directory = S_ISDIR(st.st_mode);
  5176. return 1;
  5177. }
  5178. return 0;
  5179. }
  5180. #endif /* NO_FILESYSTEMS */
  5181. static void
  5182. set_close_on_exec(int fd,
  5183. const struct mg_connection *conn /* may be null */,
  5184. struct mg_context *ctx /* may be null */)
  5185. {
  5186. #if defined(__ZEPHYR__)
  5187. (void)fd;
  5188. (void)conn;
  5189. (void)ctx;
  5190. #else
  5191. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5192. if (conn || ctx) {
  5193. struct mg_connection fc;
  5194. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5195. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5196. __func__,
  5197. strerror(ERRNO));
  5198. }
  5199. }
  5200. #endif
  5201. }
  5202. int
  5203. mg_start_thread(mg_thread_func_t func, void *param)
  5204. {
  5205. pthread_t thread_id;
  5206. pthread_attr_t attr;
  5207. int result;
  5208. (void)pthread_attr_init(&attr);
  5209. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5210. #if defined(__ZEPHYR__)
  5211. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5212. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5213. /* Compile-time option to control stack size,
  5214. * e.g. -DUSE_STACK_SIZE=16384 */
  5215. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5216. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5217. result = pthread_create(&thread_id, &attr, func, param);
  5218. pthread_attr_destroy(&attr);
  5219. return result;
  5220. }
  5221. /* Start a thread storing the thread context. */
  5222. static int
  5223. mg_start_thread_with_id(mg_thread_func_t func,
  5224. void *param,
  5225. pthread_t *threadidptr)
  5226. {
  5227. pthread_t thread_id;
  5228. pthread_attr_t attr;
  5229. int result;
  5230. (void)pthread_attr_init(&attr);
  5231. #if defined(__ZEPHYR__)
  5232. pthread_attr_setstack(&attr,
  5233. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5234. ZEPHYR_STACK_SIZE);
  5235. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5236. /* Compile-time option to control stack size,
  5237. * e.g. -DUSE_STACK_SIZE=16384 */
  5238. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5239. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5240. result = pthread_create(&thread_id, &attr, func, param);
  5241. pthread_attr_destroy(&attr);
  5242. if ((result == 0) && (threadidptr != NULL)) {
  5243. *threadidptr = thread_id;
  5244. }
  5245. return result;
  5246. }
  5247. /* Wait for a thread to finish. */
  5248. static int
  5249. mg_join_thread(pthread_t threadid)
  5250. {
  5251. int result;
  5252. result = pthread_join(threadid, NULL);
  5253. return result;
  5254. }
  5255. #if !defined(NO_CGI)
  5256. static pid_t
  5257. spawn_process(struct mg_connection *conn,
  5258. const char *prog,
  5259. char *envblk,
  5260. char *envp[],
  5261. int fdin[2],
  5262. int fdout[2],
  5263. int fderr[2],
  5264. const char *dir)
  5265. {
  5266. pid_t pid;
  5267. const char *interp;
  5268. (void)envblk;
  5269. if ((pid = fork()) == -1) {
  5270. /* Parent */
  5271. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5272. } else if (pid != 0) {
  5273. /* Make sure children close parent-side descriptors.
  5274. * The caller will close the child-side immediately. */
  5275. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5276. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5277. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5278. } else {
  5279. /* Child */
  5280. if (chdir(dir) != 0) {
  5281. mg_cry_internal(
  5282. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5283. } else if (dup2(fdin[0], 0) == -1) {
  5284. mg_cry_internal(conn,
  5285. "%s: dup2(%d, 0): %s",
  5286. __func__,
  5287. fdin[0],
  5288. strerror(ERRNO));
  5289. } else if (dup2(fdout[1], 1) == -1) {
  5290. mg_cry_internal(conn,
  5291. "%s: dup2(%d, 1): %s",
  5292. __func__,
  5293. fdout[1],
  5294. strerror(ERRNO));
  5295. } else if (dup2(fderr[1], 2) == -1) {
  5296. mg_cry_internal(conn,
  5297. "%s: dup2(%d, 2): %s",
  5298. __func__,
  5299. fderr[1],
  5300. strerror(ERRNO));
  5301. } else {
  5302. struct sigaction sa;
  5303. /* Keep stderr and stdout in two different pipes.
  5304. * Stdout will be sent back to the client,
  5305. * stderr should go into a server error log. */
  5306. (void)close(fdin[0]);
  5307. (void)close(fdout[1]);
  5308. (void)close(fderr[1]);
  5309. /* Close write end fdin and read end fdout and fderr */
  5310. (void)close(fdin[1]);
  5311. (void)close(fdout[0]);
  5312. (void)close(fderr[0]);
  5313. /* After exec, all signal handlers are restored to their default
  5314. * values, with one exception of SIGCHLD. According to
  5315. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5316. * will leave unchanged after exec if it was set to be ignored.
  5317. * Restore it to default action. */
  5318. memset(&sa, 0, sizeof(sa));
  5319. sa.sa_handler = SIG_DFL;
  5320. sigaction(SIGCHLD, &sa, NULL);
  5321. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5322. if (interp == NULL) {
  5323. /* no interpreter configured, call the programm directly */
  5324. (void)execle(prog, prog, NULL, envp);
  5325. mg_cry_internal(conn,
  5326. "%s: execle(%s): %s",
  5327. __func__,
  5328. prog,
  5329. strerror(ERRNO));
  5330. } else {
  5331. /* call the configured interpreter */
  5332. const char *interp_args =
  5333. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5334. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5335. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5336. } else {
  5337. (void)execle(interp, interp, prog, NULL, envp);
  5338. }
  5339. mg_cry_internal(conn,
  5340. "%s: execle(%s %s): %s",
  5341. __func__,
  5342. interp,
  5343. prog,
  5344. strerror(ERRNO));
  5345. }
  5346. }
  5347. exit(EXIT_FAILURE);
  5348. }
  5349. return pid;
  5350. }
  5351. #endif /* !NO_CGI */
  5352. static int
  5353. set_non_blocking_mode(SOCKET sock)
  5354. {
  5355. int flags = fcntl(sock, F_GETFL, 0);
  5356. if (flags < 0) {
  5357. return -1;
  5358. }
  5359. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5360. return -1;
  5361. }
  5362. return 0;
  5363. }
  5364. static int
  5365. set_blocking_mode(SOCKET sock)
  5366. {
  5367. int flags = fcntl(sock, F_GETFL, 0);
  5368. if (flags < 0) {
  5369. return -1;
  5370. }
  5371. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5372. return -1;
  5373. }
  5374. return 0;
  5375. }
  5376. #endif /* _WIN32 / else */
  5377. /* End of initial operating system specific define block. */
  5378. /* Get a random number (independent of C rand function) */
  5379. static uint64_t
  5380. get_random(void)
  5381. {
  5382. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5383. static uint64_t lcg = 0; /* Linear congruential generator */
  5384. uint64_t now = mg_get_current_time_ns();
  5385. if (lfsr == 0) {
  5386. /* lfsr will be only 0 if has not been initialized,
  5387. * so this code is called only once. */
  5388. lfsr = mg_get_current_time_ns();
  5389. lcg = mg_get_current_time_ns();
  5390. } else {
  5391. /* Get the next step of both random number generators. */
  5392. lfsr = (lfsr >> 1)
  5393. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5394. << 63);
  5395. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5396. }
  5397. /* Combining two pseudo-random number generators and a high resolution
  5398. * part
  5399. * of the current server time will make it hard (impossible?) to guess
  5400. * the
  5401. * next number. */
  5402. return (lfsr ^ lcg ^ now);
  5403. }
  5404. static int
  5405. mg_poll(struct mg_pollfd *pfd,
  5406. unsigned int n,
  5407. int milliseconds,
  5408. stop_flag_t *stop_flag)
  5409. {
  5410. /* Call poll, but only for a maximum time of a few seconds.
  5411. * This will allow to stop the server after some seconds, instead
  5412. * of having to wait for a long socket timeout. */
  5413. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5414. do {
  5415. int result;
  5416. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5417. /* Shut down signal */
  5418. return -2;
  5419. }
  5420. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5421. ms_now = milliseconds;
  5422. }
  5423. result = poll(pfd, n, ms_now);
  5424. if (result != 0) {
  5425. /* Poll returned either success (1) or error (-1).
  5426. * Forward both to the caller. */
  5427. return result;
  5428. }
  5429. /* Poll returned timeout (0). */
  5430. if (milliseconds > 0) {
  5431. milliseconds -= ms_now;
  5432. }
  5433. } while (milliseconds != 0);
  5434. /* timeout: return 0 */
  5435. return 0;
  5436. }
  5437. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5438. * descriptor.
  5439. * Return value:
  5440. * >=0 .. number of bytes successfully written
  5441. * -1 .. timeout
  5442. * -2 .. error
  5443. */
  5444. static int
  5445. push_inner(struct mg_context *ctx,
  5446. FILE *fp,
  5447. SOCKET sock,
  5448. SSL *ssl,
  5449. const char *buf,
  5450. int len,
  5451. double timeout)
  5452. {
  5453. uint64_t start = 0, now = 0, timeout_ns = 0;
  5454. int n, err;
  5455. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5456. #if defined(_WIN32)
  5457. typedef int len_t;
  5458. #else
  5459. typedef size_t len_t;
  5460. #endif
  5461. if (timeout > 0) {
  5462. now = mg_get_current_time_ns();
  5463. start = now;
  5464. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5465. }
  5466. if (ctx == NULL) {
  5467. return -2;
  5468. }
  5469. #if defined(NO_SSL)
  5470. if (ssl) {
  5471. return -2;
  5472. }
  5473. #endif
  5474. /* Try to read until it succeeds, fails, times out, or the server
  5475. * shuts down. */
  5476. for (;;) {
  5477. #if !defined(NO_SSL)
  5478. if (ssl != NULL) {
  5479. ERR_clear_error();
  5480. n = SSL_write(ssl, buf, len);
  5481. if (n <= 0) {
  5482. err = SSL_get_error(ssl, n);
  5483. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5484. err = ERRNO;
  5485. } else if ((err == SSL_ERROR_WANT_READ)
  5486. || (err == SSL_ERROR_WANT_WRITE)) {
  5487. n = 0;
  5488. } else {
  5489. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5490. ERR_clear_error();
  5491. return -2;
  5492. }
  5493. ERR_clear_error();
  5494. } else {
  5495. err = 0;
  5496. }
  5497. } else
  5498. #endif
  5499. if (fp != NULL) {
  5500. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5501. if (ferror(fp)) {
  5502. n = -1;
  5503. err = ERRNO;
  5504. } else {
  5505. err = 0;
  5506. }
  5507. } else {
  5508. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5509. err = (n < 0) ? ERRNO : 0;
  5510. #if defined(_WIN32)
  5511. if (err == WSAEWOULDBLOCK) {
  5512. err = 0;
  5513. n = 0;
  5514. }
  5515. #else
  5516. if (err == EWOULDBLOCK) {
  5517. err = 0;
  5518. n = 0;
  5519. }
  5520. #endif
  5521. if (n < 0) {
  5522. /* shutdown of the socket at client side */
  5523. return -2;
  5524. }
  5525. }
  5526. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5527. return -2;
  5528. }
  5529. if ((n > 0) || ((n == 0) && (len == 0))) {
  5530. /* some data has been read, or no data was requested */
  5531. return n;
  5532. }
  5533. if (n < 0) {
  5534. /* socket error - check errno */
  5535. DEBUG_TRACE("send() failed, error %d", err);
  5536. /* TODO (mid): error handling depending on the error code.
  5537. * These codes are different between Windows and Linux.
  5538. * Currently there is no problem with failing send calls,
  5539. * if there is a reproducible situation, it should be
  5540. * investigated in detail.
  5541. */
  5542. return -2;
  5543. }
  5544. /* Only in case n=0 (timeout), repeat calling the write function */
  5545. /* If send failed, wait before retry */
  5546. if (fp != NULL) {
  5547. /* For files, just wait a fixed time.
  5548. * Maybe it helps, maybe not. */
  5549. mg_sleep(5);
  5550. } else {
  5551. /* For sockets, wait for the socket using poll */
  5552. struct mg_pollfd pfd[1];
  5553. int pollres;
  5554. pfd[0].fd = sock;
  5555. pfd[0].events = POLLOUT;
  5556. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5557. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5558. return -2;
  5559. }
  5560. if (pollres > 0) {
  5561. continue;
  5562. }
  5563. }
  5564. if (timeout > 0) {
  5565. now = mg_get_current_time_ns();
  5566. if ((now - start) > timeout_ns) {
  5567. /* Timeout */
  5568. break;
  5569. }
  5570. }
  5571. }
  5572. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5573. used */
  5574. return -1;
  5575. }
  5576. static int
  5577. push_all(struct mg_context *ctx,
  5578. FILE *fp,
  5579. SOCKET sock,
  5580. SSL *ssl,
  5581. const char *buf,
  5582. int len)
  5583. {
  5584. double timeout = -1.0;
  5585. int n, nwritten = 0;
  5586. if (ctx == NULL) {
  5587. return -1;
  5588. }
  5589. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5590. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5591. }
  5592. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5593. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5594. if (n < 0) {
  5595. if (nwritten == 0) {
  5596. nwritten = -1; /* Propagate the error */
  5597. }
  5598. break;
  5599. } else if (n == 0) {
  5600. break; /* No more data to write */
  5601. } else {
  5602. nwritten += n;
  5603. len -= n;
  5604. }
  5605. }
  5606. return nwritten;
  5607. }
  5608. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5609. * Return value:
  5610. * >=0 .. number of bytes successfully read
  5611. * -1 .. timeout
  5612. * -2 .. error
  5613. */
  5614. static int
  5615. pull_inner(FILE *fp,
  5616. struct mg_connection *conn,
  5617. char *buf,
  5618. int len,
  5619. double timeout)
  5620. {
  5621. int nread, err = 0;
  5622. #if defined(_WIN32)
  5623. typedef int len_t;
  5624. #else
  5625. typedef size_t len_t;
  5626. #endif
  5627. /* We need an additional wait loop around this, because in some cases
  5628. * with TLSwe may get data from the socket but not from SSL_read.
  5629. * In this case we need to repeat at least once.
  5630. */
  5631. if (fp != NULL) {
  5632. #if !defined(_WIN32_WCE)
  5633. /* Use read() instead of fread(), because if we're reading from the
  5634. * CGI pipe, fread() may block until IO buffer is filled up. We
  5635. * cannot afford to block and must pass all read bytes immediately
  5636. * to the client. */
  5637. nread = (int)read(fileno(fp), buf, (size_t)len);
  5638. #else
  5639. /* WinCE does not support CGI pipes */
  5640. nread = (int)fread(buf, 1, (size_t)len, fp);
  5641. #endif
  5642. err = (nread < 0) ? ERRNO : 0;
  5643. if ((nread == 0) && (len > 0)) {
  5644. /* Should get data, but got EOL */
  5645. return -2;
  5646. }
  5647. #if !defined(NO_SSL)
  5648. } else if (conn->ssl != NULL) {
  5649. int ssl_pending;
  5650. struct mg_pollfd pfd[1];
  5651. int pollres;
  5652. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5653. /* We already know there is no more data buffered in conn->buf
  5654. * but there is more available in the SSL layer. So don't poll
  5655. * conn->client.sock yet. */
  5656. if (ssl_pending > len) {
  5657. ssl_pending = len;
  5658. }
  5659. pollres = 1;
  5660. } else {
  5661. pfd[0].fd = conn->client.sock;
  5662. pfd[0].events = POLLIN;
  5663. pollres = mg_poll(pfd,
  5664. 1,
  5665. (int)(timeout * 1000.0),
  5666. &(conn->phys_ctx->stop_flag));
  5667. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5668. return -2;
  5669. }
  5670. }
  5671. if (pollres > 0) {
  5672. ERR_clear_error();
  5673. nread =
  5674. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5675. if (nread <= 0) {
  5676. err = SSL_get_error(conn->ssl, nread);
  5677. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5678. err = ERRNO;
  5679. } else if ((err == SSL_ERROR_WANT_READ)
  5680. || (err == SSL_ERROR_WANT_WRITE)) {
  5681. nread = 0;
  5682. } else {
  5683. /* All errors should return -2 */
  5684. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5685. ERR_clear_error();
  5686. return -2;
  5687. }
  5688. ERR_clear_error();
  5689. } else {
  5690. err = 0;
  5691. }
  5692. } else if (pollres < 0) {
  5693. /* Error */
  5694. return -2;
  5695. } else {
  5696. /* pollres = 0 means timeout */
  5697. nread = 0;
  5698. }
  5699. #endif
  5700. } else {
  5701. struct mg_pollfd pfd[1];
  5702. int pollres;
  5703. pfd[0].fd = conn->client.sock;
  5704. pfd[0].events = POLLIN;
  5705. pollres = mg_poll(pfd,
  5706. 1,
  5707. (int)(timeout * 1000.0),
  5708. &(conn->phys_ctx->stop_flag));
  5709. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5710. return -2;
  5711. }
  5712. if (pollres > 0) {
  5713. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5714. err = (nread < 0) ? ERRNO : 0;
  5715. if (nread <= 0) {
  5716. /* shutdown of the socket at client side */
  5717. return -2;
  5718. }
  5719. } else if (pollres < 0) {
  5720. /* error callint poll */
  5721. return -2;
  5722. } else {
  5723. /* pollres = 0 means timeout */
  5724. nread = 0;
  5725. }
  5726. }
  5727. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5728. return -2;
  5729. }
  5730. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5731. /* some data has been read, or no data was requested */
  5732. return nread;
  5733. }
  5734. if (nread < 0) {
  5735. /* socket error - check errno */
  5736. #if defined(_WIN32)
  5737. if (err == WSAEWOULDBLOCK) {
  5738. /* TODO (low): check if this is still required */
  5739. /* standard case if called from close_socket_gracefully */
  5740. return -2;
  5741. } else if (err == WSAETIMEDOUT) {
  5742. /* TODO (low): check if this is still required */
  5743. /* timeout is handled by the while loop */
  5744. return 0;
  5745. } else if (err == WSAECONNABORTED) {
  5746. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5747. return -2;
  5748. } else {
  5749. DEBUG_TRACE("recv() failed, error %d", err);
  5750. return -2;
  5751. }
  5752. #else
  5753. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5754. * if the timeout is reached and if the socket was set to non-
  5755. * blocking in close_socket_gracefully, so we can not distinguish
  5756. * here. We have to wait for the timeout in both cases for now.
  5757. */
  5758. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5759. /* TODO (low): check if this is still required */
  5760. /* EAGAIN/EWOULDBLOCK:
  5761. * standard case if called from close_socket_gracefully
  5762. * => should return -1 */
  5763. /* or timeout occurred
  5764. * => the code must stay in the while loop */
  5765. /* EINTR can be generated on a socket with a timeout set even
  5766. * when SA_RESTART is effective for all relevant signals
  5767. * (see signal(7)).
  5768. * => stay in the while loop */
  5769. } else {
  5770. DEBUG_TRACE("recv() failed, error %d", err);
  5771. return -2;
  5772. }
  5773. #endif
  5774. }
  5775. /* Timeout occurred, but no data available. */
  5776. return -1;
  5777. }
  5778. static int
  5779. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5780. {
  5781. int n, nread = 0;
  5782. double timeout = -1.0;
  5783. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5784. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5785. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5786. }
  5787. if (timeout >= 0.0) {
  5788. start_time = mg_get_current_time_ns();
  5789. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5790. }
  5791. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5792. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5793. if (n == -2) {
  5794. if (nread == 0) {
  5795. nread = -1; /* Propagate the error */
  5796. }
  5797. break;
  5798. } else if (n == -1) {
  5799. /* timeout */
  5800. if (timeout >= 0.0) {
  5801. now = mg_get_current_time_ns();
  5802. if ((now - start_time) <= timeout_ns) {
  5803. continue;
  5804. }
  5805. }
  5806. break;
  5807. } else if (n == 0) {
  5808. break; /* No more data to read */
  5809. } else {
  5810. nread += n;
  5811. len -= n;
  5812. }
  5813. }
  5814. return nread;
  5815. }
  5816. static void
  5817. discard_unread_request_data(struct mg_connection *conn)
  5818. {
  5819. char buf[MG_BUF_LEN];
  5820. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5821. ;
  5822. }
  5823. static int
  5824. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5825. {
  5826. int64_t content_len, n, buffered_len, nread;
  5827. int64_t len64 =
  5828. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5829. * int, we may not read more
  5830. * bytes */
  5831. const char *body;
  5832. if (conn == NULL) {
  5833. return 0;
  5834. }
  5835. /* If Content-Length is not set for a response with body data,
  5836. * we do not know in advance how much data should be read. */
  5837. content_len = conn->content_len;
  5838. if (content_len < 0) {
  5839. /* The body data is completed when the connection is closed. */
  5840. content_len = INT64_MAX;
  5841. }
  5842. nread = 0;
  5843. if (conn->consumed_content < content_len) {
  5844. /* Adjust number of bytes to read. */
  5845. int64_t left_to_read = content_len - conn->consumed_content;
  5846. if (left_to_read < len64) {
  5847. /* Do not read more than the total content length of the
  5848. * request.
  5849. */
  5850. len64 = left_to_read;
  5851. }
  5852. /* Return buffered data */
  5853. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5854. - conn->consumed_content;
  5855. if (buffered_len > 0) {
  5856. if (len64 < buffered_len) {
  5857. buffered_len = len64;
  5858. }
  5859. body = conn->buf + conn->request_len + conn->consumed_content;
  5860. memcpy(buf, body, (size_t)buffered_len);
  5861. len64 -= buffered_len;
  5862. conn->consumed_content += buffered_len;
  5863. nread += buffered_len;
  5864. buf = (char *)buf + buffered_len;
  5865. }
  5866. /* We have returned all buffered data. Read new data from the remote
  5867. * socket.
  5868. */
  5869. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5870. conn->consumed_content += n;
  5871. nread += n;
  5872. } else {
  5873. nread = ((nread > 0) ? nread : n);
  5874. }
  5875. }
  5876. return (int)nread;
  5877. }
  5878. int
  5879. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5880. {
  5881. if (len > INT_MAX) {
  5882. len = INT_MAX;
  5883. }
  5884. if (conn == NULL) {
  5885. return 0;
  5886. }
  5887. if (conn->is_chunked) {
  5888. size_t all_read = 0;
  5889. while (len > 0) {
  5890. if (conn->is_chunked >= 3) {
  5891. /* No more data left to read */
  5892. return 0;
  5893. }
  5894. if (conn->is_chunked != 1) {
  5895. /* Has error */
  5896. return -1;
  5897. }
  5898. if (conn->consumed_content != conn->content_len) {
  5899. /* copy from the current chunk */
  5900. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5901. if (read_ret < 1) {
  5902. /* read error */
  5903. conn->is_chunked = 2;
  5904. return -1;
  5905. }
  5906. all_read += (size_t)read_ret;
  5907. len -= (size_t)read_ret;
  5908. if (conn->consumed_content == conn->content_len) {
  5909. /* Add data bytes in the current chunk have been read,
  5910. * so we are expecting \r\n now. */
  5911. char x[2];
  5912. conn->content_len += 2;
  5913. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5914. || (x[1] != '\n')) {
  5915. /* Protocol violation */
  5916. conn->is_chunked = 2;
  5917. return -1;
  5918. }
  5919. }
  5920. } else {
  5921. /* fetch a new chunk */
  5922. size_t i;
  5923. char lenbuf[64];
  5924. char *end = NULL;
  5925. unsigned long chunkSize = 0;
  5926. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5927. conn->content_len++;
  5928. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5929. lenbuf[i] = 0;
  5930. }
  5931. if ((i > 0) && (lenbuf[i] == '\r')
  5932. && (lenbuf[i - 1] != '\r')) {
  5933. continue;
  5934. }
  5935. if ((i > 1) && (lenbuf[i] == '\n')
  5936. && (lenbuf[i - 1] == '\r')) {
  5937. lenbuf[i + 1] = 0;
  5938. chunkSize = strtoul(lenbuf, &end, 16);
  5939. if (chunkSize == 0) {
  5940. /* regular end of content */
  5941. conn->is_chunked = 3;
  5942. }
  5943. break;
  5944. }
  5945. if (!isxdigit((unsigned char)lenbuf[i])) {
  5946. /* illegal character for chunk length */
  5947. conn->is_chunked = 2;
  5948. return -1;
  5949. }
  5950. }
  5951. if ((end == NULL) || (*end != '\r')) {
  5952. /* chunksize not set correctly */
  5953. conn->is_chunked = 2;
  5954. return -1;
  5955. }
  5956. if (chunkSize == 0) {
  5957. /* try discarding trailer for keep-alive */
  5958. conn->content_len += 2;
  5959. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5960. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5961. conn->is_chunked = 4;
  5962. }
  5963. break;
  5964. }
  5965. /* append a new chunk */
  5966. conn->content_len += (int64_t)chunkSize;
  5967. }
  5968. }
  5969. return (int)all_read;
  5970. }
  5971. return mg_read_inner(conn, buf, len);
  5972. }
  5973. int
  5974. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5975. {
  5976. time_t now;
  5977. int n, total, allowed;
  5978. if (conn == NULL) {
  5979. return 0;
  5980. }
  5981. if (len > INT_MAX) {
  5982. return -1;
  5983. }
  5984. if (conn->throttle > 0) {
  5985. if ((now = time(NULL)) != conn->last_throttle_time) {
  5986. conn->last_throttle_time = now;
  5987. conn->last_throttle_bytes = 0;
  5988. }
  5989. allowed = conn->throttle - conn->last_throttle_bytes;
  5990. if (allowed > (int)len) {
  5991. allowed = (int)len;
  5992. }
  5993. if ((total = push_all(conn->phys_ctx,
  5994. NULL,
  5995. conn->client.sock,
  5996. conn->ssl,
  5997. (const char *)buf,
  5998. allowed))
  5999. == allowed) {
  6000. buf = (const char *)buf + total;
  6001. conn->last_throttle_bytes += total;
  6002. while ((total < (int)len)
  6003. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6004. allowed = (conn->throttle > ((int)len - total))
  6005. ? (int)len - total
  6006. : conn->throttle;
  6007. if ((n = push_all(conn->phys_ctx,
  6008. NULL,
  6009. conn->client.sock,
  6010. conn->ssl,
  6011. (const char *)buf,
  6012. allowed))
  6013. != allowed) {
  6014. break;
  6015. }
  6016. sleep(1);
  6017. conn->last_throttle_bytes = allowed;
  6018. conn->last_throttle_time = time(NULL);
  6019. buf = (const char *)buf + n;
  6020. total += n;
  6021. }
  6022. }
  6023. } else {
  6024. total = push_all(conn->phys_ctx,
  6025. NULL,
  6026. conn->client.sock,
  6027. conn->ssl,
  6028. (const char *)buf,
  6029. (int)len);
  6030. }
  6031. if (total > 0) {
  6032. conn->num_bytes_sent += total;
  6033. }
  6034. return total;
  6035. }
  6036. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6037. int
  6038. mg_send_chunk(struct mg_connection *conn,
  6039. const char *chunk,
  6040. unsigned int chunk_len)
  6041. {
  6042. char lenbuf[16];
  6043. size_t lenbuf_len;
  6044. int ret;
  6045. int t;
  6046. /* First store the length information in a text buffer. */
  6047. sprintf(lenbuf, "%x\r\n", chunk_len);
  6048. lenbuf_len = strlen(lenbuf);
  6049. /* Then send length information, chunk and terminating \r\n. */
  6050. ret = mg_write(conn, lenbuf, lenbuf_len);
  6051. if (ret != (int)lenbuf_len) {
  6052. return -1;
  6053. }
  6054. t = ret;
  6055. ret = mg_write(conn, chunk, chunk_len);
  6056. if (ret != (int)chunk_len) {
  6057. return -1;
  6058. }
  6059. t += ret;
  6060. ret = mg_write(conn, "\r\n", 2);
  6061. if (ret != 2) {
  6062. return -1;
  6063. }
  6064. t += ret;
  6065. return t;
  6066. }
  6067. #if defined(GCC_DIAGNOSTIC)
  6068. /* This block forwards format strings to printf implementations,
  6069. * so we need to disable the format-nonliteral warning. */
  6070. #pragma GCC diagnostic push
  6071. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6072. #endif
  6073. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6074. static int
  6075. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6076. {
  6077. va_list ap_copy;
  6078. size_t size = MG_BUF_LEN / 4;
  6079. int len = -1;
  6080. *buf = NULL;
  6081. while (len < 0) {
  6082. if (*buf) {
  6083. mg_free(*buf);
  6084. }
  6085. size *= 4;
  6086. *buf = (char *)mg_malloc(size);
  6087. if (!*buf) {
  6088. break;
  6089. }
  6090. va_copy(ap_copy, ap);
  6091. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6092. va_end(ap_copy);
  6093. (*buf)[size - 1] = 0;
  6094. }
  6095. return len;
  6096. }
  6097. /* Print message to buffer. If buffer is large enough to hold the message,
  6098. * return buffer. If buffer is to small, allocate large enough buffer on
  6099. * heap,
  6100. * and return allocated buffer. */
  6101. static int
  6102. alloc_vprintf(char **out_buf,
  6103. char *prealloc_buf,
  6104. size_t prealloc_size,
  6105. const char *fmt,
  6106. va_list ap)
  6107. {
  6108. va_list ap_copy;
  6109. int len;
  6110. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6111. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6112. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6113. * Therefore, we make two passes: on first pass, get required message
  6114. * length.
  6115. * On second pass, actually print the message. */
  6116. va_copy(ap_copy, ap);
  6117. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6118. va_end(ap_copy);
  6119. if (len < 0) {
  6120. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6121. * Switch to alternative code path that uses incremental
  6122. * allocations.
  6123. */
  6124. va_copy(ap_copy, ap);
  6125. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6126. va_end(ap_copy);
  6127. } else if ((size_t)(len) >= prealloc_size) {
  6128. /* The pre-allocated buffer not large enough. */
  6129. /* Allocate a new buffer. */
  6130. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6131. if (!*out_buf) {
  6132. /* Allocation failed. Return -1 as "out of memory" error. */
  6133. return -1;
  6134. }
  6135. /* Buffer allocation successful. Store the string there. */
  6136. va_copy(ap_copy, ap);
  6137. IGNORE_UNUSED_RESULT(
  6138. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6139. va_end(ap_copy);
  6140. } else {
  6141. /* The pre-allocated buffer is large enough.
  6142. * Use it to store the string and return the address. */
  6143. va_copy(ap_copy, ap);
  6144. IGNORE_UNUSED_RESULT(
  6145. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6146. va_end(ap_copy);
  6147. *out_buf = prealloc_buf;
  6148. }
  6149. return len;
  6150. }
  6151. #if defined(GCC_DIAGNOSTIC)
  6152. /* Enable format-nonliteral warning again. */
  6153. #pragma GCC diagnostic pop
  6154. #endif
  6155. static int
  6156. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6157. {
  6158. char mem[MG_BUF_LEN];
  6159. char *buf = NULL;
  6160. int len;
  6161. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6162. len = mg_write(conn, buf, (size_t)len);
  6163. }
  6164. if (buf != mem) {
  6165. mg_free(buf);
  6166. }
  6167. return len;
  6168. }
  6169. int
  6170. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6171. {
  6172. va_list ap;
  6173. int result;
  6174. va_start(ap, fmt);
  6175. result = mg_vprintf(conn, fmt, ap);
  6176. va_end(ap);
  6177. return result;
  6178. }
  6179. int
  6180. mg_url_decode(const char *src,
  6181. int src_len,
  6182. char *dst,
  6183. int dst_len,
  6184. int is_form_url_encoded)
  6185. {
  6186. int i, j, a, b;
  6187. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6188. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6189. if ((i < src_len - 2) && (src[i] == '%')
  6190. && isxdigit((unsigned char)src[i + 1])
  6191. && isxdigit((unsigned char)src[i + 2])) {
  6192. a = tolower((unsigned char)src[i + 1]);
  6193. b = tolower((unsigned char)src[i + 2]);
  6194. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6195. i += 2;
  6196. } else if (is_form_url_encoded && (src[i] == '+')) {
  6197. dst[j] = ' ';
  6198. } else {
  6199. dst[j] = src[i];
  6200. }
  6201. }
  6202. dst[j] = '\0'; /* Null-terminate the destination */
  6203. return (i >= src_len) ? j : -1;
  6204. }
  6205. /* form url decoding of an entire string */
  6206. static void
  6207. url_decode_in_place(char *buf)
  6208. {
  6209. int len = (int)strlen(buf);
  6210. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6211. }
  6212. int
  6213. mg_get_var(const char *data,
  6214. size_t data_len,
  6215. const char *name,
  6216. char *dst,
  6217. size_t dst_len)
  6218. {
  6219. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6220. }
  6221. int
  6222. mg_get_var2(const char *data,
  6223. size_t data_len,
  6224. const char *name,
  6225. char *dst,
  6226. size_t dst_len,
  6227. size_t occurrence)
  6228. {
  6229. const char *p, *e, *s;
  6230. size_t name_len;
  6231. int len;
  6232. if ((dst == NULL) || (dst_len == 0)) {
  6233. len = -2;
  6234. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6235. len = -1;
  6236. dst[0] = '\0';
  6237. } else {
  6238. name_len = strlen(name);
  6239. e = data + data_len;
  6240. len = -1;
  6241. dst[0] = '\0';
  6242. /* data is "var1=val1&var2=val2...". Find variable first */
  6243. for (p = data; p + name_len < e; p++) {
  6244. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6245. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6246. /* Point p to variable value */
  6247. p += name_len + 1;
  6248. /* Point s to the end of the value */
  6249. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6250. if (s == NULL) {
  6251. s = e;
  6252. }
  6253. DEBUG_ASSERT(s >= p);
  6254. if (s < p) {
  6255. return -3;
  6256. }
  6257. /* Decode variable into destination buffer */
  6258. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6259. /* Redirect error code from -1 to -2 (destination buffer too
  6260. * small). */
  6261. if (len == -1) {
  6262. len = -2;
  6263. }
  6264. break;
  6265. }
  6266. }
  6267. }
  6268. return len;
  6269. }
  6270. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6271. int
  6272. mg_split_form_urlencoded(char *data,
  6273. struct mg_header *form_fields,
  6274. unsigned num_form_fields)
  6275. {
  6276. char *b;
  6277. int i;
  6278. int num = 0;
  6279. if (data == NULL) {
  6280. /* parameter error */
  6281. return -1;
  6282. }
  6283. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6284. /* determine the number of expected fields */
  6285. if (data[0] == 0) {
  6286. return 0;
  6287. }
  6288. /* count number of & to return the number of key-value-pairs */
  6289. num = 1;
  6290. while (*data) {
  6291. if (*data == '&') {
  6292. num++;
  6293. }
  6294. data++;
  6295. }
  6296. return num;
  6297. }
  6298. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6299. /* parameter error */
  6300. return -1;
  6301. }
  6302. for (i = 0; i < (int)num_form_fields; i++) {
  6303. /* extract key-value pairs from input data */
  6304. while ((*data == ' ') || (*data == '\t')) {
  6305. /* skip initial spaces */
  6306. data++;
  6307. }
  6308. if (*data == 0) {
  6309. /* end of string reached */
  6310. break;
  6311. }
  6312. form_fields[num].name = data;
  6313. /* find & or = */
  6314. b = data;
  6315. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6316. b++;
  6317. }
  6318. if (*b == 0) {
  6319. /* last key without value */
  6320. form_fields[num].value = NULL;
  6321. } else if (*b == '&') {
  6322. /* mid key without value */
  6323. form_fields[num].value = NULL;
  6324. } else {
  6325. /* terminate string */
  6326. *b = 0;
  6327. /* value starts after '=' */
  6328. data = b + 1;
  6329. form_fields[num].value = data;
  6330. }
  6331. /* new field is stored */
  6332. num++;
  6333. /* find a next key */
  6334. b = strchr(data, '&');
  6335. if (b == 0) {
  6336. /* no more data */
  6337. break;
  6338. } else {
  6339. /* terminate value of last field at '&' */
  6340. *b = 0;
  6341. /* next key-value-pairs starts after '&' */
  6342. data = b + 1;
  6343. }
  6344. }
  6345. /* Decode all values */
  6346. for (i = 0; i < num; i++) {
  6347. if (form_fields[i].name) {
  6348. url_decode_in_place((char *)form_fields[i].name);
  6349. }
  6350. if (form_fields[i].value) {
  6351. url_decode_in_place((char *)form_fields[i].value);
  6352. }
  6353. }
  6354. /* return number of fields found */
  6355. return num;
  6356. }
  6357. /* HCP24: some changes to compare hole var_name */
  6358. int
  6359. mg_get_cookie(const char *cookie_header,
  6360. const char *var_name,
  6361. char *dst,
  6362. size_t dst_size)
  6363. {
  6364. const char *s, *p, *end;
  6365. int name_len, len = -1;
  6366. if ((dst == NULL) || (dst_size == 0)) {
  6367. return -2;
  6368. }
  6369. dst[0] = '\0';
  6370. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6371. return -1;
  6372. }
  6373. name_len = (int)strlen(var_name);
  6374. end = s + strlen(s);
  6375. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6376. if (s[name_len] == '=') {
  6377. /* HCP24: now check is it a substring or a full cookie name */
  6378. if ((s == cookie_header) || (s[-1] == ' ')) {
  6379. s += name_len + 1;
  6380. if ((p = strchr(s, ' ')) == NULL) {
  6381. p = end;
  6382. }
  6383. if (p[-1] == ';') {
  6384. p--;
  6385. }
  6386. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6387. s++;
  6388. p--;
  6389. }
  6390. if ((size_t)(p - s) < dst_size) {
  6391. len = (int)(p - s);
  6392. mg_strlcpy(dst, s, (size_t)len + 1);
  6393. } else {
  6394. len = -3;
  6395. }
  6396. break;
  6397. }
  6398. }
  6399. }
  6400. return len;
  6401. }
  6402. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6403. static void
  6404. base64_encode(const unsigned char *src, int src_len, char *dst)
  6405. {
  6406. static const char *b64 =
  6407. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6408. int i, j, a, b, c;
  6409. for (i = j = 0; i < src_len; i += 3) {
  6410. a = src[i];
  6411. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6412. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6413. dst[j++] = b64[a >> 2];
  6414. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6415. if (i + 1 < src_len) {
  6416. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6417. }
  6418. if (i + 2 < src_len) {
  6419. dst[j++] = b64[c & 63];
  6420. }
  6421. }
  6422. while (j % 4 != 0) {
  6423. dst[j++] = '=';
  6424. }
  6425. dst[j++] = '\0';
  6426. }
  6427. #endif
  6428. #if defined(USE_LUA)
  6429. static unsigned char
  6430. b64reverse(char letter)
  6431. {
  6432. if ((letter >= 'A') && (letter <= 'Z')) {
  6433. return letter - 'A';
  6434. }
  6435. if ((letter >= 'a') && (letter <= 'z')) {
  6436. return letter - 'a' + 26;
  6437. }
  6438. if ((letter >= '0') && (letter <= '9')) {
  6439. return letter - '0' + 52;
  6440. }
  6441. if (letter == '+') {
  6442. return 62;
  6443. }
  6444. if (letter == '/') {
  6445. return 63;
  6446. }
  6447. if (letter == '=') {
  6448. return 255; /* normal end */
  6449. }
  6450. return 254; /* error */
  6451. }
  6452. static int
  6453. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6454. {
  6455. int i;
  6456. unsigned char a, b, c, d;
  6457. *dst_len = 0;
  6458. for (i = 0; i < src_len; i += 4) {
  6459. a = b64reverse(src[i]);
  6460. if (a >= 254) {
  6461. return i;
  6462. }
  6463. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6464. if (b >= 254) {
  6465. return i + 1;
  6466. }
  6467. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6468. if (c == 254) {
  6469. return i + 2;
  6470. }
  6471. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6472. if (d == 254) {
  6473. return i + 3;
  6474. }
  6475. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6476. if (c != 255) {
  6477. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6478. if (d != 255) {
  6479. dst[(*dst_len)++] = (c << 6) + d;
  6480. }
  6481. }
  6482. }
  6483. return -1;
  6484. }
  6485. #endif
  6486. static int
  6487. is_put_or_delete_method(const struct mg_connection *conn)
  6488. {
  6489. if (conn) {
  6490. const char *s = conn->request_info.request_method;
  6491. return (s != NULL)
  6492. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6493. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6494. }
  6495. return 0;
  6496. }
  6497. #if !defined(NO_FILES)
  6498. static int
  6499. extention_matches_script(
  6500. struct mg_connection *conn, /* in: request (must be valid) */
  6501. const char *filename /* in: filename (must be valid) */
  6502. )
  6503. {
  6504. #if !defined(NO_CGI)
  6505. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6506. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6507. filename)
  6508. > 0) {
  6509. return 1;
  6510. }
  6511. #endif
  6512. #if defined(USE_LUA)
  6513. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6514. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6515. filename)
  6516. > 0) {
  6517. return 1;
  6518. }
  6519. #endif
  6520. #if defined(USE_DUKTAPE)
  6521. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6522. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6523. filename)
  6524. > 0) {
  6525. return 1;
  6526. }
  6527. #endif
  6528. /* filename and conn could be unused, if all preocessor conditions
  6529. * are false (no script language supported). */
  6530. (void)filename;
  6531. (void)conn;
  6532. return 0;
  6533. }
  6534. /* For given directory path, substitute it to valid index file.
  6535. * Return 1 if index file has been found, 0 if not found.
  6536. * If the file is found, it's stats is returned in stp. */
  6537. static int
  6538. substitute_index_file(struct mg_connection *conn,
  6539. char *path,
  6540. size_t path_len,
  6541. struct mg_file_stat *filestat)
  6542. {
  6543. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6544. struct vec filename_vec;
  6545. size_t n = strlen(path);
  6546. int found = 0;
  6547. /* The 'path' given to us points to the directory. Remove all trailing
  6548. * directory separator characters from the end of the path, and
  6549. * then append single directory separator character. */
  6550. while ((n > 0) && (path[n - 1] == '/')) {
  6551. n--;
  6552. }
  6553. path[n] = '/';
  6554. /* Traverse index files list. For each entry, append it to the given
  6555. * path and see if the file exists. If it exists, break the loop */
  6556. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6557. /* Ignore too long entries that may overflow path buffer */
  6558. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6559. continue;
  6560. }
  6561. /* Prepare full path to the index file */
  6562. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6563. /* Does it exist? */
  6564. if (mg_stat(conn, path, filestat)) {
  6565. /* Yes it does, break the loop */
  6566. found = 1;
  6567. break;
  6568. }
  6569. }
  6570. /* If no index file exists, restore directory path */
  6571. if (!found) {
  6572. path[n] = '\0';
  6573. }
  6574. return found;
  6575. }
  6576. #endif
  6577. static void
  6578. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6579. char *filename, /* out: filename */
  6580. size_t filename_buf_len, /* in: size of filename buffer */
  6581. struct mg_file_stat *filestat, /* out: file status structure */
  6582. int *is_found, /* out: file found (directly) */
  6583. int *is_script_resource, /* out: handled by a script? */
  6584. int *is_websocket_request, /* out: websocket connetion? */
  6585. int *is_put_or_delete_request /* out: put/delete a file? */
  6586. )
  6587. {
  6588. char const *accept_encoding;
  6589. #if !defined(NO_FILES)
  6590. const char *uri = conn->request_info.local_uri;
  6591. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6592. const char *rewrite;
  6593. struct vec a, b;
  6594. ptrdiff_t match_len;
  6595. char gz_path[PATH_MAX];
  6596. int truncated;
  6597. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6598. char *tmp_str;
  6599. size_t tmp_str_len, sep_pos;
  6600. int allow_substitute_script_subresources;
  6601. #endif
  6602. #else
  6603. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6604. #endif
  6605. /* Step 1: Set all initially unknown outputs to zero */
  6606. memset(filestat, 0, sizeof(*filestat));
  6607. *filename = 0;
  6608. *is_found = 0;
  6609. *is_script_resource = 0;
  6610. /* Step 2: Check if the request attempts to modify the file system */
  6611. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6612. /* Step 3: Check if it is a websocket request, and modify the document
  6613. * root if required */
  6614. #if defined(USE_WEBSOCKET)
  6615. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6616. #if !defined(NO_FILES)
  6617. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6618. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6619. }
  6620. #endif /* !NO_FILES */
  6621. #else /* USE_WEBSOCKET */
  6622. *is_websocket_request = 0;
  6623. #endif /* USE_WEBSOCKET */
  6624. /* Step 4: Check if gzip encoded response is allowed */
  6625. conn->accept_gzip = 0;
  6626. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6627. if (strstr(accept_encoding, "gzip") != NULL) {
  6628. conn->accept_gzip = 1;
  6629. }
  6630. }
  6631. #if !defined(NO_FILES)
  6632. /* Step 5: If there is no root directory, don't look for files. */
  6633. /* Note that root == NULL is a regular use case here. This occurs,
  6634. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6635. * config is not required. */
  6636. if (root == NULL) {
  6637. /* all file related outputs have already been set to 0, just return
  6638. */
  6639. return;
  6640. }
  6641. /* Step 6: Determine the local file path from the root path and the
  6642. * request uri. */
  6643. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6644. * part of the path one byte on the right. */
  6645. mg_snprintf(
  6646. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6647. if (truncated) {
  6648. goto interpret_cleanup;
  6649. }
  6650. /* Step 7: URI rewriting */
  6651. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6652. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6653. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6654. mg_snprintf(conn,
  6655. &truncated,
  6656. filename,
  6657. filename_buf_len - 1,
  6658. "%.*s%s",
  6659. (int)b.len,
  6660. b.ptr,
  6661. uri + match_len);
  6662. break;
  6663. }
  6664. }
  6665. if (truncated) {
  6666. goto interpret_cleanup;
  6667. }
  6668. /* Step 8: Check if the file exists at the server */
  6669. /* Local file path and name, corresponding to requested URI
  6670. * is now stored in "filename" variable. */
  6671. if (mg_stat(conn, filename, filestat)) {
  6672. int uri_len = (int)strlen(uri);
  6673. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6674. /* 8.1: File exists. */
  6675. *is_found = 1;
  6676. /* 8.2: Check if it is a script type. */
  6677. if (extention_matches_script(conn, filename)) {
  6678. /* The request addresses a CGI resource, Lua script or
  6679. * server-side javascript.
  6680. * The URI corresponds to the script itself (like
  6681. * /path/script.cgi), and there is no additional resource
  6682. * path (like /path/script.cgi/something).
  6683. * Requests that modify (replace or delete) a resource, like
  6684. * PUT and DELETE requests, should replace/delete the script
  6685. * file.
  6686. * Requests that read or write from/to a resource, like GET and
  6687. * POST requests, should call the script and return the
  6688. * generated response. */
  6689. *is_script_resource = (!*is_put_or_delete_request);
  6690. }
  6691. /* 8.3: If the request target is a directory, there could be
  6692. * a substitute file (index.html, index.cgi, ...). */
  6693. if (filestat->is_directory && is_uri_end_slash) {
  6694. /* Use a local copy here, since substitute_index_file will
  6695. * change the content of the file status */
  6696. struct mg_file_stat tmp_filestat;
  6697. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6698. if (substitute_index_file(
  6699. conn, filename, filename_buf_len, &tmp_filestat)) {
  6700. /* Substitute file found. Copy stat to the output, then
  6701. * check if the file is a script file */
  6702. *filestat = tmp_filestat;
  6703. if (extention_matches_script(conn, filename)) {
  6704. /* Substitute file is a script file */
  6705. *is_script_resource = 1;
  6706. } else {
  6707. /* Substitute file is a regular file */
  6708. *is_script_resource = 0;
  6709. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6710. }
  6711. }
  6712. /* If there is no substitute file, the server could return
  6713. * a directory listing in a later step */
  6714. }
  6715. return;
  6716. }
  6717. /* Step 9: Check for zipped files: */
  6718. /* If we can't find the actual file, look for the file
  6719. * with the same name but a .gz extension. If we find it,
  6720. * use that and set the gzipped flag in the file struct
  6721. * to indicate that the response need to have the content-
  6722. * encoding: gzip header.
  6723. * We can only do this if the browser declares support. */
  6724. if (conn->accept_gzip) {
  6725. mg_snprintf(
  6726. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6727. if (truncated) {
  6728. goto interpret_cleanup;
  6729. }
  6730. if (mg_stat(conn, gz_path, filestat)) {
  6731. if (filestat) {
  6732. filestat->is_gzipped = 1;
  6733. *is_found = 1;
  6734. }
  6735. /* Currently gz files can not be scripts. */
  6736. return;
  6737. }
  6738. }
  6739. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6740. /* Step 10: Script resources may handle sub-resources */
  6741. /* Support PATH_INFO for CGI scripts. */
  6742. tmp_str_len = strlen(filename);
  6743. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6744. if (!tmp_str) {
  6745. /* Out of memory */
  6746. goto interpret_cleanup;
  6747. }
  6748. memcpy(tmp_str, filename, tmp_str_len + 1);
  6749. /* Check config, if index scripts may have sub-resources */
  6750. allow_substitute_script_subresources =
  6751. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6752. "yes");
  6753. sep_pos = tmp_str_len;
  6754. while (sep_pos > 0) {
  6755. sep_pos--;
  6756. if (tmp_str[sep_pos] == '/') {
  6757. int is_script = 0, does_exist = 0;
  6758. tmp_str[sep_pos] = 0;
  6759. if (tmp_str[0]) {
  6760. is_script = extention_matches_script(conn, tmp_str);
  6761. does_exist = mg_stat(conn, tmp_str, filestat);
  6762. }
  6763. if (does_exist && is_script) {
  6764. filename[sep_pos] = 0;
  6765. memmove(filename + sep_pos + 2,
  6766. filename + sep_pos + 1,
  6767. strlen(filename + sep_pos + 1) + 1);
  6768. conn->path_info = filename + sep_pos + 1;
  6769. filename[sep_pos + 1] = '/';
  6770. *is_script_resource = 1;
  6771. *is_found = 1;
  6772. break;
  6773. }
  6774. if (allow_substitute_script_subresources) {
  6775. if (substitute_index_file(
  6776. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6777. /* some intermediate directory has an index file */
  6778. if (extention_matches_script(conn, tmp_str)) {
  6779. DEBUG_TRACE("Substitute script %s serving path %s",
  6780. tmp_str,
  6781. filename);
  6782. /* this index file is a script */
  6783. mg_snprintf(conn,
  6784. &truncated,
  6785. filename,
  6786. filename_buf_len,
  6787. "%s//%s",
  6788. tmp_str,
  6789. filename + sep_pos + 1);
  6790. if (truncated) {
  6791. mg_free(tmp_str);
  6792. goto interpret_cleanup;
  6793. }
  6794. sep_pos = strlen(tmp_str);
  6795. filename[sep_pos] = 0;
  6796. conn->path_info = filename + sep_pos + 1;
  6797. *is_script_resource = 1;
  6798. *is_found = 1;
  6799. break;
  6800. } else {
  6801. DEBUG_TRACE("Substitute file %s serving path %s",
  6802. tmp_str,
  6803. filename);
  6804. /* non-script files will not have sub-resources */
  6805. filename[sep_pos] = 0;
  6806. conn->path_info = 0;
  6807. *is_script_resource = 0;
  6808. *is_found = 0;
  6809. break;
  6810. }
  6811. }
  6812. }
  6813. tmp_str[sep_pos] = '/';
  6814. }
  6815. }
  6816. mg_free(tmp_str);
  6817. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6818. #endif /* !defined(NO_FILES) */
  6819. return;
  6820. #if !defined(NO_FILES)
  6821. /* Reset all outputs */
  6822. interpret_cleanup:
  6823. memset(filestat, 0, sizeof(*filestat));
  6824. *filename = 0;
  6825. *is_found = 0;
  6826. *is_script_resource = 0;
  6827. *is_websocket_request = 0;
  6828. *is_put_or_delete_request = 0;
  6829. #endif /* !defined(NO_FILES) */
  6830. }
  6831. /* Check whether full request is buffered. Return:
  6832. * -1 if request or response is malformed
  6833. * 0 if request or response is not yet fully buffered
  6834. * >0 actual request length, including last \r\n\r\n */
  6835. static int
  6836. get_http_header_len(const char *buf, int buflen)
  6837. {
  6838. int i;
  6839. for (i = 0; i < buflen; i++) {
  6840. /* Do an unsigned comparison in some conditions below */
  6841. const unsigned char c = (unsigned char)buf[i];
  6842. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6843. && !isprint(c)) {
  6844. /* abort scan as soon as one malformed character is found */
  6845. return -1;
  6846. }
  6847. if (i < buflen - 1) {
  6848. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6849. /* Two newline, no carriage return - not standard compliant,
  6850. * but it should be accepted */
  6851. return i + 2;
  6852. }
  6853. }
  6854. if (i < buflen - 3) {
  6855. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6856. && (buf[i + 3] == '\n')) {
  6857. /* Two \r\n - standard compliant */
  6858. return i + 4;
  6859. }
  6860. }
  6861. }
  6862. return 0;
  6863. }
  6864. #if !defined(NO_CACHING)
  6865. /* Convert month to the month number. Return -1 on error, or month number */
  6866. static int
  6867. get_month_index(const char *s)
  6868. {
  6869. size_t i;
  6870. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6871. if (!strcmp(s, month_names[i])) {
  6872. return (int)i;
  6873. }
  6874. }
  6875. return -1;
  6876. }
  6877. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6878. static time_t
  6879. parse_date_string(const char *datetime)
  6880. {
  6881. char month_str[32] = {0};
  6882. int second, minute, hour, day, month, year;
  6883. time_t result = (time_t)0;
  6884. struct tm tm;
  6885. if ((sscanf(datetime,
  6886. "%d/%3s/%d %d:%d:%d",
  6887. &day,
  6888. month_str,
  6889. &year,
  6890. &hour,
  6891. &minute,
  6892. &second)
  6893. == 6)
  6894. || (sscanf(datetime,
  6895. "%d %3s %d %d:%d:%d",
  6896. &day,
  6897. month_str,
  6898. &year,
  6899. &hour,
  6900. &minute,
  6901. &second)
  6902. == 6)
  6903. || (sscanf(datetime,
  6904. "%*3s, %d %3s %d %d:%d:%d",
  6905. &day,
  6906. month_str,
  6907. &year,
  6908. &hour,
  6909. &minute,
  6910. &second)
  6911. == 6)
  6912. || (sscanf(datetime,
  6913. "%d-%3s-%d %d:%d:%d",
  6914. &day,
  6915. month_str,
  6916. &year,
  6917. &hour,
  6918. &minute,
  6919. &second)
  6920. == 6)) {
  6921. month = get_month_index(month_str);
  6922. if ((month >= 0) && (year >= 1970)) {
  6923. memset(&tm, 0, sizeof(tm));
  6924. tm.tm_year = year - 1900;
  6925. tm.tm_mon = month;
  6926. tm.tm_mday = day;
  6927. tm.tm_hour = hour;
  6928. tm.tm_min = minute;
  6929. tm.tm_sec = second;
  6930. result = timegm(&tm);
  6931. }
  6932. }
  6933. return result;
  6934. }
  6935. #endif /* !NO_CACHING */
  6936. /* Pre-process URIs according to RFC + protect against directory disclosure
  6937. * attacks by removing '..', excessive '/' and '\' characters */
  6938. static void
  6939. remove_dot_segments(char *inout)
  6940. {
  6941. /* Windows backend protection
  6942. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6943. * in URI by slash */
  6944. char *out_end = inout;
  6945. char *in = inout;
  6946. if (!in) {
  6947. /* Param error. */
  6948. return;
  6949. }
  6950. while (*in) {
  6951. if (*in == '\\') {
  6952. *in = '/';
  6953. }
  6954. in++;
  6955. }
  6956. /* Algorithm "remove_dot_segments" from
  6957. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6958. /* Step 1:
  6959. * The input buffer is initialized.
  6960. * The output buffer is initialized to the empty string.
  6961. */
  6962. in = inout;
  6963. /* Step 2:
  6964. * While the input buffer is not empty, loop as follows:
  6965. */
  6966. /* Less than out_end of the inout buffer is used as output, so keep
  6967. * condition: out_end <= in */
  6968. while (*in) {
  6969. /* Step 2a:
  6970. * If the input buffer begins with a prefix of "../" or "./",
  6971. * then remove that prefix from the input buffer;
  6972. */
  6973. if (!strncmp(in, "../", 3)) {
  6974. in += 3;
  6975. } else if (!strncmp(in, "./", 2)) {
  6976. in += 2;
  6977. }
  6978. /* otherwise */
  6979. /* Step 2b:
  6980. * if the input buffer begins with a prefix of "/./" or "/.",
  6981. * where "." is a complete path segment, then replace that
  6982. * prefix with "/" in the input buffer;
  6983. */
  6984. else if (!strncmp(in, "/./", 3)) {
  6985. in += 2;
  6986. } else if (!strcmp(in, "/.")) {
  6987. in[1] = 0;
  6988. }
  6989. /* otherwise */
  6990. /* Step 2c:
  6991. * if the input buffer begins with a prefix of "/../" or "/..",
  6992. * where ".." is a complete path segment, then replace that
  6993. * prefix with "/" in the input buffer and remove the last
  6994. * segment and its preceding "/" (if any) from the output
  6995. * buffer;
  6996. */
  6997. else if (!strncmp(in, "/../", 4)) {
  6998. in += 3;
  6999. if (inout != out_end) {
  7000. /* remove last segment */
  7001. do {
  7002. out_end--;
  7003. } while ((inout != out_end) && (*out_end != '/'));
  7004. }
  7005. } else if (!strcmp(in, "/..")) {
  7006. in[1] = 0;
  7007. if (inout != out_end) {
  7008. /* remove last segment */
  7009. do {
  7010. out_end--;
  7011. } while ((inout != out_end) && (*out_end != '/'));
  7012. }
  7013. }
  7014. /* otherwise */
  7015. /* Step 2d:
  7016. * if the input buffer consists only of "." or "..", then remove
  7017. * that from the input buffer;
  7018. */
  7019. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7020. *in = 0;
  7021. }
  7022. /* otherwise */
  7023. /* Step 2e:
  7024. * move the first path segment in the input buffer to the end of
  7025. * the output buffer, including the initial "/" character (if
  7026. * any) and any subsequent characters up to, but not including,
  7027. * the next "/" character or the end of the input buffer.
  7028. */
  7029. else {
  7030. do {
  7031. *out_end = *in;
  7032. out_end++;
  7033. in++;
  7034. } while ((*in != 0) && (*in != '/'));
  7035. }
  7036. }
  7037. /* Step 3:
  7038. * Finally, the output buffer is returned as the result of
  7039. * remove_dot_segments.
  7040. */
  7041. /* Terminate output */
  7042. *out_end = 0;
  7043. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7044. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7045. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7046. * or "//" anymore.
  7047. */
  7048. out_end = in = inout;
  7049. while (*in) {
  7050. if (*in == '.') {
  7051. /* remove . at the end or preceding of / */
  7052. char *in_ahead = in;
  7053. do {
  7054. in_ahead++;
  7055. } while (*in_ahead == '.');
  7056. if (*in_ahead == '/') {
  7057. in = in_ahead;
  7058. if ((out_end != inout) && (out_end[-1] == '/')) {
  7059. /* remove generated // */
  7060. out_end--;
  7061. }
  7062. } else if (*in_ahead == 0) {
  7063. in = in_ahead;
  7064. } else {
  7065. do {
  7066. *out_end++ = '.';
  7067. in++;
  7068. } while (in != in_ahead);
  7069. }
  7070. } else if (*in == '/') {
  7071. /* replace // by / */
  7072. *out_end++ = '/';
  7073. do {
  7074. in++;
  7075. } while (*in == '/');
  7076. } else {
  7077. *out_end++ = *in;
  7078. in++;
  7079. }
  7080. }
  7081. *out_end = 0;
  7082. }
  7083. static const struct {
  7084. const char *extension;
  7085. size_t ext_len;
  7086. const char *mime_type;
  7087. } builtin_mime_types[] = {
  7088. /* IANA registered MIME types
  7089. * (http://www.iana.org/assignments/media-types)
  7090. * application types */
  7091. {".doc", 4, "application/msword"},
  7092. {".eps", 4, "application/postscript"},
  7093. {".exe", 4, "application/octet-stream"},
  7094. {".js", 3, "application/javascript"},
  7095. {".json", 5, "application/json"},
  7096. {".pdf", 4, "application/pdf"},
  7097. {".ps", 3, "application/postscript"},
  7098. {".rtf", 4, "application/rtf"},
  7099. {".xhtml", 6, "application/xhtml+xml"},
  7100. {".xsl", 4, "application/xml"},
  7101. {".xslt", 5, "application/xml"},
  7102. /* fonts */
  7103. {".ttf", 4, "application/font-sfnt"},
  7104. {".cff", 4, "application/font-sfnt"},
  7105. {".otf", 4, "application/font-sfnt"},
  7106. {".aat", 4, "application/font-sfnt"},
  7107. {".sil", 4, "application/font-sfnt"},
  7108. {".pfr", 4, "application/font-tdpfr"},
  7109. {".woff", 5, "application/font-woff"},
  7110. /* audio */
  7111. {".mp3", 4, "audio/mpeg"},
  7112. {".oga", 4, "audio/ogg"},
  7113. {".ogg", 4, "audio/ogg"},
  7114. /* image */
  7115. {".gif", 4, "image/gif"},
  7116. {".ief", 4, "image/ief"},
  7117. {".jpeg", 5, "image/jpeg"},
  7118. {".jpg", 4, "image/jpeg"},
  7119. {".jpm", 4, "image/jpm"},
  7120. {".jpx", 4, "image/jpx"},
  7121. {".png", 4, "image/png"},
  7122. {".svg", 4, "image/svg+xml"},
  7123. {".tif", 4, "image/tiff"},
  7124. {".tiff", 5, "image/tiff"},
  7125. /* model */
  7126. {".wrl", 4, "model/vrml"},
  7127. /* text */
  7128. {".css", 4, "text/css"},
  7129. {".csv", 4, "text/csv"},
  7130. {".htm", 4, "text/html"},
  7131. {".html", 5, "text/html"},
  7132. {".sgm", 4, "text/sgml"},
  7133. {".shtm", 5, "text/html"},
  7134. {".shtml", 6, "text/html"},
  7135. {".txt", 4, "text/plain"},
  7136. {".xml", 4, "text/xml"},
  7137. /* video */
  7138. {".mov", 4, "video/quicktime"},
  7139. {".mp4", 4, "video/mp4"},
  7140. {".mpeg", 5, "video/mpeg"},
  7141. {".mpg", 4, "video/mpeg"},
  7142. {".ogv", 4, "video/ogg"},
  7143. {".qt", 3, "video/quicktime"},
  7144. /* not registered types
  7145. * (http://reference.sitepoint.com/html/mime-types-full,
  7146. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7147. {".arj", 4, "application/x-arj-compressed"},
  7148. {".gz", 3, "application/x-gunzip"},
  7149. {".rar", 4, "application/x-arj-compressed"},
  7150. {".swf", 4, "application/x-shockwave-flash"},
  7151. {".tar", 4, "application/x-tar"},
  7152. {".tgz", 4, "application/x-tar-gz"},
  7153. {".torrent", 8, "application/x-bittorrent"},
  7154. {".ppt", 4, "application/x-mspowerpoint"},
  7155. {".xls", 4, "application/x-msexcel"},
  7156. {".zip", 4, "application/x-zip-compressed"},
  7157. {".aac",
  7158. 4,
  7159. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7160. {".aif", 4, "audio/x-aif"},
  7161. {".m3u", 4, "audio/x-mpegurl"},
  7162. {".mid", 4, "audio/x-midi"},
  7163. {".ra", 3, "audio/x-pn-realaudio"},
  7164. {".ram", 4, "audio/x-pn-realaudio"},
  7165. {".wav", 4, "audio/x-wav"},
  7166. {".bmp", 4, "image/bmp"},
  7167. {".ico", 4, "image/x-icon"},
  7168. {".pct", 4, "image/x-pct"},
  7169. {".pict", 5, "image/pict"},
  7170. {".rgb", 4, "image/x-rgb"},
  7171. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7172. {".asf", 4, "video/x-ms-asf"},
  7173. {".avi", 4, "video/x-msvideo"},
  7174. {".m4v", 4, "video/x-m4v"},
  7175. {NULL, 0, NULL}};
  7176. const char *
  7177. mg_get_builtin_mime_type(const char *path)
  7178. {
  7179. const char *ext;
  7180. size_t i, path_len;
  7181. path_len = strlen(path);
  7182. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7183. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7184. if ((path_len > builtin_mime_types[i].ext_len)
  7185. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7186. return builtin_mime_types[i].mime_type;
  7187. }
  7188. }
  7189. return "text/plain";
  7190. }
  7191. /* Look at the "path" extension and figure what mime type it has.
  7192. * Store mime type in the vector. */
  7193. static void
  7194. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7195. {
  7196. struct vec ext_vec, mime_vec;
  7197. const char *list, *ext;
  7198. size_t path_len;
  7199. path_len = strlen(path);
  7200. if ((conn == NULL) || (vec == NULL)) {
  7201. if (vec != NULL) {
  7202. memset(vec, '\0', sizeof(struct vec));
  7203. }
  7204. return;
  7205. }
  7206. /* Scan user-defined mime types first, in case user wants to
  7207. * override default mime types. */
  7208. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7209. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7210. /* ext now points to the path suffix */
  7211. ext = path + path_len - ext_vec.len;
  7212. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7213. *vec = mime_vec;
  7214. return;
  7215. }
  7216. }
  7217. vec->ptr = mg_get_builtin_mime_type(path);
  7218. vec->len = strlen(vec->ptr);
  7219. }
  7220. /* Stringify binary data. Output buffer must be twice as big as input,
  7221. * because each byte takes 2 bytes in string representation */
  7222. static void
  7223. bin2str(char *to, const unsigned char *p, size_t len)
  7224. {
  7225. static const char *hex = "0123456789abcdef";
  7226. for (; len--; p++) {
  7227. *to++ = hex[p[0] >> 4];
  7228. *to++ = hex[p[0] & 0x0f];
  7229. }
  7230. *to = '\0';
  7231. }
  7232. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7233. */
  7234. char *
  7235. mg_md5(char buf[33], ...)
  7236. {
  7237. md5_byte_t hash[16];
  7238. const char *p;
  7239. va_list ap;
  7240. md5_state_t ctx;
  7241. md5_init(&ctx);
  7242. va_start(ap, buf);
  7243. while ((p = va_arg(ap, const char *)) != NULL) {
  7244. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7245. }
  7246. va_end(ap);
  7247. md5_finish(&ctx, hash);
  7248. bin2str(buf, hash, sizeof(hash));
  7249. return buf;
  7250. }
  7251. /* Check the user's password, return 1 if OK */
  7252. static int
  7253. check_password(const char *method,
  7254. const char *ha1,
  7255. const char *uri,
  7256. const char *nonce,
  7257. const char *nc,
  7258. const char *cnonce,
  7259. const char *qop,
  7260. const char *response)
  7261. {
  7262. char ha2[32 + 1], expected_response[32 + 1];
  7263. /* Some of the parameters may be NULL */
  7264. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7265. || (qop == NULL) || (response == NULL)) {
  7266. return 0;
  7267. }
  7268. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7269. if (strlen(response) != 32) {
  7270. return 0;
  7271. }
  7272. mg_md5(ha2, method, ":", uri, NULL);
  7273. mg_md5(expected_response,
  7274. ha1,
  7275. ":",
  7276. nonce,
  7277. ":",
  7278. nc,
  7279. ":",
  7280. cnonce,
  7281. ":",
  7282. qop,
  7283. ":",
  7284. ha2,
  7285. NULL);
  7286. return mg_strcasecmp(response, expected_response) == 0;
  7287. }
  7288. #if !defined(NO_FILESYSTEMS)
  7289. /* Use the global passwords file, if specified by auth_gpass option,
  7290. * or search for .htpasswd in the requested directory. */
  7291. static void
  7292. open_auth_file(struct mg_connection *conn,
  7293. const char *path,
  7294. struct mg_file *filep)
  7295. {
  7296. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7297. char name[PATH_MAX];
  7298. const char *p, *e,
  7299. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7300. int truncated;
  7301. if (gpass != NULL) {
  7302. /* Use global passwords file */
  7303. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7304. #if defined(DEBUG)
  7305. /* Use mg_cry_internal here, since gpass has been
  7306. * configured. */
  7307. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7308. #endif
  7309. }
  7310. /* Important: using local struct mg_file to test path for
  7311. * is_directory flag. If filep is used, mg_stat() makes it
  7312. * appear as if auth file was opened.
  7313. * TODO(mid): Check if this is still required after rewriting
  7314. * mg_stat */
  7315. } else if (mg_stat(conn, path, &filep->stat)
  7316. && filep->stat.is_directory) {
  7317. mg_snprintf(conn,
  7318. &truncated,
  7319. name,
  7320. sizeof(name),
  7321. "%s/%s",
  7322. path,
  7323. PASSWORDS_FILE_NAME);
  7324. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7325. #if defined(DEBUG)
  7326. /* Don't use mg_cry_internal here, but only a trace, since
  7327. * this is a typical case. It will occur for every directory
  7328. * without a password file. */
  7329. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7330. #endif
  7331. }
  7332. } else {
  7333. /* Try to find .htpasswd in requested directory. */
  7334. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7335. if (e[0] == '/') {
  7336. break;
  7337. }
  7338. }
  7339. mg_snprintf(conn,
  7340. &truncated,
  7341. name,
  7342. sizeof(name),
  7343. "%.*s/%s",
  7344. (int)(e - p),
  7345. p,
  7346. PASSWORDS_FILE_NAME);
  7347. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7348. #if defined(DEBUG)
  7349. /* Don't use mg_cry_internal here, but only a trace, since
  7350. * this is a typical case. It will occur for every directory
  7351. * without a password file. */
  7352. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7353. #endif
  7354. }
  7355. }
  7356. }
  7357. }
  7358. #endif /* NO_FILESYSTEMS */
  7359. /* Parsed Authorization header */
  7360. struct ah {
  7361. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7362. };
  7363. /* Return 1 on success. Always initializes the ah structure. */
  7364. static int
  7365. parse_auth_header(struct mg_connection *conn,
  7366. char *buf,
  7367. size_t buf_size,
  7368. struct ah *ah)
  7369. {
  7370. char *name, *value, *s;
  7371. const char *auth_header;
  7372. uint64_t nonce;
  7373. if (!ah || !conn) {
  7374. return 0;
  7375. }
  7376. (void)memset(ah, 0, sizeof(*ah));
  7377. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7378. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7379. return 0;
  7380. }
  7381. /* Make modifiable copy of the auth header */
  7382. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7383. s = buf;
  7384. /* Parse authorization header */
  7385. for (;;) {
  7386. /* Gobble initial spaces */
  7387. while (isspace((unsigned char)*s)) {
  7388. s++;
  7389. }
  7390. name = skip_quoted(&s, "=", " ", 0);
  7391. /* Value is either quote-delimited, or ends at first comma or space.
  7392. */
  7393. if (s[0] == '\"') {
  7394. s++;
  7395. value = skip_quoted(&s, "\"", " ", '\\');
  7396. if (s[0] == ',') {
  7397. s++;
  7398. }
  7399. } else {
  7400. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7401. * uses spaces */
  7402. }
  7403. if (*name == '\0') {
  7404. break;
  7405. }
  7406. if (!strcmp(name, "username")) {
  7407. ah->user = value;
  7408. } else if (!strcmp(name, "cnonce")) {
  7409. ah->cnonce = value;
  7410. } else if (!strcmp(name, "response")) {
  7411. ah->response = value;
  7412. } else if (!strcmp(name, "uri")) {
  7413. ah->uri = value;
  7414. } else if (!strcmp(name, "qop")) {
  7415. ah->qop = value;
  7416. } else if (!strcmp(name, "nc")) {
  7417. ah->nc = value;
  7418. } else if (!strcmp(name, "nonce")) {
  7419. ah->nonce = value;
  7420. }
  7421. }
  7422. #if !defined(NO_NONCE_CHECK)
  7423. /* Read the nonce from the response. */
  7424. if (ah->nonce == NULL) {
  7425. return 0;
  7426. }
  7427. s = NULL;
  7428. nonce = strtoull(ah->nonce, &s, 10);
  7429. if ((s == NULL) || (*s != 0)) {
  7430. return 0;
  7431. }
  7432. /* Convert the nonce from the client to a number. */
  7433. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7434. /* The converted number corresponds to the time the nounce has been
  7435. * created. This should not be earlier than the server start. */
  7436. /* Server side nonce check is valuable in all situations but one:
  7437. * if the server restarts frequently, but the client should not see
  7438. * that, so the server should accept nonces from previous starts. */
  7439. /* However, the reasonable default is to not accept a nonce from a
  7440. * previous start, so if anyone changed the access rights between
  7441. * two restarts, a new login is required. */
  7442. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7443. /* nonce is from a previous start of the server and no longer valid
  7444. * (replay attack?) */
  7445. return 0;
  7446. }
  7447. /* Check if the nonce is too high, so it has not (yet) been used by the
  7448. * server. */
  7449. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7450. + conn->dom_ctx->nonce_count)) {
  7451. return 0;
  7452. }
  7453. #else
  7454. (void)nonce;
  7455. #endif
  7456. /* CGI needs it as REMOTE_USER */
  7457. if (ah->user != NULL) {
  7458. conn->request_info.remote_user =
  7459. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7460. } else {
  7461. return 0;
  7462. }
  7463. return 1;
  7464. }
  7465. static const char *
  7466. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7467. {
  7468. #if defined(MG_USE_OPEN_FILE)
  7469. const char *eof;
  7470. size_t len;
  7471. const char *memend;
  7472. #else
  7473. (void)p; /* parameter is unused */
  7474. #endif
  7475. if (!filep) {
  7476. return NULL;
  7477. }
  7478. #if defined(MG_USE_OPEN_FILE)
  7479. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7480. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7481. /* Search for \n from p till the end of stream */
  7482. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7483. if (eof != NULL) {
  7484. eof += 1; /* Include \n */
  7485. } else {
  7486. eof = memend; /* Copy remaining data */
  7487. }
  7488. len =
  7489. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7490. memcpy(buf, *p, len);
  7491. buf[len] = '\0';
  7492. *p += len;
  7493. return len ? eof : NULL;
  7494. } else /* filep->access.fp block below */
  7495. #endif
  7496. if (filep->access.fp != NULL) {
  7497. return fgets(buf, (int)size, filep->access.fp);
  7498. } else {
  7499. return NULL;
  7500. }
  7501. }
  7502. /* Define the initial recursion depth for procesesing htpasswd files that
  7503. * include other htpasswd
  7504. * (or even the same) files. It is not difficult to provide a file or files
  7505. * s.t. they force civetweb
  7506. * to infinitely recurse and then crash.
  7507. */
  7508. #define INITIAL_DEPTH 9
  7509. #if INITIAL_DEPTH <= 0
  7510. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7511. #endif
  7512. #if !defined(NO_FILESYSTEMS)
  7513. struct read_auth_file_struct {
  7514. struct mg_connection *conn;
  7515. struct ah ah;
  7516. const char *domain;
  7517. char buf[256 + 256 + 40];
  7518. const char *f_user;
  7519. const char *f_domain;
  7520. const char *f_ha1;
  7521. };
  7522. static int
  7523. read_auth_file(struct mg_file *filep,
  7524. struct read_auth_file_struct *workdata,
  7525. int depth)
  7526. {
  7527. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7528. int is_authorized = 0;
  7529. struct mg_file fp;
  7530. size_t l;
  7531. if (!filep || !workdata || (0 == depth)) {
  7532. return 0;
  7533. }
  7534. /* Loop over passwords file */
  7535. #if defined(MG_USE_OPEN_FILE)
  7536. p = (char *)filep->access.membuf;
  7537. #endif
  7538. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7539. l = strlen(workdata->buf);
  7540. while (l > 0) {
  7541. if (isspace((unsigned char)workdata->buf[l - 1])
  7542. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7543. l--;
  7544. workdata->buf[l] = 0;
  7545. } else
  7546. break;
  7547. }
  7548. if (l < 1) {
  7549. continue;
  7550. }
  7551. workdata->f_user = workdata->buf;
  7552. if (workdata->f_user[0] == ':') {
  7553. /* user names may not contain a ':' and may not be empty,
  7554. * so lines starting with ':' may be used for a special purpose
  7555. */
  7556. if (workdata->f_user[1] == '#') {
  7557. /* :# is a comment */
  7558. continue;
  7559. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7560. if (mg_fopen(workdata->conn,
  7561. workdata->f_user + 9,
  7562. MG_FOPEN_MODE_READ,
  7563. &fp)) {
  7564. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7565. (void)mg_fclose(
  7566. &fp.access); /* ignore error on read only file */
  7567. /* No need to continue processing files once we have a
  7568. * match, since nothing will reset it back
  7569. * to 0.
  7570. */
  7571. if (is_authorized) {
  7572. return is_authorized;
  7573. }
  7574. } else {
  7575. mg_cry_internal(workdata->conn,
  7576. "%s: cannot open authorization file: %s",
  7577. __func__,
  7578. workdata->buf);
  7579. }
  7580. continue;
  7581. }
  7582. /* everything is invalid for the moment (might change in the
  7583. * future) */
  7584. mg_cry_internal(workdata->conn,
  7585. "%s: syntax error in authorization file: %s",
  7586. __func__,
  7587. workdata->buf);
  7588. continue;
  7589. }
  7590. workdata->f_domain = strchr(workdata->f_user, ':');
  7591. if (workdata->f_domain == NULL) {
  7592. mg_cry_internal(workdata->conn,
  7593. "%s: syntax error in authorization file: %s",
  7594. __func__,
  7595. workdata->buf);
  7596. continue;
  7597. }
  7598. *(char *)(workdata->f_domain) = 0;
  7599. (workdata->f_domain)++;
  7600. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7601. if (workdata->f_ha1 == NULL) {
  7602. mg_cry_internal(workdata->conn,
  7603. "%s: syntax error in authorization file: %s",
  7604. __func__,
  7605. workdata->buf);
  7606. continue;
  7607. }
  7608. *(char *)(workdata->f_ha1) = 0;
  7609. (workdata->f_ha1)++;
  7610. if (!strcmp(workdata->ah.user, workdata->f_user)
  7611. && !strcmp(workdata->domain, workdata->f_domain)) {
  7612. return check_password(workdata->conn->request_info.request_method,
  7613. workdata->f_ha1,
  7614. workdata->ah.uri,
  7615. workdata->ah.nonce,
  7616. workdata->ah.nc,
  7617. workdata->ah.cnonce,
  7618. workdata->ah.qop,
  7619. workdata->ah.response);
  7620. }
  7621. }
  7622. return is_authorized;
  7623. }
  7624. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7625. static int
  7626. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7627. {
  7628. struct read_auth_file_struct workdata;
  7629. char buf[MG_BUF_LEN];
  7630. if (!conn || !conn->dom_ctx) {
  7631. return 0;
  7632. }
  7633. memset(&workdata, 0, sizeof(workdata));
  7634. workdata.conn = conn;
  7635. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7636. return 0;
  7637. }
  7638. if (realm) {
  7639. workdata.domain = realm;
  7640. } else {
  7641. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7642. }
  7643. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7644. }
  7645. /* Public function to check http digest authentication header */
  7646. int
  7647. mg_check_digest_access_authentication(struct mg_connection *conn,
  7648. const char *realm,
  7649. const char *filename)
  7650. {
  7651. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7652. int auth;
  7653. if (!conn || !filename) {
  7654. return -1;
  7655. }
  7656. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7657. return -2;
  7658. }
  7659. auth = authorize(conn, &file, realm);
  7660. mg_fclose(&file.access);
  7661. return auth;
  7662. }
  7663. #endif /* NO_FILESYSTEMS */
  7664. /* Return 1 if request is authorised, 0 otherwise. */
  7665. static int
  7666. check_authorization(struct mg_connection *conn, const char *path)
  7667. {
  7668. #if !defined(NO_FILESYSTEMS)
  7669. char fname[PATH_MAX];
  7670. struct vec uri_vec, filename_vec;
  7671. const char *list;
  7672. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7673. int authorized = 1, truncated;
  7674. if (!conn || !conn->dom_ctx) {
  7675. return 0;
  7676. }
  7677. list = conn->dom_ctx->config[PROTECT_URI];
  7678. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7679. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7680. mg_snprintf(conn,
  7681. &truncated,
  7682. fname,
  7683. sizeof(fname),
  7684. "%.*s",
  7685. (int)filename_vec.len,
  7686. filename_vec.ptr);
  7687. if (truncated
  7688. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7689. mg_cry_internal(conn,
  7690. "%s: cannot open %s: %s",
  7691. __func__,
  7692. fname,
  7693. strerror(errno));
  7694. }
  7695. break;
  7696. }
  7697. }
  7698. if (!is_file_opened(&file.access)) {
  7699. open_auth_file(conn, path, &file);
  7700. }
  7701. if (is_file_opened(&file.access)) {
  7702. authorized = authorize(conn, &file, NULL);
  7703. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7704. }
  7705. return authorized;
  7706. #else
  7707. (void)conn;
  7708. (void)path;
  7709. return 1;
  7710. #endif /* NO_FILESYSTEMS */
  7711. }
  7712. /* Internal function. Assumes conn is valid */
  7713. static void
  7714. send_authorization_request(struct mg_connection *conn, const char *realm)
  7715. {
  7716. char date[64];
  7717. time_t curtime = time(NULL);
  7718. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7719. if (!realm) {
  7720. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7721. }
  7722. mg_lock_context(conn->phys_ctx);
  7723. nonce += conn->dom_ctx->nonce_count;
  7724. ++conn->dom_ctx->nonce_count;
  7725. mg_unlock_context(conn->phys_ctx);
  7726. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7727. conn->status_code = 401;
  7728. conn->must_close = 1;
  7729. gmt_time_string(date, sizeof(date), &curtime);
  7730. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7731. send_no_cache_header(conn);
  7732. send_additional_header(conn);
  7733. mg_printf(conn,
  7734. "Date: %s\r\n"
  7735. "Connection: %s\r\n"
  7736. "Content-Length: 0\r\n"
  7737. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7738. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7739. date,
  7740. suggest_connection_header(conn),
  7741. realm,
  7742. nonce);
  7743. }
  7744. /* Interface function. Parameters are provided by the user, so do
  7745. * at least some basic checks.
  7746. */
  7747. int
  7748. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7749. const char *realm)
  7750. {
  7751. if (conn && conn->dom_ctx) {
  7752. send_authorization_request(conn, realm);
  7753. return 0;
  7754. }
  7755. return -1;
  7756. }
  7757. #if !defined(NO_FILES)
  7758. static int
  7759. is_authorized_for_put(struct mg_connection *conn)
  7760. {
  7761. if (conn) {
  7762. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7763. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7764. int ret = 0;
  7765. if (passfile != NULL
  7766. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7767. ret = authorize(conn, &file, NULL);
  7768. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7769. }
  7770. return ret;
  7771. }
  7772. return 0;
  7773. }
  7774. #endif
  7775. int
  7776. mg_modify_passwords_file(const char *fname,
  7777. const char *domain,
  7778. const char *user,
  7779. const char *pass)
  7780. {
  7781. int found, i;
  7782. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7783. FILE *fp, *fp2;
  7784. found = 0;
  7785. fp = fp2 = NULL;
  7786. /* Regard empty password as no password - remove user record. */
  7787. if ((pass != NULL) && (pass[0] == '\0')) {
  7788. pass = NULL;
  7789. }
  7790. /* Other arguments must not be empty */
  7791. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7792. return 0;
  7793. }
  7794. /* Using the given file format, user name and domain must not contain
  7795. * ':'
  7796. */
  7797. if (strchr(user, ':') != NULL) {
  7798. return 0;
  7799. }
  7800. if (strchr(domain, ':') != NULL) {
  7801. return 0;
  7802. }
  7803. /* Do not allow control characters like newline in user name and domain.
  7804. * Do not allow excessively long names either. */
  7805. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7806. if (iscntrl((unsigned char)user[i])) {
  7807. return 0;
  7808. }
  7809. }
  7810. if (user[i]) {
  7811. return 0;
  7812. }
  7813. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7814. if (iscntrl((unsigned char)domain[i])) {
  7815. return 0;
  7816. }
  7817. }
  7818. if (domain[i]) {
  7819. return 0;
  7820. }
  7821. /* The maximum length of the path to the password file is limited */
  7822. if ((strlen(fname) + 4) >= PATH_MAX) {
  7823. return 0;
  7824. }
  7825. /* Create a temporary file name. Length has been checked before. */
  7826. strcpy(tmp, fname);
  7827. strcat(tmp, ".tmp");
  7828. /* Create the file if does not exist */
  7829. /* Use of fopen here is OK, since fname is only ASCII */
  7830. if ((fp = fopen(fname, "a+")) != NULL) {
  7831. (void)fclose(fp);
  7832. }
  7833. /* Open the given file and temporary file */
  7834. if ((fp = fopen(fname, "r")) == NULL) {
  7835. return 0;
  7836. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7837. fclose(fp);
  7838. return 0;
  7839. }
  7840. /* Copy the stuff to temporary file */
  7841. while (fgets(line, sizeof(line), fp) != NULL) {
  7842. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7843. continue;
  7844. }
  7845. u[255] = 0;
  7846. d[255] = 0;
  7847. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7848. found++;
  7849. if (pass != NULL) {
  7850. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7851. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7852. }
  7853. } else {
  7854. fprintf(fp2, "%s", line);
  7855. }
  7856. }
  7857. /* If new user, just add it */
  7858. if (!found && (pass != NULL)) {
  7859. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7860. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7861. }
  7862. /* Close files */
  7863. fclose(fp);
  7864. fclose(fp2);
  7865. /* Put the temp file in place of real file */
  7866. IGNORE_UNUSED_RESULT(remove(fname));
  7867. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7868. return 1;
  7869. }
  7870. static int
  7871. is_valid_port(unsigned long port)
  7872. {
  7873. return (port <= 0xffff);
  7874. }
  7875. static int
  7876. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7877. {
  7878. struct addrinfo hints, *res, *ressave;
  7879. int func_ret = 0;
  7880. int gai_ret;
  7881. memset(&hints, 0, sizeof(struct addrinfo));
  7882. hints.ai_family = af;
  7883. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7884. if (gai_ret != 0) {
  7885. /* gai_strerror could be used to convert gai_ret to a string */
  7886. /* POSIX return values: see
  7887. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7888. */
  7889. /* Windows return values: see
  7890. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7891. */
  7892. return 0;
  7893. }
  7894. ressave = res;
  7895. while (res) {
  7896. if (dstlen >= (size_t)res->ai_addrlen) {
  7897. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7898. func_ret = 1;
  7899. }
  7900. res = res->ai_next;
  7901. }
  7902. freeaddrinfo(ressave);
  7903. return func_ret;
  7904. }
  7905. static int
  7906. connect_socket(struct mg_context *ctx /* may be NULL */,
  7907. const char *host,
  7908. int port,
  7909. int use_ssl,
  7910. char *ebuf,
  7911. size_t ebuf_len,
  7912. SOCKET *sock /* output: socket, must not be NULL */,
  7913. union usa *sa /* output: socket address, must not be NULL */
  7914. )
  7915. {
  7916. int ip_ver = 0;
  7917. int conn_ret = -1;
  7918. int sockerr = 0;
  7919. *sock = INVALID_SOCKET;
  7920. memset(sa, 0, sizeof(*sa));
  7921. if (ebuf_len > 0) {
  7922. *ebuf = 0;
  7923. }
  7924. if (host == NULL) {
  7925. mg_snprintf(NULL,
  7926. NULL, /* No truncation check for ebuf */
  7927. ebuf,
  7928. ebuf_len,
  7929. "%s",
  7930. "NULL host");
  7931. return 0;
  7932. }
  7933. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7934. mg_snprintf(NULL,
  7935. NULL, /* No truncation check for ebuf */
  7936. ebuf,
  7937. ebuf_len,
  7938. "%s",
  7939. "invalid port");
  7940. return 0;
  7941. }
  7942. #if !defined(NO_SSL)
  7943. #if !defined(NO_SSL_DL)
  7944. #if defined(OPENSSL_API_1_1)
  7945. if (use_ssl && (TLS_client_method == NULL)) {
  7946. mg_snprintf(NULL,
  7947. NULL, /* No truncation check for ebuf */
  7948. ebuf,
  7949. ebuf_len,
  7950. "%s",
  7951. "SSL is not initialized");
  7952. return 0;
  7953. }
  7954. #else
  7955. if (use_ssl && (SSLv23_client_method == NULL)) {
  7956. mg_snprintf(NULL,
  7957. NULL, /* No truncation check for ebuf */
  7958. ebuf,
  7959. ebuf_len,
  7960. "%s",
  7961. "SSL is not initialized");
  7962. return 0;
  7963. }
  7964. #endif /* OPENSSL_API_1_1 */
  7965. #else
  7966. (void)use_ssl;
  7967. #endif /* NO_SSL_DL */
  7968. #else
  7969. (void)use_ssl;
  7970. #endif /* !defined(NO_SSL) */
  7971. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7972. sa->sin.sin_family = AF_INET;
  7973. sa->sin.sin_port = htons((uint16_t)port);
  7974. ip_ver = 4;
  7975. #if defined(USE_IPV6)
  7976. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7977. sa->sin6.sin6_family = AF_INET6;
  7978. sa->sin6.sin6_port = htons((uint16_t)port);
  7979. ip_ver = 6;
  7980. } else if (host[0] == '[') {
  7981. /* While getaddrinfo on Windows will work with [::1],
  7982. * getaddrinfo on Linux only works with ::1 (without []). */
  7983. size_t l = strlen(host + 1);
  7984. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7985. if (h) {
  7986. h[l - 1] = 0;
  7987. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7988. sa->sin6.sin6_family = AF_INET6;
  7989. sa->sin6.sin6_port = htons((uint16_t)port);
  7990. ip_ver = 6;
  7991. }
  7992. mg_free(h);
  7993. }
  7994. #endif
  7995. }
  7996. if (ip_ver == 0) {
  7997. mg_snprintf(NULL,
  7998. NULL, /* No truncation check for ebuf */
  7999. ebuf,
  8000. ebuf_len,
  8001. "%s",
  8002. "host not found");
  8003. return 0;
  8004. }
  8005. if (ip_ver == 4) {
  8006. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8007. }
  8008. #if defined(USE_IPV6)
  8009. else if (ip_ver == 6) {
  8010. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8011. }
  8012. #endif
  8013. if (*sock == INVALID_SOCKET) {
  8014. mg_snprintf(NULL,
  8015. NULL, /* No truncation check for ebuf */
  8016. ebuf,
  8017. ebuf_len,
  8018. "socket(): %s",
  8019. strerror(ERRNO));
  8020. return 0;
  8021. }
  8022. if (0 != set_non_blocking_mode(*sock)) {
  8023. mg_snprintf(NULL,
  8024. NULL, /* No truncation check for ebuf */
  8025. ebuf,
  8026. ebuf_len,
  8027. "Cannot set socket to non-blocking: %s",
  8028. strerror(ERRNO));
  8029. closesocket(*sock);
  8030. *sock = INVALID_SOCKET;
  8031. return 0;
  8032. }
  8033. set_close_on_exec(*sock, NULL, ctx);
  8034. if (ip_ver == 4) {
  8035. /* connected with IPv4 */
  8036. conn_ret = connect(*sock,
  8037. (struct sockaddr *)((void *)&sa->sin),
  8038. sizeof(sa->sin));
  8039. }
  8040. #if defined(USE_IPV6)
  8041. else if (ip_ver == 6) {
  8042. /* connected with IPv6 */
  8043. conn_ret = connect(*sock,
  8044. (struct sockaddr *)((void *)&sa->sin6),
  8045. sizeof(sa->sin6));
  8046. }
  8047. #endif
  8048. if (conn_ret != 0) {
  8049. sockerr = ERRNO;
  8050. }
  8051. #if defined(_WIN32)
  8052. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8053. #else
  8054. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8055. #endif
  8056. /* Data for getsockopt */
  8057. void *psockerr = &sockerr;
  8058. int ret;
  8059. #if defined(_WIN32)
  8060. int len = (int)sizeof(sockerr);
  8061. #else
  8062. socklen_t len = (socklen_t)sizeof(sockerr);
  8063. #endif
  8064. /* Data for poll */
  8065. struct mg_pollfd pfd[1];
  8066. int pollres;
  8067. int ms_wait = 10000; /* 10 second timeout */
  8068. stop_flag_t nonstop;
  8069. STOP_FLAG_ASSIGN(&nonstop, 0);
  8070. /* For a non-blocking socket, the connect sequence is:
  8071. * 1) call connect (will not block)
  8072. * 2) wait until the socket is ready for writing (select or poll)
  8073. * 3) check connection state with getsockopt
  8074. */
  8075. pfd[0].fd = *sock;
  8076. pfd[0].events = POLLOUT;
  8077. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8078. if (pollres != 1) {
  8079. /* Not connected */
  8080. mg_snprintf(NULL,
  8081. NULL, /* No truncation check for ebuf */
  8082. ebuf,
  8083. ebuf_len,
  8084. "connect(%s:%d): timeout",
  8085. host,
  8086. port);
  8087. closesocket(*sock);
  8088. *sock = INVALID_SOCKET;
  8089. return 0;
  8090. }
  8091. #if defined(_WIN32)
  8092. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8093. #else
  8094. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8095. #endif
  8096. if ((ret == 0) && (sockerr == 0)) {
  8097. conn_ret = 0;
  8098. }
  8099. }
  8100. if (conn_ret != 0) {
  8101. /* Not connected */
  8102. mg_snprintf(NULL,
  8103. NULL, /* No truncation check for ebuf */
  8104. ebuf,
  8105. ebuf_len,
  8106. "connect(%s:%d): error %s",
  8107. host,
  8108. port,
  8109. strerror(sockerr));
  8110. closesocket(*sock);
  8111. *sock = INVALID_SOCKET;
  8112. return 0;
  8113. }
  8114. return 1;
  8115. }
  8116. int
  8117. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8118. {
  8119. static const char *dont_escape = "._-$,;~()";
  8120. static const char *hex = "0123456789abcdef";
  8121. char *pos = dst;
  8122. const char *end = dst + dst_len - 1;
  8123. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8124. if (isalnum((unsigned char)*src)
  8125. || (strchr(dont_escape, *src) != NULL)) {
  8126. *pos = *src;
  8127. } else if (pos + 2 < end) {
  8128. pos[0] = '%';
  8129. pos[1] = hex[(unsigned char)*src >> 4];
  8130. pos[2] = hex[(unsigned char)*src & 0xf];
  8131. pos += 2;
  8132. } else {
  8133. break;
  8134. }
  8135. }
  8136. *pos = '\0';
  8137. return (*src == '\0') ? (int)(pos - dst) : -1;
  8138. }
  8139. /* Return 0 on success, non-zero if an error occurs. */
  8140. static int
  8141. print_dir_entry(struct de *de)
  8142. {
  8143. size_t namesize, escsize, i;
  8144. char *href, *esc, *p;
  8145. char size[64], mod[64];
  8146. #if defined(REENTRANT_TIME)
  8147. struct tm _tm;
  8148. struct tm *tm = &_tm;
  8149. #else
  8150. struct tm *tm;
  8151. #endif
  8152. /* Estimate worst case size for encoding and escaping */
  8153. namesize = strlen(de->file_name) + 1;
  8154. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8155. href = (char *)mg_malloc(namesize * 3 + escsize);
  8156. if (href == NULL) {
  8157. return -1;
  8158. }
  8159. mg_url_encode(de->file_name, href, namesize * 3);
  8160. esc = NULL;
  8161. if (escsize > 0) {
  8162. /* HTML escaping needed */
  8163. esc = href + namesize * 3;
  8164. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8165. mg_strlcpy(p, de->file_name + i, 2);
  8166. if (*p == '&') {
  8167. strcpy(p, "&amp;");
  8168. } else if (*p == '<') {
  8169. strcpy(p, "&lt;");
  8170. } else if (*p == '>') {
  8171. strcpy(p, "&gt;");
  8172. }
  8173. }
  8174. }
  8175. if (de->file.is_directory) {
  8176. mg_snprintf(de->conn,
  8177. NULL, /* Buffer is big enough */
  8178. size,
  8179. sizeof(size),
  8180. "%s",
  8181. "[DIRECTORY]");
  8182. } else {
  8183. /* We use (signed) cast below because MSVC 6 compiler cannot
  8184. * convert unsigned __int64 to double. Sigh. */
  8185. if (de->file.size < 1024) {
  8186. mg_snprintf(de->conn,
  8187. NULL, /* Buffer is big enough */
  8188. size,
  8189. sizeof(size),
  8190. "%d",
  8191. (int)de->file.size);
  8192. } else if (de->file.size < 0x100000) {
  8193. mg_snprintf(de->conn,
  8194. NULL, /* Buffer is big enough */
  8195. size,
  8196. sizeof(size),
  8197. "%.1fk",
  8198. (double)de->file.size / 1024.0);
  8199. } else if (de->file.size < 0x40000000) {
  8200. mg_snprintf(de->conn,
  8201. NULL, /* Buffer is big enough */
  8202. size,
  8203. sizeof(size),
  8204. "%.1fM",
  8205. (double)de->file.size / 1048576);
  8206. } else {
  8207. mg_snprintf(de->conn,
  8208. NULL, /* Buffer is big enough */
  8209. size,
  8210. sizeof(size),
  8211. "%.1fG",
  8212. (double)de->file.size / 1073741824);
  8213. }
  8214. }
  8215. /* Note: mg_snprintf will not cause a buffer overflow above.
  8216. * So, string truncation checks are not required here. */
  8217. #if defined(REENTRANT_TIME)
  8218. localtime_r(&de->file.last_modified, tm);
  8219. #else
  8220. tm = localtime(&de->file.last_modified);
  8221. #endif
  8222. if (tm != NULL) {
  8223. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8224. } else {
  8225. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8226. mod[sizeof(mod) - 1] = '\0';
  8227. }
  8228. mg_printf(de->conn,
  8229. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8230. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8231. href,
  8232. de->file.is_directory ? "/" : "",
  8233. esc ? esc : de->file_name,
  8234. de->file.is_directory ? "/" : "",
  8235. mod,
  8236. size);
  8237. mg_free(href);
  8238. return 0;
  8239. }
  8240. /* This function is called from send_directory() and used for
  8241. * sorting directory entries by size, or name, or modification time.
  8242. * On windows, __cdecl specification is needed in case if project is built
  8243. * with __stdcall convention. qsort always requires __cdels callback. */
  8244. static int WINCDECL
  8245. compare_dir_entries(const void *p1, const void *p2)
  8246. {
  8247. if (p1 && p2) {
  8248. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8249. const char *query_string = a->conn->request_info.query_string;
  8250. int cmp_result = 0;
  8251. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8252. query_string = "n";
  8253. }
  8254. if (a->file.is_directory && !b->file.is_directory) {
  8255. return -1; /* Always put directories on top */
  8256. } else if (!a->file.is_directory && b->file.is_directory) {
  8257. return 1; /* Always put directories on top */
  8258. } else if (*query_string == 'n') {
  8259. cmp_result = strcmp(a->file_name, b->file_name);
  8260. } else if (*query_string == 's') {
  8261. cmp_result = (a->file.size == b->file.size)
  8262. ? 0
  8263. : ((a->file.size > b->file.size) ? 1 : -1);
  8264. } else if (*query_string == 'd') {
  8265. cmp_result =
  8266. (a->file.last_modified == b->file.last_modified)
  8267. ? 0
  8268. : ((a->file.last_modified > b->file.last_modified) ? 1
  8269. : -1);
  8270. }
  8271. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8272. }
  8273. return 0;
  8274. }
  8275. static int
  8276. must_hide_file(struct mg_connection *conn, const char *path)
  8277. {
  8278. if (conn && conn->dom_ctx) {
  8279. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8280. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8281. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8282. || ((pattern != NULL)
  8283. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8284. }
  8285. return 0;
  8286. }
  8287. #if !defined(NO_FILESYSTEMS)
  8288. static int
  8289. scan_directory(struct mg_connection *conn,
  8290. const char *dir,
  8291. void *data,
  8292. int (*cb)(struct de *, void *))
  8293. {
  8294. char path[PATH_MAX];
  8295. struct dirent *dp;
  8296. DIR *dirp;
  8297. struct de de;
  8298. int truncated;
  8299. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8300. return 0;
  8301. } else {
  8302. de.conn = conn;
  8303. while ((dp = mg_readdir(dirp)) != NULL) {
  8304. /* Do not show current dir and hidden files */
  8305. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8306. || must_hide_file(conn, dp->d_name)) {
  8307. continue;
  8308. }
  8309. mg_snprintf(
  8310. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8311. /* If we don't memset stat structure to zero, mtime will have
  8312. * garbage and strftime() will segfault later on in
  8313. * print_dir_entry(). memset is required only if mg_stat()
  8314. * fails. For more details, see
  8315. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8316. memset(&de.file, 0, sizeof(de.file));
  8317. if (truncated) {
  8318. /* If the path is not complete, skip processing. */
  8319. continue;
  8320. }
  8321. if (!mg_stat(conn, path, &de.file)) {
  8322. mg_cry_internal(conn,
  8323. "%s: mg_stat(%s) failed: %s",
  8324. __func__,
  8325. path,
  8326. strerror(ERRNO));
  8327. }
  8328. de.file_name = dp->d_name;
  8329. if (cb(&de, data)) {
  8330. /* stopped */
  8331. break;
  8332. }
  8333. }
  8334. (void)mg_closedir(dirp);
  8335. }
  8336. return 1;
  8337. }
  8338. #endif /* NO_FILESYSTEMS */
  8339. #if !defined(NO_FILES)
  8340. static int
  8341. remove_directory(struct mg_connection *conn, const char *dir)
  8342. {
  8343. char path[PATH_MAX];
  8344. struct dirent *dp;
  8345. DIR *dirp;
  8346. struct de de;
  8347. int truncated;
  8348. int ok = 1;
  8349. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8350. return 0;
  8351. } else {
  8352. de.conn = conn;
  8353. while ((dp = mg_readdir(dirp)) != NULL) {
  8354. /* Do not show current dir (but show hidden files as they will
  8355. * also be removed) */
  8356. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8357. continue;
  8358. }
  8359. mg_snprintf(
  8360. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8361. /* If we don't memset stat structure to zero, mtime will have
  8362. * garbage and strftime() will segfault later on in
  8363. * print_dir_entry(). memset is required only if mg_stat()
  8364. * fails. For more details, see
  8365. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8366. memset(&de.file, 0, sizeof(de.file));
  8367. if (truncated) {
  8368. /* Do not delete anything shorter */
  8369. ok = 0;
  8370. continue;
  8371. }
  8372. if (!mg_stat(conn, path, &de.file)) {
  8373. mg_cry_internal(conn,
  8374. "%s: mg_stat(%s) failed: %s",
  8375. __func__,
  8376. path,
  8377. strerror(ERRNO));
  8378. ok = 0;
  8379. }
  8380. if (de.file.is_directory) {
  8381. if (remove_directory(conn, path) == 0) {
  8382. ok = 0;
  8383. }
  8384. } else {
  8385. /* This will fail file is the file is in memory */
  8386. if (mg_remove(conn, path) == 0) {
  8387. ok = 0;
  8388. }
  8389. }
  8390. }
  8391. (void)mg_closedir(dirp);
  8392. IGNORE_UNUSED_RESULT(rmdir(dir));
  8393. }
  8394. return ok;
  8395. }
  8396. #endif
  8397. struct dir_scan_data {
  8398. struct de *entries;
  8399. size_t num_entries;
  8400. size_t arr_size;
  8401. };
  8402. #if !defined(NO_FILESYSTEMS)
  8403. static int
  8404. dir_scan_callback(struct de *de, void *data)
  8405. {
  8406. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8407. struct de *entries = dsd->entries;
  8408. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8409. entries =
  8410. (struct de *)mg_realloc(entries,
  8411. dsd->arr_size * 2 * sizeof(entries[0]));
  8412. if (entries == NULL) {
  8413. /* stop scan */
  8414. return 1;
  8415. }
  8416. dsd->entries = entries;
  8417. dsd->arr_size *= 2;
  8418. }
  8419. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8420. if (entries[dsd->num_entries].file_name == NULL) {
  8421. /* stop scan */
  8422. return 1;
  8423. }
  8424. entries[dsd->num_entries].file = de->file;
  8425. entries[dsd->num_entries].conn = de->conn;
  8426. dsd->num_entries++;
  8427. return 0;
  8428. }
  8429. static void
  8430. handle_directory_request(struct mg_connection *conn, const char *dir)
  8431. {
  8432. size_t i;
  8433. int sort_direction;
  8434. struct dir_scan_data data = {NULL, 0, 128};
  8435. char date[64], *esc, *p;
  8436. const char *title;
  8437. time_t curtime = time(NULL);
  8438. if (!conn) {
  8439. return;
  8440. }
  8441. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8442. mg_send_http_error(conn,
  8443. 500,
  8444. "Error: Cannot open directory\nopendir(%s): %s",
  8445. dir,
  8446. strerror(ERRNO));
  8447. return;
  8448. }
  8449. gmt_time_string(date, sizeof(date), &curtime);
  8450. esc = NULL;
  8451. title = conn->request_info.local_uri;
  8452. if (title[strcspn(title, "&<>")]) {
  8453. /* HTML escaping needed */
  8454. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8455. if (esc) {
  8456. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8457. mg_strlcpy(p, title + i, 2);
  8458. if (*p == '&') {
  8459. strcpy(p, "&amp;");
  8460. } else if (*p == '<') {
  8461. strcpy(p, "&lt;");
  8462. } else if (*p == '>') {
  8463. strcpy(p, "&gt;");
  8464. }
  8465. }
  8466. } else {
  8467. title = "";
  8468. }
  8469. }
  8470. sort_direction = ((conn->request_info.query_string != NULL)
  8471. && (conn->request_info.query_string[0] != '\0')
  8472. && (conn->request_info.query_string[1] == 'd'))
  8473. ? 'a'
  8474. : 'd';
  8475. conn->must_close = 1;
  8476. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8477. send_static_cache_header(conn);
  8478. send_additional_header(conn);
  8479. mg_printf(conn,
  8480. "Date: %s\r\n"
  8481. "Connection: close\r\n"
  8482. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8483. date);
  8484. mg_printf(conn,
  8485. "<html><head><title>Index of %s</title>"
  8486. "<style>th {text-align: left;}</style></head>"
  8487. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8488. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8489. "<th><a href=\"?d%c\">Modified</a></th>"
  8490. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8491. "<tr><td colspan=\"3\"><hr></td></tr>",
  8492. esc ? esc : title,
  8493. esc ? esc : title,
  8494. sort_direction,
  8495. sort_direction,
  8496. sort_direction);
  8497. mg_free(esc);
  8498. /* Print first entry - link to a parent directory */
  8499. mg_printf(conn,
  8500. "<tr><td><a href=\"%s\">%s</a></td>"
  8501. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8502. "..",
  8503. "Parent directory",
  8504. "-",
  8505. "-");
  8506. /* Sort and print directory entries */
  8507. if (data.entries != NULL) {
  8508. qsort(data.entries,
  8509. data.num_entries,
  8510. sizeof(data.entries[0]),
  8511. compare_dir_entries);
  8512. for (i = 0; i < data.num_entries; i++) {
  8513. print_dir_entry(&data.entries[i]);
  8514. mg_free(data.entries[i].file_name);
  8515. }
  8516. mg_free(data.entries);
  8517. }
  8518. mg_printf(conn, "%s", "</table></pre></body></html>");
  8519. conn->status_code = 200;
  8520. }
  8521. #endif /* NO_FILESYSTEMS */
  8522. /* Send len bytes from the opened file to the client. */
  8523. static void
  8524. send_file_data(struct mg_connection *conn,
  8525. struct mg_file *filep,
  8526. int64_t offset,
  8527. int64_t len)
  8528. {
  8529. char buf[MG_BUF_LEN];
  8530. int to_read, num_read, num_written;
  8531. int64_t size;
  8532. if (!filep || !conn) {
  8533. return;
  8534. }
  8535. /* Sanity check the offset */
  8536. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8537. : (int64_t)(filep->stat.size);
  8538. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8539. #if defined(MG_USE_OPEN_FILE)
  8540. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8541. /* file stored in memory */
  8542. if (len > size - offset) {
  8543. len = size - offset;
  8544. }
  8545. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8546. } else /* else block below */
  8547. #endif
  8548. if (len > 0 && filep->access.fp != NULL) {
  8549. /* file stored on disk */
  8550. #if defined(__linux__)
  8551. /* sendfile is only available for Linux */
  8552. if ((conn->ssl == 0) && (conn->throttle == 0)
  8553. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8554. "yes"))) {
  8555. off_t sf_offs = (off_t)offset;
  8556. ssize_t sf_sent;
  8557. int sf_file = fileno(filep->access.fp);
  8558. int loop_cnt = 0;
  8559. do {
  8560. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8561. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8562. size_t sf_tosend =
  8563. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8564. sf_sent =
  8565. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8566. if (sf_sent > 0) {
  8567. len -= sf_sent;
  8568. offset += sf_sent;
  8569. } else if (loop_cnt == 0) {
  8570. /* This file can not be sent using sendfile.
  8571. * This might be the case for pseudo-files in the
  8572. * /sys/ and /proc/ file system.
  8573. * Use the regular user mode copy code instead. */
  8574. break;
  8575. } else if (sf_sent == 0) {
  8576. /* No error, but 0 bytes sent. May be EOF? */
  8577. return;
  8578. }
  8579. loop_cnt++;
  8580. } while ((len > 0) && (sf_sent >= 0));
  8581. if (sf_sent > 0) {
  8582. return; /* OK */
  8583. }
  8584. /* sf_sent<0 means error, thus fall back to the classic way */
  8585. /* This is always the case, if sf_file is not a "normal" file,
  8586. * e.g., for sending data from the output of a CGI process. */
  8587. offset = (int64_t)sf_offs;
  8588. }
  8589. #endif
  8590. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8591. mg_cry_internal(conn,
  8592. "%s: fseeko() failed: %s",
  8593. __func__,
  8594. strerror(ERRNO));
  8595. mg_send_http_error(
  8596. conn,
  8597. 500,
  8598. "%s",
  8599. "Error: Unable to access file at requested position.");
  8600. } else {
  8601. while (len > 0) {
  8602. /* Calculate how much to read from the file in the buffer */
  8603. to_read = sizeof(buf);
  8604. if ((int64_t)to_read > len) {
  8605. to_read = (int)len;
  8606. }
  8607. /* Read from file, exit the loop on error */
  8608. if ((num_read =
  8609. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8610. <= 0) {
  8611. break;
  8612. }
  8613. /* Send read bytes to the client, exit the loop on error */
  8614. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8615. != num_read) {
  8616. break;
  8617. }
  8618. /* Both read and were successful, adjust counters */
  8619. len -= num_written;
  8620. }
  8621. }
  8622. }
  8623. }
  8624. static int
  8625. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8626. {
  8627. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8628. }
  8629. static void
  8630. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8631. {
  8632. if ((filestat != NULL) && (buf != NULL)) {
  8633. mg_snprintf(NULL,
  8634. NULL, /* All calls to construct_etag use 64 byte buffer */
  8635. buf,
  8636. buf_len,
  8637. "\"%lx.%" INT64_FMT "\"",
  8638. (unsigned long)filestat->last_modified,
  8639. filestat->size);
  8640. }
  8641. }
  8642. static void
  8643. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8644. {
  8645. if (filep != NULL && filep->fp != NULL) {
  8646. #if defined(_WIN32)
  8647. (void)conn; /* Unused. */
  8648. #else
  8649. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8650. mg_cry_internal(conn,
  8651. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8652. __func__,
  8653. strerror(ERRNO));
  8654. }
  8655. #endif
  8656. }
  8657. }
  8658. #if defined(USE_ZLIB)
  8659. #include "mod_zlib.inl"
  8660. #endif
  8661. #if !defined(NO_FILESYSTEMS)
  8662. static void
  8663. handle_static_file_request(struct mg_connection *conn,
  8664. const char *path,
  8665. struct mg_file *filep,
  8666. const char *mime_type,
  8667. const char *additional_headers)
  8668. {
  8669. char date[64], lm[64], etag[64];
  8670. char range[128]; /* large enough, so there will be no overflow */
  8671. const char *msg = "OK";
  8672. const char *range_hdr;
  8673. time_t curtime = time(NULL);
  8674. int64_t cl, r1, r2;
  8675. struct vec mime_vec;
  8676. int n, truncated;
  8677. char gz_path[PATH_MAX];
  8678. const char *encoding = "";
  8679. const char *origin_hdr;
  8680. const char *cors_orig_cfg;
  8681. const char *cors1, *cors2, *cors3;
  8682. int is_head_request;
  8683. #if defined(USE_ZLIB)
  8684. /* Compression is allowed, unless there is a reason not to use
  8685. * compression. If the file is already compressed, too small or a
  8686. * "range" request was made, on the fly compression is not possible. */
  8687. int allow_on_the_fly_compression = 1;
  8688. #endif
  8689. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8690. return;
  8691. }
  8692. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8693. if (mime_type == NULL) {
  8694. get_mime_type(conn, path, &mime_vec);
  8695. } else {
  8696. mime_vec.ptr = mime_type;
  8697. mime_vec.len = strlen(mime_type);
  8698. }
  8699. if (filep->stat.size > INT64_MAX) {
  8700. mg_send_http_error(conn,
  8701. 500,
  8702. "Error: File size is too large to send\n%" INT64_FMT,
  8703. filep->stat.size);
  8704. return;
  8705. }
  8706. cl = (int64_t)filep->stat.size;
  8707. conn->status_code = 200;
  8708. range[0] = '\0';
  8709. #if defined(USE_ZLIB)
  8710. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8711. * it's important to rewrite the filename after resolving
  8712. * the mime type from it, to preserve the actual file's type */
  8713. if (!conn->accept_gzip) {
  8714. allow_on_the_fly_compression = 0;
  8715. }
  8716. #endif
  8717. /* Check if there is a range header */
  8718. range_hdr = mg_get_header(conn, "Range");
  8719. /* For gzipped files, add *.gz */
  8720. if (filep->stat.is_gzipped) {
  8721. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8722. if (truncated) {
  8723. mg_send_http_error(conn,
  8724. 500,
  8725. "Error: Path of zipped file too long (%s)",
  8726. path);
  8727. return;
  8728. }
  8729. path = gz_path;
  8730. encoding = "Content-Encoding: gzip\r\n";
  8731. #if defined(USE_ZLIB)
  8732. /* File is already compressed. No "on the fly" compression. */
  8733. allow_on_the_fly_compression = 0;
  8734. #endif
  8735. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8736. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8737. struct mg_file_stat file_stat;
  8738. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8739. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8740. && !file_stat.is_directory) {
  8741. file_stat.is_gzipped = 1;
  8742. filep->stat = file_stat;
  8743. cl = (int64_t)filep->stat.size;
  8744. path = gz_path;
  8745. encoding = "Content-Encoding: gzip\r\n";
  8746. #if defined(USE_ZLIB)
  8747. /* File is already compressed. No "on the fly" compression. */
  8748. allow_on_the_fly_compression = 0;
  8749. #endif
  8750. }
  8751. }
  8752. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8753. mg_send_http_error(conn,
  8754. 500,
  8755. "Error: Cannot open file\nfopen(%s): %s",
  8756. path,
  8757. strerror(ERRNO));
  8758. return;
  8759. }
  8760. fclose_on_exec(&filep->access, conn);
  8761. /* If "Range" request was made: parse header, send only selected part
  8762. * of the file. */
  8763. r1 = r2 = 0;
  8764. if ((range_hdr != NULL)
  8765. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8766. && (r2 >= 0)) {
  8767. /* actually, range requests don't play well with a pre-gzipped
  8768. * file (since the range is specified in the uncompressed space) */
  8769. if (filep->stat.is_gzipped) {
  8770. mg_send_http_error(
  8771. conn,
  8772. 416, /* 416 = Range Not Satisfiable */
  8773. "%s",
  8774. "Error: Range requests in gzipped files are not supported");
  8775. (void)mg_fclose(
  8776. &filep->access); /* ignore error on read only file */
  8777. return;
  8778. }
  8779. conn->status_code = 206;
  8780. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8781. mg_snprintf(conn,
  8782. NULL, /* range buffer is big enough */
  8783. range,
  8784. sizeof(range),
  8785. "Content-Range: bytes "
  8786. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8787. r1,
  8788. r1 + cl - 1,
  8789. filep->stat.size);
  8790. msg = "Partial Content";
  8791. #if defined(USE_ZLIB)
  8792. /* Do not compress ranges. */
  8793. allow_on_the_fly_compression = 0;
  8794. #endif
  8795. }
  8796. /* Do not compress small files. Small files do not benefit from file
  8797. * compression, but there is still some overhead. */
  8798. #if defined(USE_ZLIB)
  8799. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8800. /* File is below the size limit. */
  8801. allow_on_the_fly_compression = 0;
  8802. }
  8803. #endif
  8804. /* Standard CORS header */
  8805. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8806. origin_hdr = mg_get_header(conn, "Origin");
  8807. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8808. /* Cross-origin resource sharing (CORS), see
  8809. * http://www.html5rocks.com/en/tutorials/cors/,
  8810. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8811. * -
  8812. * preflight is not supported for files. */
  8813. cors1 = "Access-Control-Allow-Origin: ";
  8814. cors2 = cors_orig_cfg;
  8815. cors3 = "\r\n";
  8816. } else {
  8817. cors1 = cors2 = cors3 = "";
  8818. }
  8819. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8820. * according to
  8821. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8822. gmt_time_string(date, sizeof(date), &curtime);
  8823. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8824. construct_etag(etag, sizeof(etag), &filep->stat);
  8825. /* Send header */
  8826. (void)mg_printf(conn,
  8827. "HTTP/1.1 %d %s\r\n"
  8828. "%s%s%s" /* CORS */
  8829. "Date: %s\r\n"
  8830. "Last-Modified: %s\r\n"
  8831. "Etag: %s\r\n"
  8832. "Content-Type: %.*s\r\n"
  8833. "Connection: %s\r\n",
  8834. conn->status_code,
  8835. msg,
  8836. cors1,
  8837. cors2,
  8838. cors3,
  8839. date,
  8840. lm,
  8841. etag,
  8842. (int)mime_vec.len,
  8843. mime_vec.ptr,
  8844. suggest_connection_header(conn));
  8845. send_static_cache_header(conn);
  8846. send_additional_header(conn);
  8847. #if defined(USE_ZLIB)
  8848. /* On the fly compression allowed */
  8849. if (allow_on_the_fly_compression) {
  8850. /* For on the fly compression, we don't know the content size in
  8851. * advance, so we have to use chunked encoding */
  8852. (void)mg_printf(conn,
  8853. "Content-Encoding: gzip\r\n"
  8854. "Transfer-Encoding: chunked\r\n");
  8855. } else
  8856. #endif
  8857. {
  8858. /* Without on-the-fly compression, we know the content-length
  8859. * and we can use ranges (with on-the-fly compression we cannot).
  8860. * So we send these response headers only in this case. */
  8861. (void)mg_printf(conn,
  8862. "Content-Length: %" INT64_FMT "\r\n"
  8863. "Accept-Ranges: bytes\r\n"
  8864. "%s" /* range */
  8865. "%s" /* encoding */,
  8866. cl,
  8867. range,
  8868. encoding);
  8869. }
  8870. /* The previous code must not add any header starting with X- to make
  8871. * sure no one of the additional_headers is included twice */
  8872. if (additional_headers != NULL) {
  8873. (void)mg_printf(conn,
  8874. "%.*s\r\n\r\n",
  8875. (int)strlen(additional_headers),
  8876. additional_headers);
  8877. } else {
  8878. (void)mg_printf(conn, "\r\n");
  8879. }
  8880. if (!is_head_request) {
  8881. #if defined(USE_ZLIB)
  8882. if (allow_on_the_fly_compression) {
  8883. /* Compress and send */
  8884. send_compressed_data(conn, filep);
  8885. } else
  8886. #endif
  8887. {
  8888. /* Send file directly */
  8889. send_file_data(conn, filep, r1, cl);
  8890. }
  8891. }
  8892. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8893. }
  8894. int
  8895. mg_send_file_body(struct mg_connection *conn, const char *path)
  8896. {
  8897. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8898. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8899. return -1;
  8900. }
  8901. fclose_on_exec(&file.access, conn);
  8902. send_file_data(conn, &file, 0, INT64_MAX);
  8903. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8904. return 0; /* >= 0 for OK */
  8905. }
  8906. #endif /* NO_FILESYSTEMS */
  8907. #if !defined(NO_CACHING)
  8908. /* Return True if we should reply 304 Not Modified. */
  8909. static int
  8910. is_not_modified(const struct mg_connection *conn,
  8911. const struct mg_file_stat *filestat)
  8912. {
  8913. char etag[64];
  8914. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8915. const char *inm = mg_get_header(conn, "If-None-Match");
  8916. construct_etag(etag, sizeof(etag), filestat);
  8917. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8918. || ((ims != NULL)
  8919. && (filestat->last_modified <= parse_date_string(ims)));
  8920. }
  8921. static void
  8922. handle_not_modified_static_file_request(struct mg_connection *conn,
  8923. struct mg_file *filep)
  8924. {
  8925. char date[64], lm[64], etag[64];
  8926. time_t curtime = time(NULL);
  8927. if ((conn == NULL) || (filep == NULL)) {
  8928. return;
  8929. }
  8930. conn->status_code = 304;
  8931. gmt_time_string(date, sizeof(date), &curtime);
  8932. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8933. construct_etag(etag, sizeof(etag), &filep->stat);
  8934. (void)mg_printf(conn,
  8935. "HTTP/1.1 %d %s\r\n"
  8936. "Date: %s\r\n",
  8937. conn->status_code,
  8938. mg_get_response_code_text(conn, conn->status_code),
  8939. date);
  8940. send_static_cache_header(conn);
  8941. send_additional_header(conn);
  8942. (void)mg_printf(conn,
  8943. "Last-Modified: %s\r\n"
  8944. "Etag: %s\r\n"
  8945. "Connection: %s\r\n"
  8946. "\r\n",
  8947. lm,
  8948. etag,
  8949. suggest_connection_header(conn));
  8950. }
  8951. #endif
  8952. #if !defined(NO_FILESYSTEMS)
  8953. void
  8954. mg_send_file(struct mg_connection *conn, const char *path)
  8955. {
  8956. mg_send_mime_file2(conn, path, NULL, NULL);
  8957. }
  8958. void
  8959. mg_send_mime_file(struct mg_connection *conn,
  8960. const char *path,
  8961. const char *mime_type)
  8962. {
  8963. mg_send_mime_file2(conn, path, mime_type, NULL);
  8964. }
  8965. void
  8966. mg_send_mime_file2(struct mg_connection *conn,
  8967. const char *path,
  8968. const char *mime_type,
  8969. const char *additional_headers)
  8970. {
  8971. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8972. if (!conn) {
  8973. /* No conn */
  8974. return;
  8975. }
  8976. if (mg_stat(conn, path, &file.stat)) {
  8977. #if !defined(NO_CACHING)
  8978. if (is_not_modified(conn, &file.stat)) {
  8979. /* Send 304 "Not Modified" - this must not send any body data */
  8980. handle_not_modified_static_file_request(conn, &file);
  8981. } else
  8982. #endif /* NO_CACHING */
  8983. if (file.stat.is_directory) {
  8984. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8985. "yes")) {
  8986. handle_directory_request(conn, path);
  8987. } else {
  8988. mg_send_http_error(conn,
  8989. 403,
  8990. "%s",
  8991. "Error: Directory listing denied");
  8992. }
  8993. } else {
  8994. handle_static_file_request(
  8995. conn, path, &file, mime_type, additional_headers);
  8996. }
  8997. } else {
  8998. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8999. }
  9000. }
  9001. /* For a given PUT path, create all intermediate subdirectories.
  9002. * Return 0 if the path itself is a directory.
  9003. * Return 1 if the path leads to a file.
  9004. * Return -1 for if the path is too long.
  9005. * Return -2 if path can not be created.
  9006. */
  9007. static int
  9008. put_dir(struct mg_connection *conn, const char *path)
  9009. {
  9010. char buf[PATH_MAX];
  9011. const char *s, *p;
  9012. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9013. size_t len;
  9014. int res = 1;
  9015. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9016. len = (size_t)(p - path);
  9017. if (len >= sizeof(buf)) {
  9018. /* path too long */
  9019. res = -1;
  9020. break;
  9021. }
  9022. memcpy(buf, path, len);
  9023. buf[len] = '\0';
  9024. /* Try to create intermediate directory */
  9025. DEBUG_TRACE("mkdir(%s)", buf);
  9026. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9027. /* path does not exixt and can not be created */
  9028. res = -2;
  9029. break;
  9030. }
  9031. /* Is path itself a directory? */
  9032. if (p[1] == '\0') {
  9033. res = 0;
  9034. }
  9035. }
  9036. return res;
  9037. }
  9038. static void
  9039. remove_bad_file(const struct mg_connection *conn, const char *path)
  9040. {
  9041. int r = mg_remove(conn, path);
  9042. if (r != 0) {
  9043. mg_cry_internal(conn,
  9044. "%s: Cannot remove invalid file %s",
  9045. __func__,
  9046. path);
  9047. }
  9048. }
  9049. long long
  9050. mg_store_body(struct mg_connection *conn, const char *path)
  9051. {
  9052. char buf[MG_BUF_LEN];
  9053. long long len = 0;
  9054. int ret, n;
  9055. struct mg_file fi;
  9056. if (conn->consumed_content != 0) {
  9057. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9058. return -11;
  9059. }
  9060. ret = put_dir(conn, path);
  9061. if (ret < 0) {
  9062. /* -1 for path too long,
  9063. * -2 for path can not be created. */
  9064. return ret;
  9065. }
  9066. if (ret != 1) {
  9067. /* Return 0 means, path itself is a directory. */
  9068. return 0;
  9069. }
  9070. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9071. return -12;
  9072. }
  9073. ret = mg_read(conn, buf, sizeof(buf));
  9074. while (ret > 0) {
  9075. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9076. if (n != ret) {
  9077. (void)mg_fclose(
  9078. &fi.access); /* File is bad and will be removed anyway. */
  9079. remove_bad_file(conn, path);
  9080. return -13;
  9081. }
  9082. len += ret;
  9083. ret = mg_read(conn, buf, sizeof(buf));
  9084. }
  9085. /* File is open for writing. If fclose fails, there was probably an
  9086. * error flushing the buffer to disk, so the file on disk might be
  9087. * broken. Delete it and return an error to the caller. */
  9088. if (mg_fclose(&fi.access) != 0) {
  9089. remove_bad_file(conn, path);
  9090. return -14;
  9091. }
  9092. return len;
  9093. }
  9094. #endif /* NO_FILESYSTEMS */
  9095. /* Parse a buffer:
  9096. * Forward the string pointer till the end of a word, then
  9097. * terminate it and forward till the begin of the next word.
  9098. */
  9099. static int
  9100. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9101. {
  9102. /* Forward until a space is found - use isgraph here */
  9103. /* See http://www.cplusplus.com/reference/cctype/ */
  9104. while (isgraph((unsigned char)**ppw)) {
  9105. (*ppw)++;
  9106. }
  9107. /* Check end of word */
  9108. if (eol) {
  9109. /* must be a end of line */
  9110. if ((**ppw != '\r') && (**ppw != '\n')) {
  9111. return -1;
  9112. }
  9113. } else {
  9114. /* must be a end of a word, but not a line */
  9115. if (**ppw != ' ') {
  9116. return -1;
  9117. }
  9118. }
  9119. /* Terminate and forward to the next word */
  9120. do {
  9121. **ppw = 0;
  9122. (*ppw)++;
  9123. } while (isspace((unsigned char)**ppw));
  9124. /* Check after term */
  9125. if (!eol) {
  9126. /* if it's not the end of line, there must be a next word */
  9127. if (!isgraph((unsigned char)**ppw)) {
  9128. return -1;
  9129. }
  9130. }
  9131. /* ok */
  9132. return 1;
  9133. }
  9134. /* Parse HTTP headers from the given buffer, advance buf pointer
  9135. * to the point where parsing stopped.
  9136. * All parameters must be valid pointers (not NULL).
  9137. * Return <0 on error. */
  9138. static int
  9139. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9140. {
  9141. int i;
  9142. int num_headers = 0;
  9143. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9144. char *dp = *buf;
  9145. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9146. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9147. dp++;
  9148. }
  9149. if (dp == *buf) {
  9150. /* End of headers reached. */
  9151. break;
  9152. }
  9153. if (*dp != ':') {
  9154. /* This is not a valid field. */
  9155. return -1;
  9156. }
  9157. /* End of header key (*dp == ':') */
  9158. /* Truncate here and set the key name */
  9159. *dp = 0;
  9160. hdr[i].name = *buf;
  9161. /* Skip all spaces */
  9162. do {
  9163. dp++;
  9164. } while ((*dp == ' ') || (*dp == '\t'));
  9165. /* The rest of the line is the value */
  9166. hdr[i].value = dp;
  9167. /* Find end of line */
  9168. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9169. dp++;
  9170. };
  9171. /* eliminate \r */
  9172. if (*dp == '\r') {
  9173. *dp = 0;
  9174. dp++;
  9175. if (*dp != '\n') {
  9176. /* This is not a valid line. */
  9177. return -1;
  9178. }
  9179. }
  9180. /* here *dp is either 0 or '\n' */
  9181. /* in any case, we have a new header */
  9182. num_headers = i + 1;
  9183. if (*dp) {
  9184. *dp = 0;
  9185. dp++;
  9186. *buf = dp;
  9187. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9188. /* This is the end of the header */
  9189. break;
  9190. }
  9191. } else {
  9192. *buf = dp;
  9193. break;
  9194. }
  9195. }
  9196. return num_headers;
  9197. }
  9198. struct mg_http_method_info {
  9199. const char *name;
  9200. int request_has_body;
  9201. int response_has_body;
  9202. int is_safe;
  9203. int is_idempotent;
  9204. int is_cacheable;
  9205. };
  9206. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9207. static const struct mg_http_method_info http_methods[] = {
  9208. /* HTTP (RFC 2616) */
  9209. {"GET", 0, 1, 1, 1, 1},
  9210. {"POST", 1, 1, 0, 0, 0},
  9211. {"PUT", 1, 0, 0, 1, 0},
  9212. {"DELETE", 0, 0, 0, 1, 0},
  9213. {"HEAD", 0, 0, 1, 1, 1},
  9214. {"OPTIONS", 0, 0, 1, 1, 0},
  9215. {"CONNECT", 1, 1, 0, 0, 0},
  9216. /* TRACE method (RFC 2616) is not supported for security reasons */
  9217. /* PATCH method (RFC 5789) */
  9218. {"PATCH", 1, 0, 0, 0, 0},
  9219. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9220. /* WEBDAV (RFC 2518) */
  9221. {"PROPFIND", 0, 1, 1, 1, 0},
  9222. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9223. * Some PROPFIND results MAY be cached, with care,
  9224. * as there is no cache validation mechanism for
  9225. * most properties. This method is both safe and
  9226. * idempotent (see Section 9.1 of [RFC2616]). */
  9227. {"MKCOL", 0, 0, 0, 1, 0},
  9228. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9229. * When MKCOL is invoked without a request body,
  9230. * the newly created collection SHOULD have no
  9231. * members. A MKCOL request message may contain
  9232. * a message body. The precise behavior of a MKCOL
  9233. * request when the body is present is undefined,
  9234. * ... ==> We do not support MKCOL with body data.
  9235. * This method is idempotent, but not safe (see
  9236. * Section 9.1 of [RFC2616]). Responses to this
  9237. * method MUST NOT be cached. */
  9238. /* Unsupported WEBDAV Methods: */
  9239. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9240. /* + 11 methods from RFC 3253 */
  9241. /* ORDERPATCH (RFC 3648) */
  9242. /* ACL (RFC 3744) */
  9243. /* SEARCH (RFC 5323) */
  9244. /* + MicroSoft extensions
  9245. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9246. /* REPORT method (RFC 3253) */
  9247. {"REPORT", 1, 1, 1, 1, 1},
  9248. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9249. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9250. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9251. * to be useful for REST in case a "GET request with body" is
  9252. * required. */
  9253. {NULL, 0, 0, 0, 0, 0}
  9254. /* end of list */
  9255. };
  9256. static const struct mg_http_method_info *
  9257. get_http_method_info(const char *method)
  9258. {
  9259. /* Check if the method is known to the server. The list of all known
  9260. * HTTP methods can be found here at
  9261. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9262. */
  9263. const struct mg_http_method_info *m = http_methods;
  9264. while (m->name) {
  9265. if (!strcmp(m->name, method)) {
  9266. return m;
  9267. }
  9268. m++;
  9269. }
  9270. return NULL;
  9271. }
  9272. static int
  9273. is_valid_http_method(const char *method)
  9274. {
  9275. return (get_http_method_info(method) != NULL);
  9276. }
  9277. /* Parse HTTP request, fill in mg_request_info structure.
  9278. * This function modifies the buffer by NUL-terminating
  9279. * HTTP request components, header names and header values.
  9280. * Parameters:
  9281. * buf (in/out): pointer to the HTTP header to parse and split
  9282. * len (in): length of HTTP header buffer
  9283. * re (out): parsed header as mg_request_info
  9284. * buf and ri must be valid pointers (not NULL), len>0.
  9285. * Returns <0 on error. */
  9286. static int
  9287. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9288. {
  9289. int request_length;
  9290. int init_skip = 0;
  9291. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9292. * remote_port */
  9293. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9294. NULL;
  9295. ri->num_headers = 0;
  9296. /* RFC says that all initial whitespaces should be ingored */
  9297. /* This included all leading \r and \n (isspace) */
  9298. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9299. while ((len > 0) && isspace((unsigned char)*buf)) {
  9300. buf++;
  9301. len--;
  9302. init_skip++;
  9303. }
  9304. if (len == 0) {
  9305. /* Incomplete request */
  9306. return 0;
  9307. }
  9308. /* Control characters are not allowed, including zero */
  9309. if (iscntrl((unsigned char)*buf)) {
  9310. return -1;
  9311. }
  9312. /* Find end of HTTP header */
  9313. request_length = get_http_header_len(buf, len);
  9314. if (request_length <= 0) {
  9315. return request_length;
  9316. }
  9317. buf[request_length - 1] = '\0';
  9318. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9319. return -1;
  9320. }
  9321. /* The first word has to be the HTTP method */
  9322. ri->request_method = buf;
  9323. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9324. return -1;
  9325. }
  9326. /* Check for a valid http method */
  9327. if (!is_valid_http_method(ri->request_method)) {
  9328. return -1;
  9329. }
  9330. /* The second word is the URI */
  9331. ri->request_uri = buf;
  9332. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9333. return -1;
  9334. }
  9335. /* Next would be the HTTP version */
  9336. ri->http_version = buf;
  9337. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9338. return -1;
  9339. }
  9340. /* Check for a valid HTTP version key */
  9341. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9342. /* Invalid request */
  9343. return -1;
  9344. }
  9345. ri->http_version += 5;
  9346. /* Parse all HTTP headers */
  9347. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9348. if (ri->num_headers < 0) {
  9349. /* Error while parsing headers */
  9350. return -1;
  9351. }
  9352. return request_length + init_skip;
  9353. }
  9354. static int
  9355. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9356. {
  9357. int response_length;
  9358. int init_skip = 0;
  9359. char *tmp, *tmp2;
  9360. long l;
  9361. /* Initialize elements. */
  9362. ri->http_version = ri->status_text = NULL;
  9363. ri->num_headers = ri->status_code = 0;
  9364. /* RFC says that all initial whitespaces should be ingored */
  9365. /* This included all leading \r and \n (isspace) */
  9366. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9367. while ((len > 0) && isspace((unsigned char)*buf)) {
  9368. buf++;
  9369. len--;
  9370. init_skip++;
  9371. }
  9372. if (len == 0) {
  9373. /* Incomplete request */
  9374. return 0;
  9375. }
  9376. /* Control characters are not allowed, including zero */
  9377. if (iscntrl((unsigned char)*buf)) {
  9378. return -1;
  9379. }
  9380. /* Find end of HTTP header */
  9381. response_length = get_http_header_len(buf, len);
  9382. if (response_length <= 0) {
  9383. return response_length;
  9384. }
  9385. buf[response_length - 1] = '\0';
  9386. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9387. return -1;
  9388. }
  9389. /* The first word is the HTTP version */
  9390. /* Check for a valid HTTP version key */
  9391. if (strncmp(buf, "HTTP/", 5) != 0) {
  9392. /* Invalid request */
  9393. return -1;
  9394. }
  9395. buf += 5;
  9396. if (!isgraph((unsigned char)buf[0])) {
  9397. /* Invalid request */
  9398. return -1;
  9399. }
  9400. ri->http_version = buf;
  9401. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9402. return -1;
  9403. }
  9404. /* The second word is the status as a number */
  9405. tmp = buf;
  9406. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9407. return -1;
  9408. }
  9409. l = strtol(tmp, &tmp2, 10);
  9410. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9411. /* Everything else but a 3 digit code is invalid */
  9412. return -1;
  9413. }
  9414. ri->status_code = (int)l;
  9415. /* The rest of the line is the status text */
  9416. ri->status_text = buf;
  9417. /* Find end of status text */
  9418. /* isgraph or isspace = isprint */
  9419. while (isprint((unsigned char)*buf)) {
  9420. buf++;
  9421. }
  9422. if ((*buf != '\r') && (*buf != '\n')) {
  9423. return -1;
  9424. }
  9425. /* Terminate string and forward buf to next line */
  9426. do {
  9427. *buf = 0;
  9428. buf++;
  9429. } while (isspace((unsigned char)*buf));
  9430. /* Parse all HTTP headers */
  9431. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9432. if (ri->num_headers < 0) {
  9433. /* Error while parsing headers */
  9434. return -1;
  9435. }
  9436. return response_length + init_skip;
  9437. }
  9438. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9439. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9440. * buffer (which marks the end of HTTP request). Buffer buf may already
  9441. * have some data. The length of the data is stored in nread.
  9442. * Upon every read operation, increase nread by the number of bytes read. */
  9443. static int
  9444. read_message(FILE *fp,
  9445. struct mg_connection *conn,
  9446. char *buf,
  9447. int bufsiz,
  9448. int *nread)
  9449. {
  9450. int request_len, n = 0;
  9451. struct timespec last_action_time;
  9452. double request_timeout;
  9453. if (!conn) {
  9454. return 0;
  9455. }
  9456. memset(&last_action_time, 0, sizeof(last_action_time));
  9457. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9458. /* value of request_timeout is in seconds, config in milliseconds */
  9459. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9460. } else {
  9461. request_timeout = -1.0;
  9462. }
  9463. if (conn->handled_requests > 0) {
  9464. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9465. request_timeout =
  9466. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9467. }
  9468. }
  9469. request_len = get_http_header_len(buf, *nread);
  9470. while (request_len == 0) {
  9471. /* Full request not yet received */
  9472. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9473. /* Server is to be stopped. */
  9474. return -1;
  9475. }
  9476. if (*nread >= bufsiz) {
  9477. /* Request too long */
  9478. return -2;
  9479. }
  9480. n = pull_inner(
  9481. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9482. if (n == -2) {
  9483. /* Receive error */
  9484. return -1;
  9485. }
  9486. /* update clock after every read request */
  9487. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9488. if (n > 0) {
  9489. *nread += n;
  9490. request_len = get_http_header_len(buf, *nread);
  9491. }
  9492. if ((request_len == 0) && (request_timeout >= 0)) {
  9493. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9494. > request_timeout) {
  9495. /* Timeout */
  9496. return -1;
  9497. }
  9498. }
  9499. }
  9500. return request_len;
  9501. }
  9502. #if !defined(NO_CGI) || !defined(NO_FILES)
  9503. static int
  9504. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9505. {
  9506. const char *expect;
  9507. char buf[MG_BUF_LEN];
  9508. int success = 0;
  9509. if (!conn) {
  9510. return 0;
  9511. }
  9512. expect = mg_get_header(conn, "Expect");
  9513. DEBUG_ASSERT(fp != NULL);
  9514. if (!fp) {
  9515. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9516. return 0;
  9517. }
  9518. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9519. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9520. */
  9521. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9522. } else {
  9523. if (expect != NULL) {
  9524. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9525. conn->status_code = 100;
  9526. } else {
  9527. conn->status_code = 200;
  9528. }
  9529. DEBUG_ASSERT(conn->consumed_content == 0);
  9530. if (conn->consumed_content != 0) {
  9531. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9532. return 0;
  9533. }
  9534. for (;;) {
  9535. int nread = mg_read(conn, buf, sizeof(buf));
  9536. if (nread <= 0) {
  9537. success = (nread == 0);
  9538. break;
  9539. }
  9540. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9541. break;
  9542. }
  9543. }
  9544. /* Each error code path in this function must send an error */
  9545. if (!success) {
  9546. /* NOTE: Maybe some data has already been sent. */
  9547. /* TODO (low): If some data has been sent, a correct error
  9548. * reply can no longer be sent, so just close the connection */
  9549. mg_send_http_error(conn, 500, "%s", "");
  9550. }
  9551. }
  9552. return success;
  9553. }
  9554. #endif
  9555. #if defined(USE_TIMERS)
  9556. #define TIMER_API static
  9557. #include "timer.inl"
  9558. #endif /* USE_TIMERS */
  9559. #if !defined(NO_CGI)
  9560. /* This structure helps to create an environment for the spawned CGI
  9561. * program.
  9562. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9563. * last element must be NULL.
  9564. * However, on Windows there is a requirement that all these
  9565. * VARIABLE=VALUE\0
  9566. * strings must reside in a contiguous buffer. The end of the buffer is
  9567. * marked by two '\0' characters.
  9568. * We satisfy both worlds: we create an envp array (which is vars), all
  9569. * entries are actually pointers inside buf. */
  9570. struct cgi_environment {
  9571. struct mg_connection *conn;
  9572. /* Data block */
  9573. char *buf; /* Environment buffer */
  9574. size_t buflen; /* Space available in buf */
  9575. size_t bufused; /* Space taken in buf */
  9576. /* Index block */
  9577. char **var; /* char **envp */
  9578. size_t varlen; /* Number of variables available in var */
  9579. size_t varused; /* Number of variables stored in var */
  9580. };
  9581. static void addenv(struct cgi_environment *env,
  9582. PRINTF_FORMAT_STRING(const char *fmt),
  9583. ...) PRINTF_ARGS(2, 3);
  9584. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9585. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9586. static void
  9587. addenv(struct cgi_environment *env, const char *fmt, ...)
  9588. {
  9589. size_t i, n, space;
  9590. int truncated = 0;
  9591. char *added;
  9592. va_list ap;
  9593. if ((env->varlen - env->varused) < 2) {
  9594. mg_cry_internal(env->conn,
  9595. "%s: Cannot register CGI variable [%s]",
  9596. __func__,
  9597. fmt);
  9598. return;
  9599. }
  9600. /* Calculate how much space is left in the buffer */
  9601. space = (env->buflen - env->bufused);
  9602. do {
  9603. /* Space for "\0\0" is always needed. */
  9604. if (space <= 2) {
  9605. /* Allocate new buffer */
  9606. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9607. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9608. if (!added) {
  9609. /* Out of memory */
  9610. mg_cry_internal(
  9611. env->conn,
  9612. "%s: Cannot allocate memory for CGI variable [%s]",
  9613. __func__,
  9614. fmt);
  9615. return;
  9616. }
  9617. /* Retarget pointers */
  9618. env->buf = added;
  9619. env->buflen = n;
  9620. for (i = 0, n = 0; i < env->varused; i++) {
  9621. env->var[i] = added + n;
  9622. n += strlen(added + n) + 1;
  9623. }
  9624. space = (env->buflen - env->bufused);
  9625. }
  9626. /* Make a pointer to the free space int the buffer */
  9627. added = env->buf + env->bufused;
  9628. /* Copy VARIABLE=VALUE\0 string into the free space */
  9629. va_start(ap, fmt);
  9630. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9631. va_end(ap);
  9632. /* Do not add truncated strings to the environment */
  9633. if (truncated) {
  9634. /* Reallocate the buffer */
  9635. space = 0;
  9636. }
  9637. } while (truncated);
  9638. /* Calculate number of bytes added to the environment */
  9639. n = strlen(added) + 1;
  9640. env->bufused += n;
  9641. /* Append a pointer to the added string into the envp array */
  9642. env->var[env->varused] = added;
  9643. env->varused++;
  9644. }
  9645. /* Return 0 on success, non-zero if an error occurs. */
  9646. static int
  9647. prepare_cgi_environment(struct mg_connection *conn,
  9648. const char *prog,
  9649. struct cgi_environment *env)
  9650. {
  9651. const char *s;
  9652. struct vec var_vec;
  9653. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9654. int i, truncated, uri_len;
  9655. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9656. return -1;
  9657. }
  9658. env->conn = conn;
  9659. env->buflen = CGI_ENVIRONMENT_SIZE;
  9660. env->bufused = 0;
  9661. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9662. if (env->buf == NULL) {
  9663. mg_cry_internal(conn,
  9664. "%s: Not enough memory for environmental buffer",
  9665. __func__);
  9666. return -1;
  9667. }
  9668. env->varlen = MAX_CGI_ENVIR_VARS;
  9669. env->varused = 0;
  9670. env->var =
  9671. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9672. if (env->var == NULL) {
  9673. mg_cry_internal(conn,
  9674. "%s: Not enough memory for environmental variables",
  9675. __func__);
  9676. mg_free(env->buf);
  9677. return -1;
  9678. }
  9679. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9680. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9681. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9682. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9683. /* Prepare the environment block */
  9684. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9685. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9686. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9687. #if defined(USE_IPV6)
  9688. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9689. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9690. } else
  9691. #endif
  9692. {
  9693. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9694. }
  9695. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9696. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9697. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9698. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9699. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9700. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9701. /* SCRIPT_NAME */
  9702. uri_len = (int)strlen(conn->request_info.local_uri);
  9703. if (conn->path_info == NULL) {
  9704. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9705. /* URI: /path_to_script/script.cgi */
  9706. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9707. } else {
  9708. /* URI: /path_to_script/ ... using index.cgi */
  9709. const char *index_file = strrchr(prog, '/');
  9710. if (index_file) {
  9711. addenv(env,
  9712. "SCRIPT_NAME=%s%s",
  9713. conn->request_info.local_uri,
  9714. index_file + 1);
  9715. }
  9716. }
  9717. } else {
  9718. /* URI: /path_to_script/script.cgi/path_info */
  9719. addenv(env,
  9720. "SCRIPT_NAME=%.*s",
  9721. uri_len - (int)strlen(conn->path_info),
  9722. conn->request_info.local_uri);
  9723. }
  9724. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9725. if (conn->path_info == NULL) {
  9726. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9727. } else {
  9728. addenv(env,
  9729. "PATH_TRANSLATED=%s%s",
  9730. conn->dom_ctx->config[DOCUMENT_ROOT],
  9731. conn->path_info);
  9732. }
  9733. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9734. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9735. addenv(env, "CONTENT_TYPE=%s", s);
  9736. }
  9737. if (conn->request_info.query_string != NULL) {
  9738. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9739. }
  9740. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9741. addenv(env, "CONTENT_LENGTH=%s", s);
  9742. }
  9743. if ((s = getenv("PATH")) != NULL) {
  9744. addenv(env, "PATH=%s", s);
  9745. }
  9746. if (conn->path_info != NULL) {
  9747. addenv(env, "PATH_INFO=%s", conn->path_info);
  9748. }
  9749. if (conn->status_code > 0) {
  9750. /* CGI error handler should show the status code */
  9751. addenv(env, "STATUS=%d", conn->status_code);
  9752. }
  9753. #if defined(_WIN32)
  9754. if ((s = getenv("COMSPEC")) != NULL) {
  9755. addenv(env, "COMSPEC=%s", s);
  9756. }
  9757. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9758. addenv(env, "SYSTEMROOT=%s", s);
  9759. }
  9760. if ((s = getenv("SystemDrive")) != NULL) {
  9761. addenv(env, "SystemDrive=%s", s);
  9762. }
  9763. if ((s = getenv("ProgramFiles")) != NULL) {
  9764. addenv(env, "ProgramFiles=%s", s);
  9765. }
  9766. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9767. addenv(env, "ProgramFiles(x86)=%s", s);
  9768. }
  9769. #else
  9770. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9771. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9772. }
  9773. #endif /* _WIN32 */
  9774. if ((s = getenv("PERLLIB")) != NULL) {
  9775. addenv(env, "PERLLIB=%s", s);
  9776. }
  9777. if (conn->request_info.remote_user != NULL) {
  9778. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9779. addenv(env, "%s", "AUTH_TYPE=Digest");
  9780. }
  9781. /* Add all headers as HTTP_* variables */
  9782. for (i = 0; i < conn->request_info.num_headers; i++) {
  9783. (void)mg_snprintf(conn,
  9784. &truncated,
  9785. http_var_name,
  9786. sizeof(http_var_name),
  9787. "HTTP_%s",
  9788. conn->request_info.http_headers[i].name);
  9789. if (truncated) {
  9790. mg_cry_internal(conn,
  9791. "%s: HTTP header variable too long [%s]",
  9792. __func__,
  9793. conn->request_info.http_headers[i].name);
  9794. continue;
  9795. }
  9796. /* Convert variable name into uppercase, and change - to _ */
  9797. for (p = http_var_name; *p != '\0'; p++) {
  9798. if (*p == '-') {
  9799. *p = '_';
  9800. }
  9801. *p = (char)toupper((unsigned char)*p);
  9802. }
  9803. addenv(env,
  9804. "%s=%s",
  9805. http_var_name,
  9806. conn->request_info.http_headers[i].value);
  9807. }
  9808. /* Add user-specified variables */
  9809. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9810. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9811. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9812. }
  9813. env->var[env->varused] = NULL;
  9814. env->buf[env->bufused] = '\0';
  9815. return 0;
  9816. }
  9817. /* Data for CGI process control: PID and number of references */
  9818. struct process_control_data {
  9819. pid_t pid;
  9820. int references;
  9821. };
  9822. static int
  9823. abort_process(void *data)
  9824. {
  9825. /* Waitpid checks for child status and won't work for a pid that does
  9826. * not identify a child of the current process. Thus, if the pid is
  9827. * reused, we will not affect a different process. */
  9828. struct process_control_data *proc = (struct process_control_data *)data;
  9829. int status = 0;
  9830. int refs;
  9831. pid_t ret_pid;
  9832. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9833. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9834. /* Stop child process */
  9835. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9836. kill(proc->pid, SIGABRT);
  9837. /* Wait until process is terminated (don't leave zombies) */
  9838. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9839. ;
  9840. } else {
  9841. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9842. }
  9843. /* Dec reference counter */
  9844. refs = mg_atomic_dec(&proc->references);
  9845. if (refs == 0) {
  9846. /* no more references - free data */
  9847. mg_free(data);
  9848. }
  9849. return 0;
  9850. }
  9851. /* Local (static) function assumes all arguments are valid. */
  9852. static void
  9853. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9854. {
  9855. char *buf;
  9856. size_t buflen;
  9857. int headers_len, data_len, i, truncated;
  9858. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9859. const char *status, *status_text, *connection_state;
  9860. char *pbuf, dir[PATH_MAX], *p;
  9861. struct mg_request_info ri;
  9862. struct cgi_environment blk;
  9863. FILE *in = NULL, *out = NULL, *err = NULL;
  9864. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9865. pid_t pid = (pid_t)-1;
  9866. struct process_control_data *proc = NULL;
  9867. #if defined(USE_TIMERS)
  9868. double cgi_timeout = -1.0;
  9869. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9870. /* Get timeout in seconds */
  9871. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9872. }
  9873. #endif
  9874. buf = NULL;
  9875. buflen = conn->phys_ctx->max_request_size;
  9876. i = prepare_cgi_environment(conn, prog, &blk);
  9877. if (i != 0) {
  9878. blk.buf = NULL;
  9879. blk.var = NULL;
  9880. goto done;
  9881. }
  9882. /* CGI must be executed in its own directory. 'dir' must point to the
  9883. * directory containing executable program, 'p' must point to the
  9884. * executable program name relative to 'dir'. */
  9885. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9886. if (truncated) {
  9887. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9888. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9889. goto done;
  9890. }
  9891. if ((p = strrchr(dir, '/')) != NULL) {
  9892. *p++ = '\0';
  9893. } else {
  9894. dir[0] = '.';
  9895. dir[1] = '\0';
  9896. p = (char *)prog;
  9897. }
  9898. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9899. status = strerror(ERRNO);
  9900. mg_cry_internal(
  9901. conn,
  9902. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9903. prog,
  9904. status);
  9905. mg_send_http_error(conn,
  9906. 500,
  9907. "Error: Cannot create CGI pipe: %s",
  9908. status);
  9909. goto done;
  9910. }
  9911. proc = (struct process_control_data *)
  9912. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9913. if (proc == NULL) {
  9914. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9915. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9916. goto done;
  9917. }
  9918. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9919. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9920. if (pid == (pid_t)-1) {
  9921. status = strerror(ERRNO);
  9922. mg_cry_internal(
  9923. conn,
  9924. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9925. prog,
  9926. status);
  9927. mg_send_http_error(conn,
  9928. 500,
  9929. "Error: Cannot spawn CGI process [%s]: %s",
  9930. prog,
  9931. status);
  9932. mg_free(proc);
  9933. proc = NULL;
  9934. goto done;
  9935. }
  9936. /* Store data in shared process_control_data */
  9937. proc->pid = pid;
  9938. proc->references = 1;
  9939. #if defined(USE_TIMERS)
  9940. if (cgi_timeout > 0.0) {
  9941. proc->references = 2;
  9942. // Start a timer for CGI
  9943. timer_add(conn->phys_ctx,
  9944. cgi_timeout /* in seconds */,
  9945. 0.0,
  9946. 1,
  9947. abort_process,
  9948. (void *)proc);
  9949. }
  9950. #endif
  9951. /* Parent closes only one side of the pipes.
  9952. * If we don't mark them as closed, close() attempt before
  9953. * return from this function throws an exception on Windows.
  9954. * Windows does not like when closed descriptor is closed again. */
  9955. (void)close(fdin[0]);
  9956. (void)close(fdout[1]);
  9957. (void)close(fderr[1]);
  9958. fdin[0] = fdout[1] = fderr[1] = -1;
  9959. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9960. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9961. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9962. status = strerror(ERRNO);
  9963. mg_cry_internal(conn,
  9964. "Error: CGI program \"%s\": Can not open fd: %s",
  9965. prog,
  9966. status);
  9967. mg_send_http_error(conn,
  9968. 500,
  9969. "Error: CGI can not open fd\nfdopen: %s",
  9970. status);
  9971. goto done;
  9972. }
  9973. setbuf(in, NULL);
  9974. setbuf(out, NULL);
  9975. setbuf(err, NULL);
  9976. fout.access.fp = out;
  9977. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9978. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9979. conn->content_len);
  9980. /* This is a POST/PUT request, or another request with body data. */
  9981. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9982. /* Error sending the body data */
  9983. mg_cry_internal(
  9984. conn,
  9985. "Error: CGI program \"%s\": Forward body data failed",
  9986. prog);
  9987. goto done;
  9988. }
  9989. }
  9990. /* Close so child gets an EOF. */
  9991. fclose(in);
  9992. in = NULL;
  9993. fdin[1] = -1;
  9994. /* Now read CGI reply into a buffer. We need to set correct
  9995. * status code, thus we need to see all HTTP headers first.
  9996. * Do not send anything back to client, until we buffer in all
  9997. * HTTP headers. */
  9998. data_len = 0;
  9999. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10000. if (buf == NULL) {
  10001. mg_send_http_error(conn,
  10002. 500,
  10003. "Error: Not enough memory for CGI buffer (%u bytes)",
  10004. (unsigned int)buflen);
  10005. mg_cry_internal(
  10006. conn,
  10007. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10008. "bytes)",
  10009. prog,
  10010. (unsigned int)buflen);
  10011. goto done;
  10012. }
  10013. DEBUG_TRACE("CGI: %s", "wait for response");
  10014. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10015. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10016. if (headers_len <= 0) {
  10017. /* Could not parse the CGI response. Check if some error message on
  10018. * stderr. */
  10019. i = pull_all(err, conn, buf, (int)buflen);
  10020. if (i > 0) {
  10021. /* CGI program explicitly sent an error */
  10022. /* Write the error message to the internal log */
  10023. mg_cry_internal(conn,
  10024. "Error: CGI program \"%s\" sent error "
  10025. "message: [%.*s]",
  10026. prog,
  10027. i,
  10028. buf);
  10029. /* Don't send the error message back to the client */
  10030. mg_send_http_error(conn,
  10031. 500,
  10032. "Error: CGI program \"%s\" failed.",
  10033. prog);
  10034. } else {
  10035. /* CGI program did not explicitly send an error, but a broken
  10036. * respon header */
  10037. mg_cry_internal(conn,
  10038. "Error: CGI program sent malformed or too big "
  10039. "(>%u bytes) HTTP headers: [%.*s]",
  10040. (unsigned)buflen,
  10041. data_len,
  10042. buf);
  10043. mg_send_http_error(conn,
  10044. 500,
  10045. "Error: CGI program sent malformed or too big "
  10046. "(>%u bytes) HTTP headers: [%.*s]",
  10047. (unsigned)buflen,
  10048. data_len,
  10049. buf);
  10050. }
  10051. /* in both cases, abort processing CGI */
  10052. goto done;
  10053. }
  10054. pbuf = buf;
  10055. buf[headers_len - 1] = '\0';
  10056. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10057. /* Make up and send the status line */
  10058. status_text = "OK";
  10059. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10060. != NULL) {
  10061. conn->status_code = atoi(status);
  10062. status_text = status;
  10063. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10064. status_text++;
  10065. }
  10066. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10067. != NULL) {
  10068. conn->status_code = 307;
  10069. } else {
  10070. conn->status_code = 200;
  10071. }
  10072. connection_state =
  10073. get_header(ri.http_headers, ri.num_headers, "Connection");
  10074. if (!header_has_option(connection_state, "keep-alive")) {
  10075. conn->must_close = 1;
  10076. }
  10077. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10078. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10079. /* Send headers */
  10080. for (i = 0; i < ri.num_headers; i++) {
  10081. DEBUG_TRACE("CGI header: %s: %s",
  10082. ri.http_headers[i].name,
  10083. ri.http_headers[i].value);
  10084. mg_printf(conn,
  10085. "%s: %s\r\n",
  10086. ri.http_headers[i].name,
  10087. ri.http_headers[i].value);
  10088. }
  10089. mg_write(conn, "\r\n", 2);
  10090. /* Send chunk of data that may have been read after the headers */
  10091. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10092. /* Read the rest of CGI output and send to the client */
  10093. DEBUG_TRACE("CGI: %s", "forward all data");
  10094. send_file_data(conn, &fout, 0, INT64_MAX);
  10095. DEBUG_TRACE("CGI: %s", "all data sent");
  10096. done:
  10097. mg_free(blk.var);
  10098. mg_free(blk.buf);
  10099. if (pid != (pid_t)-1) {
  10100. abort_process((void *)proc);
  10101. }
  10102. if (fdin[0] != -1) {
  10103. close(fdin[0]);
  10104. }
  10105. if (fdout[1] != -1) {
  10106. close(fdout[1]);
  10107. }
  10108. if (fderr[1] != -1) {
  10109. close(fderr[1]);
  10110. }
  10111. if (in != NULL) {
  10112. fclose(in);
  10113. } else if (fdin[1] != -1) {
  10114. close(fdin[1]);
  10115. }
  10116. if (out != NULL) {
  10117. fclose(out);
  10118. } else if (fdout[0] != -1) {
  10119. close(fdout[0]);
  10120. }
  10121. if (err != NULL) {
  10122. fclose(err);
  10123. } else if (fderr[0] != -1) {
  10124. close(fderr[0]);
  10125. }
  10126. mg_free(buf);
  10127. }
  10128. #endif /* !NO_CGI */
  10129. #if !defined(NO_FILES)
  10130. static void
  10131. mkcol(struct mg_connection *conn, const char *path)
  10132. {
  10133. int rc, body_len;
  10134. struct de de;
  10135. char date[64];
  10136. time_t curtime = time(NULL);
  10137. if (conn == NULL) {
  10138. return;
  10139. }
  10140. /* TODO (mid): Check the mg_send_http_error situations in this function
  10141. */
  10142. memset(&de.file, 0, sizeof(de.file));
  10143. if (!mg_stat(conn, path, &de.file)) {
  10144. mg_cry_internal(conn,
  10145. "%s: mg_stat(%s) failed: %s",
  10146. __func__,
  10147. path,
  10148. strerror(ERRNO));
  10149. }
  10150. if (de.file.last_modified) {
  10151. /* TODO (mid): This check does not seem to make any sense ! */
  10152. /* TODO (mid): Add a webdav unit test first, before changing
  10153. * anything here. */
  10154. mg_send_http_error(
  10155. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10156. return;
  10157. }
  10158. body_len = conn->data_len - conn->request_len;
  10159. if (body_len > 0) {
  10160. mg_send_http_error(
  10161. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10162. return;
  10163. }
  10164. rc = mg_mkdir(conn, path, 0755);
  10165. if (rc == 0) {
  10166. conn->status_code = 201;
  10167. gmt_time_string(date, sizeof(date), &curtime);
  10168. mg_printf(conn,
  10169. "HTTP/1.1 %d Created\r\n"
  10170. "Date: %s\r\n",
  10171. conn->status_code,
  10172. date);
  10173. send_static_cache_header(conn);
  10174. send_additional_header(conn);
  10175. mg_printf(conn,
  10176. "Content-Length: 0\r\n"
  10177. "Connection: %s\r\n\r\n",
  10178. suggest_connection_header(conn));
  10179. } else {
  10180. if (errno == EEXIST) {
  10181. mg_send_http_error(
  10182. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10183. } else if (errno == EACCES) {
  10184. mg_send_http_error(
  10185. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10186. } else if (errno == ENOENT) {
  10187. mg_send_http_error(
  10188. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10189. } else {
  10190. mg_send_http_error(
  10191. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10192. }
  10193. }
  10194. }
  10195. static void
  10196. put_file(struct mg_connection *conn, const char *path)
  10197. {
  10198. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10199. const char *range;
  10200. int64_t r1, r2;
  10201. int rc;
  10202. char date[64];
  10203. time_t curtime = time(NULL);
  10204. if (conn == NULL) {
  10205. return;
  10206. }
  10207. if (mg_stat(conn, path, &file.stat)) {
  10208. /* File already exists */
  10209. conn->status_code = 200;
  10210. if (file.stat.is_directory) {
  10211. /* This is an already existing directory,
  10212. * so there is nothing to do for the server. */
  10213. rc = 0;
  10214. } else {
  10215. /* File exists and is not a directory. */
  10216. /* Can it be replaced? */
  10217. #if defined(MG_USE_OPEN_FILE)
  10218. if (file.access.membuf != NULL) {
  10219. /* This is an "in-memory" file, that can not be replaced */
  10220. mg_send_http_error(conn,
  10221. 405,
  10222. "Error: Put not possible\nReplacing %s "
  10223. "is not supported",
  10224. path);
  10225. return;
  10226. }
  10227. #endif
  10228. /* Check if the server may write this file */
  10229. if (access(path, W_OK) == 0) {
  10230. /* Access granted */
  10231. rc = 1;
  10232. } else {
  10233. mg_send_http_error(
  10234. conn,
  10235. 403,
  10236. "Error: Put not possible\nReplacing %s is not allowed",
  10237. path);
  10238. return;
  10239. }
  10240. }
  10241. } else {
  10242. /* File should be created */
  10243. conn->status_code = 201;
  10244. rc = put_dir(conn, path);
  10245. }
  10246. if (rc == 0) {
  10247. /* put_dir returns 0 if path is a directory */
  10248. gmt_time_string(date, sizeof(date), &curtime);
  10249. mg_printf(conn,
  10250. "HTTP/1.1 %d %s\r\n",
  10251. conn->status_code,
  10252. mg_get_response_code_text(NULL, conn->status_code));
  10253. send_no_cache_header(conn);
  10254. send_additional_header(conn);
  10255. mg_printf(conn,
  10256. "Date: %s\r\n"
  10257. "Content-Length: 0\r\n"
  10258. "Connection: %s\r\n\r\n",
  10259. date,
  10260. suggest_connection_header(conn));
  10261. /* Request to create a directory has been fulfilled successfully.
  10262. * No need to put a file. */
  10263. return;
  10264. }
  10265. if (rc == -1) {
  10266. /* put_dir returns -1 if the path is too long */
  10267. mg_send_http_error(conn,
  10268. 414,
  10269. "Error: Path too long\nput_dir(%s): %s",
  10270. path,
  10271. strerror(ERRNO));
  10272. return;
  10273. }
  10274. if (rc == -2) {
  10275. /* put_dir returns -2 if the directory can not be created */
  10276. mg_send_http_error(conn,
  10277. 500,
  10278. "Error: Can not create directory\nput_dir(%s): %s",
  10279. path,
  10280. strerror(ERRNO));
  10281. return;
  10282. }
  10283. /* A file should be created or overwritten. */
  10284. /* Currently CivetWeb does not nead read+write access. */
  10285. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10286. || file.access.fp == NULL) {
  10287. (void)mg_fclose(&file.access);
  10288. mg_send_http_error(conn,
  10289. 500,
  10290. "Error: Can not create file\nfopen(%s): %s",
  10291. path,
  10292. strerror(ERRNO));
  10293. return;
  10294. }
  10295. fclose_on_exec(&file.access, conn);
  10296. range = mg_get_header(conn, "Content-Range");
  10297. r1 = r2 = 0;
  10298. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10299. conn->status_code = 206; /* Partial content */
  10300. fseeko(file.access.fp, r1, SEEK_SET);
  10301. }
  10302. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10303. /* forward_body_data failed.
  10304. * The error code has already been sent to the client,
  10305. * and conn->status_code is already set. */
  10306. (void)mg_fclose(&file.access);
  10307. return;
  10308. }
  10309. if (mg_fclose(&file.access) != 0) {
  10310. /* fclose failed. This might have different reasons, but a likely
  10311. * one is "no space on disk", http 507. */
  10312. conn->status_code = 507;
  10313. }
  10314. gmt_time_string(date, sizeof(date), &curtime);
  10315. mg_printf(conn,
  10316. "HTTP/1.1 %d %s\r\n",
  10317. conn->status_code,
  10318. mg_get_response_code_text(NULL, conn->status_code));
  10319. send_no_cache_header(conn);
  10320. send_additional_header(conn);
  10321. mg_printf(conn,
  10322. "Date: %s\r\n"
  10323. "Content-Length: 0\r\n"
  10324. "Connection: %s\r\n\r\n",
  10325. date,
  10326. suggest_connection_header(conn));
  10327. }
  10328. static void
  10329. delete_file(struct mg_connection *conn, const char *path)
  10330. {
  10331. struct de de;
  10332. memset(&de.file, 0, sizeof(de.file));
  10333. if (!mg_stat(conn, path, &de.file)) {
  10334. /* mg_stat returns 0 if the file does not exist */
  10335. mg_send_http_error(conn,
  10336. 404,
  10337. "Error: Cannot delete file\nFile %s not found",
  10338. path);
  10339. return;
  10340. }
  10341. #if 0 /* Ignore if a file in memory is inside a folder */
  10342. if (de.access.membuf != NULL) {
  10343. /* the file is cached in memory */
  10344. mg_send_http_error(
  10345. conn,
  10346. 405,
  10347. "Error: Delete not possible\nDeleting %s is not supported",
  10348. path);
  10349. return;
  10350. }
  10351. #endif
  10352. if (de.file.is_directory) {
  10353. if (remove_directory(conn, path)) {
  10354. /* Delete is successful: Return 204 without content. */
  10355. mg_send_http_error(conn, 204, "%s", "");
  10356. } else {
  10357. /* Delete is not successful: Return 500 (Server error). */
  10358. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10359. }
  10360. return;
  10361. }
  10362. /* This is an existing file (not a directory).
  10363. * Check if write permission is granted. */
  10364. if (access(path, W_OK) != 0) {
  10365. /* File is read only */
  10366. mg_send_http_error(
  10367. conn,
  10368. 403,
  10369. "Error: Delete not possible\nDeleting %s is not allowed",
  10370. path);
  10371. return;
  10372. }
  10373. /* Try to delete it. */
  10374. if (mg_remove(conn, path) == 0) {
  10375. /* Delete was successful: Return 204 without content. */
  10376. mg_send_http_error(conn, 204, "%s", "");
  10377. } else {
  10378. /* Delete not successful (file locked). */
  10379. mg_send_http_error(conn,
  10380. 423,
  10381. "Error: Cannot delete file\nremove(%s): %s",
  10382. path,
  10383. strerror(ERRNO));
  10384. }
  10385. }
  10386. #endif /* !NO_FILES */
  10387. #if !defined(NO_FILESYSTEMS)
  10388. static void
  10389. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10390. static void
  10391. do_ssi_include(struct mg_connection *conn,
  10392. const char *ssi,
  10393. char *tag,
  10394. int include_level)
  10395. {
  10396. char file_name[MG_BUF_LEN], path[512], *p;
  10397. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10398. size_t len;
  10399. int truncated = 0;
  10400. if (conn == NULL) {
  10401. return;
  10402. }
  10403. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10404. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10405. * always < MG_BUF_LEN. */
  10406. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10407. /* File name is relative to the webserver root */
  10408. file_name[511] = 0;
  10409. (void)mg_snprintf(conn,
  10410. &truncated,
  10411. path,
  10412. sizeof(path),
  10413. "%s/%s",
  10414. conn->dom_ctx->config[DOCUMENT_ROOT],
  10415. file_name);
  10416. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10417. /* File name is relative to the webserver working directory
  10418. * or it is absolute system path */
  10419. file_name[511] = 0;
  10420. (void)
  10421. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10422. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10423. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10424. /* File name is relative to the currect document */
  10425. file_name[511] = 0;
  10426. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10427. if (!truncated) {
  10428. if ((p = strrchr(path, '/')) != NULL) {
  10429. p[1] = '\0';
  10430. }
  10431. len = strlen(path);
  10432. (void)mg_snprintf(conn,
  10433. &truncated,
  10434. path + len,
  10435. sizeof(path) - len,
  10436. "%s",
  10437. file_name);
  10438. }
  10439. } else {
  10440. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10441. return;
  10442. }
  10443. if (truncated) {
  10444. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10445. return;
  10446. }
  10447. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10448. mg_cry_internal(conn,
  10449. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10450. tag,
  10451. path,
  10452. strerror(ERRNO));
  10453. } else {
  10454. fclose_on_exec(&file.access, conn);
  10455. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10456. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10457. path)
  10458. > 0) {
  10459. send_ssi_file(conn, path, &file, include_level + 1);
  10460. } else {
  10461. send_file_data(conn, &file, 0, INT64_MAX);
  10462. }
  10463. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10464. }
  10465. }
  10466. #if !defined(NO_POPEN)
  10467. static void
  10468. do_ssi_exec(struct mg_connection *conn, char *tag)
  10469. {
  10470. char cmd[1024] = "";
  10471. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10472. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10473. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10474. } else {
  10475. cmd[1023] = 0;
  10476. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10477. mg_cry_internal(conn,
  10478. "Cannot SSI #exec: [%s]: %s",
  10479. cmd,
  10480. strerror(ERRNO));
  10481. } else {
  10482. send_file_data(conn, &file, 0, INT64_MAX);
  10483. pclose(file.access.fp);
  10484. }
  10485. }
  10486. }
  10487. #endif /* !NO_POPEN */
  10488. static int
  10489. mg_fgetc(struct mg_file *filep, int offset)
  10490. {
  10491. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10492. if (filep == NULL) {
  10493. return EOF;
  10494. }
  10495. #if defined(MG_USE_OPEN_FILE)
  10496. if ((filep->access.membuf != NULL) && (offset >= 0)
  10497. && (((unsigned int)(offset)) < filep->stat.size)) {
  10498. return ((const unsigned char *)filep->access.membuf)[offset];
  10499. } else /* else block below */
  10500. #endif
  10501. if (filep->access.fp != NULL) {
  10502. return fgetc(filep->access.fp);
  10503. } else {
  10504. return EOF;
  10505. }
  10506. }
  10507. static void
  10508. send_ssi_file(struct mg_connection *conn,
  10509. const char *path,
  10510. struct mg_file *filep,
  10511. int include_level)
  10512. {
  10513. char buf[MG_BUF_LEN];
  10514. int ch, offset, len, in_tag, in_ssi_tag;
  10515. if (include_level > 10) {
  10516. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10517. return;
  10518. }
  10519. in_tag = in_ssi_tag = len = offset = 0;
  10520. /* Read file, byte by byte, and look for SSI include tags */
  10521. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10522. if (in_tag) {
  10523. /* We are in a tag, either SSI tag or html tag */
  10524. if (ch == '>') {
  10525. /* Tag is closing */
  10526. buf[len++] = '>';
  10527. if (in_ssi_tag) {
  10528. /* Handle SSI tag */
  10529. buf[len] = 0;
  10530. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10531. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10532. #if !defined(NO_POPEN)
  10533. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10534. do_ssi_exec(conn, buf + 9);
  10535. #endif /* !NO_POPEN */
  10536. } else {
  10537. mg_cry_internal(conn,
  10538. "%s: unknown SSI "
  10539. "command: \"%s\"",
  10540. path,
  10541. buf);
  10542. }
  10543. len = 0;
  10544. in_ssi_tag = in_tag = 0;
  10545. } else {
  10546. /* Not an SSI tag */
  10547. /* Flush buffer */
  10548. (void)mg_write(conn, buf, (size_t)len);
  10549. len = 0;
  10550. in_tag = 0;
  10551. }
  10552. } else {
  10553. /* Tag is still open */
  10554. buf[len++] = (char)(ch & 0xff);
  10555. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10556. /* All SSI tags start with <!--# */
  10557. in_ssi_tag = 1;
  10558. }
  10559. if ((len + 2) > (int)sizeof(buf)) {
  10560. /* Tag to long for buffer */
  10561. mg_cry_internal(conn, "%s: tag is too large", path);
  10562. return;
  10563. }
  10564. }
  10565. } else {
  10566. /* We are not in a tag yet. */
  10567. if (ch == '<') {
  10568. /* Tag is opening */
  10569. in_tag = 1;
  10570. if (len > 0) {
  10571. /* Flush current buffer.
  10572. * Buffer is filled with "len" bytes. */
  10573. (void)mg_write(conn, buf, (size_t)len);
  10574. }
  10575. /* Store the < */
  10576. len = 1;
  10577. buf[0] = '<';
  10578. } else {
  10579. /* No Tag */
  10580. /* Add data to buffer */
  10581. buf[len++] = (char)(ch & 0xff);
  10582. /* Flush if buffer is full */
  10583. if (len == (int)sizeof(buf)) {
  10584. mg_write(conn, buf, (size_t)len);
  10585. len = 0;
  10586. }
  10587. }
  10588. }
  10589. }
  10590. /* Send the rest of buffered data */
  10591. if (len > 0) {
  10592. mg_write(conn, buf, (size_t)len);
  10593. }
  10594. }
  10595. static void
  10596. handle_ssi_file_request(struct mg_connection *conn,
  10597. const char *path,
  10598. struct mg_file *filep)
  10599. {
  10600. char date[64];
  10601. time_t curtime = time(NULL);
  10602. const char *cors_orig_cfg;
  10603. const char *cors1, *cors2, *cors3;
  10604. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10605. return;
  10606. }
  10607. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10608. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10609. /* Cross-origin resource sharing (CORS). */
  10610. cors1 = "Access-Control-Allow-Origin: ";
  10611. cors2 = cors_orig_cfg;
  10612. cors3 = "\r\n";
  10613. } else {
  10614. cors1 = cors2 = cors3 = "";
  10615. }
  10616. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10617. /* File exists (precondition for calling this function),
  10618. * but can not be opened by the server. */
  10619. mg_send_http_error(conn,
  10620. 500,
  10621. "Error: Cannot read file\nfopen(%s): %s",
  10622. path,
  10623. strerror(ERRNO));
  10624. } else {
  10625. conn->must_close = 1;
  10626. gmt_time_string(date, sizeof(date), &curtime);
  10627. fclose_on_exec(&filep->access, conn);
  10628. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10629. send_no_cache_header(conn);
  10630. send_additional_header(conn);
  10631. mg_printf(conn,
  10632. "%s%s%s"
  10633. "Date: %s\r\n"
  10634. "Content-Type: text/html\r\n"
  10635. "Connection: %s\r\n\r\n",
  10636. cors1,
  10637. cors2,
  10638. cors3,
  10639. date,
  10640. suggest_connection_header(conn));
  10641. send_ssi_file(conn, path, filep, 0);
  10642. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10643. }
  10644. }
  10645. #endif /* NO_FILESYSTEMS */
  10646. #if !defined(NO_FILES)
  10647. static void
  10648. send_options(struct mg_connection *conn)
  10649. {
  10650. char date[64];
  10651. time_t curtime = time(NULL);
  10652. if (!conn) {
  10653. return;
  10654. }
  10655. conn->status_code = 200;
  10656. conn->must_close = 1;
  10657. gmt_time_string(date, sizeof(date), &curtime);
  10658. /* We do not set a "Cache-Control" header here, but leave the default.
  10659. * Since browsers do not send an OPTIONS request, we can not test the
  10660. * effect anyway. */
  10661. mg_printf(conn,
  10662. "HTTP/1.1 200 OK\r\n"
  10663. "Date: %s\r\n"
  10664. "Connection: %s\r\n"
  10665. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10666. "PROPFIND, MKCOL\r\n"
  10667. "DAV: 1\r\n",
  10668. date,
  10669. suggest_connection_header(conn));
  10670. send_additional_header(conn);
  10671. mg_printf(conn, "\r\n");
  10672. }
  10673. /* Writes PROPFIND properties for a collection element */
  10674. static int
  10675. print_props(struct mg_connection *conn,
  10676. const char *uri,
  10677. const char *name,
  10678. struct mg_file_stat *filep)
  10679. {
  10680. size_t href_size, i, j;
  10681. int len;
  10682. char *href, mtime[64];
  10683. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10684. return 0;
  10685. }
  10686. /* Estimate worst case size for encoding */
  10687. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10688. href = (char *)mg_malloc(href_size);
  10689. if (href == NULL) {
  10690. return 0;
  10691. }
  10692. len = mg_url_encode(uri, href, href_size);
  10693. if (len >= 0) {
  10694. /* Append an extra string */
  10695. mg_url_encode(name, href + len, href_size - (size_t)len);
  10696. }
  10697. /* Directory separator should be preserved. */
  10698. for (i = j = 0; href[i]; j++) {
  10699. if (!strncmp(href + i, "%2f", 3)) {
  10700. href[j] = '/';
  10701. i += 3;
  10702. } else {
  10703. href[j] = href[i++];
  10704. }
  10705. }
  10706. href[j] = '\0';
  10707. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10708. mg_printf(conn,
  10709. "<d:response>"
  10710. "<d:href>%s</d:href>"
  10711. "<d:propstat>"
  10712. "<d:prop>"
  10713. "<d:resourcetype>%s</d:resourcetype>"
  10714. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10715. "<d:getlastmodified>%s</d:getlastmodified>"
  10716. "</d:prop>"
  10717. "<d:status>HTTP/1.1 200 OK</d:status>"
  10718. "</d:propstat>"
  10719. "</d:response>\n",
  10720. href,
  10721. filep->is_directory ? "<d:collection/>" : "",
  10722. filep->size,
  10723. mtime);
  10724. mg_free(href);
  10725. return 1;
  10726. }
  10727. static int
  10728. print_dav_dir_entry(struct de *de, void *data)
  10729. {
  10730. struct mg_connection *conn = (struct mg_connection *)data;
  10731. if (!de || !conn
  10732. || !print_props(
  10733. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10734. /* stop scan */
  10735. return 1;
  10736. }
  10737. return 0;
  10738. }
  10739. static void
  10740. handle_propfind(struct mg_connection *conn,
  10741. const char *path,
  10742. struct mg_file_stat *filep)
  10743. {
  10744. const char *depth = mg_get_header(conn, "Depth");
  10745. char date[64];
  10746. time_t curtime = time(NULL);
  10747. gmt_time_string(date, sizeof(date), &curtime);
  10748. if (!conn || !path || !filep || !conn->dom_ctx) {
  10749. return;
  10750. }
  10751. conn->must_close = 1;
  10752. conn->status_code = 207;
  10753. mg_printf(conn,
  10754. "HTTP/1.1 207 Multi-Status\r\n"
  10755. "Date: %s\r\n",
  10756. date);
  10757. send_static_cache_header(conn);
  10758. send_additional_header(conn);
  10759. mg_printf(conn,
  10760. "Connection: %s\r\n"
  10761. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10762. suggest_connection_header(conn));
  10763. mg_printf(conn,
  10764. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10765. "<d:multistatus xmlns:d='DAV:'>\n");
  10766. /* Print properties for the requested resource itself */
  10767. print_props(conn, conn->request_info.local_uri, "", filep);
  10768. /* If it is a directory, print directory entries too if Depth is not 0
  10769. */
  10770. if (filep->is_directory
  10771. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10772. "yes")
  10773. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10774. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10775. }
  10776. mg_printf(conn, "%s\n", "</d:multistatus>");
  10777. }
  10778. #endif
  10779. void
  10780. mg_lock_connection(struct mg_connection *conn)
  10781. {
  10782. if (conn) {
  10783. (void)pthread_mutex_lock(&conn->mutex);
  10784. }
  10785. }
  10786. void
  10787. mg_unlock_connection(struct mg_connection *conn)
  10788. {
  10789. if (conn) {
  10790. (void)pthread_mutex_unlock(&conn->mutex);
  10791. }
  10792. }
  10793. void
  10794. mg_lock_context(struct mg_context *ctx)
  10795. {
  10796. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10797. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10798. }
  10799. }
  10800. void
  10801. mg_unlock_context(struct mg_context *ctx)
  10802. {
  10803. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10804. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10805. }
  10806. }
  10807. #if defined(USE_LUA)
  10808. #include "mod_lua.inl"
  10809. #endif /* USE_LUA */
  10810. #if defined(USE_DUKTAPE)
  10811. #include "mod_duktape.inl"
  10812. #endif /* USE_DUKTAPE */
  10813. #if defined(USE_WEBSOCKET)
  10814. #if !defined(NO_SSL_DL)
  10815. #define SHA_API static
  10816. #include "sha1.inl"
  10817. #endif
  10818. static int
  10819. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10820. {
  10821. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10822. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10823. SHA_CTX sha_ctx;
  10824. int truncated;
  10825. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10826. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10827. if (truncated) {
  10828. conn->must_close = 1;
  10829. return 0;
  10830. }
  10831. DEBUG_TRACE("%s", "Send websocket handshake");
  10832. SHA1_Init(&sha_ctx);
  10833. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10834. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10835. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10836. mg_printf(conn,
  10837. "HTTP/1.1 101 Switching Protocols\r\n"
  10838. "Upgrade: websocket\r\n"
  10839. "Connection: Upgrade\r\n"
  10840. "Sec-WebSocket-Accept: %s\r\n",
  10841. b64_sha);
  10842. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10843. mg_printf(conn,
  10844. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10845. conn->request_info.acceptedWebSocketSubprotocol);
  10846. } else {
  10847. mg_printf(conn, "%s", "\r\n");
  10848. }
  10849. return 1;
  10850. }
  10851. #if !defined(MG_MAX_UNANSWERED_PING)
  10852. /* Configuration of the maximum number of websocket PINGs that might
  10853. * stay unanswered before the connection is considered broken.
  10854. * Note: The name of this define may still change (until it is
  10855. * defined as a compile parameter in a documentation).
  10856. */
  10857. #define MG_MAX_UNANSWERED_PING (5)
  10858. #endif
  10859. static void
  10860. read_websocket(struct mg_connection *conn,
  10861. mg_websocket_data_handler ws_data_handler,
  10862. void *callback_data)
  10863. {
  10864. /* Pointer to the beginning of the portion of the incoming websocket
  10865. * message queue.
  10866. * The original websocket upgrade request is never removed, so the queue
  10867. * begins after it. */
  10868. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10869. int n, error, exit_by_callback;
  10870. int ret;
  10871. /* body_len is the length of the entire queue in bytes
  10872. * len is the length of the current message
  10873. * data_len is the length of the current message's data payload
  10874. * header_len is the length of the current message's header */
  10875. size_t i, len, mask_len = 0, header_len, body_len;
  10876. uint64_t data_len = 0;
  10877. /* "The masking key is a 32-bit value chosen at random by the client."
  10878. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10879. */
  10880. unsigned char mask[4];
  10881. /* data points to the place where the message is stored when passed to
  10882. * the websocket_data callback. This is either mem on the stack, or a
  10883. * dynamically allocated buffer if it is too large. */
  10884. unsigned char mem[4096];
  10885. unsigned char mop; /* mask flag and opcode */
  10886. /* Variables used for connection monitoring */
  10887. double timeout = -1.0;
  10888. int enable_ping_pong = 0;
  10889. int ping_count = 0;
  10890. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10891. enable_ping_pong =
  10892. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10893. "yes");
  10894. }
  10895. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10896. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10897. }
  10898. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10899. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10900. }
  10901. /* Enter data processing loop */
  10902. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10903. conn->request_info.remote_addr,
  10904. conn->request_info.remote_port);
  10905. conn->in_websocket_handling = 1;
  10906. mg_set_thread_name("wsock");
  10907. /* Loop continuously, reading messages from the socket, invoking the
  10908. * callback, and waiting repeatedly until an error occurs. */
  10909. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10910. && (!conn->must_close)) {
  10911. header_len = 0;
  10912. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10913. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10914. len = buf[1] & 127;
  10915. mask_len = (buf[1] & 128) ? 4 : 0;
  10916. if ((len < 126) && (body_len >= mask_len)) {
  10917. /* inline 7-bit length field */
  10918. data_len = len;
  10919. header_len = 2 + mask_len;
  10920. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10921. /* 16-bit length field */
  10922. header_len = 4 + mask_len;
  10923. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10924. } else if (body_len >= (10 + mask_len)) {
  10925. /* 64-bit length field */
  10926. uint32_t l1, l2;
  10927. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10928. memcpy(&l2, &buf[6], 4);
  10929. header_len = 10 + mask_len;
  10930. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10931. if (data_len > (uint64_t)0x7FFF0000ul) {
  10932. /* no can do */
  10933. mg_cry_internal(
  10934. conn,
  10935. "%s",
  10936. "websocket out of memory; closing connection");
  10937. break;
  10938. }
  10939. }
  10940. }
  10941. if ((header_len > 0) && (body_len >= header_len)) {
  10942. /* Allocate space to hold websocket payload */
  10943. unsigned char *data = mem;
  10944. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10945. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10946. conn->phys_ctx);
  10947. if (data == NULL) {
  10948. /* Allocation failed, exit the loop and then close the
  10949. * connection */
  10950. mg_cry_internal(
  10951. conn,
  10952. "%s",
  10953. "websocket out of memory; closing connection");
  10954. break;
  10955. }
  10956. }
  10957. /* Copy the mask before we shift the queue and destroy it */
  10958. if (mask_len > 0) {
  10959. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10960. } else {
  10961. memset(mask, 0, sizeof(mask));
  10962. }
  10963. /* Read frame payload from the first message in the queue into
  10964. * data and advance the queue by moving the memory in place. */
  10965. DEBUG_ASSERT(body_len >= header_len);
  10966. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10967. mop = buf[0]; /* current mask and opcode */
  10968. /* Overflow case */
  10969. len = body_len - header_len;
  10970. memcpy(data, buf + header_len, len);
  10971. error = 0;
  10972. while ((uint64_t)len < data_len) {
  10973. n = pull_inner(NULL,
  10974. conn,
  10975. (char *)(data + len),
  10976. (int)(data_len - len),
  10977. timeout);
  10978. if (n <= -2) {
  10979. error = 1;
  10980. break;
  10981. } else if (n > 0) {
  10982. len += (size_t)n;
  10983. } else {
  10984. /* Timeout: should retry */
  10985. /* TODO: retry condition */
  10986. }
  10987. }
  10988. if (error) {
  10989. mg_cry_internal(
  10990. conn,
  10991. "%s",
  10992. "Websocket pull failed; closing connection");
  10993. if (data != mem) {
  10994. mg_free(data);
  10995. }
  10996. break;
  10997. }
  10998. conn->data_len = conn->request_len;
  10999. } else {
  11000. mop = buf[0]; /* current mask and opcode, overwritten by
  11001. * memmove() */
  11002. /* Length of the message being read at the front of the
  11003. * queue. Cast to 31 bit is OK, since we limited
  11004. * data_len before. */
  11005. len = (size_t)data_len + header_len;
  11006. /* Copy the data payload into the data pointer for the
  11007. * callback. Cast to 31 bit is OK, since we
  11008. * limited data_len */
  11009. memcpy(data, buf + header_len, (size_t)data_len);
  11010. /* Move the queue forward len bytes */
  11011. memmove(buf, buf + len, body_len - len);
  11012. /* Mark the queue as advanced */
  11013. conn->data_len -= (int)len;
  11014. }
  11015. /* Apply mask if necessary */
  11016. if (mask_len > 0) {
  11017. for (i = 0; i < (size_t)data_len; i++) {
  11018. data[i] ^= mask[i & 3];
  11019. }
  11020. }
  11021. exit_by_callback = 0;
  11022. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11023. /* filter PONG messages */
  11024. DEBUG_TRACE("PONG from %s:%u",
  11025. conn->request_info.remote_addr,
  11026. conn->request_info.remote_port);
  11027. /* No unanwered PINGs left */
  11028. ping_count = 0;
  11029. } else if (enable_ping_pong
  11030. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11031. /* reply PING messages */
  11032. DEBUG_TRACE("Reply PING from %s:%u",
  11033. conn->request_info.remote_addr,
  11034. conn->request_info.remote_port);
  11035. ret = mg_websocket_write(conn,
  11036. MG_WEBSOCKET_OPCODE_PONG,
  11037. (char *)data,
  11038. (size_t)data_len);
  11039. if (ret <= 0) {
  11040. /* Error: send failed */
  11041. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11042. break;
  11043. }
  11044. } else {
  11045. /* Exit the loop if callback signals to exit (server side),
  11046. * or "connection close" opcode received (client side). */
  11047. if ((ws_data_handler != NULL)
  11048. && !ws_data_handler(conn,
  11049. mop,
  11050. (char *)data,
  11051. (size_t)data_len,
  11052. callback_data)) {
  11053. exit_by_callback = 1;
  11054. }
  11055. }
  11056. /* It a buffer has been allocated, free it again */
  11057. if (data != mem) {
  11058. mg_free(data);
  11059. }
  11060. if (exit_by_callback) {
  11061. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11062. conn->request_info.remote_addr,
  11063. conn->request_info.remote_port);
  11064. break;
  11065. }
  11066. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11067. /* Opcode == 8, connection close */
  11068. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11069. conn->request_info.remote_addr,
  11070. conn->request_info.remote_port);
  11071. break;
  11072. }
  11073. /* Not breaking the loop, process next websocket frame. */
  11074. } else {
  11075. /* Read from the socket into the next available location in the
  11076. * message queue. */
  11077. n = pull_inner(NULL,
  11078. conn,
  11079. conn->buf + conn->data_len,
  11080. conn->buf_size - conn->data_len,
  11081. timeout);
  11082. if (n <= -2) {
  11083. /* Error, no bytes read */
  11084. DEBUG_TRACE("PULL from %s:%u failed",
  11085. conn->request_info.remote_addr,
  11086. conn->request_info.remote_port);
  11087. break;
  11088. }
  11089. if (n > 0) {
  11090. conn->data_len += n;
  11091. /* Reset open PING count */
  11092. ping_count = 0;
  11093. } else {
  11094. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11095. && (!conn->must_close)) {
  11096. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11097. /* Stop sending PING */
  11098. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11099. "- closing connection",
  11100. ping_count,
  11101. conn->request_info.remote_addr,
  11102. conn->request_info.remote_port);
  11103. break;
  11104. }
  11105. if (enable_ping_pong) {
  11106. /* Send Websocket PING message */
  11107. DEBUG_TRACE("PING to %s:%u",
  11108. conn->request_info.remote_addr,
  11109. conn->request_info.remote_port);
  11110. ret = mg_websocket_write(conn,
  11111. MG_WEBSOCKET_OPCODE_PING,
  11112. NULL,
  11113. 0);
  11114. if (ret <= 0) {
  11115. /* Error: send failed */
  11116. DEBUG_TRACE("Send PING failed (%i)", ret);
  11117. break;
  11118. }
  11119. ping_count++;
  11120. }
  11121. }
  11122. /* Timeout: should retry */
  11123. /* TODO: get timeout def */
  11124. }
  11125. }
  11126. }
  11127. /* Leave data processing loop */
  11128. mg_set_thread_name("worker");
  11129. conn->in_websocket_handling = 0;
  11130. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11131. conn->request_info.remote_addr,
  11132. conn->request_info.remote_port);
  11133. }
  11134. static int
  11135. mg_websocket_write_exec(struct mg_connection *conn,
  11136. int opcode,
  11137. const char *data,
  11138. size_t dataLen,
  11139. uint32_t masking_key)
  11140. {
  11141. unsigned char header[14];
  11142. size_t headerLen;
  11143. int retval;
  11144. #if defined(GCC_DIAGNOSTIC)
  11145. /* Disable spurious conversion warning for GCC */
  11146. #pragma GCC diagnostic push
  11147. #pragma GCC diagnostic ignored "-Wconversion"
  11148. #endif
  11149. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11150. #if defined(GCC_DIAGNOSTIC)
  11151. #pragma GCC diagnostic pop
  11152. #endif
  11153. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11154. if (dataLen < 126) {
  11155. /* inline 7-bit length field */
  11156. header[1] = (unsigned char)dataLen;
  11157. headerLen = 2;
  11158. } else if (dataLen <= 0xFFFF) {
  11159. /* 16-bit length field */
  11160. uint16_t len = htons((uint16_t)dataLen);
  11161. header[1] = 126;
  11162. memcpy(header + 2, &len, 2);
  11163. headerLen = 4;
  11164. } else {
  11165. /* 64-bit length field */
  11166. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11167. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11168. header[1] = 127;
  11169. memcpy(header + 2, &len1, 4);
  11170. memcpy(header + 6, &len2, 4);
  11171. headerLen = 10;
  11172. }
  11173. if (masking_key) {
  11174. /* add mask */
  11175. header[1] |= 0x80;
  11176. memcpy(header + headerLen, &masking_key, 4);
  11177. headerLen += 4;
  11178. }
  11179. /* Note that POSIX/Winsock's send() is threadsafe
  11180. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11181. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11182. * push(), although that is only a problem if the packet is large or
  11183. * outgoing buffer is full). */
  11184. /* TODO: Check if this lock should be moved to user land.
  11185. * Currently the server sets this lock for websockets, but
  11186. * not for any other connection. It must be set for every
  11187. * conn read/written by more than one thread, no matter if
  11188. * it is a websocket or regular connection. */
  11189. (void)mg_lock_connection(conn);
  11190. retval = mg_write(conn, header, headerLen);
  11191. if (retval != (int)headerLen) {
  11192. /* Did not send complete header */
  11193. retval = -1;
  11194. } else {
  11195. if (dataLen > 0) {
  11196. retval = mg_write(conn, data, dataLen);
  11197. }
  11198. /* if dataLen == 0, the header length (2) is returned */
  11199. }
  11200. /* TODO: Remove this unlock as well, when lock is removed. */
  11201. mg_unlock_connection(conn);
  11202. return retval;
  11203. }
  11204. int
  11205. mg_websocket_write(struct mg_connection *conn,
  11206. int opcode,
  11207. const char *data,
  11208. size_t dataLen)
  11209. {
  11210. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11211. }
  11212. static void
  11213. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11214. {
  11215. size_t i = 0;
  11216. i = 0;
  11217. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11218. /* Convert in 32 bit words, if data is 4 byte aligned */
  11219. while (i < (in_len - 3)) {
  11220. *(uint32_t *)(void *)(out + i) =
  11221. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11222. i += 4;
  11223. }
  11224. }
  11225. if (i != in_len) {
  11226. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11227. while (i < in_len) {
  11228. *(uint8_t *)(void *)(out + i) =
  11229. *(uint8_t *)(void *)(in + i)
  11230. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11231. i++;
  11232. }
  11233. }
  11234. }
  11235. int
  11236. mg_websocket_client_write(struct mg_connection *conn,
  11237. int opcode,
  11238. const char *data,
  11239. size_t dataLen)
  11240. {
  11241. int retval = -1;
  11242. char *masked_data =
  11243. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11244. uint32_t masking_key = 0;
  11245. if (masked_data == NULL) {
  11246. /* Return -1 in an error case */
  11247. mg_cry_internal(conn,
  11248. "%s",
  11249. "Cannot allocate buffer for masked websocket response: "
  11250. "Out of memory");
  11251. return -1;
  11252. }
  11253. do {
  11254. /* Get a masking key - but not 0 */
  11255. masking_key = (uint32_t)get_random();
  11256. } while (masking_key == 0);
  11257. mask_data(data, dataLen, masking_key, masked_data);
  11258. retval = mg_websocket_write_exec(
  11259. conn, opcode, masked_data, dataLen, masking_key);
  11260. mg_free(masked_data);
  11261. return retval;
  11262. }
  11263. static void
  11264. handle_websocket_request(struct mg_connection *conn,
  11265. const char *path,
  11266. int is_callback_resource,
  11267. struct mg_websocket_subprotocols *subprotocols,
  11268. mg_websocket_connect_handler ws_connect_handler,
  11269. mg_websocket_ready_handler ws_ready_handler,
  11270. mg_websocket_data_handler ws_data_handler,
  11271. mg_websocket_close_handler ws_close_handler,
  11272. void *cbData)
  11273. {
  11274. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11275. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11276. ptrdiff_t lua_websock = 0;
  11277. #if !defined(USE_LUA)
  11278. (void)path;
  11279. #endif
  11280. /* Step 1: Check websocket protocol version. */
  11281. /* Step 1.1: Check Sec-WebSocket-Key. */
  11282. if (!websock_key) {
  11283. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11284. * requires a Sec-WebSocket-Key header.
  11285. */
  11286. /* It could be the hixie draft version
  11287. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11288. */
  11289. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11290. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11291. char key3[8];
  11292. if ((key1 != NULL) && (key2 != NULL)) {
  11293. /* This version uses 8 byte body data in a GET request */
  11294. conn->content_len = 8;
  11295. if (8 == mg_read(conn, key3, 8)) {
  11296. /* This is the hixie version */
  11297. mg_send_http_error(conn,
  11298. 426,
  11299. "%s",
  11300. "Protocol upgrade to RFC 6455 required");
  11301. return;
  11302. }
  11303. }
  11304. /* This is an unknown version */
  11305. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11306. return;
  11307. }
  11308. /* Step 1.2: Check websocket protocol version. */
  11309. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11310. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11311. /* Reject wrong versions */
  11312. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11313. return;
  11314. }
  11315. /* Step 1.3: Could check for "Host", but we do not really nead this
  11316. * value for anything, so just ignore it. */
  11317. /* Step 2: If a callback is responsible, call it. */
  11318. if (is_callback_resource) {
  11319. /* Step 2.1 check and select subprotocol */
  11320. const char *protocols[64]; // max 64 headers
  11321. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11322. "Sec-WebSocket-Protocol",
  11323. protocols,
  11324. 64);
  11325. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11326. int cnt = 0;
  11327. int idx;
  11328. unsigned long len;
  11329. const char *sep, *curSubProtocol,
  11330. *acceptedWebSocketSubprotocol = NULL;
  11331. /* look for matching subprotocol */
  11332. do {
  11333. const char *protocol = protocols[cnt];
  11334. do {
  11335. sep = strchr(protocol, ',');
  11336. curSubProtocol = protocol;
  11337. len = sep ? (unsigned long)(sep - protocol)
  11338. : (unsigned long)strlen(protocol);
  11339. while (sep && isspace((unsigned char)*++sep))
  11340. ; // ignore leading whitespaces
  11341. protocol = sep;
  11342. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11343. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11344. && (strncmp(curSubProtocol,
  11345. subprotocols->subprotocols[idx],
  11346. len)
  11347. == 0)) {
  11348. acceptedWebSocketSubprotocol =
  11349. subprotocols->subprotocols[idx];
  11350. break;
  11351. }
  11352. }
  11353. } while (sep && !acceptedWebSocketSubprotocol);
  11354. } while (++cnt < nbSubprotocolHeader
  11355. && !acceptedWebSocketSubprotocol);
  11356. conn->request_info.acceptedWebSocketSubprotocol =
  11357. acceptedWebSocketSubprotocol;
  11358. } else if (nbSubprotocolHeader > 0) {
  11359. /* keep legacy behavior */
  11360. const char *protocol = protocols[0];
  11361. /* The protocol is a comma separated list of names. */
  11362. /* The server must only return one value from this list. */
  11363. /* First check if it is a list or just a single value. */
  11364. const char *sep = strrchr(protocol, ',');
  11365. if (sep == NULL) {
  11366. /* Just a single protocol -> accept it. */
  11367. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11368. } else {
  11369. /* Multiple protocols -> accept the last one. */
  11370. /* This is just a quick fix if the client offers multiple
  11371. * protocols. The handler should have a list of accepted
  11372. * protocols on his own
  11373. * and use it to select one protocol among those the client
  11374. * has
  11375. * offered.
  11376. */
  11377. while (isspace((unsigned char)*++sep)) {
  11378. ; /* ignore leading whitespaces */
  11379. }
  11380. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11381. }
  11382. }
  11383. if ((ws_connect_handler != NULL)
  11384. && (ws_connect_handler(conn, cbData) != 0)) {
  11385. /* C callback has returned non-zero, do not proceed with
  11386. * handshake.
  11387. */
  11388. /* Note that C callbacks are no longer called when Lua is
  11389. * responsible, so C can no longer filter callbacks for Lua. */
  11390. return;
  11391. }
  11392. }
  11393. #if defined(USE_LUA)
  11394. /* Step 3: No callback. Check if Lua is responsible. */
  11395. else {
  11396. /* Step 3.1: Check if Lua is responsible. */
  11397. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11398. lua_websock = match_prefix(
  11399. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11400. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11401. path);
  11402. }
  11403. if (lua_websock) {
  11404. /* Step 3.2: Lua is responsible: call it. */
  11405. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11406. if (!conn->lua_websocket_state) {
  11407. /* Lua rejected the new client */
  11408. return;
  11409. }
  11410. }
  11411. }
  11412. #endif
  11413. /* Step 4: Check if there is a responsible websocket handler. */
  11414. if (!is_callback_resource && !lua_websock) {
  11415. /* There is no callback, and Lua is not responsible either. */
  11416. /* Reply with a 404 Not Found. We are still at a standard
  11417. * HTTP request here, before the websocket handshake, so
  11418. * we can still send standard HTTP error replies. */
  11419. mg_send_http_error(conn, 404, "%s", "Not found");
  11420. return;
  11421. }
  11422. /* Step 5: The websocket connection has been accepted */
  11423. if (!send_websocket_handshake(conn, websock_key)) {
  11424. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11425. return;
  11426. }
  11427. /* Step 6: Call the ready handler */
  11428. if (is_callback_resource) {
  11429. if (ws_ready_handler != NULL) {
  11430. ws_ready_handler(conn, cbData);
  11431. }
  11432. #if defined(USE_LUA)
  11433. } else if (lua_websock) {
  11434. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11435. /* the ready handler returned false */
  11436. return;
  11437. }
  11438. #endif
  11439. }
  11440. /* Step 7: Enter the read loop */
  11441. if (is_callback_resource) {
  11442. read_websocket(conn, ws_data_handler, cbData);
  11443. #if defined(USE_LUA)
  11444. } else if (lua_websock) {
  11445. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11446. #endif
  11447. }
  11448. /* Step 8: Call the close handler */
  11449. if (ws_close_handler) {
  11450. ws_close_handler(conn, cbData);
  11451. }
  11452. }
  11453. #endif /* !USE_WEBSOCKET */
  11454. /* Is upgrade request:
  11455. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11456. * 1 = upgrade to websocket
  11457. * 2 = upgrade to HTTP/2
  11458. * -1 = upgrade to unknown protocol
  11459. */
  11460. static int
  11461. should_switch_to_protocol(const struct mg_connection *conn)
  11462. {
  11463. const char *upgrade, *connection;
  11464. /* A websocket protocoll has the following HTTP headers:
  11465. *
  11466. * Connection: Upgrade
  11467. * Upgrade: Websocket
  11468. */
  11469. connection = mg_get_header(conn, "Connection");
  11470. if (connection == NULL) {
  11471. return PROTOCOL_TYPE_HTTP1;
  11472. }
  11473. if (!mg_strcasestr(connection, "upgrade")) {
  11474. return PROTOCOL_TYPE_HTTP1;
  11475. }
  11476. upgrade = mg_get_header(conn, "Upgrade");
  11477. if (upgrade == NULL) {
  11478. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11479. return -1;
  11480. }
  11481. /* Upgrade to ... */
  11482. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11483. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11484. * "Sec-WebSocket-Version" are also required.
  11485. * Don't check them here, since even an unsupported websocket protocol
  11486. * request still IS a websocket request (in contrast to a standard HTTP
  11487. * request). It will fail later in handle_websocket_request.
  11488. */
  11489. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11490. }
  11491. if (0 != mg_strcasestr(upgrade, "h2")) {
  11492. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11493. }
  11494. /* Upgrade to another protocol */
  11495. return -1;
  11496. }
  11497. static int
  11498. isbyte(int n)
  11499. {
  11500. return (n >= 0) && (n <= 255);
  11501. }
  11502. static int
  11503. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11504. {
  11505. int n, a, b, c, d, slash = 32, len = 0;
  11506. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11507. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11508. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11509. && (slash < 33)) {
  11510. len = n;
  11511. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11512. | (uint32_t)d;
  11513. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11514. }
  11515. return len;
  11516. }
  11517. static int
  11518. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11519. {
  11520. int throttle = 0;
  11521. struct vec vec, val;
  11522. uint32_t net, mask;
  11523. char mult;
  11524. double v;
  11525. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11526. mult = ',';
  11527. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11528. || (v < 0)
  11529. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11530. && (mult != ','))) {
  11531. continue;
  11532. }
  11533. v *= (lowercase(&mult) == 'k')
  11534. ? 1024
  11535. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11536. if (vec.len == 1 && vec.ptr[0] == '*') {
  11537. throttle = (int)v;
  11538. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11539. if ((remote_ip & mask) == net) {
  11540. throttle = (int)v;
  11541. }
  11542. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11543. throttle = (int)v;
  11544. }
  11545. }
  11546. return throttle;
  11547. }
  11548. static uint32_t
  11549. get_remote_ip(const struct mg_connection *conn)
  11550. {
  11551. if (!conn) {
  11552. return 0;
  11553. }
  11554. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11555. }
  11556. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11557. #include "handle_form.inl"
  11558. #if defined(MG_LEGACY_INTERFACE)
  11559. /* Implement the deprecated mg_upload function by calling the new
  11560. * mg_handle_form_request function. While mg_upload could only handle
  11561. * HTML forms sent as POST request in multipart/form-data format
  11562. * containing only file input elements, mg_handle_form_request can
  11563. * handle all form input elements and all standard request methods. */
  11564. struct mg_upload_user_data {
  11565. struct mg_connection *conn;
  11566. const char *destination_dir;
  11567. int num_uploaded_files;
  11568. };
  11569. /* Helper function for deprecated mg_upload. */
  11570. static int
  11571. mg_upload_field_found(const char *key,
  11572. const char *filename,
  11573. char *path,
  11574. size_t pathlen,
  11575. void *user_data)
  11576. {
  11577. int truncated = 0;
  11578. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11579. (void)key;
  11580. if (!filename) {
  11581. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11582. return FORM_FIELD_STORAGE_ABORT;
  11583. }
  11584. mg_snprintf(fud->conn,
  11585. &truncated,
  11586. path,
  11587. pathlen - 1,
  11588. "%s/%s",
  11589. fud->destination_dir,
  11590. filename);
  11591. if (truncated) {
  11592. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11593. return FORM_FIELD_STORAGE_ABORT;
  11594. }
  11595. return FORM_FIELD_STORAGE_STORE;
  11596. }
  11597. /* Helper function for deprecated mg_upload. */
  11598. static int
  11599. mg_upload_field_get(const char *key,
  11600. const char *value,
  11601. size_t value_size,
  11602. void *user_data)
  11603. {
  11604. /* Function should never be called */
  11605. (void)key;
  11606. (void)value;
  11607. (void)value_size;
  11608. (void)user_data;
  11609. return 0;
  11610. }
  11611. /* Helper function for deprecated mg_upload. */
  11612. static int
  11613. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11614. {
  11615. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11616. (void)file_size;
  11617. fud->num_uploaded_files++;
  11618. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11619. return 0;
  11620. }
  11621. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11622. int
  11623. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11624. {
  11625. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11626. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11627. mg_upload_field_get,
  11628. mg_upload_field_stored,
  11629. 0};
  11630. int ret;
  11631. fdh.user_data = (void *)&fud;
  11632. ret = mg_handle_form_request(conn, &fdh);
  11633. if (ret < 0) {
  11634. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11635. }
  11636. return fud.num_uploaded_files;
  11637. }
  11638. #endif
  11639. static int
  11640. get_first_ssl_listener_index(const struct mg_context *ctx)
  11641. {
  11642. unsigned int i;
  11643. int idx = -1;
  11644. if (ctx) {
  11645. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11646. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11647. }
  11648. }
  11649. return idx;
  11650. }
  11651. /* Return host (without port) */
  11652. /* Use mg_free to free the result */
  11653. static const char *
  11654. alloc_get_host(struct mg_connection *conn)
  11655. {
  11656. char buf[1025];
  11657. size_t buflen = sizeof(buf);
  11658. const char *host_header = get_header(conn->request_info.http_headers,
  11659. conn->request_info.num_headers,
  11660. "Host");
  11661. char *host;
  11662. if (host_header != NULL) {
  11663. char *pos;
  11664. /* Create a local copy of the "Host" header, since it might be
  11665. * modified here. */
  11666. mg_strlcpy(buf, host_header, buflen);
  11667. buf[buflen - 1] = '\0';
  11668. host = buf;
  11669. while (isspace((unsigned char)*host)) {
  11670. host++;
  11671. }
  11672. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11673. * is found. */
  11674. if (*host == '[') {
  11675. pos = strchr(host, ']');
  11676. if (!pos) {
  11677. /* Malformed hostname starts with '[', but no ']' found */
  11678. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11679. return NULL;
  11680. }
  11681. /* terminate after ']' */
  11682. pos[1] = 0;
  11683. } else {
  11684. /* Otherwise, a ':' separates hostname and port number */
  11685. pos = strchr(host, ':');
  11686. if (pos != NULL) {
  11687. *pos = '\0';
  11688. }
  11689. }
  11690. if (conn->ssl) {
  11691. /* This is a HTTPS connection, maybe we have a hostname
  11692. * from SNI (set in ssl_servername_callback). */
  11693. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11694. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11695. /* We are not using the default domain */
  11696. if (mg_strcasecmp(host, sslhost)) {
  11697. /* Mismatch between SNI domain and HTTP domain */
  11698. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11699. sslhost,
  11700. host);
  11701. return NULL;
  11702. }
  11703. }
  11704. DEBUG_TRACE("HTTPS Host: %s", host);
  11705. } else {
  11706. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11707. while (dom) {
  11708. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11709. /* Found matching domain */
  11710. DEBUG_TRACE("HTTP domain %s found",
  11711. dom->config[AUTHENTICATION_DOMAIN]);
  11712. /* TODO: Check if this is a HTTP or HTTPS domain */
  11713. conn->dom_ctx = dom;
  11714. break;
  11715. }
  11716. mg_lock_context(conn->phys_ctx);
  11717. dom = dom->next;
  11718. mg_unlock_context(conn->phys_ctx);
  11719. }
  11720. DEBUG_TRACE("HTTP Host: %s", host);
  11721. }
  11722. } else {
  11723. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11724. host = buf;
  11725. DEBUG_TRACE("IP: %s", host);
  11726. }
  11727. return mg_strdup_ctx(host, conn->phys_ctx);
  11728. }
  11729. static void
  11730. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11731. {
  11732. char target_url[MG_BUF_LEN];
  11733. int truncated = 0;
  11734. conn->must_close = 1;
  11735. /* Send host, port, uri and (if it exists) ?query_string */
  11736. if (conn->host) {
  11737. /* Use "308 Permanent Redirect" */
  11738. int redirect_code = 308;
  11739. /* Create target URL */
  11740. mg_snprintf(
  11741. conn,
  11742. &truncated,
  11743. target_url,
  11744. sizeof(target_url),
  11745. "https://%s:%d%s%s%s",
  11746. conn->host,
  11747. #if defined(USE_IPV6)
  11748. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11749. == AF_INET6)
  11750. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11751. .lsa.sin6.sin6_port)
  11752. :
  11753. #endif
  11754. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11755. .lsa.sin.sin_port),
  11756. conn->request_info.local_uri,
  11757. (conn->request_info.query_string == NULL) ? "" : "?",
  11758. (conn->request_info.query_string == NULL)
  11759. ? ""
  11760. : conn->request_info.query_string);
  11761. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11762. * is used as buffer size) */
  11763. if (truncated) {
  11764. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11765. return;
  11766. }
  11767. /* Use redirect helper function */
  11768. mg_send_http_redirect(conn, target_url, redirect_code);
  11769. }
  11770. }
  11771. static void
  11772. mg_set_handler_type(struct mg_context *phys_ctx,
  11773. struct mg_domain_context *dom_ctx,
  11774. const char *uri,
  11775. int handler_type,
  11776. int is_delete_request,
  11777. mg_request_handler handler,
  11778. struct mg_websocket_subprotocols *subprotocols,
  11779. mg_websocket_connect_handler connect_handler,
  11780. mg_websocket_ready_handler ready_handler,
  11781. mg_websocket_data_handler data_handler,
  11782. mg_websocket_close_handler close_handler,
  11783. mg_authorization_handler auth_handler,
  11784. void *cbdata)
  11785. {
  11786. struct mg_handler_info *tmp_rh, **lastref;
  11787. size_t urilen = strlen(uri);
  11788. if (handler_type == WEBSOCKET_HANDLER) {
  11789. DEBUG_ASSERT(handler == NULL);
  11790. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11791. || ready_handler != NULL || data_handler != NULL
  11792. || close_handler != NULL);
  11793. DEBUG_ASSERT(auth_handler == NULL);
  11794. if (handler != NULL) {
  11795. return;
  11796. }
  11797. if (!is_delete_request && (connect_handler == NULL)
  11798. && (ready_handler == NULL) && (data_handler == NULL)
  11799. && (close_handler == NULL)) {
  11800. return;
  11801. }
  11802. if (auth_handler != NULL) {
  11803. return;
  11804. }
  11805. } else if (handler_type == REQUEST_HANDLER) {
  11806. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11807. && data_handler == NULL && close_handler == NULL);
  11808. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11809. DEBUG_ASSERT(auth_handler == NULL);
  11810. if ((connect_handler != NULL) || (ready_handler != NULL)
  11811. || (data_handler != NULL) || (close_handler != NULL)) {
  11812. return;
  11813. }
  11814. if (!is_delete_request && (handler == NULL)) {
  11815. return;
  11816. }
  11817. if (auth_handler != NULL) {
  11818. return;
  11819. }
  11820. } else { /* AUTH_HANDLER */
  11821. DEBUG_ASSERT(handler == NULL);
  11822. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11823. && data_handler == NULL && close_handler == NULL);
  11824. DEBUG_ASSERT(auth_handler != NULL);
  11825. if (handler != NULL) {
  11826. return;
  11827. }
  11828. if ((connect_handler != NULL) || (ready_handler != NULL)
  11829. || (data_handler != NULL) || (close_handler != NULL)) {
  11830. return;
  11831. }
  11832. if (!is_delete_request && (auth_handler == NULL)) {
  11833. return;
  11834. }
  11835. }
  11836. if (!phys_ctx || !dom_ctx) {
  11837. return;
  11838. }
  11839. mg_lock_context(phys_ctx);
  11840. /* first try to find an existing handler */
  11841. do {
  11842. lastref = &(dom_ctx->handlers);
  11843. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11844. tmp_rh = tmp_rh->next) {
  11845. if (tmp_rh->handler_type == handler_type
  11846. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11847. if (!is_delete_request) {
  11848. /* update existing handler */
  11849. if (handler_type == REQUEST_HANDLER) {
  11850. /* Wait for end of use before updating */
  11851. if (tmp_rh->refcount) {
  11852. mg_unlock_context(phys_ctx);
  11853. mg_sleep(1);
  11854. mg_lock_context(phys_ctx);
  11855. /* tmp_rh might have been freed, search again. */
  11856. break;
  11857. }
  11858. /* Ok, the handler is no more use -> Update it */
  11859. tmp_rh->handler = handler;
  11860. } else if (handler_type == WEBSOCKET_HANDLER) {
  11861. tmp_rh->subprotocols = subprotocols;
  11862. tmp_rh->connect_handler = connect_handler;
  11863. tmp_rh->ready_handler = ready_handler;
  11864. tmp_rh->data_handler = data_handler;
  11865. tmp_rh->close_handler = close_handler;
  11866. } else { /* AUTH_HANDLER */
  11867. tmp_rh->auth_handler = auth_handler;
  11868. }
  11869. tmp_rh->cbdata = cbdata;
  11870. } else {
  11871. /* remove existing handler */
  11872. if (handler_type == REQUEST_HANDLER) {
  11873. /* Wait for end of use before removing */
  11874. if (tmp_rh->refcount) {
  11875. tmp_rh->removing = 1;
  11876. mg_unlock_context(phys_ctx);
  11877. mg_sleep(1);
  11878. mg_lock_context(phys_ctx);
  11879. /* tmp_rh might have been freed, search again. */
  11880. break;
  11881. }
  11882. /* Ok, the handler is no more used */
  11883. }
  11884. *lastref = tmp_rh->next;
  11885. mg_free(tmp_rh->uri);
  11886. mg_free(tmp_rh);
  11887. }
  11888. mg_unlock_context(phys_ctx);
  11889. return;
  11890. }
  11891. lastref = &(tmp_rh->next);
  11892. }
  11893. } while (tmp_rh != NULL);
  11894. if (is_delete_request) {
  11895. /* no handler to set, this was a remove request to a non-existing
  11896. * handler */
  11897. mg_unlock_context(phys_ctx);
  11898. return;
  11899. }
  11900. tmp_rh =
  11901. (struct mg_handler_info *)mg_calloc_ctx(1,
  11902. sizeof(struct mg_handler_info),
  11903. phys_ctx);
  11904. if (tmp_rh == NULL) {
  11905. mg_unlock_context(phys_ctx);
  11906. mg_cry_ctx_internal(phys_ctx,
  11907. "%s",
  11908. "Cannot create new request handler struct, OOM");
  11909. return;
  11910. }
  11911. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11912. if (!tmp_rh->uri) {
  11913. mg_unlock_context(phys_ctx);
  11914. mg_free(tmp_rh);
  11915. mg_cry_ctx_internal(phys_ctx,
  11916. "%s",
  11917. "Cannot create new request handler struct, OOM");
  11918. return;
  11919. }
  11920. tmp_rh->uri_len = urilen;
  11921. if (handler_type == REQUEST_HANDLER) {
  11922. tmp_rh->refcount = 0;
  11923. tmp_rh->removing = 0;
  11924. tmp_rh->handler = handler;
  11925. } else if (handler_type == WEBSOCKET_HANDLER) {
  11926. tmp_rh->subprotocols = subprotocols;
  11927. tmp_rh->connect_handler = connect_handler;
  11928. tmp_rh->ready_handler = ready_handler;
  11929. tmp_rh->data_handler = data_handler;
  11930. tmp_rh->close_handler = close_handler;
  11931. } else { /* AUTH_HANDLER */
  11932. tmp_rh->auth_handler = auth_handler;
  11933. }
  11934. tmp_rh->cbdata = cbdata;
  11935. tmp_rh->handler_type = handler_type;
  11936. tmp_rh->next = NULL;
  11937. *lastref = tmp_rh;
  11938. mg_unlock_context(phys_ctx);
  11939. }
  11940. void
  11941. mg_set_request_handler(struct mg_context *ctx,
  11942. const char *uri,
  11943. mg_request_handler handler,
  11944. void *cbdata)
  11945. {
  11946. mg_set_handler_type(ctx,
  11947. &(ctx->dd),
  11948. uri,
  11949. REQUEST_HANDLER,
  11950. handler == NULL,
  11951. handler,
  11952. NULL,
  11953. NULL,
  11954. NULL,
  11955. NULL,
  11956. NULL,
  11957. NULL,
  11958. cbdata);
  11959. }
  11960. void
  11961. mg_set_websocket_handler(struct mg_context *ctx,
  11962. const char *uri,
  11963. mg_websocket_connect_handler connect_handler,
  11964. mg_websocket_ready_handler ready_handler,
  11965. mg_websocket_data_handler data_handler,
  11966. mg_websocket_close_handler close_handler,
  11967. void *cbdata)
  11968. {
  11969. mg_set_websocket_handler_with_subprotocols(ctx,
  11970. uri,
  11971. NULL,
  11972. connect_handler,
  11973. ready_handler,
  11974. data_handler,
  11975. close_handler,
  11976. cbdata);
  11977. }
  11978. void
  11979. mg_set_websocket_handler_with_subprotocols(
  11980. struct mg_context *ctx,
  11981. const char *uri,
  11982. struct mg_websocket_subprotocols *subprotocols,
  11983. mg_websocket_connect_handler connect_handler,
  11984. mg_websocket_ready_handler ready_handler,
  11985. mg_websocket_data_handler data_handler,
  11986. mg_websocket_close_handler close_handler,
  11987. void *cbdata)
  11988. {
  11989. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11990. && (data_handler == NULL)
  11991. && (close_handler == NULL);
  11992. mg_set_handler_type(ctx,
  11993. &(ctx->dd),
  11994. uri,
  11995. WEBSOCKET_HANDLER,
  11996. is_delete_request,
  11997. NULL,
  11998. subprotocols,
  11999. connect_handler,
  12000. ready_handler,
  12001. data_handler,
  12002. close_handler,
  12003. NULL,
  12004. cbdata);
  12005. }
  12006. void
  12007. mg_set_auth_handler(struct mg_context *ctx,
  12008. const char *uri,
  12009. mg_authorization_handler handler,
  12010. void *cbdata)
  12011. {
  12012. mg_set_handler_type(ctx,
  12013. &(ctx->dd),
  12014. uri,
  12015. AUTH_HANDLER,
  12016. handler == NULL,
  12017. NULL,
  12018. NULL,
  12019. NULL,
  12020. NULL,
  12021. NULL,
  12022. NULL,
  12023. handler,
  12024. cbdata);
  12025. }
  12026. static int
  12027. get_request_handler(struct mg_connection *conn,
  12028. int handler_type,
  12029. mg_request_handler *handler,
  12030. struct mg_websocket_subprotocols **subprotocols,
  12031. mg_websocket_connect_handler *connect_handler,
  12032. mg_websocket_ready_handler *ready_handler,
  12033. mg_websocket_data_handler *data_handler,
  12034. mg_websocket_close_handler *close_handler,
  12035. mg_authorization_handler *auth_handler,
  12036. void **cbdata,
  12037. struct mg_handler_info **handler_info)
  12038. {
  12039. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12040. if (request_info) {
  12041. const char *uri = request_info->local_uri;
  12042. size_t urilen = strlen(uri);
  12043. struct mg_handler_info *tmp_rh;
  12044. int step, matched;
  12045. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12046. return 0;
  12047. }
  12048. mg_lock_context(conn->phys_ctx);
  12049. for (step = 0; step < 3; step++) {
  12050. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12051. tmp_rh = tmp_rh->next) {
  12052. if (tmp_rh->handler_type != handler_type) {
  12053. continue;
  12054. }
  12055. if (step == 0) {
  12056. /* first try for an exact match */
  12057. matched = (tmp_rh->uri_len == urilen)
  12058. && (strcmp(tmp_rh->uri, uri) == 0);
  12059. } else if (step == 1) {
  12060. /* next try for a partial match, we will accept
  12061. uri/something */
  12062. matched =
  12063. (tmp_rh->uri_len < urilen)
  12064. && (uri[tmp_rh->uri_len] == '/')
  12065. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12066. } else {
  12067. /* finally try for pattern match */
  12068. matched =
  12069. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12070. }
  12071. if (matched) {
  12072. if (handler_type == WEBSOCKET_HANDLER) {
  12073. *subprotocols = tmp_rh->subprotocols;
  12074. *connect_handler = tmp_rh->connect_handler;
  12075. *ready_handler = tmp_rh->ready_handler;
  12076. *data_handler = tmp_rh->data_handler;
  12077. *close_handler = tmp_rh->close_handler;
  12078. } else if (handler_type == REQUEST_HANDLER) {
  12079. if (tmp_rh->removing) {
  12080. /* Treat as none found */
  12081. step = 2;
  12082. break;
  12083. }
  12084. *handler = tmp_rh->handler;
  12085. /* Acquire handler and give it back */
  12086. tmp_rh->refcount++;
  12087. *handler_info = tmp_rh;
  12088. } else { /* AUTH_HANDLER */
  12089. *auth_handler = tmp_rh->auth_handler;
  12090. }
  12091. *cbdata = tmp_rh->cbdata;
  12092. mg_unlock_context(conn->phys_ctx);
  12093. return 1;
  12094. }
  12095. }
  12096. }
  12097. mg_unlock_context(conn->phys_ctx);
  12098. }
  12099. return 0; /* none found */
  12100. }
  12101. /* Check if the script file is in a path, allowed for script files.
  12102. * This can be used if uploading files is possible not only for the server
  12103. * admin, and the upload mechanism does not check the file extension.
  12104. */
  12105. static int
  12106. is_in_script_path(const struct mg_connection *conn, const char *path)
  12107. {
  12108. /* TODO (Feature): Add config value for allowed script path.
  12109. * Default: All allowed. */
  12110. (void)conn;
  12111. (void)path;
  12112. return 1;
  12113. }
  12114. #if defined(USE_WEBSOCKET) \
  12115. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  12116. static int
  12117. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  12118. void *cbdata)
  12119. {
  12120. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12121. if (pcallbacks->websocket_connect) {
  12122. return pcallbacks->websocket_connect(conn);
  12123. }
  12124. /* No handler set - assume "OK" */
  12125. return 0;
  12126. }
  12127. static void
  12128. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  12129. {
  12130. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12131. if (pcallbacks->websocket_ready) {
  12132. pcallbacks->websocket_ready(conn);
  12133. }
  12134. }
  12135. static int
  12136. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  12137. int bits,
  12138. char *data,
  12139. size_t len,
  12140. void *cbdata)
  12141. {
  12142. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12143. if (pcallbacks->websocket_data) {
  12144. return pcallbacks->websocket_data(conn, bits, data, len);
  12145. }
  12146. /* No handler set - assume "OK" */
  12147. return 1;
  12148. }
  12149. static void
  12150. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  12151. void *cbdata)
  12152. {
  12153. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12154. if (pcallbacks->connection_close) {
  12155. pcallbacks->connection_close(conn);
  12156. }
  12157. }
  12158. #endif
  12159. /* This is the heart of the Civetweb's logic.
  12160. * This function is called when the request is read, parsed and validated,
  12161. * and Civetweb must decide what action to take: serve a file, or
  12162. * a directory, or call embedded function, etcetera. */
  12163. static void
  12164. handle_request(struct mg_connection *conn)
  12165. {
  12166. struct mg_request_info *ri = &conn->request_info;
  12167. char path[PATH_MAX];
  12168. int uri_len, ssl_index;
  12169. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12170. is_put_or_delete_request = 0, is_callback_resource = 0;
  12171. int i;
  12172. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12173. mg_request_handler callback_handler = NULL;
  12174. struct mg_handler_info *handler_info = NULL;
  12175. struct mg_websocket_subprotocols *subprotocols;
  12176. mg_websocket_connect_handler ws_connect_handler = NULL;
  12177. mg_websocket_ready_handler ws_ready_handler = NULL;
  12178. mg_websocket_data_handler ws_data_handler = NULL;
  12179. mg_websocket_close_handler ws_close_handler = NULL;
  12180. void *callback_data = NULL;
  12181. mg_authorization_handler auth_handler = NULL;
  12182. void *auth_callback_data = NULL;
  12183. int handler_type;
  12184. time_t curtime = time(NULL);
  12185. char date[64];
  12186. path[0] = 0;
  12187. /* 1. get the request url */
  12188. /* 1.1. split into url and query string */
  12189. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12190. != NULL) {
  12191. *((char *)conn->request_info.query_string++) = '\0';
  12192. }
  12193. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12194. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12195. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12196. if (ssl_index >= 0) {
  12197. redirect_to_https_port(conn, ssl_index);
  12198. } else {
  12199. /* A http to https forward port has been specified,
  12200. * but no https port to forward to. */
  12201. mg_send_http_error(conn,
  12202. 503,
  12203. "%s",
  12204. "Error: SSL forward not configured properly");
  12205. mg_cry_internal(conn,
  12206. "%s",
  12207. "Can not redirect to SSL, no SSL port available");
  12208. }
  12209. return;
  12210. }
  12211. uri_len = (int)strlen(ri->local_uri);
  12212. /* 1.3. decode url (if config says so) */
  12213. if (should_decode_url(conn)) {
  12214. mg_url_decode(
  12215. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12216. }
  12217. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12218. * not possible */
  12219. remove_dot_segments((char *)ri->local_uri);
  12220. /* step 1. completed, the url is known now */
  12221. uri_len = (int)strlen(ri->local_uri);
  12222. DEBUG_TRACE("URL: %s", ri->local_uri);
  12223. /* 2. if this ip has limited speed, set it for this connection */
  12224. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12225. get_remote_ip(conn),
  12226. ri->local_uri);
  12227. /* 3. call a "handle everything" callback, if registered */
  12228. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12229. /* Note that since V1.7 the "begin_request" function is called
  12230. * before an authorization check. If an authorization check is
  12231. * required, use a request_handler instead. */
  12232. i = conn->phys_ctx->callbacks.begin_request(conn);
  12233. if (i > 0) {
  12234. /* callback already processed the request. Store the
  12235. return value as a status code for the access log. */
  12236. conn->status_code = i;
  12237. if (!conn->must_close) {
  12238. discard_unread_request_data(conn);
  12239. }
  12240. return;
  12241. } else if (i == 0) {
  12242. /* civetweb should process the request */
  12243. } else {
  12244. /* unspecified - may change with the next version */
  12245. return;
  12246. }
  12247. }
  12248. /* request not yet handled by a handler or redirect, so the request
  12249. * is processed here */
  12250. /* 4. Check for CORS preflight requests and handle them (if configured).
  12251. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12252. */
  12253. if (!strcmp(ri->request_method, "OPTIONS")) {
  12254. /* Send a response to CORS preflights only if
  12255. * access_control_allow_methods is not NULL and not an empty string.
  12256. * In this case, scripts can still handle CORS. */
  12257. const char *cors_meth_cfg =
  12258. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12259. const char *cors_orig_cfg =
  12260. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12261. const char *cors_origin =
  12262. get_header(ri->http_headers, ri->num_headers, "Origin");
  12263. const char *cors_acrm = get_header(ri->http_headers,
  12264. ri->num_headers,
  12265. "Access-Control-Request-Method");
  12266. /* Todo: check if cors_origin is in cors_orig_cfg.
  12267. * Or, let the client check this. */
  12268. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12269. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12270. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12271. /* This is a valid CORS preflight, and the server is configured
  12272. * to
  12273. * handle it automatically. */
  12274. const char *cors_acrh =
  12275. get_header(ri->http_headers,
  12276. ri->num_headers,
  12277. "Access-Control-Request-Headers");
  12278. gmt_time_string(date, sizeof(date), &curtime);
  12279. mg_printf(conn,
  12280. "HTTP/1.1 200 OK\r\n"
  12281. "Date: %s\r\n"
  12282. "Access-Control-Allow-Origin: %s\r\n"
  12283. "Access-Control-Allow-Methods: %s\r\n"
  12284. "Content-Length: 0\r\n"
  12285. "Connection: %s\r\n",
  12286. date,
  12287. cors_orig_cfg,
  12288. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12289. suggest_connection_header(conn));
  12290. if (cors_acrh != NULL) {
  12291. /* CORS request is asking for additional headers */
  12292. const char *cors_hdr_cfg =
  12293. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12294. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12295. /* Allow only if access_control_allow_headers is
  12296. * not NULL and not an empty string. If this
  12297. * configuration is set to *, allow everything.
  12298. * Otherwise this configuration must be a list
  12299. * of allowed HTTP header names. */
  12300. mg_printf(conn,
  12301. "Access-Control-Allow-Headers: %s\r\n",
  12302. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12303. : cors_hdr_cfg));
  12304. }
  12305. }
  12306. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12307. mg_printf(conn, "\r\n");
  12308. return;
  12309. }
  12310. }
  12311. /* 5. interpret the url to find out how the request must be handled
  12312. */
  12313. /* 5.1. first test, if the request targets the regular http(s)://
  12314. * protocol namespace or the websocket ws(s):// protocol namespace.
  12315. */
  12316. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12317. #if defined(USE_WEBSOCKET)
  12318. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12319. #else
  12320. handler_type = REQUEST_HANDLER;
  12321. #endif /* defined(USE_WEBSOCKET) */
  12322. /* 5.2. check if the request will be handled by a callback */
  12323. if (get_request_handler(conn,
  12324. handler_type,
  12325. &callback_handler,
  12326. &subprotocols,
  12327. &ws_connect_handler,
  12328. &ws_ready_handler,
  12329. &ws_data_handler,
  12330. &ws_close_handler,
  12331. NULL,
  12332. &callback_data,
  12333. &handler_info)) {
  12334. /* 5.2.1. A callback will handle this request. All requests
  12335. * handled
  12336. * by a callback have to be considered as requests to a script
  12337. * resource. */
  12338. is_callback_resource = 1;
  12339. is_script_resource = 1;
  12340. is_put_or_delete_request = is_put_or_delete_method(conn);
  12341. } else {
  12342. no_callback_resource:
  12343. /* 5.2.2. No callback is responsible for this request. The URI
  12344. * addresses a file based resource (static content or Lua/cgi
  12345. * scripts in the file system). */
  12346. is_callback_resource = 0;
  12347. interpret_uri(conn,
  12348. path,
  12349. sizeof(path),
  12350. &file.stat,
  12351. &is_found,
  12352. &is_script_resource,
  12353. &is_websocket_request,
  12354. &is_put_or_delete_request);
  12355. }
  12356. /* 6. authorization check */
  12357. /* 6.1. a custom authorization handler is installed */
  12358. if (get_request_handler(conn,
  12359. AUTH_HANDLER,
  12360. NULL,
  12361. NULL,
  12362. NULL,
  12363. NULL,
  12364. NULL,
  12365. NULL,
  12366. &auth_handler,
  12367. &auth_callback_data,
  12368. NULL)) {
  12369. if (!auth_handler(conn, auth_callback_data)) {
  12370. return;
  12371. }
  12372. } else if (is_put_or_delete_request && !is_script_resource
  12373. && !is_callback_resource) {
  12374. /* 6.2. this request is a PUT/DELETE to a real file */
  12375. /* 6.2.1. thus, the server must have real files */
  12376. #if defined(NO_FILES)
  12377. if (1) {
  12378. #else
  12379. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12380. #endif
  12381. /* This server does not have any real files, thus the
  12382. * PUT/DELETE methods are not valid. */
  12383. mg_send_http_error(conn,
  12384. 405,
  12385. "%s method not allowed",
  12386. conn->request_info.request_method);
  12387. return;
  12388. }
  12389. #if !defined(NO_FILES)
  12390. /* 6.2.2. Check if put authorization for static files is
  12391. * available.
  12392. */
  12393. if (!is_authorized_for_put(conn)) {
  12394. send_authorization_request(conn, NULL);
  12395. return;
  12396. }
  12397. #endif
  12398. } else {
  12399. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12400. * or it is a PUT or DELETE request to a resource that does not
  12401. * correspond to a file. Check authorization. */
  12402. if (!check_authorization(conn, path)) {
  12403. send_authorization_request(conn, NULL);
  12404. return;
  12405. }
  12406. }
  12407. /* request is authorized or does not need authorization */
  12408. /* 7. check if there are request handlers for this uri */
  12409. if (is_callback_resource) {
  12410. if (!is_websocket_request) {
  12411. i = callback_handler(conn, callback_data);
  12412. /* Callback handler will not be used anymore. Release it */
  12413. mg_lock_context(conn->phys_ctx);
  12414. handler_info->refcount--;
  12415. mg_unlock_context(conn->phys_ctx);
  12416. if (i > 0) {
  12417. /* Do nothing, callback has served the request. Store
  12418. * then return value as status code for the log and discard
  12419. * all data from the client not used by the callback. */
  12420. conn->status_code = i;
  12421. if (!conn->must_close) {
  12422. discard_unread_request_data(conn);
  12423. }
  12424. } else {
  12425. /* The handler did NOT handle the request. */
  12426. /* Some proper reactions would be:
  12427. * a) close the connections without sending anything
  12428. * b) send a 404 not found
  12429. * c) try if there is a file matching the URI
  12430. * It would be possible to do a, b or c in the callback
  12431. * implementation, and return 1 - we cannot do anything
  12432. * here, that is not possible in the callback.
  12433. *
  12434. * TODO: What would be the best reaction here?
  12435. * (Note: The reaction may change, if there is a better
  12436. *idea.)
  12437. */
  12438. /* For the moment, use option c: We look for a proper file,
  12439. * but since a file request is not always a script resource,
  12440. * the authorization check might be different. */
  12441. interpret_uri(conn,
  12442. path,
  12443. sizeof(path),
  12444. &file.stat,
  12445. &is_found,
  12446. &is_script_resource,
  12447. &is_websocket_request,
  12448. &is_put_or_delete_request);
  12449. callback_handler = NULL;
  12450. /* Here we are at a dead end:
  12451. * According to URI matching, a callback should be
  12452. * responsible for handling the request,
  12453. * we called it, but the callback declared itself
  12454. * not responsible.
  12455. * We use a goto here, to get out of this dead end,
  12456. * and continue with the default handling.
  12457. * A goto here is simpler and better to understand
  12458. * than some curious loop. */
  12459. goto no_callback_resource;
  12460. }
  12461. } else {
  12462. #if defined(USE_WEBSOCKET)
  12463. handle_websocket_request(conn,
  12464. path,
  12465. is_callback_resource,
  12466. subprotocols,
  12467. ws_connect_handler,
  12468. ws_ready_handler,
  12469. ws_data_handler,
  12470. ws_close_handler,
  12471. callback_data);
  12472. #endif
  12473. }
  12474. return;
  12475. }
  12476. /* 8. handle websocket requests */
  12477. #if defined(USE_WEBSOCKET)
  12478. if (is_websocket_request) {
  12479. if (is_script_resource) {
  12480. if (is_in_script_path(conn, path)) {
  12481. /* Websocket Lua script */
  12482. handle_websocket_request(conn,
  12483. path,
  12484. 0 /* Lua Script */,
  12485. NULL,
  12486. NULL,
  12487. NULL,
  12488. NULL,
  12489. NULL,
  12490. conn->phys_ctx->user_data);
  12491. } else {
  12492. /* Script was in an illegal path */
  12493. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12494. }
  12495. } else {
  12496. #if defined(MG_LEGACY_INTERFACE)
  12497. handle_websocket_request(
  12498. conn,
  12499. path,
  12500. !is_script_resource /* could be deprecated global callback
  12501. */
  12502. ,
  12503. NULL,
  12504. deprecated_websocket_connect_wrapper,
  12505. deprecated_websocket_ready_wrapper,
  12506. deprecated_websocket_data_wrapper,
  12507. NULL,
  12508. conn->phys_ctx->callbacks);
  12509. #else
  12510. mg_send_http_error(conn, 404, "%s", "Not found");
  12511. #endif
  12512. }
  12513. return;
  12514. } else
  12515. #endif
  12516. #if defined(NO_FILES)
  12517. /* 9a. In case the server uses only callbacks, this uri is
  12518. * unknown.
  12519. * Then, all request handling ends here. */
  12520. mg_send_http_error(conn, 404, "%s", "Not Found");
  12521. #else
  12522. /* 9b. This request is either for a static file or resource handled
  12523. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12524. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12525. mg_send_http_error(conn, 404, "%s", "Not Found");
  12526. return;
  12527. }
  12528. /* 10. Request is handled by a script */
  12529. if (is_script_resource) {
  12530. handle_file_based_request(conn, path, &file);
  12531. return;
  12532. }
  12533. /* 11. Handle put/delete/mkcol requests */
  12534. if (is_put_or_delete_request) {
  12535. /* 11.1. PUT method */
  12536. if (!strcmp(ri->request_method, "PUT")) {
  12537. put_file(conn, path);
  12538. return;
  12539. }
  12540. /* 11.2. DELETE method */
  12541. if (!strcmp(ri->request_method, "DELETE")) {
  12542. delete_file(conn, path);
  12543. return;
  12544. }
  12545. /* 11.3. MKCOL method */
  12546. if (!strcmp(ri->request_method, "MKCOL")) {
  12547. mkcol(conn, path);
  12548. return;
  12549. }
  12550. /* 11.4. PATCH method
  12551. * This method is not supported for static resources,
  12552. * only for scripts (Lua, CGI) and callbacks. */
  12553. mg_send_http_error(conn,
  12554. 405,
  12555. "%s method not allowed",
  12556. conn->request_info.request_method);
  12557. return;
  12558. }
  12559. /* 11. File does not exist, or it was configured that it should be
  12560. * hidden */
  12561. if (!is_found || (must_hide_file(conn, path))) {
  12562. mg_send_http_error(conn, 404, "%s", "Not found");
  12563. return;
  12564. }
  12565. /* 12. Directory uris should end with a slash */
  12566. if (file.stat.is_directory && (uri_len > 0)
  12567. && (ri->local_uri[uri_len - 1] != '/')) {
  12568. gmt_time_string(date, sizeof(date), &curtime);
  12569. mg_printf(conn,
  12570. "HTTP/1.1 301 Moved Permanently\r\n"
  12571. "Location: %s/\r\n"
  12572. "Date: %s\r\n"
  12573. /* "Cache-Control: private\r\n" (= default) */
  12574. "Content-Length: 0\r\n"
  12575. "Connection: %s\r\n",
  12576. ri->request_uri,
  12577. date,
  12578. suggest_connection_header(conn));
  12579. send_additional_header(conn);
  12580. mg_printf(conn, "\r\n");
  12581. return;
  12582. }
  12583. /* 13. Handle other methods than GET/HEAD */
  12584. /* 13.1. Handle PROPFIND */
  12585. if (!strcmp(ri->request_method, "PROPFIND")) {
  12586. handle_propfind(conn, path, &file.stat);
  12587. return;
  12588. }
  12589. /* 13.2. Handle OPTIONS for files */
  12590. if (!strcmp(ri->request_method, "OPTIONS")) {
  12591. /* This standard handler is only used for real files.
  12592. * Scripts should support the OPTIONS method themselves, to allow a
  12593. * maximum flexibility.
  12594. * Lua and CGI scripts may fully support CORS this way (including
  12595. * preflights). */
  12596. send_options(conn);
  12597. return;
  12598. }
  12599. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12600. if ((0 != strcmp(ri->request_method, "GET"))
  12601. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12602. mg_send_http_error(conn,
  12603. 405,
  12604. "%s method not allowed",
  12605. conn->request_info.request_method);
  12606. return;
  12607. }
  12608. /* 14. directories */
  12609. if (file.stat.is_directory) {
  12610. /* Substitute files have already been handled above. */
  12611. /* Here we can either generate and send a directory listing,
  12612. * or send an "access denied" error. */
  12613. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12614. "yes")) {
  12615. handle_directory_request(conn, path);
  12616. } else {
  12617. mg_send_http_error(conn,
  12618. 403,
  12619. "%s",
  12620. "Error: Directory listing denied");
  12621. }
  12622. return;
  12623. }
  12624. /* 15. read a normal file with GET or HEAD */
  12625. handle_file_based_request(conn, path, &file);
  12626. #endif /* !defined(NO_FILES) */
  12627. }
  12628. /* Include HTTP/2 modules */
  12629. #ifdef USE_HTTP2
  12630. #if defined(NO_SSL)
  12631. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  12632. #endif
  12633. #include "mod_http2.inl"
  12634. #endif
  12635. #if !defined(NO_FILESYSTEMS)
  12636. static void
  12637. handle_file_based_request(struct mg_connection *conn,
  12638. const char *path,
  12639. struct mg_file *file)
  12640. {
  12641. if (!conn || !conn->dom_ctx) {
  12642. return;
  12643. }
  12644. if (0) {
  12645. #if defined(USE_LUA)
  12646. } else if (match_prefix(
  12647. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12648. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12649. path)
  12650. > 0) {
  12651. if (is_in_script_path(conn, path)) {
  12652. /* Lua server page: an SSI like page containing mostly plain
  12653. * html
  12654. * code
  12655. * plus some tags with server generated contents. */
  12656. handle_lsp_request(conn, path, file, NULL);
  12657. } else {
  12658. /* Script was in an illegal path */
  12659. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12660. }
  12661. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12662. strlen(
  12663. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12664. path)
  12665. > 0) {
  12666. if (is_in_script_path(conn, path)) {
  12667. /* Lua in-server module script: a CGI like script used to
  12668. * generate
  12669. * the
  12670. * entire reply. */
  12671. mg_exec_lua_script(conn, path, NULL);
  12672. } else {
  12673. /* Script was in an illegal path */
  12674. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12675. }
  12676. #endif
  12677. #if defined(USE_DUKTAPE)
  12678. } else if (match_prefix(
  12679. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12680. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12681. path)
  12682. > 0) {
  12683. if (is_in_script_path(conn, path)) {
  12684. /* Call duktape to generate the page */
  12685. mg_exec_duktape_script(conn, path);
  12686. } else {
  12687. /* Script was in an illegal path */
  12688. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12689. }
  12690. #endif
  12691. #if !defined(NO_CGI)
  12692. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12693. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12694. path)
  12695. > 0) {
  12696. if (is_in_script_path(conn, path)) {
  12697. /* CGI scripts may support all HTTP methods */
  12698. handle_cgi_request(conn, path);
  12699. } else {
  12700. /* Script was in an illegal path */
  12701. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12702. }
  12703. #endif /* !NO_CGI */
  12704. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12705. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12706. path)
  12707. > 0) {
  12708. if (is_in_script_path(conn, path)) {
  12709. handle_ssi_file_request(conn, path, file);
  12710. } else {
  12711. /* Script was in an illegal path */
  12712. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12713. }
  12714. #if !defined(NO_CACHING)
  12715. } else if ((!conn->in_error_handler)
  12716. && is_not_modified(conn, &file->stat)) {
  12717. /* Send 304 "Not Modified" - this must not send any body data */
  12718. handle_not_modified_static_file_request(conn, file);
  12719. #endif /* !NO_CACHING */
  12720. } else {
  12721. handle_static_file_request(conn, path, file, NULL, NULL);
  12722. }
  12723. }
  12724. #endif /* NO_FILESYSTEMS */
  12725. static void
  12726. close_all_listening_sockets(struct mg_context *ctx)
  12727. {
  12728. unsigned int i;
  12729. if (!ctx) {
  12730. return;
  12731. }
  12732. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12733. closesocket(ctx->listening_sockets[i].sock);
  12734. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12735. }
  12736. mg_free(ctx->listening_sockets);
  12737. ctx->listening_sockets = NULL;
  12738. mg_free(ctx->listening_socket_fds);
  12739. ctx->listening_socket_fds = NULL;
  12740. }
  12741. /* Valid listening port specification is: [ip_address:]port[s]
  12742. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12743. * Examples for IPv6: [::]:80, [::1]:80,
  12744. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12745. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12746. * In order to bind to both, IPv4 and IPv6, you can either add
  12747. * both ports using 8080,[::]:8080, or the short form +8080.
  12748. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12749. * one only accepting IPv4 the other only IPv6. +8080 creates
  12750. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12751. * environment, they might work differently, or might not work
  12752. * at all - it must be tested what options work best in the
  12753. * relevant network environment.
  12754. */
  12755. static int
  12756. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12757. {
  12758. unsigned int a, b, c, d;
  12759. unsigned port;
  12760. unsigned long portUL;
  12761. int ch, len;
  12762. const char *cb;
  12763. char *endptr;
  12764. #if defined(USE_IPV6)
  12765. char buf[100] = {0};
  12766. #endif
  12767. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12768. * Also, all-zeroes in the socket address means binding to all addresses
  12769. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12770. memset(so, 0, sizeof(*so));
  12771. so->lsa.sin.sin_family = AF_INET;
  12772. *ip_version = 0;
  12773. /* Initialize port and len as invalid. */
  12774. port = 0;
  12775. len = 0;
  12776. /* Test for different ways to format this string */
  12777. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12778. == 5) {
  12779. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12780. so->lsa.sin.sin_addr.s_addr =
  12781. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12782. so->lsa.sin.sin_port = htons((uint16_t)port);
  12783. *ip_version = 4;
  12784. #if defined(USE_IPV6)
  12785. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12786. && mg_inet_pton(
  12787. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12788. /* IPv6 address, examples: see above */
  12789. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12790. */
  12791. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12792. *ip_version = 6;
  12793. #endif
  12794. } else if ((vec->ptr[0] == '+')
  12795. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12796. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12797. /* Add 1 to len for the + character we skipped before */
  12798. len++;
  12799. #if defined(USE_IPV6)
  12800. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12801. so->lsa.sin6.sin6_family = AF_INET6;
  12802. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12803. *ip_version = 4 + 6;
  12804. #else
  12805. /* Bind to IPv4 only, since IPv6 is not built in. */
  12806. so->lsa.sin.sin_port = htons((uint16_t)port);
  12807. *ip_version = 4;
  12808. #endif
  12809. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12810. && (vec->ptr != endptr)) {
  12811. len = (int)(endptr - vec->ptr);
  12812. port = (uint16_t)portUL;
  12813. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12814. so->lsa.sin.sin_port = htons((uint16_t)port);
  12815. *ip_version = 4;
  12816. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12817. /* String could be a hostname. This check algotithm
  12818. * will only work for RFC 952 compliant hostnames,
  12819. * starting with a letter, containing only letters,
  12820. * digits and hyphen ('-'). Newer specs may allow
  12821. * more, but this is not guaranteed here, since it
  12822. * may interfere with rules for port option lists. */
  12823. /* According to RFC 1035, hostnames are restricted to 255 characters
  12824. * in total (63 between two dots). */
  12825. char hostname[256];
  12826. size_t hostnlen = (size_t)(cb - vec->ptr);
  12827. if (hostnlen >= sizeof(hostname)) {
  12828. /* This would be invalid in any case */
  12829. *ip_version = 0;
  12830. return 0;
  12831. }
  12832. memcpy(hostname, vec->ptr, hostnlen);
  12833. hostname[hostnlen] = 0;
  12834. if (mg_inet_pton(
  12835. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12836. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12837. *ip_version = 4;
  12838. so->lsa.sin.sin_family = AF_INET;
  12839. so->lsa.sin.sin_port = htons((uint16_t)port);
  12840. len += (int)(hostnlen + 1);
  12841. } else {
  12842. port = 0;
  12843. len = 0;
  12844. }
  12845. #if defined(USE_IPV6)
  12846. } else if (mg_inet_pton(AF_INET6,
  12847. hostname,
  12848. &so->lsa.sin6,
  12849. sizeof(so->lsa.sin6))) {
  12850. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12851. *ip_version = 6;
  12852. so->lsa.sin6.sin6_family = AF_INET6;
  12853. so->lsa.sin.sin_port = htons((uint16_t)port);
  12854. len += (int)(hostnlen + 1);
  12855. } else {
  12856. port = 0;
  12857. len = 0;
  12858. }
  12859. #endif
  12860. }
  12861. } else {
  12862. /* Parsing failure. */
  12863. }
  12864. /* sscanf and the option splitting code ensure the following condition
  12865. */
  12866. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12867. *ip_version = 0;
  12868. return 0;
  12869. }
  12870. ch = vec->ptr[len]; /* Next character after the port number */
  12871. so->is_ssl = (ch == 's');
  12872. so->ssl_redir = (ch == 'r');
  12873. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12874. if (is_valid_port(port)
  12875. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12876. return 1;
  12877. }
  12878. /* Reset ip_version to 0 if there is an error */
  12879. *ip_version = 0;
  12880. return 0;
  12881. }
  12882. /* Is there any SSL port in use? */
  12883. static int
  12884. is_ssl_port_used(const char *ports)
  12885. {
  12886. if (ports) {
  12887. /* There are several different allowed syntax variants:
  12888. * - "80" for a single port using every network interface
  12889. * - "localhost:80" for a single port using only localhost
  12890. * - "80,localhost:8080" for two ports, one bound to localhost
  12891. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12892. * to IPv4 localhost, one to IPv6 localhost
  12893. * - "+80" use port 80 for IPv4 and IPv6
  12894. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12895. * for both: IPv4 and IPv4
  12896. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12897. * additionally port 8080 bound to localhost connections
  12898. *
  12899. * If we just look for 's' anywhere in the string, "localhost:80"
  12900. * will be detected as SSL (false positive).
  12901. * Looking for 's' after a digit may cause false positives in
  12902. * "my24service:8080".
  12903. * Looking from 's' backward if there are only ':' and numbers
  12904. * before will not work for "24service:8080" (non SSL, port 8080)
  12905. * or "24s" (SSL, port 24).
  12906. *
  12907. * Remark: Initially hostnames were not allowed to start with a
  12908. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12909. * Section 2.1).
  12910. *
  12911. * To get this correct, the entire string must be parsed as a whole,
  12912. * reading it as a list element for element and parsing with an
  12913. * algorithm equivalent to parse_port_string.
  12914. *
  12915. * In fact, we use local interface names here, not arbitrary
  12916. * hostnames, so in most cases the only name will be "localhost".
  12917. *
  12918. * So, for now, we use this simple algorithm, that may still return
  12919. * a false positive in bizarre cases.
  12920. */
  12921. int i;
  12922. int portslen = (int)strlen(ports);
  12923. char prevIsNumber = 0;
  12924. for (i = 0; i < portslen; i++) {
  12925. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12926. return 1;
  12927. }
  12928. if (ports[i] >= '0' && ports[i] <= '9') {
  12929. prevIsNumber = 1;
  12930. } else {
  12931. prevIsNumber = 0;
  12932. }
  12933. }
  12934. }
  12935. return 0;
  12936. }
  12937. static int
  12938. set_ports_option(struct mg_context *phys_ctx)
  12939. {
  12940. const char *list;
  12941. int on = 1;
  12942. #if defined(USE_IPV6)
  12943. int off = 0;
  12944. #endif
  12945. struct vec vec;
  12946. struct socket so, *ptr;
  12947. struct mg_pollfd *pfd;
  12948. union usa usa;
  12949. socklen_t len;
  12950. int ip_version;
  12951. int portsTotal = 0;
  12952. int portsOk = 0;
  12953. const char *opt_txt;
  12954. long opt_listen_backlog;
  12955. if (!phys_ctx) {
  12956. return 0;
  12957. }
  12958. memset(&so, 0, sizeof(so));
  12959. memset(&usa, 0, sizeof(usa));
  12960. len = sizeof(usa);
  12961. list = phys_ctx->dd.config[LISTENING_PORTS];
  12962. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12963. portsTotal++;
  12964. if (!parse_port_string(&vec, &so, &ip_version)) {
  12965. mg_cry_ctx_internal(
  12966. phys_ctx,
  12967. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12968. (int)vec.len,
  12969. vec.ptr,
  12970. portsTotal,
  12971. "[IP_ADDRESS:]PORT[s|r]");
  12972. continue;
  12973. }
  12974. #if !defined(NO_SSL)
  12975. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12976. mg_cry_ctx_internal(phys_ctx,
  12977. "Cannot add SSL socket (entry %i)",
  12978. portsTotal);
  12979. continue;
  12980. }
  12981. #endif
  12982. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12983. == INVALID_SOCKET) {
  12984. mg_cry_ctx_internal(phys_ctx,
  12985. "cannot create socket (entry %i)",
  12986. portsTotal);
  12987. continue;
  12988. }
  12989. #if defined(_WIN32)
  12990. /* Windows SO_REUSEADDR lets many procs binds to a
  12991. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12992. * if someone already has the socket -- DTL */
  12993. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12994. * Windows might need a few seconds before
  12995. * the same port can be used again in the
  12996. * same process, so a short Sleep may be
  12997. * required between mg_stop and mg_start.
  12998. */
  12999. if (setsockopt(so.sock,
  13000. SOL_SOCKET,
  13001. SO_EXCLUSIVEADDRUSE,
  13002. (SOCK_OPT_TYPE)&on,
  13003. sizeof(on))
  13004. != 0) {
  13005. /* Set reuse option, but don't abort on errors. */
  13006. mg_cry_ctx_internal(
  13007. phys_ctx,
  13008. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13009. portsTotal);
  13010. }
  13011. #else
  13012. if (setsockopt(so.sock,
  13013. SOL_SOCKET,
  13014. SO_REUSEADDR,
  13015. (SOCK_OPT_TYPE)&on,
  13016. sizeof(on))
  13017. != 0) {
  13018. /* Set reuse option, but don't abort on errors. */
  13019. mg_cry_ctx_internal(
  13020. phys_ctx,
  13021. "cannot set socket option SO_REUSEADDR (entry %i)",
  13022. portsTotal);
  13023. }
  13024. #endif
  13025. if (ip_version > 4) {
  13026. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13027. #if defined(USE_IPV6)
  13028. if (ip_version > 6) {
  13029. if (so.lsa.sa.sa_family == AF_INET6
  13030. && setsockopt(so.sock,
  13031. IPPROTO_IPV6,
  13032. IPV6_V6ONLY,
  13033. (void *)&off,
  13034. sizeof(off))
  13035. != 0) {
  13036. /* Set IPv6 only option, but don't abort on errors. */
  13037. mg_cry_ctx_internal(phys_ctx,
  13038. "cannot set socket option "
  13039. "IPV6_V6ONLY=off (entry %i)",
  13040. portsTotal);
  13041. }
  13042. } else {
  13043. if (so.lsa.sa.sa_family == AF_INET6
  13044. && setsockopt(so.sock,
  13045. IPPROTO_IPV6,
  13046. IPV6_V6ONLY,
  13047. (void *)&on,
  13048. sizeof(on))
  13049. != 0) {
  13050. /* Set IPv6 only option, but don't abort on errors. */
  13051. mg_cry_ctx_internal(phys_ctx,
  13052. "cannot set socket option "
  13053. "IPV6_V6ONLY=on (entry %i)",
  13054. portsTotal);
  13055. }
  13056. }
  13057. #else
  13058. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13059. closesocket(so.sock);
  13060. so.sock = INVALID_SOCKET;
  13061. continue;
  13062. #endif
  13063. }
  13064. if (so.lsa.sa.sa_family == AF_INET) {
  13065. len = sizeof(so.lsa.sin);
  13066. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13067. mg_cry_ctx_internal(phys_ctx,
  13068. "cannot bind to %.*s: %d (%s)",
  13069. (int)vec.len,
  13070. vec.ptr,
  13071. (int)ERRNO,
  13072. strerror(errno));
  13073. closesocket(so.sock);
  13074. so.sock = INVALID_SOCKET;
  13075. continue;
  13076. }
  13077. }
  13078. #if defined(USE_IPV6)
  13079. else if (so.lsa.sa.sa_family == AF_INET6) {
  13080. len = sizeof(so.lsa.sin6);
  13081. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13082. mg_cry_ctx_internal(phys_ctx,
  13083. "cannot bind to IPv6 %.*s: %d (%s)",
  13084. (int)vec.len,
  13085. vec.ptr,
  13086. (int)ERRNO,
  13087. strerror(errno));
  13088. closesocket(so.sock);
  13089. so.sock = INVALID_SOCKET;
  13090. continue;
  13091. }
  13092. }
  13093. #endif
  13094. else {
  13095. mg_cry_ctx_internal(
  13096. phys_ctx,
  13097. "cannot bind: address family not supported (entry %i)",
  13098. portsTotal);
  13099. closesocket(so.sock);
  13100. so.sock = INVALID_SOCKET;
  13101. continue;
  13102. }
  13103. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13104. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13105. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13106. mg_cry_ctx_internal(phys_ctx,
  13107. "%s value \"%s\" is invalid",
  13108. config_options[LISTEN_BACKLOG_SIZE].name,
  13109. opt_txt);
  13110. closesocket(so.sock);
  13111. so.sock = INVALID_SOCKET;
  13112. continue;
  13113. }
  13114. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13115. mg_cry_ctx_internal(phys_ctx,
  13116. "cannot listen to %.*s: %d (%s)",
  13117. (int)vec.len,
  13118. vec.ptr,
  13119. (int)ERRNO,
  13120. strerror(errno));
  13121. closesocket(so.sock);
  13122. so.sock = INVALID_SOCKET;
  13123. continue;
  13124. }
  13125. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13126. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13127. int err = (int)ERRNO;
  13128. mg_cry_ctx_internal(phys_ctx,
  13129. "call to getsockname failed %.*s: %d (%s)",
  13130. (int)vec.len,
  13131. vec.ptr,
  13132. err,
  13133. strerror(errno));
  13134. closesocket(so.sock);
  13135. so.sock = INVALID_SOCKET;
  13136. continue;
  13137. }
  13138. /* Update lsa port in case of random free ports */
  13139. #if defined(USE_IPV6)
  13140. if (so.lsa.sa.sa_family == AF_INET6) {
  13141. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13142. } else
  13143. #endif
  13144. {
  13145. so.lsa.sin.sin_port = usa.sin.sin_port;
  13146. }
  13147. if ((ptr = (struct socket *)
  13148. mg_realloc_ctx(phys_ctx->listening_sockets,
  13149. (phys_ctx->num_listening_sockets + 1)
  13150. * sizeof(phys_ctx->listening_sockets[0]),
  13151. phys_ctx))
  13152. == NULL) {
  13153. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13154. closesocket(so.sock);
  13155. so.sock = INVALID_SOCKET;
  13156. continue;
  13157. }
  13158. if ((pfd = (struct mg_pollfd *)
  13159. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13160. (phys_ctx->num_listening_sockets + 1)
  13161. * sizeof(phys_ctx->listening_socket_fds[0]),
  13162. phys_ctx))
  13163. == NULL) {
  13164. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13165. closesocket(so.sock);
  13166. so.sock = INVALID_SOCKET;
  13167. mg_free(ptr);
  13168. continue;
  13169. }
  13170. set_close_on_exec(so.sock, NULL, phys_ctx);
  13171. phys_ctx->listening_sockets = ptr;
  13172. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13173. phys_ctx->listening_socket_fds = pfd;
  13174. phys_ctx->num_listening_sockets++;
  13175. portsOk++;
  13176. }
  13177. if (portsOk != portsTotal) {
  13178. close_all_listening_sockets(phys_ctx);
  13179. portsOk = 0;
  13180. }
  13181. return portsOk;
  13182. }
  13183. static const char *
  13184. header_val(const struct mg_connection *conn, const char *header)
  13185. {
  13186. const char *header_value;
  13187. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13188. return "-";
  13189. } else {
  13190. return header_value;
  13191. }
  13192. }
  13193. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13194. static void log_access(const struct mg_connection *conn);
  13195. #include "external_log_access.inl"
  13196. #elif !defined(NO_FILESYSTEMS)
  13197. static void
  13198. log_access(const struct mg_connection *conn)
  13199. {
  13200. const struct mg_request_info *ri;
  13201. struct mg_file fi;
  13202. char date[64], src_addr[IP_ADDR_STR_LEN];
  13203. struct tm *tm;
  13204. const char *referer;
  13205. const char *user_agent;
  13206. char buf[4096];
  13207. if (!conn || !conn->dom_ctx) {
  13208. return;
  13209. }
  13210. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13211. if (mg_fopen(conn,
  13212. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13213. MG_FOPEN_MODE_APPEND,
  13214. &fi)
  13215. == 0) {
  13216. fi.access.fp = NULL;
  13217. }
  13218. } else {
  13219. fi.access.fp = NULL;
  13220. }
  13221. /* Log is written to a file and/or a callback. If both are not set,
  13222. * executing the rest of the function is pointless. */
  13223. if ((fi.access.fp == NULL)
  13224. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13225. return;
  13226. }
  13227. tm = localtime(&conn->conn_birth_time);
  13228. if (tm != NULL) {
  13229. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13230. } else {
  13231. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13232. date[sizeof(date) - 1] = '\0';
  13233. }
  13234. ri = &conn->request_info;
  13235. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13236. referer = header_val(conn, "Referer");
  13237. user_agent = header_val(conn, "User-Agent");
  13238. mg_snprintf(conn,
  13239. NULL, /* Ignore truncation in access log */
  13240. buf,
  13241. sizeof(buf),
  13242. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13243. src_addr,
  13244. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13245. date,
  13246. ri->request_method ? ri->request_method : "-",
  13247. ri->request_uri ? ri->request_uri : "-",
  13248. ri->query_string ? "?" : "",
  13249. ri->query_string ? ri->query_string : "",
  13250. ri->http_version,
  13251. conn->status_code,
  13252. conn->num_bytes_sent,
  13253. referer,
  13254. user_agent);
  13255. if (conn->phys_ctx->callbacks.log_access) {
  13256. conn->phys_ctx->callbacks.log_access(conn, buf);
  13257. }
  13258. if (fi.access.fp) {
  13259. int ok = 1;
  13260. flockfile(fi.access.fp);
  13261. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13262. ok = 0;
  13263. }
  13264. if (fflush(fi.access.fp) != 0) {
  13265. ok = 0;
  13266. }
  13267. funlockfile(fi.access.fp);
  13268. if (mg_fclose(&fi.access) != 0) {
  13269. ok = 0;
  13270. }
  13271. if (!ok) {
  13272. mg_cry_internal(conn,
  13273. "Error writing log file %s",
  13274. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13275. }
  13276. }
  13277. }
  13278. #else
  13279. #error Must either enable filesystems or provide a custom log_access implementation
  13280. #endif /* Externally provided function */
  13281. /* Verify given socket address against the ACL.
  13282. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13283. */
  13284. static int
  13285. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13286. {
  13287. int allowed, flag;
  13288. uint32_t net, mask;
  13289. struct vec vec;
  13290. if (phys_ctx) {
  13291. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13292. /* If any ACL is set, deny by default */
  13293. allowed = (list == NULL) ? '+' : '-';
  13294. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13295. flag = vec.ptr[0];
  13296. if ((flag != '+' && flag != '-')
  13297. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13298. mg_cry_ctx_internal(phys_ctx,
  13299. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13300. __func__);
  13301. return -1;
  13302. }
  13303. if (net == (remote_ip & mask)) {
  13304. allowed = flag;
  13305. }
  13306. }
  13307. return allowed == '+';
  13308. }
  13309. return -1;
  13310. }
  13311. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13312. static int
  13313. set_uid_option(struct mg_context *phys_ctx)
  13314. {
  13315. int success = 0;
  13316. if (phys_ctx) {
  13317. /* We are currently running as curr_uid. */
  13318. const uid_t curr_uid = getuid();
  13319. /* If set, we want to run as run_as_user. */
  13320. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13321. const struct passwd *to_pw = NULL;
  13322. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13323. /* run_as_user does not exist on the system. We can't proceed
  13324. * further. */
  13325. mg_cry_ctx_internal(phys_ctx,
  13326. "%s: unknown user [%s]",
  13327. __func__,
  13328. run_as_user);
  13329. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13330. /* There was either no request to change user, or we're already
  13331. * running as run_as_user. Nothing else to do.
  13332. */
  13333. success = 1;
  13334. } else {
  13335. /* Valid change request. */
  13336. if (setgid(to_pw->pw_gid) == -1) {
  13337. mg_cry_ctx_internal(phys_ctx,
  13338. "%s: setgid(%s): %s",
  13339. __func__,
  13340. run_as_user,
  13341. strerror(errno));
  13342. } else if (setgroups(0, NULL) == -1) {
  13343. mg_cry_ctx_internal(phys_ctx,
  13344. "%s: setgroups(): %s",
  13345. __func__,
  13346. strerror(errno));
  13347. } else if (setuid(to_pw->pw_uid) == -1) {
  13348. mg_cry_ctx_internal(phys_ctx,
  13349. "%s: setuid(%s): %s",
  13350. __func__,
  13351. run_as_user,
  13352. strerror(errno));
  13353. } else {
  13354. success = 1;
  13355. }
  13356. }
  13357. }
  13358. return success;
  13359. }
  13360. #endif /* !_WIN32 */
  13361. static void
  13362. tls_dtor(void *key)
  13363. {
  13364. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13365. /* key == pthread_getspecific(sTlsKey); */
  13366. if (tls) {
  13367. if (tls->is_master == 2) {
  13368. tls->is_master = -3; /* Mark memory as dead */
  13369. mg_free(tls);
  13370. }
  13371. }
  13372. pthread_setspecific(sTlsKey, NULL);
  13373. }
  13374. #if !defined(NO_SSL)
  13375. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13376. struct mg_domain_context *dom_ctx,
  13377. const char *pem,
  13378. const char *chain);
  13379. static const char *ssl_error(void);
  13380. static int
  13381. refresh_trust(struct mg_connection *conn)
  13382. {
  13383. struct stat cert_buf;
  13384. int64_t t = 0;
  13385. const char *pem;
  13386. const char *chain;
  13387. int should_verify_peer;
  13388. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13389. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13390. * refresh_trust still can not work. */
  13391. return 0;
  13392. }
  13393. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13394. if (chain == NULL) {
  13395. /* pem is not NULL here */
  13396. chain = pem;
  13397. }
  13398. if (*chain == 0) {
  13399. chain = NULL;
  13400. }
  13401. if (stat(pem, &cert_buf) != -1) {
  13402. t = (int64_t)cert_buf.st_mtime;
  13403. }
  13404. mg_lock_context(conn->phys_ctx);
  13405. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13406. conn->dom_ctx->ssl_cert_last_mtime = t;
  13407. should_verify_peer = 0;
  13408. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13409. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13410. == 0) {
  13411. should_verify_peer = 1;
  13412. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13413. "optional")
  13414. == 0) {
  13415. should_verify_peer = 1;
  13416. }
  13417. }
  13418. if (should_verify_peer) {
  13419. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13420. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13421. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13422. ca_file,
  13423. ca_path)
  13424. != 1) {
  13425. mg_unlock_context(conn->phys_ctx);
  13426. mg_cry_ctx_internal(
  13427. conn->phys_ctx,
  13428. "SSL_CTX_load_verify_locations error: %s "
  13429. "ssl_verify_peer requires setting "
  13430. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13431. "present in "
  13432. "the .conf file?",
  13433. ssl_error());
  13434. return 0;
  13435. }
  13436. }
  13437. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13438. mg_unlock_context(conn->phys_ctx);
  13439. return 0;
  13440. }
  13441. }
  13442. mg_unlock_context(conn->phys_ctx);
  13443. return 1;
  13444. }
  13445. #if defined(OPENSSL_API_1_1)
  13446. #else
  13447. static pthread_mutex_t *ssl_mutexes;
  13448. #endif /* OPENSSL_API_1_1 */
  13449. static int
  13450. sslize(struct mg_connection *conn,
  13451. int (*func)(SSL *),
  13452. const struct mg_client_options *client_options)
  13453. {
  13454. int ret, err;
  13455. int short_trust;
  13456. unsigned timeout = 1024;
  13457. unsigned i;
  13458. if (!conn) {
  13459. return 0;
  13460. }
  13461. short_trust =
  13462. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13463. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13464. if (short_trust) {
  13465. int trust_ret = refresh_trust(conn);
  13466. if (!trust_ret) {
  13467. return trust_ret;
  13468. }
  13469. }
  13470. mg_lock_context(conn->phys_ctx);
  13471. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13472. mg_unlock_context(conn->phys_ctx);
  13473. if (conn->ssl == NULL) {
  13474. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13475. OPENSSL_REMOVE_THREAD_STATE();
  13476. return 0;
  13477. }
  13478. SSL_set_app_data(conn->ssl, (char *)conn);
  13479. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13480. if (ret != 1) {
  13481. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13482. SSL_free(conn->ssl);
  13483. conn->ssl = NULL;
  13484. OPENSSL_REMOVE_THREAD_STATE();
  13485. return 0;
  13486. }
  13487. if (client_options) {
  13488. if (client_options->host_name) {
  13489. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13490. }
  13491. }
  13492. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13493. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13494. /* NOTE: The loop below acts as a back-off, so we can end
  13495. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13496. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13497. if (to >= 0) {
  13498. timeout = (unsigned)to;
  13499. }
  13500. }
  13501. /* SSL functions may fail and require to be called again:
  13502. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13503. * Here "func" could be SSL_connect or SSL_accept. */
  13504. for (i = 0; i <= timeout; i += 50) {
  13505. ERR_clear_error();
  13506. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13507. ret = func(conn->ssl);
  13508. if (ret != 1) {
  13509. err = SSL_get_error(conn->ssl, ret);
  13510. if ((err == SSL_ERROR_WANT_CONNECT)
  13511. || (err == SSL_ERROR_WANT_ACCEPT)
  13512. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13513. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13514. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13515. /* Don't wait if the server is going to be stopped. */
  13516. break;
  13517. }
  13518. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13519. /* Simply retry the function call. */
  13520. mg_sleep(50);
  13521. } else {
  13522. /* Need to retry the function call "later".
  13523. * See https://linux.die.net/man/3/ssl_get_error
  13524. * This is typical for non-blocking sockets. */
  13525. struct mg_pollfd pfd;
  13526. int pollres;
  13527. pfd.fd = conn->client.sock;
  13528. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13529. || (err == SSL_ERROR_WANT_WRITE))
  13530. ? POLLOUT
  13531. : POLLIN;
  13532. pollres =
  13533. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13534. if (pollres < 0) {
  13535. /* Break if error occured (-1)
  13536. * or server shutdown (-2) */
  13537. break;
  13538. }
  13539. }
  13540. } else if (err == SSL_ERROR_SYSCALL) {
  13541. /* This is an IO error. Look at errno. */
  13542. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13543. break;
  13544. } else {
  13545. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13546. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13547. break;
  13548. }
  13549. } else {
  13550. /* success */
  13551. break;
  13552. }
  13553. }
  13554. ERR_clear_error();
  13555. if (ret != 1) {
  13556. SSL_free(conn->ssl);
  13557. conn->ssl = NULL;
  13558. OPENSSL_REMOVE_THREAD_STATE();
  13559. return 0;
  13560. }
  13561. return 1;
  13562. }
  13563. /* Return OpenSSL error message (from CRYPTO lib) */
  13564. static const char *
  13565. ssl_error(void)
  13566. {
  13567. unsigned long err;
  13568. err = ERR_get_error();
  13569. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13570. }
  13571. static int
  13572. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13573. {
  13574. int i;
  13575. const char hexdigit[] = "0123456789abcdef";
  13576. if ((memlen <= 0) || (buflen <= 0)) {
  13577. return 0;
  13578. }
  13579. if (buflen < (3 * memlen)) {
  13580. return 0;
  13581. }
  13582. for (i = 0; i < memlen; i++) {
  13583. if (i > 0) {
  13584. buf[3 * i - 1] = ' ';
  13585. }
  13586. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13587. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13588. }
  13589. buf[3 * memlen - 1] = 0;
  13590. return 1;
  13591. }
  13592. static int
  13593. ssl_get_client_cert_info(const struct mg_connection *conn,
  13594. struct mg_client_cert *client_cert)
  13595. {
  13596. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13597. if (cert) {
  13598. char str_buf[1024];
  13599. unsigned char buf[256];
  13600. char *str_serial = NULL;
  13601. unsigned int ulen;
  13602. int ilen;
  13603. unsigned char *tmp_buf;
  13604. unsigned char *tmp_p;
  13605. /* Handle to algorithm used for fingerprint */
  13606. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13607. /* Get Subject and issuer */
  13608. X509_NAME *subj = X509_get_subject_name(cert);
  13609. X509_NAME *iss = X509_get_issuer_name(cert);
  13610. /* Get serial number */
  13611. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13612. /* Translate serial number to a hex string */
  13613. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13614. if (serial_bn) {
  13615. str_serial = BN_bn2hex(serial_bn);
  13616. BN_free(serial_bn);
  13617. }
  13618. client_cert->serial =
  13619. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13620. /* Translate subject and issuer to a string */
  13621. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13622. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13623. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13624. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13625. /* Calculate SHA1 fingerprint and store as a hex string */
  13626. ulen = 0;
  13627. /* ASN1_digest is deprecated. Do the calculation manually,
  13628. * using EVP_Digest. */
  13629. ilen = i2d_X509(cert, NULL);
  13630. tmp_buf = (ilen > 0)
  13631. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13632. conn->phys_ctx)
  13633. : NULL;
  13634. if (tmp_buf) {
  13635. tmp_p = tmp_buf;
  13636. (void)i2d_X509(cert, &tmp_p);
  13637. if (!EVP_Digest(
  13638. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13639. ulen = 0;
  13640. }
  13641. mg_free(tmp_buf);
  13642. }
  13643. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13644. *str_buf = 0;
  13645. }
  13646. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13647. client_cert->peer_cert = (void *)cert;
  13648. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13649. * see https://linux.die.net/man/3/bn_bn2hex */
  13650. OPENSSL_free(str_serial);
  13651. return 1;
  13652. }
  13653. return 0;
  13654. }
  13655. #if defined(OPENSSL_API_1_1)
  13656. #else
  13657. static void
  13658. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13659. {
  13660. (void)line;
  13661. (void)file;
  13662. if (mode & 1) {
  13663. /* 1 is CRYPTO_LOCK */
  13664. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13665. } else {
  13666. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13667. }
  13668. }
  13669. #endif /* OPENSSL_API_1_1 */
  13670. #if !defined(NO_SSL_DL)
  13671. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13672. static void *
  13673. load_tls_dll(char *ebuf,
  13674. size_t ebuf_len,
  13675. const char *dll_name,
  13676. struct ssl_func *sw,
  13677. int *feature_missing)
  13678. {
  13679. union {
  13680. void *p;
  13681. void (*fp)(void);
  13682. } u;
  13683. void *dll_handle;
  13684. struct ssl_func *fp;
  13685. int ok;
  13686. int truncated = 0;
  13687. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13688. mg_snprintf(NULL,
  13689. NULL, /* No truncation check for ebuf */
  13690. ebuf,
  13691. ebuf_len,
  13692. "%s: cannot load %s",
  13693. __func__,
  13694. dll_name);
  13695. return NULL;
  13696. }
  13697. ok = 1;
  13698. for (fp = sw; fp->name != NULL; fp++) {
  13699. #if defined(_WIN32)
  13700. /* GetProcAddress() returns pointer to function */
  13701. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13702. #else
  13703. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13704. * pointers to function pointers. We need to use a union to make a
  13705. * cast. */
  13706. u.p = dlsym(dll_handle, fp->name);
  13707. #endif /* _WIN32 */
  13708. /* Set pointer (might be NULL) */
  13709. fp->ptr = u.fp;
  13710. if (u.fp == NULL) {
  13711. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13712. if (feature_missing) {
  13713. feature_missing[fp->required]++;
  13714. }
  13715. if (fp->required == TLS_Mandatory) {
  13716. /* Mandatory function is missing */
  13717. if (ok) {
  13718. /* This is the first missing function.
  13719. * Create a new error message. */
  13720. mg_snprintf(NULL,
  13721. &truncated,
  13722. ebuf,
  13723. ebuf_len,
  13724. "%s: %s: cannot find %s",
  13725. __func__,
  13726. dll_name,
  13727. fp->name);
  13728. ok = 0;
  13729. } else {
  13730. /* This is yet anothermissing function.
  13731. * Append existing error message. */
  13732. size_t cur_len = strlen(ebuf);
  13733. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13734. mg_snprintf(NULL,
  13735. &truncated,
  13736. ebuf + cur_len,
  13737. ebuf_len - cur_len - 3,
  13738. ", %s",
  13739. fp->name);
  13740. if (truncated) {
  13741. /* If truncated, add "..." */
  13742. strcat(ebuf, "...");
  13743. }
  13744. }
  13745. }
  13746. }
  13747. }
  13748. }
  13749. if (!ok) {
  13750. (void)dlclose(dll_handle);
  13751. return NULL;
  13752. }
  13753. return dll_handle;
  13754. }
  13755. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13756. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13757. #endif /* NO_SSL_DL */
  13758. #if defined(SSL_ALREADY_INITIALIZED)
  13759. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13760. #else
  13761. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13762. #endif
  13763. static int
  13764. initialize_ssl(char *ebuf, size_t ebuf_len)
  13765. {
  13766. #if !defined(OPENSSL_API_1_1)
  13767. int i, num_locks;
  13768. size_t size;
  13769. #endif
  13770. if (ebuf_len > 0) {
  13771. ebuf[0] = 0;
  13772. }
  13773. #if !defined(NO_SSL_DL)
  13774. if (!cryptolib_dll_handle) {
  13775. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13776. cryptolib_dll_handle = load_tls_dll(
  13777. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13778. if (!cryptolib_dll_handle) {
  13779. mg_snprintf(NULL,
  13780. NULL, /* No truncation check for ebuf */
  13781. ebuf,
  13782. ebuf_len,
  13783. "%s: error loading library %s",
  13784. __func__,
  13785. CRYPTO_LIB);
  13786. DEBUG_TRACE("%s", ebuf);
  13787. return 0;
  13788. }
  13789. }
  13790. #endif /* NO_SSL_DL */
  13791. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13792. return 1;
  13793. }
  13794. #if !defined(OPENSSL_API_1_1)
  13795. /* Initialize locking callbacks, needed for thread safety.
  13796. * http://www.openssl.org/support/faq.html#PROG1
  13797. */
  13798. num_locks = CRYPTO_num_locks();
  13799. if (num_locks < 0) {
  13800. num_locks = 0;
  13801. }
  13802. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13803. /* allocate mutex array, if required */
  13804. if (num_locks == 0) {
  13805. /* No mutex array required */
  13806. ssl_mutexes = NULL;
  13807. } else {
  13808. /* Mutex array required - allocate it */
  13809. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13810. /* Check OOM */
  13811. if (ssl_mutexes == NULL) {
  13812. mg_snprintf(NULL,
  13813. NULL, /* No truncation check for ebuf */
  13814. ebuf,
  13815. ebuf_len,
  13816. "%s: cannot allocate mutexes: %s",
  13817. __func__,
  13818. ssl_error());
  13819. DEBUG_TRACE("%s", ebuf);
  13820. return 0;
  13821. }
  13822. /* initialize mutex array */
  13823. for (i = 0; i < num_locks; i++) {
  13824. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13825. mg_snprintf(NULL,
  13826. NULL, /* No truncation check for ebuf */
  13827. ebuf,
  13828. ebuf_len,
  13829. "%s: error initializing mutex %i of %i",
  13830. __func__,
  13831. i,
  13832. num_locks);
  13833. DEBUG_TRACE("%s", ebuf);
  13834. mg_free(ssl_mutexes);
  13835. return 0;
  13836. }
  13837. }
  13838. }
  13839. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13840. CRYPTO_set_id_callback(&mg_current_thread_id);
  13841. #endif /* OPENSSL_API_1_1 */
  13842. #if !defined(NO_SSL_DL)
  13843. if (!ssllib_dll_handle) {
  13844. ssllib_dll_handle =
  13845. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13846. if (!ssllib_dll_handle) {
  13847. #if !defined(OPENSSL_API_1_1)
  13848. mg_free(ssl_mutexes);
  13849. #endif
  13850. DEBUG_TRACE("%s", ebuf);
  13851. return 0;
  13852. }
  13853. }
  13854. #endif /* NO_SSL_DL */
  13855. #if defined(OPENSSL_API_1_1)
  13856. /* Initialize SSL library */
  13857. OPENSSL_init_ssl(0, NULL);
  13858. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13859. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13860. NULL);
  13861. #else
  13862. /* Initialize SSL library */
  13863. SSL_library_init();
  13864. SSL_load_error_strings();
  13865. #endif
  13866. return 1;
  13867. }
  13868. static int
  13869. ssl_use_pem_file(struct mg_context *phys_ctx,
  13870. struct mg_domain_context *dom_ctx,
  13871. const char *pem,
  13872. const char *chain)
  13873. {
  13874. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13875. mg_cry_ctx_internal(phys_ctx,
  13876. "%s: cannot open certificate file %s: %s",
  13877. __func__,
  13878. pem,
  13879. ssl_error());
  13880. return 0;
  13881. }
  13882. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13883. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13884. mg_cry_ctx_internal(phys_ctx,
  13885. "%s: cannot open private key file %s: %s",
  13886. __func__,
  13887. pem,
  13888. ssl_error());
  13889. return 0;
  13890. }
  13891. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13892. mg_cry_ctx_internal(phys_ctx,
  13893. "%s: certificate and private key do not match: %s",
  13894. __func__,
  13895. pem);
  13896. return 0;
  13897. }
  13898. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13899. * chain files that contain private keys and certificates in
  13900. * SSL_CTX_use_certificate_chain_file.
  13901. * The CivetWeb-Server used pem-Files that contained both information.
  13902. * In order to make wolfSSL work, it is split in two files.
  13903. * One file that contains key and certificate used by the server and
  13904. * an optional chain file for the ssl stack.
  13905. */
  13906. if (chain) {
  13907. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13908. mg_cry_ctx_internal(phys_ctx,
  13909. "%s: cannot use certificate chain file %s: %s",
  13910. __func__,
  13911. chain,
  13912. ssl_error());
  13913. return 0;
  13914. }
  13915. }
  13916. return 1;
  13917. }
  13918. #if defined(OPENSSL_API_1_1)
  13919. static unsigned long
  13920. ssl_get_protocol(int version_id)
  13921. {
  13922. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13923. if (version_id > 0)
  13924. ret |= SSL_OP_NO_SSLv2;
  13925. if (version_id > 1)
  13926. ret |= SSL_OP_NO_SSLv3;
  13927. if (version_id > 2)
  13928. ret |= SSL_OP_NO_TLSv1;
  13929. if (version_id > 3)
  13930. ret |= SSL_OP_NO_TLSv1_1;
  13931. if (version_id > 4)
  13932. ret |= SSL_OP_NO_TLSv1_2;
  13933. #if defined(SSL_OP_NO_TLSv1_3)
  13934. if (version_id > 5)
  13935. ret |= SSL_OP_NO_TLSv1_3;
  13936. #endif
  13937. return ret;
  13938. }
  13939. #else
  13940. static long
  13941. ssl_get_protocol(int version_id)
  13942. {
  13943. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13944. if (version_id > 0)
  13945. ret |= SSL_OP_NO_SSLv2;
  13946. if (version_id > 1)
  13947. ret |= SSL_OP_NO_SSLv3;
  13948. if (version_id > 2)
  13949. ret |= SSL_OP_NO_TLSv1;
  13950. if (version_id > 3)
  13951. ret |= SSL_OP_NO_TLSv1_1;
  13952. if (version_id > 4)
  13953. ret |= SSL_OP_NO_TLSv1_2;
  13954. #if defined(SSL_OP_NO_TLSv1_3)
  13955. if (version_id > 5)
  13956. ret |= SSL_OP_NO_TLSv1_3;
  13957. #endif
  13958. return (long)ret;
  13959. }
  13960. #endif /* OPENSSL_API_1_1 */
  13961. /* SSL callback documentation:
  13962. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13963. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13964. * https://linux.die.net/man/3/ssl_set_info_callback */
  13965. /* Note: There is no "const" for the first argument in the documentation
  13966. * examples, however some (maybe most, but not all) headers of OpenSSL
  13967. * versions / OpenSSL compatibility layers have it. Having a different
  13968. * definition will cause a warning in C and an error in C++. Use "const SSL
  13969. * *", while automatical conversion from "SSL *" works for all compilers,
  13970. * but not other way around */
  13971. static void
  13972. ssl_info_callback(const SSL *ssl, int what, int ret)
  13973. {
  13974. (void)ret;
  13975. if (what & SSL_CB_HANDSHAKE_START) {
  13976. SSL_get_app_data(ssl);
  13977. }
  13978. if (what & SSL_CB_HANDSHAKE_DONE) {
  13979. /* TODO: check for openSSL 1.1 */
  13980. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13981. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13982. }
  13983. }
  13984. static int
  13985. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13986. {
  13987. #if defined(GCC_DIAGNOSTIC)
  13988. #pragma GCC diagnostic push
  13989. #pragma GCC diagnostic ignored "-Wcast-align"
  13990. #endif /* defined(GCC_DIAGNOSTIC) */
  13991. /* We used an aligned pointer in SSL_set_app_data */
  13992. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13993. #if defined(GCC_DIAGNOSTIC)
  13994. #pragma GCC diagnostic pop
  13995. #endif /* defined(GCC_DIAGNOSTIC) */
  13996. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13997. (void)ad;
  13998. (void)arg;
  13999. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14000. DEBUG_ASSERT(0);
  14001. return SSL_TLSEXT_ERR_NOACK;
  14002. }
  14003. conn->dom_ctx = &(conn->phys_ctx->dd);
  14004. /* Old clients (Win XP) will not support SNI. Then, there
  14005. * is no server name available in the request - we can
  14006. * only work with the default certificate.
  14007. * Multiple HTTPS hosts on one IP+port are only possible
  14008. * with a certificate containing all alternative names.
  14009. */
  14010. if ((servername == NULL) || (*servername == 0)) {
  14011. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14012. mg_lock_context(conn->phys_ctx);
  14013. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14014. mg_unlock_context(conn->phys_ctx);
  14015. return SSL_TLSEXT_ERR_NOACK;
  14016. }
  14017. DEBUG_TRACE("TLS connection to host %s", servername);
  14018. while (conn->dom_ctx) {
  14019. if (!mg_strcasecmp(servername,
  14020. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14021. /* Found matching domain */
  14022. DEBUG_TRACE("TLS domain %s found",
  14023. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14024. break;
  14025. }
  14026. mg_lock_context(conn->phys_ctx);
  14027. conn->dom_ctx = conn->dom_ctx->next;
  14028. mg_unlock_context(conn->phys_ctx);
  14029. }
  14030. if (conn->dom_ctx == NULL) {
  14031. /* Default domain */
  14032. DEBUG_TRACE("TLS default domain %s used",
  14033. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14034. conn->dom_ctx = &(conn->phys_ctx->dd);
  14035. }
  14036. mg_lock_context(conn->phys_ctx);
  14037. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14038. mg_unlock_context(conn->phys_ctx);
  14039. return SSL_TLSEXT_ERR_OK;
  14040. }
  14041. #if defined(USE_HTTP2)
  14042. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14043. static const char *alpn_proto_order[] = {alpn_proto_list,
  14044. alpn_proto_list + 3,
  14045. alpn_proto_list + 3 + 8,
  14046. NULL};
  14047. #else
  14048. static const char alpn_proto_list[] = "\x08http/1.1\x08http/1.0";
  14049. static const char *alpn_proto_order[] = {alpn_proto_list,
  14050. alpn_proto_list + 8,
  14051. NULL};
  14052. #endif
  14053. static int
  14054. alpn_select_cb(SSL *ssl,
  14055. const unsigned char **out,
  14056. unsigned char *outlen,
  14057. const unsigned char *in,
  14058. unsigned int inlen,
  14059. void *arg)
  14060. {
  14061. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14062. unsigned int i, j;
  14063. struct mg_workerTLS *tls =
  14064. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14065. (void)ssl;
  14066. (void)dom_ctx;
  14067. if (tls == NULL) {
  14068. /* Need to store protocol in Thread Local Storage */
  14069. /* If there is no Thread Local Storage, don't use ALPN */
  14070. return SSL_TLSEXT_ERR_NOACK;
  14071. }
  14072. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14073. /* check all accepted protocols in this order */
  14074. const char *alpn_proto = alpn_proto_order[j];
  14075. /* search input for matching protocol */
  14076. for (i = 0; i < inlen; i++) {
  14077. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14078. *out = in + i + 1;
  14079. *outlen = in[i];
  14080. tls->alpn_proto = alpn_proto;
  14081. return SSL_TLSEXT_ERR_OK;
  14082. }
  14083. }
  14084. }
  14085. /* Nothing found */
  14086. return SSL_TLSEXT_ERR_NOACK;
  14087. }
  14088. static int
  14089. next_protos_advertised_cb(SSL *ssl,
  14090. const unsigned char **data,
  14091. unsigned int *len,
  14092. void *arg)
  14093. {
  14094. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14095. *data = (const unsigned char *)alpn_proto_list;
  14096. *len = (unsigned int)strlen((const char *)data);
  14097. (void)ssl;
  14098. (void)dom_ctx;
  14099. return SSL_TLSEXT_ERR_OK;
  14100. }
  14101. static int
  14102. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14103. {
  14104. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14105. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14106. (const unsigned char *)alpn_proto_list,
  14107. alpn_len);
  14108. if (ret != 0) {
  14109. mg_cry_ctx_internal(phys_ctx,
  14110. "SSL_CTX_set_alpn_protos error: %s",
  14111. ssl_error());
  14112. }
  14113. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14114. alpn_select_cb,
  14115. (void *)dom_ctx);
  14116. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14117. next_protos_advertised_cb,
  14118. (void *)dom_ctx);
  14119. return ret;
  14120. }
  14121. /* Setup SSL CTX as required by CivetWeb */
  14122. static int
  14123. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14124. struct mg_domain_context *dom_ctx,
  14125. const char *pem,
  14126. const char *chain)
  14127. {
  14128. int callback_ret;
  14129. int should_verify_peer;
  14130. int peer_certificate_optional;
  14131. const char *ca_path;
  14132. const char *ca_file;
  14133. int use_default_verify_paths;
  14134. int verify_depth;
  14135. struct timespec now_mt;
  14136. md5_byte_t ssl_context_id[16];
  14137. md5_state_t md5state;
  14138. int protocol_ver;
  14139. #if defined(OPENSSL_API_1_1)
  14140. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14141. mg_cry_ctx_internal(phys_ctx,
  14142. "SSL_CTX_new (server) error: %s",
  14143. ssl_error());
  14144. return 0;
  14145. }
  14146. #else
  14147. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14148. mg_cry_ctx_internal(phys_ctx,
  14149. "SSL_CTX_new (server) error: %s",
  14150. ssl_error());
  14151. return 0;
  14152. }
  14153. #endif /* OPENSSL_API_1_1 */
  14154. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14155. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14156. | SSL_OP_NO_TLSv1_1);
  14157. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14158. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14159. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14160. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14161. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14162. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14163. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14164. #if defined(SSL_OP_NO_RENEGOTIATION)
  14165. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14166. #endif
  14167. #if !defined(NO_SSL_DL)
  14168. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14169. #endif /* NO_SSL_DL */
  14170. /* In SSL documentation examples callback defined without const
  14171. * specifier 'void (*)(SSL *, int, int)' See:
  14172. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14173. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14174. * But in the source code const SSL is used:
  14175. * 'void (*)(const SSL *, int, int)' See:
  14176. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14177. * Problem about wrong documentation described, but not resolved:
  14178. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14179. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14180. * But when compiled with modern C++ compiler, correct const should be
  14181. * provided
  14182. */
  14183. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14184. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14185. ssl_servername_callback);
  14186. /* If a callback has been specified, call it. */
  14187. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14188. ? 0
  14189. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14190. phys_ctx->user_data));
  14191. /* If callback returns 0, civetweb sets up the SSL certificate.
  14192. * If it returns 1, civetweb assumes the calback already did this.
  14193. * If it returns -1, initializing ssl fails. */
  14194. if (callback_ret < 0) {
  14195. mg_cry_ctx_internal(phys_ctx,
  14196. "SSL callback returned error: %i",
  14197. callback_ret);
  14198. return 0;
  14199. }
  14200. if (callback_ret > 0) {
  14201. /* Callback did everything. */
  14202. return 1;
  14203. }
  14204. /* If a domain callback has been specified, call it. */
  14205. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14206. ? 0
  14207. : (phys_ctx->callbacks.init_ssl_domain(
  14208. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14209. dom_ctx->ssl_ctx,
  14210. phys_ctx->user_data));
  14211. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14212. * If it returns 1, civetweb assumes the calback already did this.
  14213. * If it returns -1, initializing ssl fails. */
  14214. if (callback_ret < 0) {
  14215. mg_cry_ctx_internal(phys_ctx,
  14216. "Domain SSL callback returned error: %i",
  14217. callback_ret);
  14218. return 0;
  14219. }
  14220. if (callback_ret > 0) {
  14221. /* Domain callback did everything. */
  14222. return 1;
  14223. }
  14224. /* Use some combination of start time, domain and port as a SSL
  14225. * context ID. This should be unique on the current machine. */
  14226. md5_init(&md5state);
  14227. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14228. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14229. md5_append(&md5state,
  14230. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14231. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14232. md5_append(&md5state,
  14233. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14234. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14235. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14236. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14237. md5_finish(&md5state, ssl_context_id);
  14238. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14239. (unsigned char *)ssl_context_id,
  14240. sizeof(ssl_context_id));
  14241. if (pem != NULL) {
  14242. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14243. return 0;
  14244. }
  14245. }
  14246. /* Should we support client certificates? */
  14247. /* Default is "no". */
  14248. should_verify_peer = 0;
  14249. peer_certificate_optional = 0;
  14250. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14251. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14252. /* Yes, they are mandatory */
  14253. should_verify_peer = 1;
  14254. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14255. "optional")
  14256. == 0) {
  14257. /* Yes, they are optional */
  14258. should_verify_peer = 1;
  14259. peer_certificate_optional = 1;
  14260. }
  14261. }
  14262. use_default_verify_paths =
  14263. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14264. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14265. == 0);
  14266. if (should_verify_peer) {
  14267. ca_path = dom_ctx->config[SSL_CA_PATH];
  14268. ca_file = dom_ctx->config[SSL_CA_FILE];
  14269. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14270. != 1) {
  14271. mg_cry_ctx_internal(phys_ctx,
  14272. "SSL_CTX_load_verify_locations error: %s "
  14273. "ssl_verify_peer requires setting "
  14274. "either ssl_ca_path or ssl_ca_file. "
  14275. "Is any of them present in the "
  14276. ".conf file?",
  14277. ssl_error());
  14278. return 0;
  14279. }
  14280. if (peer_certificate_optional) {
  14281. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14282. } else {
  14283. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14284. SSL_VERIFY_PEER
  14285. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14286. NULL);
  14287. }
  14288. if (use_default_verify_paths
  14289. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14290. mg_cry_ctx_internal(phys_ctx,
  14291. "SSL_CTX_set_default_verify_paths error: %s",
  14292. ssl_error());
  14293. return 0;
  14294. }
  14295. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14296. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14297. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14298. }
  14299. }
  14300. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14301. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14302. dom_ctx->config[SSL_CIPHER_LIST])
  14303. != 1) {
  14304. mg_cry_ctx_internal(phys_ctx,
  14305. "SSL_CTX_set_cipher_list error: %s",
  14306. ssl_error());
  14307. }
  14308. }
  14309. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14310. #if !defined(NO_SSL_DL)
  14311. if (!tls_feature_missing[TLS_ALPN])
  14312. #endif
  14313. {
  14314. init_alpn(phys_ctx, dom_ctx);
  14315. }
  14316. return 1;
  14317. }
  14318. /* Check if SSL is required.
  14319. * If so, dynamically load SSL library
  14320. * and set up ctx->ssl_ctx pointer. */
  14321. static int
  14322. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14323. {
  14324. void *ssl_ctx = 0;
  14325. int callback_ret;
  14326. const char *pem;
  14327. const char *chain;
  14328. char ebuf[128];
  14329. if (!phys_ctx) {
  14330. return 0;
  14331. }
  14332. if (!dom_ctx) {
  14333. dom_ctx = &(phys_ctx->dd);
  14334. }
  14335. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14336. /* No SSL port is set. No need to setup SSL. */
  14337. return 1;
  14338. }
  14339. /* Check for external SSL_CTX */
  14340. callback_ret =
  14341. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14342. ? 0
  14343. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14344. phys_ctx->user_data));
  14345. if (callback_ret < 0) {
  14346. mg_cry_ctx_internal(phys_ctx,
  14347. "external_ssl_ctx callback returned error: %i",
  14348. callback_ret);
  14349. return 0;
  14350. } else if (callback_ret > 0) {
  14351. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14352. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14353. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14354. return 0;
  14355. }
  14356. return 1;
  14357. }
  14358. /* Check for external domain SSL_CTX */
  14359. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14360. ? 0
  14361. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14362. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14363. &ssl_ctx,
  14364. phys_ctx->user_data));
  14365. if (callback_ret < 0) {
  14366. mg_cry_ctx_internal(
  14367. phys_ctx,
  14368. "external_ssl_ctx_domain callback returned error: %i",
  14369. callback_ret);
  14370. return 0;
  14371. } else if (callback_ret > 0) {
  14372. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14373. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14374. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14375. return 0;
  14376. }
  14377. return 1;
  14378. }
  14379. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14380. * 0, CivetWeb should continue initializing SSL */
  14381. /* If PEM file is not specified and the init_ssl callbacks
  14382. * are not specified, setup will fail. */
  14383. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14384. && (phys_ctx->callbacks.init_ssl == NULL)
  14385. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14386. /* No certificate and no init_ssl callbacks:
  14387. * Essential data to set up TLS is missing.
  14388. */
  14389. mg_cry_ctx_internal(phys_ctx,
  14390. "Initializing SSL failed: -%s is not set",
  14391. config_options[SSL_CERTIFICATE].name);
  14392. return 0;
  14393. }
  14394. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14395. if (chain == NULL) {
  14396. chain = pem;
  14397. }
  14398. if ((chain != NULL) && (*chain == 0)) {
  14399. chain = NULL;
  14400. }
  14401. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14402. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14403. return 0;
  14404. }
  14405. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14406. }
  14407. static void
  14408. uninitialize_ssl(void)
  14409. {
  14410. #if defined(OPENSSL_API_1_1)
  14411. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14412. /* Shutdown according to
  14413. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14414. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14415. */
  14416. CONF_modules_unload(1);
  14417. #else
  14418. int i;
  14419. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14420. /* Shutdown according to
  14421. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14422. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14423. */
  14424. CRYPTO_set_locking_callback(NULL);
  14425. CRYPTO_set_id_callback(NULL);
  14426. ENGINE_cleanup();
  14427. CONF_modules_unload(1);
  14428. ERR_free_strings();
  14429. EVP_cleanup();
  14430. CRYPTO_cleanup_all_ex_data();
  14431. OPENSSL_REMOVE_THREAD_STATE();
  14432. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14433. pthread_mutex_destroy(&ssl_mutexes[i]);
  14434. }
  14435. mg_free(ssl_mutexes);
  14436. ssl_mutexes = NULL;
  14437. #endif /* OPENSSL_API_1_1 */
  14438. }
  14439. }
  14440. #endif /* !NO_SSL */
  14441. #if !defined(NO_FILESYSTEMS)
  14442. static int
  14443. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14444. {
  14445. if (phys_ctx) {
  14446. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14447. const char *path;
  14448. struct mg_connection fc;
  14449. if (!dom_ctx) {
  14450. dom_ctx = &(phys_ctx->dd);
  14451. }
  14452. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14453. if ((path != NULL)
  14454. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14455. mg_cry_ctx_internal(phys_ctx,
  14456. "Cannot open %s: %s",
  14457. path,
  14458. strerror(ERRNO));
  14459. return 0;
  14460. }
  14461. return 1;
  14462. }
  14463. return 0;
  14464. }
  14465. #endif /* NO_FILESYSTEMS */
  14466. static int
  14467. set_acl_option(struct mg_context *phys_ctx)
  14468. {
  14469. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14470. }
  14471. static void
  14472. reset_per_request_attributes(struct mg_connection *conn)
  14473. {
  14474. if (!conn) {
  14475. return;
  14476. }
  14477. conn->connection_type =
  14478. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14479. conn->num_bytes_sent = conn->consumed_content = 0;
  14480. conn->path_info = NULL;
  14481. conn->status_code = -1;
  14482. conn->content_len = -1;
  14483. conn->is_chunked = 0;
  14484. conn->must_close = 0;
  14485. conn->request_len = 0;
  14486. conn->throttle = 0;
  14487. conn->accept_gzip = 0;
  14488. conn->response_info.content_length = conn->request_info.content_length = -1;
  14489. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14490. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14491. conn->response_info.status_text = NULL;
  14492. conn->response_info.status_code = 0;
  14493. conn->request_info.remote_user = NULL;
  14494. conn->request_info.request_method = NULL;
  14495. conn->request_info.request_uri = NULL;
  14496. conn->request_info.local_uri = NULL;
  14497. #if defined(MG_LEGACY_INTERFACE)
  14498. /* Legacy before split into local_uri and request_uri */
  14499. conn->request_info.uri = NULL;
  14500. #endif
  14501. }
  14502. static int
  14503. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14504. {
  14505. if (setsockopt(sock,
  14506. IPPROTO_TCP,
  14507. TCP_NODELAY,
  14508. (SOCK_OPT_TYPE)&nodelay_on,
  14509. sizeof(nodelay_on))
  14510. != 0) {
  14511. /* Error */
  14512. return 1;
  14513. }
  14514. /* OK */
  14515. return 0;
  14516. }
  14517. #if !defined(__ZEPHYR__)
  14518. static void
  14519. close_socket_gracefully(struct mg_connection *conn)
  14520. {
  14521. #if defined(_WIN32)
  14522. char buf[MG_BUF_LEN];
  14523. int n;
  14524. #endif
  14525. struct linger linger;
  14526. int error_code = 0;
  14527. int linger_timeout = -2;
  14528. socklen_t opt_len = sizeof(error_code);
  14529. if (!conn) {
  14530. return;
  14531. }
  14532. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14533. * "Note that enabling a nonzero timeout on a nonblocking socket
  14534. * is not recommended.", so set it to blocking now */
  14535. set_blocking_mode(conn->client.sock);
  14536. /* Send FIN to the client */
  14537. shutdown(conn->client.sock, SHUTDOWN_WR);
  14538. #if defined(_WIN32)
  14539. /* Read and discard pending incoming data. If we do not do that and
  14540. * close
  14541. * the socket, the data in the send buffer may be discarded. This
  14542. * behaviour is seen on Windows, when client keeps sending data
  14543. * when server decides to close the connection; then when client
  14544. * does recv() it gets no data back. */
  14545. do {
  14546. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14547. } while (n > 0);
  14548. #endif
  14549. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14550. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14551. }
  14552. /* Set linger option according to configuration */
  14553. if (linger_timeout >= 0) {
  14554. /* Set linger option to avoid socket hanging out after close. This
  14555. * prevent ephemeral port exhaust problem under high QPS. */
  14556. linger.l_onoff = 1;
  14557. #if defined(_MSC_VER)
  14558. #pragma warning(push)
  14559. #pragma warning(disable : 4244)
  14560. #endif
  14561. #if defined(GCC_DIAGNOSTIC)
  14562. #pragma GCC diagnostic push
  14563. #pragma GCC diagnostic ignored "-Wconversion"
  14564. #endif
  14565. /* Data type of linger structure elements may differ,
  14566. * so we don't know what cast we need here.
  14567. * Disable type conversion warnings. */
  14568. linger.l_linger = (linger_timeout + 999) / 1000;
  14569. #if defined(GCC_DIAGNOSTIC)
  14570. #pragma GCC diagnostic pop
  14571. #endif
  14572. #if defined(_MSC_VER)
  14573. #pragma warning(pop)
  14574. #endif
  14575. } else {
  14576. linger.l_onoff = 0;
  14577. linger.l_linger = 0;
  14578. }
  14579. if (linger_timeout < -1) {
  14580. /* Default: don't configure any linger */
  14581. } else if (getsockopt(conn->client.sock,
  14582. SOL_SOCKET,
  14583. SO_ERROR,
  14584. #if defined(_WIN32) /* WinSock uses different data type here */
  14585. (char *)&error_code,
  14586. #else
  14587. &error_code,
  14588. #endif
  14589. &opt_len)
  14590. != 0) {
  14591. /* Cannot determine if socket is already closed. This should
  14592. * not occur and never did in a test. Log an error message
  14593. * and continue. */
  14594. mg_cry_internal(conn,
  14595. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14596. __func__,
  14597. strerror(ERRNO));
  14598. #if defined(_WIN32)
  14599. } else if (error_code == WSAECONNRESET) {
  14600. #else
  14601. } else if (error_code == ECONNRESET) {
  14602. #endif
  14603. /* Socket already closed by client/peer, close socket without linger
  14604. */
  14605. } else {
  14606. /* Set linger timeout */
  14607. if (setsockopt(conn->client.sock,
  14608. SOL_SOCKET,
  14609. SO_LINGER,
  14610. (char *)&linger,
  14611. sizeof(linger))
  14612. != 0) {
  14613. mg_cry_internal(
  14614. conn,
  14615. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14616. __func__,
  14617. linger.l_onoff,
  14618. linger.l_linger,
  14619. strerror(ERRNO));
  14620. }
  14621. }
  14622. /* Now we know that our FIN is ACK-ed, safe to close */
  14623. closesocket(conn->client.sock);
  14624. conn->client.sock = INVALID_SOCKET;
  14625. }
  14626. #endif
  14627. static void
  14628. close_connection(struct mg_connection *conn)
  14629. {
  14630. #if defined(USE_SERVER_STATS)
  14631. conn->conn_state = 6; /* to close */
  14632. #endif
  14633. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14634. if (conn->lua_websocket_state) {
  14635. lua_websocket_close(conn, conn->lua_websocket_state);
  14636. conn->lua_websocket_state = NULL;
  14637. }
  14638. #endif
  14639. mg_lock_connection(conn);
  14640. /* Set close flag, so keep-alive loops will stop */
  14641. conn->must_close = 1;
  14642. /* call the connection_close callback if assigned */
  14643. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14644. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14645. conn->phys_ctx->callbacks.connection_close(conn);
  14646. }
  14647. }
  14648. /* Reset user data, after close callback is called.
  14649. * Do not reuse it. If the user needs a destructor,
  14650. * it must be done in the connection_close callback. */
  14651. mg_set_user_connection_data(conn, NULL);
  14652. #if defined(USE_SERVER_STATS)
  14653. conn->conn_state = 7; /* closing */
  14654. #endif
  14655. #if !defined(NO_SSL)
  14656. if (conn->ssl != NULL) {
  14657. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14658. */
  14659. SSL_shutdown(conn->ssl);
  14660. SSL_free(conn->ssl);
  14661. OPENSSL_REMOVE_THREAD_STATE();
  14662. conn->ssl = NULL;
  14663. }
  14664. #endif
  14665. if (conn->client.sock != INVALID_SOCKET) {
  14666. #if defined(__ZEPHYR__)
  14667. closesocket(conn->client.sock);
  14668. #else
  14669. close_socket_gracefully(conn);
  14670. #endif
  14671. conn->client.sock = INVALID_SOCKET;
  14672. }
  14673. if (conn->host) {
  14674. mg_free((void *)conn->host);
  14675. conn->host = NULL;
  14676. }
  14677. mg_unlock_connection(conn);
  14678. #if defined(USE_SERVER_STATS)
  14679. conn->conn_state = 8; /* closed */
  14680. #endif
  14681. }
  14682. void
  14683. mg_close_connection(struct mg_connection *conn)
  14684. {
  14685. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14686. return;
  14687. }
  14688. #if defined(USE_WEBSOCKET)
  14689. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14690. if (conn->in_websocket_handling) {
  14691. /* Set close flag, so the server thread can exit. */
  14692. conn->must_close = 1;
  14693. return;
  14694. }
  14695. }
  14696. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14697. unsigned int i;
  14698. /* client context: loops must end */
  14699. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14700. conn->must_close = 1;
  14701. /* We need to get the client thread out of the select/recv call
  14702. * here. */
  14703. /* Since we use a sleep quantum of some seconds to check for recv
  14704. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14705. /* join worker thread */
  14706. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14707. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14708. }
  14709. }
  14710. #endif /* defined(USE_WEBSOCKET) */
  14711. close_connection(conn);
  14712. #if !defined(NO_SSL)
  14713. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14714. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14715. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14716. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14717. }
  14718. #endif
  14719. #if defined(USE_WEBSOCKET)
  14720. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14721. mg_free(conn->phys_ctx->worker_threadids);
  14722. (void)pthread_mutex_destroy(&conn->mutex);
  14723. mg_free(conn);
  14724. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14725. (void)pthread_mutex_destroy(&conn->mutex);
  14726. mg_free(conn);
  14727. }
  14728. #else
  14729. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14730. (void)pthread_mutex_destroy(&conn->mutex);
  14731. mg_free(conn);
  14732. }
  14733. #endif /* defined(USE_WEBSOCKET) */
  14734. }
  14735. static struct mg_connection *
  14736. mg_connect_client_impl(const struct mg_client_options *client_options,
  14737. int use_ssl,
  14738. char *ebuf,
  14739. size_t ebuf_len)
  14740. {
  14741. struct mg_connection *conn = NULL;
  14742. SOCKET sock;
  14743. union usa sa;
  14744. struct sockaddr *psa;
  14745. socklen_t len;
  14746. unsigned max_req_size =
  14747. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14748. /* Size of structures, aligned to 8 bytes */
  14749. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14750. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14751. conn =
  14752. (struct mg_connection *)mg_calloc(1,
  14753. conn_size + ctx_size + max_req_size);
  14754. if (conn == NULL) {
  14755. mg_snprintf(NULL,
  14756. NULL, /* No truncation check for ebuf */
  14757. ebuf,
  14758. ebuf_len,
  14759. "calloc(): %s",
  14760. strerror(ERRNO));
  14761. return NULL;
  14762. }
  14763. #if defined(GCC_DIAGNOSTIC)
  14764. #pragma GCC diagnostic push
  14765. #pragma GCC diagnostic ignored "-Wcast-align"
  14766. #endif /* defined(GCC_DIAGNOSTIC) */
  14767. /* conn_size is aligned to 8 bytes */
  14768. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14769. #if defined(GCC_DIAGNOSTIC)
  14770. #pragma GCC diagnostic pop
  14771. #endif /* defined(GCC_DIAGNOSTIC) */
  14772. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14773. conn->buf_size = (int)max_req_size;
  14774. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14775. conn->dom_ctx = &(conn->phys_ctx->dd);
  14776. if (!connect_socket(conn->phys_ctx,
  14777. client_options->host,
  14778. client_options->port,
  14779. use_ssl,
  14780. ebuf,
  14781. ebuf_len,
  14782. &sock,
  14783. &sa)) {
  14784. /* ebuf is set by connect_socket,
  14785. * free all memory and return NULL; */
  14786. mg_free(conn);
  14787. return NULL;
  14788. }
  14789. #if !defined(NO_SSL)
  14790. #if defined(OPENSSL_API_1_1)
  14791. if (use_ssl
  14792. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14793. == NULL) {
  14794. mg_snprintf(NULL,
  14795. NULL, /* No truncation check for ebuf */
  14796. ebuf,
  14797. ebuf_len,
  14798. "SSL_CTX_new error: %s",
  14799. ssl_error());
  14800. closesocket(sock);
  14801. mg_free(conn);
  14802. return NULL;
  14803. }
  14804. #else
  14805. if (use_ssl
  14806. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14807. == NULL) {
  14808. mg_snprintf(NULL,
  14809. NULL, /* No truncation check for ebuf */
  14810. ebuf,
  14811. ebuf_len,
  14812. "SSL_CTX_new error: %s",
  14813. ssl_error());
  14814. closesocket(sock);
  14815. mg_free(conn);
  14816. return NULL;
  14817. }
  14818. #endif /* OPENSSL_API_1_1 */
  14819. #endif /* NO_SSL */
  14820. #if defined(USE_IPV6)
  14821. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14822. : sizeof(conn->client.rsa.sin6);
  14823. psa = (sa.sa.sa_family == AF_INET)
  14824. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14825. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14826. #else
  14827. len = sizeof(conn->client.rsa.sin);
  14828. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14829. #endif
  14830. conn->client.sock = sock;
  14831. conn->client.lsa = sa;
  14832. if (getsockname(sock, psa, &len) != 0) {
  14833. mg_cry_internal(conn,
  14834. "%s: getsockname() failed: %s",
  14835. __func__,
  14836. strerror(ERRNO));
  14837. }
  14838. conn->client.is_ssl = use_ssl ? 1 : 0;
  14839. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14840. mg_snprintf(NULL,
  14841. NULL, /* No truncation check for ebuf */
  14842. ebuf,
  14843. ebuf_len,
  14844. "Can not create mutex");
  14845. #if !defined(NO_SSL)
  14846. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14847. #endif
  14848. closesocket(sock);
  14849. mg_free(conn);
  14850. return NULL;
  14851. }
  14852. #if !defined(NO_SSL)
  14853. if (use_ssl) {
  14854. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14855. * SSL_CTX_set_verify call is needed to switch off server
  14856. * certificate checking, which is off by default in OpenSSL and
  14857. * on in yaSSL. */
  14858. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14859. * SSL_VERIFY_PEER, verify_ssl_server); */
  14860. if (client_options->client_cert) {
  14861. if (!ssl_use_pem_file(conn->phys_ctx,
  14862. conn->dom_ctx,
  14863. client_options->client_cert,
  14864. NULL)) {
  14865. mg_snprintf(NULL,
  14866. NULL, /* No truncation check for ebuf */
  14867. ebuf,
  14868. ebuf_len,
  14869. "Can not use SSL client certificate");
  14870. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14871. closesocket(sock);
  14872. mg_free(conn);
  14873. return NULL;
  14874. }
  14875. }
  14876. if (client_options->server_cert) {
  14877. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14878. client_options->server_cert,
  14879. NULL)
  14880. != 1) {
  14881. mg_cry_internal(conn,
  14882. "SSL_CTX_load_verify_locations error: %s ",
  14883. ssl_error());
  14884. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14885. closesocket(sock);
  14886. mg_free(conn);
  14887. return NULL;
  14888. }
  14889. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14890. } else {
  14891. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14892. }
  14893. if (!sslize(conn, SSL_connect, client_options)) {
  14894. mg_snprintf(NULL,
  14895. NULL, /* No truncation check for ebuf */
  14896. ebuf,
  14897. ebuf_len,
  14898. "SSL connection error");
  14899. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14900. closesocket(sock);
  14901. mg_free(conn);
  14902. return NULL;
  14903. }
  14904. }
  14905. #endif
  14906. return conn;
  14907. }
  14908. CIVETWEB_API struct mg_connection *
  14909. mg_connect_client_secure(const struct mg_client_options *client_options,
  14910. char *error_buffer,
  14911. size_t error_buffer_size)
  14912. {
  14913. return mg_connect_client_impl(client_options,
  14914. 1,
  14915. error_buffer,
  14916. error_buffer_size);
  14917. }
  14918. struct mg_connection *
  14919. mg_connect_client(const char *host,
  14920. int port,
  14921. int use_ssl,
  14922. char *error_buffer,
  14923. size_t error_buffer_size)
  14924. {
  14925. struct mg_client_options opts;
  14926. memset(&opts, 0, sizeof(opts));
  14927. opts.host = host;
  14928. opts.port = port;
  14929. return mg_connect_client_impl(&opts,
  14930. use_ssl,
  14931. error_buffer,
  14932. error_buffer_size);
  14933. }
  14934. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14935. struct mg_connection *
  14936. mg_connect_client2(const char *host,
  14937. const char *protocol,
  14938. int port,
  14939. const char *path,
  14940. struct mg_init_data *init,
  14941. struct mg_error_data *error)
  14942. {
  14943. int is_ssl, is_ws;
  14944. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14945. if (error != NULL) {
  14946. error->code = 0;
  14947. if (error->text_buffer_size > 0) {
  14948. *error->text = 0;
  14949. }
  14950. }
  14951. if ((host == NULL) || (protocol == NULL)) {
  14952. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14953. mg_snprintf(NULL,
  14954. NULL, /* No truncation check for error buffers */
  14955. error->text,
  14956. error->text_buffer_size,
  14957. "%s",
  14958. "Invalid parameters");
  14959. }
  14960. return NULL;
  14961. }
  14962. /* check all known protocolls */
  14963. if (!mg_strcasecmp(protocol, "http")) {
  14964. is_ssl = 0;
  14965. is_ws = 0;
  14966. } else if (!mg_strcasecmp(protocol, "https")) {
  14967. is_ssl = 1;
  14968. is_ws = 0;
  14969. #if defined(USE_WEBSOCKET)
  14970. } else if (!mg_strcasecmp(protocol, "ws")) {
  14971. is_ssl = 0;
  14972. is_ws = 1;
  14973. } else if (!mg_strcasecmp(protocol, "wss")) {
  14974. is_ssl = 1;
  14975. is_ws = 1;
  14976. #endif
  14977. } else {
  14978. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14979. mg_snprintf(NULL,
  14980. NULL, /* No truncation check for error buffers */
  14981. error->text,
  14982. error->text_buffer_size,
  14983. "Protocol %s not supported",
  14984. protocol);
  14985. }
  14986. return NULL;
  14987. }
  14988. /* TODO: The current implementation here just calls the old
  14989. * implementations, without using any new options. This is just a first
  14990. * step to test the new interfaces. */
  14991. #if defined(USE_WEBSOCKET)
  14992. if (is_ws) {
  14993. /* TODO: implement all options */
  14994. return mg_connect_websocket_client(
  14995. host,
  14996. port,
  14997. is_ssl,
  14998. ((error != NULL) ? error->text : NULL),
  14999. ((error != NULL) ? error->text_buffer_size : 0),
  15000. (path ? path : ""),
  15001. NULL /* TODO: origin */,
  15002. deprecated_websocket_data_wrapper,
  15003. deprecated_websocket_close_wrapper,
  15004. (void *)init->callbacks);
  15005. }
  15006. #endif
  15007. /* TODO: all additional options */
  15008. struct mg_client_options opts;
  15009. memset(&opts, 0, sizeof(opts));
  15010. opts.host = host;
  15011. opts.port = port;
  15012. return mg_connect_client_impl(&opts,
  15013. is_ssl,
  15014. ((error != NULL) ? error->text : NULL),
  15015. ((error != NULL) ? error->text_buffer_size
  15016. : 0));
  15017. }
  15018. #endif
  15019. static const struct {
  15020. const char *proto;
  15021. size_t proto_len;
  15022. unsigned default_port;
  15023. } abs_uri_protocols[] = {{"http://", 7, 80},
  15024. {"https://", 8, 443},
  15025. {"ws://", 5, 80},
  15026. {"wss://", 6, 443},
  15027. {NULL, 0, 0}};
  15028. /* Check if the uri is valid.
  15029. * return 0 for invalid uri,
  15030. * return 1 for *,
  15031. * return 2 for relative uri,
  15032. * return 3 for absolute uri without port,
  15033. * return 4 for absolute uri with port */
  15034. static int
  15035. get_uri_type(const char *uri)
  15036. {
  15037. int i;
  15038. const char *hostend, *portbegin;
  15039. char *portend;
  15040. unsigned long port;
  15041. /* According to the HTTP standard
  15042. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15043. * URI can be an asterisk (*) or should start with slash (relative uri),
  15044. * or it should start with the protocol (absolute uri). */
  15045. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15046. /* asterisk */
  15047. return 1;
  15048. }
  15049. /* Valid URIs according to RFC 3986
  15050. * (https://www.ietf.org/rfc/rfc3986.txt)
  15051. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15052. * and unreserved characters A-Z a-z 0-9 and -._~
  15053. * and % encoded symbols.
  15054. */
  15055. for (i = 0; uri[i] != 0; i++) {
  15056. if (uri[i] < 33) {
  15057. /* control characters and spaces are invalid */
  15058. return 0;
  15059. }
  15060. if (uri[i] > 126) {
  15061. /* non-ascii characters must be % encoded */
  15062. return 0;
  15063. } else {
  15064. switch (uri[i]) {
  15065. case '"': /* 34 */
  15066. case '<': /* 60 */
  15067. case '>': /* 62 */
  15068. case '\\': /* 92 */
  15069. case '^': /* 94 */
  15070. case '`': /* 96 */
  15071. case '{': /* 123 */
  15072. case '|': /* 124 */
  15073. case '}': /* 125 */
  15074. return 0;
  15075. default:
  15076. /* character is ok */
  15077. break;
  15078. }
  15079. }
  15080. }
  15081. /* A relative uri starts with a / character */
  15082. if (uri[0] == '/') {
  15083. /* relative uri */
  15084. return 2;
  15085. }
  15086. /* It could be an absolute uri: */
  15087. /* This function only checks if the uri is valid, not if it is
  15088. * addressing the current server. So civetweb can also be used
  15089. * as a proxy server. */
  15090. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15091. if (mg_strncasecmp(uri,
  15092. abs_uri_protocols[i].proto,
  15093. abs_uri_protocols[i].proto_len)
  15094. == 0) {
  15095. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15096. if (!hostend) {
  15097. return 0;
  15098. }
  15099. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15100. if (!portbegin) {
  15101. return 3;
  15102. }
  15103. port = strtoul(portbegin + 1, &portend, 10);
  15104. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15105. return 0;
  15106. }
  15107. return 4;
  15108. }
  15109. }
  15110. return 0;
  15111. }
  15112. /* Return NULL or the relative uri at the current server */
  15113. static const char *
  15114. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15115. {
  15116. const char *server_domain;
  15117. size_t server_domain_len;
  15118. size_t request_domain_len = 0;
  15119. unsigned long port = 0;
  15120. int i, auth_domain_check_enabled;
  15121. const char *hostbegin = NULL;
  15122. const char *hostend = NULL;
  15123. const char *portbegin;
  15124. char *portend;
  15125. auth_domain_check_enabled =
  15126. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15127. /* DNS is case insensitive, so use case insensitive string compare here
  15128. */
  15129. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15130. if (mg_strncasecmp(uri,
  15131. abs_uri_protocols[i].proto,
  15132. abs_uri_protocols[i].proto_len)
  15133. == 0) {
  15134. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15135. hostend = strchr(hostbegin, '/');
  15136. if (!hostend) {
  15137. return 0;
  15138. }
  15139. portbegin = strchr(hostbegin, ':');
  15140. if ((!portbegin) || (portbegin > hostend)) {
  15141. port = abs_uri_protocols[i].default_port;
  15142. request_domain_len = (size_t)(hostend - hostbegin);
  15143. } else {
  15144. port = strtoul(portbegin + 1, &portend, 10);
  15145. if ((portend != hostend) || (port <= 0)
  15146. || !is_valid_port(port)) {
  15147. return 0;
  15148. }
  15149. request_domain_len = (size_t)(portbegin - hostbegin);
  15150. }
  15151. /* protocol found, port set */
  15152. break;
  15153. }
  15154. }
  15155. if (!port) {
  15156. /* port remains 0 if the protocol is not found */
  15157. return 0;
  15158. }
  15159. /* Check if the request is directed to a different server. */
  15160. /* First check if the port is the same (IPv4 and IPv6). */
  15161. #if defined(USE_IPV6)
  15162. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  15163. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  15164. /* Request is directed to a different port */
  15165. return 0;
  15166. }
  15167. } else
  15168. #endif
  15169. {
  15170. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  15171. /* Request is directed to a different port */
  15172. return 0;
  15173. }
  15174. }
  15175. /* Finally check if the server corresponds to the authentication
  15176. * domain of the server (the server domain).
  15177. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15178. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15179. * but do not allow substrings (like
  15180. * http://notmydomain.com/path/file.ext
  15181. * or http://mydomain.com.fake/path/file.ext).
  15182. */
  15183. if (auth_domain_check_enabled) {
  15184. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15185. server_domain_len = strlen(server_domain);
  15186. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15187. return 0;
  15188. }
  15189. if ((request_domain_len == server_domain_len)
  15190. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15191. /* Request is directed to this server - full name match. */
  15192. } else {
  15193. if (request_domain_len < (server_domain_len + 2)) {
  15194. /* Request is directed to another server: The server name
  15195. * is longer than the request name.
  15196. * Drop this case here to avoid overflows in the
  15197. * following checks. */
  15198. return 0;
  15199. }
  15200. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15201. /* Request is directed to another server: It could be a
  15202. * substring
  15203. * like notmyserver.com */
  15204. return 0;
  15205. }
  15206. if (0
  15207. != memcmp(server_domain,
  15208. hostbegin + request_domain_len - server_domain_len,
  15209. server_domain_len)) {
  15210. /* Request is directed to another server:
  15211. * The server name is different. */
  15212. return 0;
  15213. }
  15214. }
  15215. }
  15216. return hostend;
  15217. }
  15218. static int
  15219. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15220. {
  15221. if (ebuf_len > 0) {
  15222. ebuf[0] = '\0';
  15223. }
  15224. *err = 0;
  15225. reset_per_request_attributes(conn);
  15226. if (!conn) {
  15227. mg_snprintf(conn,
  15228. NULL, /* No truncation check for ebuf */
  15229. ebuf,
  15230. ebuf_len,
  15231. "%s",
  15232. "Internal error");
  15233. *err = 500;
  15234. return 0;
  15235. }
  15236. /* Set the time the request was received. This value should be used for
  15237. * timeouts. */
  15238. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15239. conn->request_len =
  15240. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15241. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15242. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15243. mg_snprintf(conn,
  15244. NULL, /* No truncation check for ebuf */
  15245. ebuf,
  15246. ebuf_len,
  15247. "%s",
  15248. "Invalid message size");
  15249. *err = 500;
  15250. return 0;
  15251. }
  15252. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15253. mg_snprintf(conn,
  15254. NULL, /* No truncation check for ebuf */
  15255. ebuf,
  15256. ebuf_len,
  15257. "%s",
  15258. "Message too large");
  15259. *err = 413;
  15260. return 0;
  15261. }
  15262. if (conn->request_len <= 0) {
  15263. if (conn->data_len > 0) {
  15264. mg_snprintf(conn,
  15265. NULL, /* No truncation check for ebuf */
  15266. ebuf,
  15267. ebuf_len,
  15268. "%s",
  15269. "Malformed message");
  15270. *err = 400;
  15271. } else {
  15272. /* Server did not recv anything -> just close the connection */
  15273. conn->must_close = 1;
  15274. mg_snprintf(conn,
  15275. NULL, /* No truncation check for ebuf */
  15276. ebuf,
  15277. ebuf_len,
  15278. "%s",
  15279. "No data received");
  15280. *err = 0;
  15281. }
  15282. return 0;
  15283. }
  15284. return 1;
  15285. }
  15286. static int
  15287. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15288. {
  15289. const char *cl;
  15290. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15291. return 0;
  15292. }
  15293. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15294. <= 0) {
  15295. mg_snprintf(conn,
  15296. NULL, /* No truncation check for ebuf */
  15297. ebuf,
  15298. ebuf_len,
  15299. "%s",
  15300. "Bad request");
  15301. *err = 400;
  15302. return 0;
  15303. }
  15304. /* Message is a valid request */
  15305. /* Is there a "host" ? */
  15306. if (conn->host != NULL) {
  15307. mg_free((void *)conn->host);
  15308. }
  15309. conn->host = alloc_get_host(conn);
  15310. if (!conn->host) {
  15311. mg_snprintf(conn,
  15312. NULL, /* No truncation check for ebuf */
  15313. ebuf,
  15314. ebuf_len,
  15315. "%s",
  15316. "Bad request: Host mismatch");
  15317. *err = 400;
  15318. return 0;
  15319. }
  15320. if (((cl = get_header(conn->request_info.http_headers,
  15321. conn->request_info.num_headers,
  15322. "Transfer-Encoding"))
  15323. != NULL)
  15324. && mg_strcasecmp(cl, "identity")) {
  15325. if (mg_strcasecmp(cl, "chunked")) {
  15326. mg_snprintf(conn,
  15327. NULL, /* No truncation check for ebuf */
  15328. ebuf,
  15329. ebuf_len,
  15330. "%s",
  15331. "Bad request");
  15332. *err = 400;
  15333. return 0;
  15334. }
  15335. conn->is_chunked = 1;
  15336. conn->content_len = 0; /* not yet read */
  15337. } else if ((cl = get_header(conn->request_info.http_headers,
  15338. conn->request_info.num_headers,
  15339. "Content-Length"))
  15340. != NULL) {
  15341. /* Request has content length set */
  15342. char *endptr = NULL;
  15343. conn->content_len = strtoll(cl, &endptr, 10);
  15344. if ((endptr == cl) || (conn->content_len < 0)) {
  15345. mg_snprintf(conn,
  15346. NULL, /* No truncation check for ebuf */
  15347. ebuf,
  15348. ebuf_len,
  15349. "%s",
  15350. "Bad request");
  15351. *err = 411;
  15352. return 0;
  15353. }
  15354. /* Publish the content length back to the request info. */
  15355. conn->request_info.content_length = conn->content_len;
  15356. } else {
  15357. /* There is no exception, see RFC7230. */
  15358. conn->content_len = 0;
  15359. }
  15360. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15361. return 1;
  15362. }
  15363. /* conn is assumed to be valid in this internal function */
  15364. static int
  15365. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15366. {
  15367. const char *cl;
  15368. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15369. return 0;
  15370. }
  15371. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15372. <= 0) {
  15373. mg_snprintf(conn,
  15374. NULL, /* No truncation check for ebuf */
  15375. ebuf,
  15376. ebuf_len,
  15377. "%s",
  15378. "Bad response");
  15379. *err = 400;
  15380. return 0;
  15381. }
  15382. /* Message is a valid response */
  15383. if (((cl = get_header(conn->response_info.http_headers,
  15384. conn->response_info.num_headers,
  15385. "Transfer-Encoding"))
  15386. != NULL)
  15387. && mg_strcasecmp(cl, "identity")) {
  15388. if (mg_strcasecmp(cl, "chunked")) {
  15389. mg_snprintf(conn,
  15390. NULL, /* No truncation check for ebuf */
  15391. ebuf,
  15392. ebuf_len,
  15393. "%s",
  15394. "Bad request");
  15395. *err = 400;
  15396. return 0;
  15397. }
  15398. conn->is_chunked = 1;
  15399. conn->content_len = 0; /* not yet read */
  15400. } else if ((cl = get_header(conn->response_info.http_headers,
  15401. conn->response_info.num_headers,
  15402. "Content-Length"))
  15403. != NULL) {
  15404. char *endptr = NULL;
  15405. conn->content_len = strtoll(cl, &endptr, 10);
  15406. if ((endptr == cl) || (conn->content_len < 0)) {
  15407. mg_snprintf(conn,
  15408. NULL, /* No truncation check for ebuf */
  15409. ebuf,
  15410. ebuf_len,
  15411. "%s",
  15412. "Bad request");
  15413. *err = 411;
  15414. return 0;
  15415. }
  15416. /* Publish the content length back to the response info. */
  15417. conn->response_info.content_length = conn->content_len;
  15418. /* TODO: check if it is still used in response_info */
  15419. conn->request_info.content_length = conn->content_len;
  15420. /* TODO: we should also consider HEAD method */
  15421. if (conn->response_info.status_code == 304) {
  15422. conn->content_len = 0;
  15423. }
  15424. } else {
  15425. /* TODO: we should also consider HEAD method */
  15426. if (((conn->response_info.status_code >= 100)
  15427. && (conn->response_info.status_code <= 199))
  15428. || (conn->response_info.status_code == 204)
  15429. || (conn->response_info.status_code == 304)) {
  15430. conn->content_len = 0;
  15431. } else {
  15432. conn->content_len = -1; /* unknown content length */
  15433. }
  15434. }
  15435. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15436. return 1;
  15437. }
  15438. int
  15439. mg_get_response(struct mg_connection *conn,
  15440. char *ebuf,
  15441. size_t ebuf_len,
  15442. int timeout)
  15443. {
  15444. int err, ret;
  15445. char txt[32]; /* will not overflow */
  15446. char *save_timeout;
  15447. char *new_timeout;
  15448. if (ebuf_len > 0) {
  15449. ebuf[0] = '\0';
  15450. }
  15451. if (!conn) {
  15452. mg_snprintf(conn,
  15453. NULL, /* No truncation check for ebuf */
  15454. ebuf,
  15455. ebuf_len,
  15456. "%s",
  15457. "Parameter error");
  15458. return -1;
  15459. }
  15460. /* Reset the previous responses */
  15461. conn->data_len = 0;
  15462. /* Implementation of API function for HTTP clients */
  15463. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15464. if (timeout >= 0) {
  15465. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15466. new_timeout = txt;
  15467. } else {
  15468. new_timeout = NULL;
  15469. }
  15470. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15471. ret = get_response(conn, ebuf, ebuf_len, &err);
  15472. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15473. #if defined(MG_LEGACY_INTERFACE)
  15474. /* TODO: 1) uri is deprecated;
  15475. * 2) here, ri.uri is the http response code */
  15476. conn->request_info.uri = conn->request_info.request_uri;
  15477. #endif
  15478. conn->request_info.local_uri = conn->request_info.request_uri;
  15479. /* TODO (mid): Define proper return values - maybe return length?
  15480. * For the first test use <0 for error and >0 for OK */
  15481. return (ret == 0) ? -1 : +1;
  15482. }
  15483. struct mg_connection *
  15484. mg_download(const char *host,
  15485. int port,
  15486. int use_ssl,
  15487. char *ebuf,
  15488. size_t ebuf_len,
  15489. const char *fmt,
  15490. ...)
  15491. {
  15492. struct mg_connection *conn;
  15493. va_list ap;
  15494. int i;
  15495. int reqerr;
  15496. if (ebuf_len > 0) {
  15497. ebuf[0] = '\0';
  15498. }
  15499. va_start(ap, fmt);
  15500. /* open a connection */
  15501. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15502. if (conn != NULL) {
  15503. i = mg_vprintf(conn, fmt, ap);
  15504. if (i <= 0) {
  15505. mg_snprintf(conn,
  15506. NULL, /* No truncation check for ebuf */
  15507. ebuf,
  15508. ebuf_len,
  15509. "%s",
  15510. "Error sending request");
  15511. } else {
  15512. /* make sure the buffer is clear */
  15513. conn->data_len = 0;
  15514. get_response(conn, ebuf, ebuf_len, &reqerr);
  15515. #if defined(MG_LEGACY_INTERFACE)
  15516. /* TODO: 1) uri is deprecated;
  15517. * 2) here, ri.uri is the http response code */
  15518. conn->request_info.uri = conn->request_info.request_uri;
  15519. #endif
  15520. conn->request_info.local_uri = conn->request_info.request_uri;
  15521. }
  15522. }
  15523. /* if an error occurred, close the connection */
  15524. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15525. mg_close_connection(conn);
  15526. conn = NULL;
  15527. }
  15528. va_end(ap);
  15529. return conn;
  15530. }
  15531. struct websocket_client_thread_data {
  15532. struct mg_connection *conn;
  15533. mg_websocket_data_handler data_handler;
  15534. mg_websocket_close_handler close_handler;
  15535. void *callback_data;
  15536. };
  15537. #if defined(USE_WEBSOCKET)
  15538. #if defined(_WIN32)
  15539. static unsigned __stdcall websocket_client_thread(void *data)
  15540. #else
  15541. static void *
  15542. websocket_client_thread(void *data)
  15543. #endif
  15544. {
  15545. struct websocket_client_thread_data *cdata =
  15546. (struct websocket_client_thread_data *)data;
  15547. void *user_thread_ptr = NULL;
  15548. #if !defined(_WIN32)
  15549. struct sigaction sa;
  15550. /* Ignore SIGPIPE */
  15551. memset(&sa, 0, sizeof(sa));
  15552. sa.sa_handler = SIG_IGN;
  15553. sigaction(SIGPIPE, &sa, NULL);
  15554. #endif
  15555. mg_set_thread_name("ws-clnt");
  15556. if (cdata->conn->phys_ctx) {
  15557. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15558. /* 3 indicates a websocket client thread */
  15559. /* TODO: check if conn->phys_ctx can be set */
  15560. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15561. cdata->conn->phys_ctx, 3);
  15562. }
  15563. }
  15564. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15565. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15566. if (cdata->close_handler != NULL) {
  15567. cdata->close_handler(cdata->conn, cdata->callback_data);
  15568. }
  15569. /* The websocket_client context has only this thread. If it runs out,
  15570. set the stop_flag to 2 (= "stopped"). */
  15571. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15572. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15573. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15574. 3,
  15575. user_thread_ptr);
  15576. }
  15577. mg_free((void *)cdata);
  15578. #if defined(_WIN32)
  15579. return 0;
  15580. #else
  15581. return NULL;
  15582. #endif
  15583. }
  15584. #endif
  15585. static struct mg_connection *
  15586. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15587. int use_ssl,
  15588. char *error_buffer,
  15589. size_t error_buffer_size,
  15590. const char *path,
  15591. const char *origin,
  15592. mg_websocket_data_handler data_func,
  15593. mg_websocket_close_handler close_func,
  15594. void *user_data)
  15595. {
  15596. struct mg_connection *conn = NULL;
  15597. #if defined(USE_WEBSOCKET)
  15598. struct websocket_client_thread_data *thread_data;
  15599. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15600. const char *handshake_req;
  15601. int port = client_options->port;
  15602. const char *host = client_options->host;
  15603. int i;
  15604. if (origin != NULL) {
  15605. handshake_req = "GET %s HTTP/1.1\r\n"
  15606. "Host: %s\r\n"
  15607. "Upgrade: websocket\r\n"
  15608. "Connection: Upgrade\r\n"
  15609. "Sec-WebSocket-Key: %s\r\n"
  15610. "Sec-WebSocket-Version: 13\r\n"
  15611. "Origin: %s\r\n"
  15612. "\r\n";
  15613. } else {
  15614. handshake_req = "GET %s HTTP/1.1\r\n"
  15615. "Host: %s\r\n"
  15616. "Upgrade: websocket\r\n"
  15617. "Connection: Upgrade\r\n"
  15618. "Sec-WebSocket-Key: %s\r\n"
  15619. "Sec-WebSocket-Version: 13\r\n"
  15620. "\r\n";
  15621. }
  15622. #if defined(__clang__)
  15623. #pragma clang diagnostic push
  15624. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15625. #endif
  15626. /* Establish the client connection and request upgrade */
  15627. conn =
  15628. mg_connect_client(host, port, use_ssl, error_buffer, error_buffer_size);
  15629. if (conn == NULL) {
  15630. /* error_buffer already filled */
  15631. return NULL;
  15632. }
  15633. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15634. if (i <= 0) {
  15635. mg_snprintf(conn,
  15636. NULL, /* No truncation check for ebuf */
  15637. error_buffer,
  15638. error_buffer_size,
  15639. "%s",
  15640. "Error sending request");
  15641. mg_close_connection(conn);
  15642. return NULL;
  15643. }
  15644. conn->data_len = 0;
  15645. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15646. mg_close_connection(conn);
  15647. return NULL;
  15648. }
  15649. conn->request_info.local_uri = conn->request_info.request_uri;
  15650. #if defined(__clang__)
  15651. #pragma clang diagnostic pop
  15652. #endif
  15653. /* Connection object will be null if something goes wrong */
  15654. if (conn == NULL) {
  15655. if (!*error_buffer) {
  15656. /* There should be already an error message */
  15657. mg_snprintf(conn,
  15658. NULL, /* No truncation check for ebuf */
  15659. error_buffer,
  15660. error_buffer_size,
  15661. "Unexpected error");
  15662. }
  15663. return NULL;
  15664. }
  15665. if (conn->response_info.status_code != 101) {
  15666. /* We sent an "upgrade" request. For a correct websocket
  15667. * protocol handshake, we expect a "101 Continue" response.
  15668. * Otherwise it is a protocol violation. Maybe the HTTP
  15669. * Server does not know websockets. */
  15670. if (!*error_buffer) {
  15671. /* set an error, if not yet set */
  15672. mg_snprintf(conn,
  15673. NULL, /* No truncation check for ebuf */
  15674. error_buffer,
  15675. error_buffer_size,
  15676. "Unexpected server reply");
  15677. }
  15678. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15679. mg_close_connection(conn);
  15680. return NULL;
  15681. }
  15682. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15683. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15684. if (!thread_data) {
  15685. DEBUG_TRACE("%s\r\n", "Out of memory");
  15686. mg_close_connection(conn);
  15687. return NULL;
  15688. }
  15689. thread_data->conn = conn;
  15690. thread_data->data_handler = data_func;
  15691. thread_data->close_handler = close_func;
  15692. thread_data->callback_data = user_data;
  15693. conn->phys_ctx->worker_threadids =
  15694. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15695. if (!conn->phys_ctx->worker_threadids) {
  15696. DEBUG_TRACE("%s\r\n", "Out of memory");
  15697. mg_free(thread_data);
  15698. mg_close_connection(conn);
  15699. return NULL;
  15700. }
  15701. /* Now upgrade to ws/wss client context */
  15702. conn->phys_ctx->user_data = user_data;
  15703. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15704. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15705. /* Start a thread to read the websocket client connection
  15706. * This thread will automatically stop when mg_disconnect is
  15707. * called on the client connection */
  15708. if (mg_start_thread_with_id(websocket_client_thread,
  15709. thread_data,
  15710. conn->phys_ctx->worker_threadids)
  15711. != 0) {
  15712. conn->phys_ctx->cfg_worker_threads = 0;
  15713. mg_free(thread_data);
  15714. mg_close_connection(conn);
  15715. conn = NULL;
  15716. DEBUG_TRACE("%s",
  15717. "Websocket client connect thread could not be started\r\n");
  15718. }
  15719. #else
  15720. /* Appease "unused parameter" warnings */
  15721. (void)client_options;
  15722. (void)use_ssl;
  15723. (void)error_buffer;
  15724. (void)error_buffer_size;
  15725. (void)path;
  15726. (void)origin;
  15727. (void)user_data;
  15728. (void)data_func;
  15729. (void)close_func;
  15730. #endif
  15731. return conn;
  15732. }
  15733. struct mg_connection *
  15734. mg_connect_websocket_client(const char *host,
  15735. int port,
  15736. int use_ssl,
  15737. char *error_buffer,
  15738. size_t error_buffer_size,
  15739. const char *path,
  15740. const char *origin,
  15741. mg_websocket_data_handler data_func,
  15742. mg_websocket_close_handler close_func,
  15743. void *user_data)
  15744. {
  15745. struct mg_client_options client_options;
  15746. memset(&client_options, 0, sizeof(client_options));
  15747. client_options.host = host;
  15748. client_options.port = port;
  15749. return mg_connect_websocket_client_impl(&client_options,
  15750. use_ssl,
  15751. error_buffer,
  15752. error_buffer_size,
  15753. path,
  15754. origin,
  15755. data_func,
  15756. close_func,
  15757. user_data);
  15758. }
  15759. struct mg_connection *
  15760. mg_connect_websocket_client_secure(
  15761. const struct mg_client_options *client_options,
  15762. char *error_buffer,
  15763. size_t error_buffer_size,
  15764. const char *path,
  15765. const char *origin,
  15766. mg_websocket_data_handler data_func,
  15767. mg_websocket_close_handler close_func,
  15768. void *user_data)
  15769. {
  15770. if (!client_options) {
  15771. return NULL;
  15772. }
  15773. return mg_connect_websocket_client_impl(client_options,
  15774. 1,
  15775. error_buffer,
  15776. error_buffer_size,
  15777. path,
  15778. origin,
  15779. data_func,
  15780. close_func,
  15781. user_data);
  15782. }
  15783. /* Prepare connection data structure */
  15784. static void
  15785. init_connection(struct mg_connection *conn)
  15786. {
  15787. /* Is keep alive allowed by the server */
  15788. int keep_alive_enabled =
  15789. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15790. if (!keep_alive_enabled) {
  15791. conn->must_close = 1;
  15792. }
  15793. /* Important: on new connection, reset the receiving buffer. Credit
  15794. * goes to crule42. */
  15795. conn->data_len = 0;
  15796. conn->handled_requests = 0;
  15797. mg_set_user_connection_data(conn, NULL);
  15798. #if defined(USE_SERVER_STATS)
  15799. conn->conn_state = 2; /* init */
  15800. #endif
  15801. /* call the init_connection callback if assigned */
  15802. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15803. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15804. void *conn_data = NULL;
  15805. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15806. mg_set_user_connection_data(conn, conn_data);
  15807. }
  15808. }
  15809. }
  15810. /* Process a connection - may handle multiple requests
  15811. * using the same connection.
  15812. * Must be called with a valid connection (conn and
  15813. * conn->phys_ctx must be valid).
  15814. */
  15815. static void
  15816. process_new_connection(struct mg_connection *conn)
  15817. {
  15818. struct mg_request_info *ri = &conn->request_info;
  15819. int keep_alive, discard_len;
  15820. char ebuf[100];
  15821. const char *hostend;
  15822. int reqerr, uri_type;
  15823. #if defined(USE_SERVER_STATS)
  15824. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15825. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15826. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15827. /* could use atomic compare exchange, but this
  15828. * seems overkill for statistics data */
  15829. conn->phys_ctx->max_active_connections = mcon;
  15830. }
  15831. #endif
  15832. init_connection(conn);
  15833. DEBUG_TRACE("Start processing connection from %s",
  15834. conn->request_info.remote_addr);
  15835. /* Loop over multiple requests sent using the same connection
  15836. * (while "keep alive"). */
  15837. do {
  15838. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15839. conn->handled_requests + 1);
  15840. #if defined(USE_SERVER_STATS)
  15841. conn->conn_state = 3; /* ready */
  15842. #endif
  15843. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15844. /* The request sent by the client could not be understood by
  15845. * the server, or it was incomplete or a timeout. Send an
  15846. * error message and close the connection. */
  15847. if (reqerr > 0) {
  15848. DEBUG_ASSERT(ebuf[0] != '\0');
  15849. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15850. }
  15851. } else if (strcmp(ri->http_version, "1.0")
  15852. && strcmp(ri->http_version, "1.1")) {
  15853. /* HTTP/2 is not allowed here */
  15854. mg_snprintf(conn,
  15855. NULL, /* No truncation check for ebuf */
  15856. ebuf,
  15857. sizeof(ebuf),
  15858. "Bad HTTP version: [%s]",
  15859. ri->http_version);
  15860. mg_send_http_error(conn, 505, "%s", ebuf);
  15861. }
  15862. if (ebuf[0] == '\0') {
  15863. uri_type = get_uri_type(conn->request_info.request_uri);
  15864. switch (uri_type) {
  15865. case 1:
  15866. /* Asterisk */
  15867. conn->request_info.local_uri = 0;
  15868. /* TODO: Deal with '*'. */
  15869. break;
  15870. case 2:
  15871. /* relative uri */
  15872. conn->request_info.local_uri = conn->request_info.request_uri;
  15873. break;
  15874. case 3:
  15875. case 4:
  15876. /* absolute uri (with/without port) */
  15877. hostend = get_rel_url_at_current_server(
  15878. conn->request_info.request_uri, conn);
  15879. if (hostend) {
  15880. conn->request_info.local_uri = hostend;
  15881. } else {
  15882. conn->request_info.local_uri = NULL;
  15883. }
  15884. break;
  15885. default:
  15886. mg_snprintf(conn,
  15887. NULL, /* No truncation check for ebuf */
  15888. ebuf,
  15889. sizeof(ebuf),
  15890. "Invalid URI");
  15891. mg_send_http_error(conn, 400, "%s", ebuf);
  15892. conn->request_info.local_uri = NULL;
  15893. break;
  15894. }
  15895. #if defined(MG_LEGACY_INTERFACE)
  15896. /* Legacy before split into local_uri and request_uri */
  15897. conn->request_info.uri = conn->request_info.local_uri;
  15898. #endif
  15899. }
  15900. if (ebuf[0] != '\0') {
  15901. conn->protocol_type = -1;
  15902. } else if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  15903. /* HTTP/1 allows protocol upgrade */
  15904. conn->protocol_type = should_switch_to_protocol(conn);
  15905. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15906. /* This will occur, if a HTTP/1.1 request should be upgraded
  15907. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15908. * Since most (all?) major browsers only support HTTP/2 using
  15909. * ALPN, this is hard to test and very low priority.
  15910. * Deactivate it (at least for now).
  15911. */
  15912. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15913. }
  15914. }
  15915. DEBUG_TRACE("http: %s, error: %s",
  15916. (ri->http_version ? ri->http_version : "none"),
  15917. (ebuf[0] ? ebuf : "none"));
  15918. if (ebuf[0] == '\0') {
  15919. if (conn->request_info.local_uri) {
  15920. /* handle request to local server */
  15921. #if defined(USE_SERVER_STATS)
  15922. conn->conn_state = 4; /* processing */
  15923. #endif
  15924. handle_request(conn);
  15925. #if defined(USE_SERVER_STATS)
  15926. conn->conn_state = 5; /* processed */
  15927. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15928. conn->consumed_content);
  15929. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15930. conn->num_bytes_sent);
  15931. #endif
  15932. DEBUG_TRACE("%s", "handle_request done");
  15933. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15934. conn->phys_ctx->callbacks.end_request(conn,
  15935. conn->status_code);
  15936. DEBUG_TRACE("%s", "end_request callback done");
  15937. }
  15938. log_access(conn);
  15939. } else {
  15940. /* TODO: handle non-local request (PROXY) */
  15941. conn->must_close = 1;
  15942. }
  15943. } else {
  15944. conn->must_close = 1;
  15945. }
  15946. if (ri->remote_user != NULL) {
  15947. mg_free((void *)ri->remote_user);
  15948. /* Important! When having connections with and without auth
  15949. * would cause double free and then crash */
  15950. ri->remote_user = NULL;
  15951. }
  15952. /* NOTE(lsm): order is important here. should_keep_alive() call
  15953. * is using parsed request, which will be invalid after
  15954. * memmove's below.
  15955. * Therefore, memorize should_keep_alive() result now for later
  15956. * use in loop exit condition. */
  15957. /* Enable it only if this request is completely discardable. */
  15958. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  15959. && should_keep_alive(conn) && (conn->content_len >= 0)
  15960. && (conn->request_len > 0)
  15961. && ((conn->is_chunked == 4)
  15962. || (!conn->is_chunked
  15963. && ((conn->consumed_content == conn->content_len)
  15964. || ((conn->request_len + conn->content_len)
  15965. <= conn->data_len))))
  15966. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  15967. if (keep_alive) {
  15968. /* Discard all buffered data for this request */
  15969. discard_len =
  15970. ((conn->request_len + conn->content_len) < conn->data_len)
  15971. ? (int)(conn->request_len + conn->content_len)
  15972. : conn->data_len;
  15973. conn->data_len -= discard_len;
  15974. if (conn->data_len > 0) {
  15975. DEBUG_TRACE("discard_len = %d", discard_len);
  15976. memmove(conn->buf,
  15977. conn->buf + discard_len,
  15978. (size_t)conn->data_len);
  15979. }
  15980. }
  15981. DEBUG_ASSERT(conn->data_len >= 0);
  15982. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15983. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15984. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15985. (long int)conn->data_len,
  15986. (long int)conn->buf_size);
  15987. break;
  15988. }
  15989. conn->handled_requests++;
  15990. } while (keep_alive);
  15991. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15992. conn->request_info.remote_addr,
  15993. difftime(time(NULL), conn->conn_birth_time));
  15994. close_connection(conn);
  15995. #if defined(USE_SERVER_STATS)
  15996. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15997. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15998. #endif
  15999. }
  16000. #if defined(ALTERNATIVE_QUEUE)
  16001. static void
  16002. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16003. {
  16004. unsigned int i;
  16005. while (!ctx->stop_flag) {
  16006. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16007. /* find a free worker slot and signal it */
  16008. if (ctx->client_socks[i].in_use == 2) {
  16009. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16010. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16011. ctx->client_socks[i] = *sp;
  16012. ctx->client_socks[i].in_use = 1;
  16013. /* socket has been moved to the consumer */
  16014. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16015. (void)event_signal(ctx->client_wait_events[i]);
  16016. return;
  16017. }
  16018. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16019. }
  16020. }
  16021. /* queue is full */
  16022. mg_sleep(1);
  16023. }
  16024. /* must consume */
  16025. set_blocking_mode(sp->sock);
  16026. closesocket(sp->sock);
  16027. }
  16028. static int
  16029. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16030. {
  16031. DEBUG_TRACE("%s", "going idle");
  16032. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16033. ctx->client_socks[thread_index].in_use = 2;
  16034. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16035. event_wait(ctx->client_wait_events[thread_index]);
  16036. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16037. *sp = ctx->client_socks[thread_index];
  16038. if (ctx->stop_flag) {
  16039. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16040. if (sp->in_use == 1) {
  16041. /* must consume */
  16042. set_blocking_mode(sp->sock);
  16043. closesocket(sp->sock);
  16044. }
  16045. return 0;
  16046. }
  16047. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16048. if (sp->in_use == 1) {
  16049. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16050. return 1;
  16051. }
  16052. /* must not reach here */
  16053. DEBUG_ASSERT(0);
  16054. return 0;
  16055. }
  16056. #else /* ALTERNATIVE_QUEUE */
  16057. /* Worker threads take accepted socket from the queue */
  16058. static int
  16059. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16060. {
  16061. (void)thread_index;
  16062. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16063. DEBUG_TRACE("%s", "going idle");
  16064. /* If the queue is empty, wait. We're idle at this point. */
  16065. while ((ctx->sq_head == ctx->sq_tail)
  16066. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16067. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16068. }
  16069. /* If we're stopping, sq_head may be equal to sq_tail. */
  16070. if (ctx->sq_head > ctx->sq_tail) {
  16071. /* Copy socket from the queue and increment tail */
  16072. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16073. ctx->sq_tail++;
  16074. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16075. /* Wrap pointers if needed */
  16076. while (ctx->sq_tail > ctx->sq_size) {
  16077. ctx->sq_tail -= ctx->sq_size;
  16078. ctx->sq_head -= ctx->sq_size;
  16079. }
  16080. }
  16081. (void)pthread_cond_signal(&ctx->sq_empty);
  16082. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16083. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16084. }
  16085. /* Master thread adds accepted socket to a queue */
  16086. static void
  16087. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16088. {
  16089. int queue_filled;
  16090. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16091. queue_filled = ctx->sq_head - ctx->sq_tail;
  16092. /* If the queue is full, wait */
  16093. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16094. && (queue_filled >= ctx->sq_size)) {
  16095. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  16096. #if defined(USE_SERVER_STATS)
  16097. if (queue_filled > ctx->sq_max_fill) {
  16098. ctx->sq_max_fill = queue_filled;
  16099. }
  16100. #endif
  16101. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16102. ctx->sq_blocked = 0; /* Not blocked now */
  16103. queue_filled = ctx->sq_head - ctx->sq_tail;
  16104. }
  16105. if (queue_filled < ctx->sq_size) {
  16106. /* Copy socket to the queue and increment head */
  16107. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16108. ctx->sq_head++;
  16109. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16110. }
  16111. queue_filled = ctx->sq_head - ctx->sq_tail;
  16112. #if defined(USE_SERVER_STATS)
  16113. if (queue_filled > ctx->sq_max_fill) {
  16114. ctx->sq_max_fill = queue_filled;
  16115. }
  16116. #endif
  16117. (void)pthread_cond_signal(&ctx->sq_full);
  16118. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16119. }
  16120. #endif /* ALTERNATIVE_QUEUE */
  16121. static void
  16122. worker_thread_run(struct mg_connection *conn)
  16123. {
  16124. struct mg_context *ctx = conn->phys_ctx;
  16125. int thread_index;
  16126. struct mg_workerTLS tls;
  16127. #if defined(MG_LEGACY_INTERFACE)
  16128. uint32_t addr;
  16129. #endif
  16130. mg_set_thread_name("worker");
  16131. tls.is_master = 0;
  16132. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16133. #if defined(_WIN32)
  16134. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16135. #endif
  16136. /* Initialize thread local storage before calling any callback */
  16137. pthread_setspecific(sTlsKey, &tls);
  16138. /* Check if there is a user callback */
  16139. if (ctx->callbacks.init_thread) {
  16140. /* call init_thread for a worker thread (type 1), and store the
  16141. * return value */
  16142. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16143. } else {
  16144. /* No callback: set user pointer to NULL */
  16145. tls.user_ptr = NULL;
  16146. }
  16147. /* Connection structure has been pre-allocated */
  16148. thread_index = (int)(conn - ctx->worker_connections);
  16149. if ((thread_index < 0)
  16150. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16151. mg_cry_ctx_internal(ctx,
  16152. "Internal error: Invalid worker index %i",
  16153. thread_index);
  16154. return;
  16155. }
  16156. /* Request buffers are not pre-allocated. They are private to the
  16157. * request and do not contain any state information that might be
  16158. * of interest to anyone observing a server status. */
  16159. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16160. if (conn->buf == NULL) {
  16161. mg_cry_ctx_internal(
  16162. ctx,
  16163. "Out of memory: Cannot allocate buffer for worker %i",
  16164. thread_index);
  16165. return;
  16166. }
  16167. conn->buf_size = (int)ctx->max_request_size;
  16168. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16169. conn->host = NULL; /* until we have more information. */
  16170. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16171. conn->request_info.user_data = ctx->user_data;
  16172. /* Allocate a mutex for this connection to allow communication both
  16173. * within the request handler and from elsewhere in the application
  16174. */
  16175. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16176. mg_free(conn->buf);
  16177. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16178. return;
  16179. }
  16180. #if defined(USE_SERVER_STATS)
  16181. conn->conn_state = 1; /* not consumed */
  16182. #endif
  16183. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16184. * signal sq_empty condvar to wake up the master waiting in
  16185. * produce_socket() */
  16186. while (consume_socket(ctx, &conn->client, thread_index)) {
  16187. /* New connections must start with new protocol negotiation */
  16188. tls.alpn_proto = NULL;
  16189. #if defined(USE_SERVER_STATS)
  16190. conn->conn_close_time = 0;
  16191. #endif
  16192. conn->conn_birth_time = time(NULL);
  16193. /* Fill in IP, port info early so even if SSL setup below fails,
  16194. * error handler would have the corresponding info.
  16195. * Thanks to Johannes Winkelmann for the patch.
  16196. */
  16197. #if defined(USE_IPV6)
  16198. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  16199. conn->request_info.remote_port =
  16200. ntohs(conn->client.rsa.sin6.sin6_port);
  16201. } else
  16202. #endif
  16203. {
  16204. conn->request_info.remote_port =
  16205. ntohs(conn->client.rsa.sin.sin_port);
  16206. }
  16207. sockaddr_to_string(conn->request_info.remote_addr,
  16208. sizeof(conn->request_info.remote_addr),
  16209. &conn->client.rsa);
  16210. DEBUG_TRACE("Start processing connection from %s",
  16211. conn->request_info.remote_addr);
  16212. conn->request_info.is_ssl = conn->client.is_ssl;
  16213. if (conn->client.is_ssl) {
  16214. #if !defined(NO_SSL)
  16215. /* HTTPS connection */
  16216. if (sslize(conn, SSL_accept, NULL)) {
  16217. /* conn->dom_ctx is set in get_request */
  16218. /* Get SSL client certificate information (if set) */
  16219. struct mg_client_cert client_cert;
  16220. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16221. conn->request_info.client_cert = &client_cert;
  16222. }
  16223. /* process HTTPS connection */
  16224. #if defined(USE_HTTP2)
  16225. if ((tls.alpn_proto != NULL)
  16226. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16227. /* process HTTPS/2 connection */
  16228. init_connection(conn);
  16229. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16230. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16231. conn->content_len = -1;
  16232. conn->is_chunked = 0;
  16233. process_new_http2_connection(conn);
  16234. } else
  16235. #endif
  16236. {
  16237. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16238. process_new_connection(conn);
  16239. }
  16240. /* Free client certificate info */
  16241. if (conn->request_info.client_cert) {
  16242. mg_free((void *)(conn->request_info.client_cert->subject));
  16243. mg_free((void *)(conn->request_info.client_cert->issuer));
  16244. mg_free((void *)(conn->request_info.client_cert->serial));
  16245. mg_free((void *)(conn->request_info.client_cert->finger));
  16246. /* Free certificate memory */
  16247. X509_free(
  16248. (X509 *)conn->request_info.client_cert->peer_cert);
  16249. conn->request_info.client_cert->peer_cert = 0;
  16250. conn->request_info.client_cert->subject = 0;
  16251. conn->request_info.client_cert->issuer = 0;
  16252. conn->request_info.client_cert->serial = 0;
  16253. conn->request_info.client_cert->finger = 0;
  16254. conn->request_info.client_cert = 0;
  16255. }
  16256. } else {
  16257. /* make sure the connection is cleaned up on SSL failure */
  16258. close_connection(conn);
  16259. }
  16260. #endif
  16261. } else {
  16262. /* process HTTP connection */
  16263. process_new_connection(conn);
  16264. }
  16265. DEBUG_TRACE("%s", "Connection closed");
  16266. #if defined(USE_SERVER_STATS)
  16267. conn->conn_close_time = time(NULL);
  16268. #endif
  16269. }
  16270. /* Call exit thread user callback */
  16271. if (ctx->callbacks.exit_thread) {
  16272. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16273. }
  16274. /* delete thread local storage objects */
  16275. pthread_setspecific(sTlsKey, NULL);
  16276. #if defined(_WIN32)
  16277. CloseHandle(tls.pthread_cond_helper_mutex);
  16278. #endif
  16279. pthread_mutex_destroy(&conn->mutex);
  16280. /* Free the request buffer. */
  16281. conn->buf_size = 0;
  16282. mg_free(conn->buf);
  16283. conn->buf = NULL;
  16284. #if defined(USE_SERVER_STATS)
  16285. conn->conn_state = 9; /* done */
  16286. #endif
  16287. DEBUG_TRACE("%s", "exiting");
  16288. }
  16289. /* Threads have different return types on Windows and Unix. */
  16290. #if defined(_WIN32)
  16291. static unsigned __stdcall worker_thread(void *thread_func_param)
  16292. {
  16293. worker_thread_run((struct mg_connection *)thread_func_param);
  16294. return 0;
  16295. }
  16296. #else
  16297. static void *
  16298. worker_thread(void *thread_func_param)
  16299. {
  16300. #if !defined(__ZEPHYR__)
  16301. struct sigaction sa;
  16302. /* Ignore SIGPIPE */
  16303. memset(&sa, 0, sizeof(sa));
  16304. sa.sa_handler = SIG_IGN;
  16305. sigaction(SIGPIPE, &sa, NULL);
  16306. #endif
  16307. worker_thread_run((struct mg_connection *)thread_func_param);
  16308. return NULL;
  16309. }
  16310. #endif /* _WIN32 */
  16311. /* This is an internal function, thus all arguments are expected to be
  16312. * valid - a NULL check is not required. */
  16313. static void
  16314. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16315. {
  16316. struct socket so;
  16317. char src_addr[IP_ADDR_STR_LEN];
  16318. socklen_t len = sizeof(so.rsa);
  16319. #if !defined(__ZEPHYR__)
  16320. int on = 1;
  16321. #endif
  16322. memset(&so, 0, sizeof(so));
  16323. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16324. == INVALID_SOCKET) {
  16325. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  16326. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16327. mg_cry_ctx_internal(ctx,
  16328. "%s: %s is not allowed to connect",
  16329. __func__,
  16330. src_addr);
  16331. closesocket(so.sock);
  16332. } else {
  16333. /* Put so socket structure into the queue */
  16334. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16335. set_close_on_exec(so.sock, NULL, ctx);
  16336. so.is_ssl = listener->is_ssl;
  16337. so.ssl_redir = listener->ssl_redir;
  16338. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16339. mg_cry_ctx_internal(ctx,
  16340. "%s: getsockname() failed: %s",
  16341. __func__,
  16342. strerror(ERRNO));
  16343. }
  16344. #if !defined(__ZEPHYR__)
  16345. /* Set TCP keep-alive. This is needed because if HTTP-level
  16346. * keep-alive
  16347. * is enabled, and client resets the connection, server won't get
  16348. * TCP FIN or RST and will keep the connection open forever. With
  16349. * TCP keep-alive, next keep-alive handshake will figure out that
  16350. * the client is down and will close the server end.
  16351. * Thanks to Igor Klopov who suggested the patch. */
  16352. if (setsockopt(so.sock,
  16353. SOL_SOCKET,
  16354. SO_KEEPALIVE,
  16355. (SOCK_OPT_TYPE)&on,
  16356. sizeof(on))
  16357. != 0) {
  16358. mg_cry_ctx_internal(
  16359. ctx,
  16360. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16361. __func__,
  16362. strerror(ERRNO));
  16363. }
  16364. #endif
  16365. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16366. * to effectively fill up the underlying IP packet payload and
  16367. * reduce the overhead of sending lots of small buffers. However
  16368. * this hurts the server's throughput (ie. operations per second)
  16369. * when HTTP 1.1 persistent connections are used and the responses
  16370. * are relatively small (eg. less than 1400 bytes).
  16371. */
  16372. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16373. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16374. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16375. mg_cry_ctx_internal(
  16376. ctx,
  16377. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16378. __func__,
  16379. strerror(ERRNO));
  16380. }
  16381. }
  16382. /* The "non blocking" property should already be
  16383. * inherited from the parent socket. Set it for
  16384. * non-compliant socket implementations. */
  16385. set_non_blocking_mode(so.sock);
  16386. so.in_use = 0;
  16387. produce_socket(ctx, &so);
  16388. }
  16389. }
  16390. static void
  16391. master_thread_run(struct mg_context *ctx)
  16392. {
  16393. struct mg_workerTLS tls;
  16394. struct mg_pollfd *pfd;
  16395. unsigned int i;
  16396. unsigned int workerthreadcount;
  16397. if (!ctx) {
  16398. return;
  16399. }
  16400. mg_set_thread_name("master");
  16401. /* Increase priority of the master thread */
  16402. #if defined(_WIN32)
  16403. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16404. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16405. int min_prio = sched_get_priority_min(SCHED_RR);
  16406. int max_prio = sched_get_priority_max(SCHED_RR);
  16407. if ((min_prio >= 0) && (max_prio >= 0)
  16408. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16409. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16410. struct sched_param sched_param = {0};
  16411. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16412. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16413. }
  16414. #endif
  16415. /* Initialize thread local storage */
  16416. #if defined(_WIN32)
  16417. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16418. #endif
  16419. tls.is_master = 1;
  16420. pthread_setspecific(sTlsKey, &tls);
  16421. if (ctx->callbacks.init_thread) {
  16422. /* Callback for the master thread (type 0) */
  16423. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16424. } else {
  16425. tls.user_ptr = NULL;
  16426. }
  16427. /* Server starts *now* */
  16428. ctx->start_time = time(NULL);
  16429. /* Start the server */
  16430. pfd = ctx->listening_socket_fds;
  16431. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16432. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16433. pfd[i].fd = ctx->listening_sockets[i].sock;
  16434. pfd[i].events = POLLIN;
  16435. }
  16436. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16437. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16438. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16439. * successful poll, and POLLIN is defined as
  16440. * (POLLRDNORM | POLLRDBAND)
  16441. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16442. * pfd[i].revents == POLLIN. */
  16443. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16444. && (pfd[i].revents & POLLIN)) {
  16445. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16446. }
  16447. }
  16448. }
  16449. }
  16450. /* Here stop_flag is 1 - Initiate shutdown. */
  16451. DEBUG_TRACE("%s", "stopping workers");
  16452. /* Stop signal received: somebody called mg_stop. Quit. */
  16453. close_all_listening_sockets(ctx);
  16454. /* Wakeup workers that are waiting for connections to handle. */
  16455. #if defined(ALTERNATIVE_QUEUE)
  16456. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16457. event_signal(ctx->client_wait_events[i]);
  16458. }
  16459. #else
  16460. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16461. pthread_cond_broadcast(&ctx->sq_full);
  16462. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16463. #endif
  16464. /* Join all worker threads to avoid leaking threads. */
  16465. workerthreadcount = ctx->cfg_worker_threads;
  16466. for (i = 0; i < workerthreadcount; i++) {
  16467. if (ctx->worker_threadids[i] != 0) {
  16468. mg_join_thread(ctx->worker_threadids[i]);
  16469. }
  16470. }
  16471. #if defined(USE_LUA)
  16472. /* Free Lua state of lua background task */
  16473. if (ctx->lua_background_state) {
  16474. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16475. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16476. if (lua_istable(lstate, -1)) {
  16477. reg_boolean(lstate, "shutdown", 1);
  16478. lua_pop(lstate, 1);
  16479. mg_sleep(2);
  16480. }
  16481. lua_close(lstate);
  16482. ctx->lua_background_state = 0;
  16483. }
  16484. #endif
  16485. DEBUG_TRACE("%s", "exiting");
  16486. /* call exit thread callback */
  16487. if (ctx->callbacks.exit_thread) {
  16488. /* Callback for the master thread (type 0) */
  16489. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16490. }
  16491. #if defined(_WIN32)
  16492. CloseHandle(tls.pthread_cond_helper_mutex);
  16493. #endif
  16494. pthread_setspecific(sTlsKey, NULL);
  16495. /* Signal mg_stop() that we're done.
  16496. * WARNING: This must be the very last thing this
  16497. * thread does, as ctx becomes invalid after this line. */
  16498. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16499. }
  16500. /* Threads have different return types on Windows and Unix. */
  16501. #if defined(_WIN32)
  16502. static unsigned __stdcall master_thread(void *thread_func_param)
  16503. {
  16504. master_thread_run((struct mg_context *)thread_func_param);
  16505. return 0;
  16506. }
  16507. #else
  16508. static void *
  16509. master_thread(void *thread_func_param)
  16510. {
  16511. #if !defined(__ZEPHYR__)
  16512. struct sigaction sa;
  16513. /* Ignore SIGPIPE */
  16514. memset(&sa, 0, sizeof(sa));
  16515. sa.sa_handler = SIG_IGN;
  16516. sigaction(SIGPIPE, &sa, NULL);
  16517. #endif
  16518. master_thread_run((struct mg_context *)thread_func_param);
  16519. return NULL;
  16520. }
  16521. #endif /* _WIN32 */
  16522. static void
  16523. free_context(struct mg_context *ctx)
  16524. {
  16525. int i;
  16526. struct mg_handler_info *tmp_rh;
  16527. if (ctx == NULL) {
  16528. return;
  16529. }
  16530. if (ctx->callbacks.exit_context) {
  16531. ctx->callbacks.exit_context(ctx);
  16532. }
  16533. /* All threads exited, no sync is needed. Destroy thread mutex and
  16534. * condvars
  16535. */
  16536. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16537. #if defined(ALTERNATIVE_QUEUE)
  16538. mg_free(ctx->client_socks);
  16539. if (ctx->client_wait_events != NULL) {
  16540. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16541. event_destroy(ctx->client_wait_events[i]);
  16542. }
  16543. mg_free(ctx->client_wait_events);
  16544. }
  16545. #else
  16546. (void)pthread_cond_destroy(&ctx->sq_empty);
  16547. (void)pthread_cond_destroy(&ctx->sq_full);
  16548. mg_free(ctx->squeue);
  16549. #endif
  16550. /* Destroy other context global data structures mutex */
  16551. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16552. #if defined(USE_TIMERS)
  16553. timers_exit(ctx);
  16554. #endif
  16555. /* Deallocate config parameters */
  16556. for (i = 0; i < NUM_OPTIONS; i++) {
  16557. if (ctx->dd.config[i] != NULL) {
  16558. #if defined(_MSC_VER)
  16559. #pragma warning(suppress : 6001)
  16560. #endif
  16561. mg_free(ctx->dd.config[i]);
  16562. }
  16563. }
  16564. /* Deallocate request handlers */
  16565. while (ctx->dd.handlers) {
  16566. tmp_rh = ctx->dd.handlers;
  16567. ctx->dd.handlers = tmp_rh->next;
  16568. mg_free(tmp_rh->uri);
  16569. mg_free(tmp_rh);
  16570. }
  16571. #if !defined(NO_SSL)
  16572. /* Deallocate SSL context */
  16573. if (ctx->dd.ssl_ctx != NULL) {
  16574. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16575. int callback_ret =
  16576. (ctx->callbacks.external_ssl_ctx == NULL)
  16577. ? 0
  16578. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16579. if (callback_ret == 0) {
  16580. SSL_CTX_free(ctx->dd.ssl_ctx);
  16581. }
  16582. /* else: ignore error and ommit SSL_CTX_free in case
  16583. * callback_ret is 1 */
  16584. }
  16585. #endif /* !NO_SSL */
  16586. /* Deallocate worker thread ID array */
  16587. mg_free(ctx->worker_threadids);
  16588. /* Deallocate worker thread ID array */
  16589. mg_free(ctx->worker_connections);
  16590. /* deallocate system name string */
  16591. mg_free(ctx->systemName);
  16592. /* Deallocate context itself */
  16593. mg_free(ctx);
  16594. }
  16595. void
  16596. mg_stop(struct mg_context *ctx)
  16597. {
  16598. pthread_t mt;
  16599. if (!ctx) {
  16600. return;
  16601. }
  16602. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16603. * two threads is not allowed. */
  16604. mt = ctx->masterthreadid;
  16605. if (mt == 0) {
  16606. return;
  16607. }
  16608. ctx->masterthreadid = 0;
  16609. /* Set stop flag, so all threads know they have to exit. */
  16610. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16611. /* Wait until everything has stopped. */
  16612. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16613. (void)mg_sleep(10);
  16614. }
  16615. mg_join_thread(mt);
  16616. free_context(ctx);
  16617. #if defined(_WIN32)
  16618. (void)WSACleanup();
  16619. #endif /* _WIN32 */
  16620. }
  16621. static void
  16622. get_system_name(char **sysName)
  16623. {
  16624. #if defined(_WIN32)
  16625. #if defined(_WIN32_WCE)
  16626. *sysName = mg_strdup("WinCE");
  16627. #else
  16628. char name[128];
  16629. DWORD dwVersion = 0;
  16630. DWORD dwMajorVersion = 0;
  16631. DWORD dwMinorVersion = 0;
  16632. DWORD dwBuild = 0;
  16633. BOOL wowRet, isWoW = FALSE;
  16634. #if defined(_MSC_VER)
  16635. #pragma warning(push)
  16636. /* GetVersion was declared deprecated */
  16637. #pragma warning(disable : 4996)
  16638. #endif
  16639. dwVersion = GetVersion();
  16640. #if defined(_MSC_VER)
  16641. #pragma warning(pop)
  16642. #endif
  16643. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16644. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16645. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16646. (void)dwBuild;
  16647. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16648. sprintf(name,
  16649. "Windows %u.%u%s",
  16650. (unsigned)dwMajorVersion,
  16651. (unsigned)dwMinorVersion,
  16652. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16653. *sysName = mg_strdup(name);
  16654. #endif
  16655. #elif defined(__ZEPHYR__)
  16656. *sysName = mg_strdup("Zephyr OS");
  16657. #else
  16658. struct utsname name;
  16659. memset(&name, 0, sizeof(name));
  16660. uname(&name);
  16661. *sysName = mg_strdup(name.sysname);
  16662. #endif
  16663. }
  16664. static void
  16665. legacy_init(const char **options)
  16666. {
  16667. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16668. if (options) {
  16669. const char **run_options = options;
  16670. const char *optname = config_options[LISTENING_PORTS].name;
  16671. /* Try to find the "listening_ports" option */
  16672. while (*run_options) {
  16673. if (!strcmp(*run_options, optname)) {
  16674. ports_option = run_options[1];
  16675. }
  16676. run_options += 2;
  16677. }
  16678. }
  16679. if (is_ssl_port_used(ports_option)) {
  16680. /* Initialize with SSL support */
  16681. mg_init_library(MG_FEATURES_TLS);
  16682. } else {
  16683. /* Initialize without SSL support */
  16684. mg_init_library(MG_FEATURES_DEFAULT);
  16685. }
  16686. }
  16687. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16688. static
  16689. #endif
  16690. struct mg_context *
  16691. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16692. {
  16693. struct mg_context *ctx;
  16694. const char *name, *value, *default_value;
  16695. int idx, ok, workerthreadcount;
  16696. unsigned int i;
  16697. int itmp;
  16698. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16699. const char **options =
  16700. ((init != NULL) ? (init->configuration_options) : (NULL));
  16701. struct mg_workerTLS tls;
  16702. #if defined(_WIN32)
  16703. WSADATA data;
  16704. WSAStartup(MAKEWORD(2, 2), &data);
  16705. #endif /* _WIN32 */
  16706. if (error != NULL) {
  16707. error->code = 0;
  16708. if (error->text_buffer_size > 0) {
  16709. *error->text = 0;
  16710. }
  16711. }
  16712. if (mg_init_library_called == 0) {
  16713. /* Legacy INIT, if mg_start is called without mg_init_library.
  16714. * Note: This will cause a memory leak when unloading the library.
  16715. */
  16716. legacy_init(options);
  16717. }
  16718. if (mg_init_library_called == 0) {
  16719. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16720. mg_snprintf(NULL,
  16721. NULL, /* No truncation check for error buffers */
  16722. error->text,
  16723. error->text_buffer_size,
  16724. "%s",
  16725. "Library uninitialized");
  16726. }
  16727. return NULL;
  16728. }
  16729. /* Allocate context and initialize reasonable general case defaults. */
  16730. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16731. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16732. mg_snprintf(NULL,
  16733. NULL, /* No truncation check for error buffers */
  16734. error->text,
  16735. error->text_buffer_size,
  16736. "%s",
  16737. "Out of memory");
  16738. }
  16739. return NULL;
  16740. }
  16741. /* Random number generator will initialize at the first call */
  16742. ctx->dd.auth_nonce_mask =
  16743. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16744. /* Save started thread index to reuse in other external API calls
  16745. * For the sake of thread synchronization all non-civetweb threads
  16746. * can be considered as single external thread */
  16747. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16748. tls.is_master = -1; /* Thread calling mg_start */
  16749. tls.thread_idx = ctx->starter_thread_idx;
  16750. #if defined(_WIN32)
  16751. tls.pthread_cond_helper_mutex = NULL;
  16752. #endif
  16753. pthread_setspecific(sTlsKey, &tls);
  16754. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16755. #if !defined(ALTERNATIVE_QUEUE)
  16756. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16757. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16758. ctx->sq_blocked = 0;
  16759. #endif
  16760. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16761. if (!ok) {
  16762. const char *err_msg =
  16763. "Cannot initialize thread synchronization objects";
  16764. /* Fatal error - abort start. However, this situation should never
  16765. * occur in practice. */
  16766. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16767. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16768. mg_snprintf(NULL,
  16769. NULL, /* No truncation check for error buffers */
  16770. error->text,
  16771. error->text_buffer_size,
  16772. "%s",
  16773. err_msg);
  16774. }
  16775. mg_free(ctx);
  16776. pthread_setspecific(sTlsKey, NULL);
  16777. return NULL;
  16778. }
  16779. if ((init != NULL) && (init->callbacks != NULL)) {
  16780. /* Set all callbacks except exit_context. */
  16781. ctx->callbacks = *init->callbacks;
  16782. exit_callback = init->callbacks->exit_context;
  16783. /* The exit callback is activated once the context is successfully
  16784. * created. It should not be called, if an incomplete context object
  16785. * is deleted during a failed initialization. */
  16786. ctx->callbacks.exit_context = 0;
  16787. }
  16788. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16789. ctx->dd.handlers = NULL;
  16790. ctx->dd.next = NULL;
  16791. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16792. ctx->dd.shared_lua_websockets = NULL;
  16793. #endif
  16794. /* Store options */
  16795. while (options && (name = *options++) != NULL) {
  16796. if ((idx = get_option_index(name)) == -1) {
  16797. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16798. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16799. mg_snprintf(NULL,
  16800. NULL, /* No truncation check for error buffers */
  16801. error->text,
  16802. error->text_buffer_size,
  16803. "Invalid configuration option: %s",
  16804. name);
  16805. }
  16806. free_context(ctx);
  16807. pthread_setspecific(sTlsKey, NULL);
  16808. return NULL;
  16809. } else if ((value = *options++) == NULL) {
  16810. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16811. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16812. mg_snprintf(NULL,
  16813. NULL, /* No truncation check for error buffers */
  16814. error->text,
  16815. error->text_buffer_size,
  16816. "Invalid configuration option value: %s",
  16817. name);
  16818. }
  16819. free_context(ctx);
  16820. pthread_setspecific(sTlsKey, NULL);
  16821. return NULL;
  16822. }
  16823. if (ctx->dd.config[idx] != NULL) {
  16824. /* A duplicate configuration option is not an error - the last
  16825. * option value will be used. */
  16826. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16827. mg_free(ctx->dd.config[idx]);
  16828. }
  16829. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16830. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16831. }
  16832. /* Set default value if needed */
  16833. for (i = 0; config_options[i].name != NULL; i++) {
  16834. default_value = config_options[i].default_value;
  16835. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16836. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16837. }
  16838. }
  16839. /* Request size option */
  16840. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16841. if (itmp < 1024) {
  16842. mg_cry_ctx_internal(ctx,
  16843. "%s too small",
  16844. config_options[MAX_REQUEST_SIZE].name);
  16845. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16846. mg_snprintf(NULL,
  16847. NULL, /* No truncation check for error buffers */
  16848. error->text,
  16849. error->text_buffer_size,
  16850. "Invalid configuration option value: %s",
  16851. config_options[MAX_REQUEST_SIZE].name);
  16852. }
  16853. free_context(ctx);
  16854. pthread_setspecific(sTlsKey, NULL);
  16855. return NULL;
  16856. }
  16857. ctx->max_request_size = (unsigned)itmp;
  16858. /* Queue length */
  16859. #if !defined(ALTERNATIVE_QUEUE)
  16860. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16861. if (itmp < 1) {
  16862. mg_cry_ctx_internal(ctx,
  16863. "%s too small",
  16864. config_options[CONNECTION_QUEUE_SIZE].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. config_options[CONNECTION_QUEUE_SIZE].name);
  16872. }
  16873. free_context(ctx);
  16874. pthread_setspecific(sTlsKey, NULL);
  16875. return NULL;
  16876. }
  16877. ctx->squeue =
  16878. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16879. if (ctx->squeue == NULL) {
  16880. mg_cry_ctx_internal(ctx,
  16881. "Out of memory: Cannot allocate %s",
  16882. config_options[CONNECTION_QUEUE_SIZE].name);
  16883. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16884. mg_snprintf(NULL,
  16885. NULL, /* No truncation check for error buffers */
  16886. error->text,
  16887. error->text_buffer_size,
  16888. "Out of memory: Cannot allocate %s",
  16889. config_options[CONNECTION_QUEUE_SIZE].name);
  16890. }
  16891. free_context(ctx);
  16892. pthread_setspecific(sTlsKey, NULL);
  16893. return NULL;
  16894. }
  16895. ctx->sq_size = itmp;
  16896. #endif
  16897. /* Worker thread count option */
  16898. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16899. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16900. if (workerthreadcount <= 0) {
  16901. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16902. } else {
  16903. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16904. }
  16905. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16906. mg_snprintf(NULL,
  16907. NULL, /* No truncation check for error buffers */
  16908. error->text,
  16909. error->text_buffer_size,
  16910. "Invalid configuration option value: %s",
  16911. config_options[NUM_THREADS].name);
  16912. }
  16913. free_context(ctx);
  16914. pthread_setspecific(sTlsKey, NULL);
  16915. return NULL;
  16916. }
  16917. /* Document root */
  16918. #if defined(NO_FILES)
  16919. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16920. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16921. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16922. mg_snprintf(NULL,
  16923. NULL, /* No truncation check for error buffers */
  16924. error->text,
  16925. error->text_buffer_size,
  16926. "Invalid configuration option value: %s",
  16927. config_options[DOCUMENT_ROOT].name);
  16928. }
  16929. free_context(ctx);
  16930. pthread_setspecific(sTlsKey, NULL);
  16931. return NULL;
  16932. }
  16933. #endif
  16934. get_system_name(&ctx->systemName);
  16935. #if defined(USE_LUA)
  16936. /* If a Lua background script has been configured, start it. */
  16937. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16938. char ebuf[256];
  16939. struct vec opt_vec;
  16940. struct vec eq_vec;
  16941. const char *sparams;
  16942. lua_State *state = mg_prepare_lua_context_script(
  16943. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16944. if (!state) {
  16945. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16946. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16947. mg_snprintf(NULL,
  16948. NULL, /* No truncation check for error buffers */
  16949. error->text,
  16950. error->text_buffer_size,
  16951. "Error in script %s: %s",
  16952. config_options[DOCUMENT_ROOT].name,
  16953. ebuf);
  16954. }
  16955. free_context(ctx);
  16956. pthread_setspecific(sTlsKey, NULL);
  16957. return NULL;
  16958. }
  16959. ctx->lua_background_state = (void *)state;
  16960. lua_newtable(state);
  16961. reg_boolean(state, "shutdown", 0);
  16962. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16963. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16964. reg_llstring(
  16965. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16966. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16967. break;
  16968. }
  16969. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16970. } else {
  16971. ctx->lua_background_state = 0;
  16972. }
  16973. #endif
  16974. /* Step by step initialization of ctx - depending on build options */
  16975. #if !defined(NO_FILESYSTEMS)
  16976. if (!set_gpass_option(ctx, NULL)) {
  16977. const char *err_msg = "Invalid global password file";
  16978. /* Fatal error - abort start. */
  16979. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16980. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16981. mg_snprintf(NULL,
  16982. NULL, /* No truncation check for error buffers */
  16983. error->text,
  16984. error->text_buffer_size,
  16985. "%s",
  16986. err_msg);
  16987. }
  16988. free_context(ctx);
  16989. pthread_setspecific(sTlsKey, NULL);
  16990. return NULL;
  16991. }
  16992. #endif
  16993. #if !defined(NO_SSL)
  16994. if (!init_ssl_ctx(ctx, NULL)) {
  16995. const char *err_msg = "Error initializing SSL context";
  16996. /* Fatal error - abort start. */
  16997. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16998. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16999. mg_snprintf(NULL,
  17000. NULL, /* No truncation check for error buffers */
  17001. error->text,
  17002. error->text_buffer_size,
  17003. "%s",
  17004. err_msg);
  17005. }
  17006. free_context(ctx);
  17007. pthread_setspecific(sTlsKey, NULL);
  17008. return NULL;
  17009. }
  17010. #endif
  17011. if (!set_ports_option(ctx)) {
  17012. const char *err_msg = "Failed to setup server ports";
  17013. /* Fatal error - abort start. */
  17014. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17015. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17016. mg_snprintf(NULL,
  17017. NULL, /* No truncation check for error buffers */
  17018. error->text,
  17019. error->text_buffer_size,
  17020. "%s",
  17021. err_msg);
  17022. }
  17023. free_context(ctx);
  17024. pthread_setspecific(sTlsKey, NULL);
  17025. return NULL;
  17026. }
  17027. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17028. if (!set_uid_option(ctx)) {
  17029. const char *err_msg = "Failed to run as configured user";
  17030. /* Fatal error - abort start. */
  17031. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17032. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17033. mg_snprintf(NULL,
  17034. NULL, /* No truncation check for error buffers */
  17035. error->text,
  17036. error->text_buffer_size,
  17037. "%s",
  17038. err_msg);
  17039. }
  17040. free_context(ctx);
  17041. pthread_setspecific(sTlsKey, NULL);
  17042. return NULL;
  17043. }
  17044. #endif
  17045. if (!set_acl_option(ctx)) {
  17046. const char *err_msg = "Failed to setup access control list";
  17047. /* Fatal error - abort start. */
  17048. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17049. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17050. mg_snprintf(NULL,
  17051. NULL, /* No truncation check for error buffers */
  17052. error->text,
  17053. error->text_buffer_size,
  17054. "%s",
  17055. err_msg);
  17056. }
  17057. free_context(ctx);
  17058. pthread_setspecific(sTlsKey, NULL);
  17059. return NULL;
  17060. }
  17061. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17062. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17063. sizeof(pthread_t),
  17064. ctx);
  17065. if (ctx->worker_threadids == NULL) {
  17066. const char *err_msg = "Not enough memory for worker thread ID array";
  17067. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17068. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17069. mg_snprintf(NULL,
  17070. NULL, /* No truncation check for error buffers */
  17071. error->text,
  17072. error->text_buffer_size,
  17073. "%s",
  17074. err_msg);
  17075. }
  17076. free_context(ctx);
  17077. pthread_setspecific(sTlsKey, NULL);
  17078. return NULL;
  17079. }
  17080. ctx->worker_connections =
  17081. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17082. sizeof(struct mg_connection),
  17083. ctx);
  17084. if (ctx->worker_connections == NULL) {
  17085. const char *err_msg =
  17086. "Not enough memory for worker thread connection array";
  17087. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17088. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17089. mg_snprintf(NULL,
  17090. NULL, /* No truncation check for error buffers */
  17091. error->text,
  17092. error->text_buffer_size,
  17093. "%s",
  17094. err_msg);
  17095. }
  17096. free_context(ctx);
  17097. pthread_setspecific(sTlsKey, NULL);
  17098. return NULL;
  17099. }
  17100. #if defined(ALTERNATIVE_QUEUE)
  17101. ctx->client_wait_events =
  17102. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17103. sizeof(ctx->client_wait_events[0]),
  17104. ctx);
  17105. if (ctx->client_wait_events == NULL) {
  17106. const char *err_msg = "Not enough memory for worker event array";
  17107. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17108. mg_free(ctx->worker_threadids);
  17109. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17110. mg_snprintf(NULL,
  17111. NULL, /* No truncation check for error buffers */
  17112. error->text,
  17113. error->text_buffer_size,
  17114. "%s",
  17115. err_msg);
  17116. }
  17117. free_context(ctx);
  17118. pthread_setspecific(sTlsKey, NULL);
  17119. return NULL;
  17120. }
  17121. ctx->client_socks =
  17122. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17123. sizeof(ctx->client_socks[0]),
  17124. ctx);
  17125. if (ctx->client_socks == NULL) {
  17126. const char *err_msg = "Not enough memory for worker socket array";
  17127. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17128. mg_free(ctx->client_wait_events);
  17129. mg_free(ctx->worker_threadids);
  17130. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17131. mg_snprintf(NULL,
  17132. NULL, /* No truncation check for error buffers */
  17133. error->text,
  17134. error->text_buffer_size,
  17135. "%s",
  17136. err_msg);
  17137. }
  17138. free_context(ctx);
  17139. pthread_setspecific(sTlsKey, NULL);
  17140. return NULL;
  17141. }
  17142. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17143. ctx->client_wait_events[i] = event_create();
  17144. if (ctx->client_wait_events[i] == 0) {
  17145. const char *err_msg = "Error creating worker event %i";
  17146. mg_cry_ctx_internal(ctx, err_msg, i);
  17147. while (i > 0) {
  17148. i--;
  17149. event_destroy(ctx->client_wait_events[i]);
  17150. }
  17151. mg_free(ctx->client_socks);
  17152. mg_free(ctx->client_wait_events);
  17153. mg_free(ctx->worker_threadids);
  17154. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17155. mg_snprintf(NULL,
  17156. NULL, /* No truncation check for error buffers */
  17157. error->text,
  17158. error->text_buffer_size,
  17159. err_msg,
  17160. i);
  17161. }
  17162. free_context(ctx);
  17163. pthread_setspecific(sTlsKey, NULL);
  17164. return NULL;
  17165. }
  17166. }
  17167. #endif
  17168. #if defined(USE_TIMERS)
  17169. if (timers_init(ctx) != 0) {
  17170. const char *err_msg = "Error creating timers";
  17171. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17172. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17173. mg_snprintf(NULL,
  17174. NULL, /* No truncation check for error buffers */
  17175. error->text,
  17176. error->text_buffer_size,
  17177. "%s",
  17178. err_msg);
  17179. }
  17180. free_context(ctx);
  17181. pthread_setspecific(sTlsKey, NULL);
  17182. return NULL;
  17183. }
  17184. #endif
  17185. /* Context has been created - init user libraries */
  17186. if (ctx->callbacks.init_context) {
  17187. ctx->callbacks.init_context(ctx);
  17188. }
  17189. /* From now, the context is successfully created.
  17190. * When it is destroyed, the exit callback should be called. */
  17191. ctx->callbacks.exit_context = exit_callback;
  17192. ctx->context_type = CONTEXT_SERVER; /* server context */
  17193. /* Start worker threads */
  17194. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17195. /* worker_thread sets up the other fields */
  17196. ctx->worker_connections[i].phys_ctx = ctx;
  17197. if (mg_start_thread_with_id(worker_thread,
  17198. &ctx->worker_connections[i],
  17199. &ctx->worker_threadids[i])
  17200. != 0) {
  17201. long error_no = (long)ERRNO;
  17202. /* thread was not created */
  17203. if (i > 0) {
  17204. /* If the second, third, ... thread cannot be created, set a
  17205. * warning, but keep running. */
  17206. mg_cry_ctx_internal(ctx,
  17207. "Cannot start worker thread %i: error %ld",
  17208. i + 1,
  17209. error_no);
  17210. /* If the server initialization should stop here, all
  17211. * threads that have already been created must be stopped
  17212. * first, before any free_context(ctx) call.
  17213. */
  17214. } else {
  17215. /* If the first worker thread cannot be created, stop
  17216. * initialization and free the entire server context. */
  17217. mg_cry_ctx_internal(ctx,
  17218. "Cannot create threads: error %ld",
  17219. error_no);
  17220. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17221. mg_snprintf(
  17222. NULL,
  17223. NULL, /* No truncation check for error buffers */
  17224. error->text,
  17225. error->text_buffer_size,
  17226. "Cannot create first worker thread: error %ld",
  17227. error_no);
  17228. }
  17229. free_context(ctx);
  17230. pthread_setspecific(sTlsKey, NULL);
  17231. return NULL;
  17232. }
  17233. break;
  17234. }
  17235. }
  17236. /* Start master (listening) thread */
  17237. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17238. pthread_setspecific(sTlsKey, NULL);
  17239. return ctx;
  17240. }
  17241. struct mg_context *
  17242. mg_start(const struct mg_callbacks *callbacks,
  17243. void *user_data,
  17244. const char **options)
  17245. {
  17246. struct mg_init_data init = {0};
  17247. init.callbacks = callbacks;
  17248. init.user_data = user_data;
  17249. init.configuration_options = options;
  17250. return mg_start2(&init, NULL);
  17251. }
  17252. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17253. /* Add an additional domain to an already running web server. */
  17254. int
  17255. mg_start_domain2(struct mg_context *ctx,
  17256. const char **options,
  17257. struct mg_error_data *error)
  17258. {
  17259. const char *name;
  17260. const char *value;
  17261. const char *default_value;
  17262. struct mg_domain_context *new_dom;
  17263. struct mg_domain_context *dom;
  17264. int idx, i;
  17265. if (error != NULL) {
  17266. error->code = 0;
  17267. if (error->text_buffer_size > 0) {
  17268. *error->text = 0;
  17269. }
  17270. }
  17271. if ((ctx == NULL) || (options == NULL)) {
  17272. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17273. mg_snprintf(NULL,
  17274. NULL, /* No truncation check for error buffers */
  17275. error->text,
  17276. error->text_buffer_size,
  17277. "%s",
  17278. "Invalid parameters");
  17279. }
  17280. return -1;
  17281. }
  17282. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17283. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17284. mg_snprintf(NULL,
  17285. NULL, /* No truncation check for error buffers */
  17286. error->text,
  17287. error->text_buffer_size,
  17288. "%s",
  17289. "Server already stopped");
  17290. }
  17291. return -1;
  17292. }
  17293. new_dom = (struct mg_domain_context *)
  17294. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17295. if (!new_dom) {
  17296. /* Out of memory */
  17297. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17298. mg_snprintf(NULL,
  17299. NULL, /* No truncation check for error buffers */
  17300. error->text,
  17301. error->text_buffer_size,
  17302. "%s",
  17303. "Out or memory");
  17304. }
  17305. return -6;
  17306. }
  17307. /* Store options - TODO: unite duplicate code */
  17308. while (options && (name = *options++) != NULL) {
  17309. if ((idx = get_option_index(name)) == -1) {
  17310. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17311. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17312. mg_snprintf(NULL,
  17313. NULL, /* No truncation check for error buffers */
  17314. error->text,
  17315. error->text_buffer_size,
  17316. "Invalid option: %s",
  17317. name);
  17318. }
  17319. mg_free(new_dom);
  17320. return -2;
  17321. } else if ((value = *options++) == NULL) {
  17322. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17323. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17324. mg_snprintf(NULL,
  17325. NULL, /* No truncation check for error buffers */
  17326. error->text,
  17327. error->text_buffer_size,
  17328. "Invalid option value: %s",
  17329. name);
  17330. }
  17331. mg_free(new_dom);
  17332. return -2;
  17333. }
  17334. if (new_dom->config[idx] != NULL) {
  17335. /* Duplicate option: Later values overwrite earlier ones. */
  17336. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17337. mg_free(new_dom->config[idx]);
  17338. }
  17339. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17340. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17341. }
  17342. /* Authentication domain is mandatory */
  17343. /* TODO: Maybe use a new option hostname? */
  17344. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17345. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17346. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17347. mg_snprintf(NULL,
  17348. NULL, /* No truncation check for error buffers */
  17349. error->text,
  17350. error->text_buffer_size,
  17351. "Mandatory option %s missing",
  17352. config_options[AUTHENTICATION_DOMAIN].name);
  17353. }
  17354. mg_free(new_dom);
  17355. return -4;
  17356. }
  17357. /* Set default value if needed. Take the config value from
  17358. * ctx as a default value. */
  17359. for (i = 0; config_options[i].name != NULL; i++) {
  17360. default_value = ctx->dd.config[i];
  17361. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17362. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17363. }
  17364. }
  17365. new_dom->handlers = NULL;
  17366. new_dom->next = NULL;
  17367. new_dom->nonce_count = 0;
  17368. new_dom->auth_nonce_mask =
  17369. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17370. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17371. new_dom->shared_lua_websockets = NULL;
  17372. #endif
  17373. #if !defined(NO_SSL)
  17374. if (!init_ssl_ctx(ctx, new_dom)) {
  17375. /* Init SSL failed */
  17376. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17377. mg_snprintf(NULL,
  17378. NULL, /* No truncation check for error buffers */
  17379. error->text,
  17380. error->text_buffer_size,
  17381. "%s",
  17382. "Initializing SSL context failed");
  17383. }
  17384. mg_free(new_dom);
  17385. return -3;
  17386. }
  17387. #endif
  17388. /* Add element to linked list. */
  17389. mg_lock_context(ctx);
  17390. idx = 0;
  17391. dom = &(ctx->dd);
  17392. for (;;) {
  17393. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17394. dom->config[AUTHENTICATION_DOMAIN])) {
  17395. /* Domain collision */
  17396. mg_cry_ctx_internal(ctx,
  17397. "domain %s already in use",
  17398. new_dom->config[AUTHENTICATION_DOMAIN]);
  17399. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17400. mg_snprintf(NULL,
  17401. NULL, /* No truncation check for error buffers */
  17402. error->text,
  17403. error->text_buffer_size,
  17404. "Domain %s specified by %s is already in use",
  17405. new_dom->config[AUTHENTICATION_DOMAIN],
  17406. config_options[AUTHENTICATION_DOMAIN].name);
  17407. }
  17408. mg_free(new_dom);
  17409. mg_unlock_context(ctx);
  17410. return -5;
  17411. }
  17412. /* Count number of domains */
  17413. idx++;
  17414. if (dom->next == NULL) {
  17415. dom->next = new_dom;
  17416. break;
  17417. }
  17418. dom = dom->next;
  17419. }
  17420. mg_unlock_context(ctx);
  17421. /* Return domain number */
  17422. return idx;
  17423. }
  17424. int
  17425. mg_start_domain(struct mg_context *ctx, const char **options)
  17426. {
  17427. return mg_start_domain2(ctx, options, NULL);
  17428. }
  17429. #endif
  17430. /* Feature check API function */
  17431. unsigned
  17432. mg_check_feature(unsigned feature)
  17433. {
  17434. static const unsigned feature_set = 0
  17435. /* Set bits for available features according to API documentation.
  17436. * This bit mask is created at compile time, according to the active
  17437. * preprocessor defines. It is a single const value at runtime. */
  17438. #if !defined(NO_FILES)
  17439. | MG_FEATURES_FILES
  17440. #endif
  17441. #if !defined(NO_SSL)
  17442. | MG_FEATURES_SSL
  17443. #endif
  17444. #if !defined(NO_CGI)
  17445. | MG_FEATURES_CGI
  17446. #endif
  17447. #if defined(USE_IPV6)
  17448. | MG_FEATURES_IPV6
  17449. #endif
  17450. #if defined(USE_WEBSOCKET)
  17451. | MG_FEATURES_WEBSOCKET
  17452. #endif
  17453. #if defined(USE_LUA)
  17454. | MG_FEATURES_LUA
  17455. #endif
  17456. #if defined(USE_DUKTAPE)
  17457. | MG_FEATURES_SSJS
  17458. #endif
  17459. #if !defined(NO_CACHING)
  17460. | MG_FEATURES_CACHE
  17461. #endif
  17462. #if defined(USE_SERVER_STATS)
  17463. | MG_FEATURES_STATS
  17464. #endif
  17465. #if defined(USE_ZLIB)
  17466. | MG_FEATURES_COMPRESSION
  17467. #endif
  17468. /* Set some extra bits not defined in the API documentation.
  17469. * These bits may change without further notice. */
  17470. #if defined(MG_LEGACY_INTERFACE)
  17471. | 0x00008000u
  17472. #endif
  17473. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17474. | 0x00004000u
  17475. #endif
  17476. #if defined(MEMORY_DEBUGGING)
  17477. | 0x00001000u
  17478. #endif
  17479. #if defined(USE_TIMERS)
  17480. | 0x00020000u
  17481. #endif
  17482. #if !defined(NO_NONCE_CHECK)
  17483. | 0x00040000u
  17484. #endif
  17485. #if !defined(NO_POPEN)
  17486. | 0x00080000u
  17487. #endif
  17488. ;
  17489. return (feature & feature_set);
  17490. }
  17491. static size_t
  17492. mg_str_append(char **dst, char *end, const char *src)
  17493. {
  17494. size_t len = strlen(src);
  17495. if (*dst != end) {
  17496. /* Append src if enough space, or close dst. */
  17497. if ((size_t)(end - *dst) > len) {
  17498. strcpy(*dst, src);
  17499. *dst += len;
  17500. } else {
  17501. *dst = end;
  17502. }
  17503. }
  17504. return len;
  17505. }
  17506. /* Get system information. It can be printed or stored by the caller.
  17507. * Return the size of available information. */
  17508. int
  17509. mg_get_system_info(char *buffer, int buflen)
  17510. {
  17511. char *end, *append_eoobj = NULL, block[256];
  17512. size_t system_info_length = 0;
  17513. #if defined(_WIN32)
  17514. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17515. #else
  17516. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17517. #endif
  17518. if ((buffer == NULL) || (buflen < 1)) {
  17519. buflen = 0;
  17520. end = buffer;
  17521. } else {
  17522. *buffer = 0;
  17523. end = buffer + buflen;
  17524. }
  17525. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17526. /* has enough space to append eoobj */
  17527. append_eoobj = buffer;
  17528. if (end) {
  17529. end -= sizeof(eoobj) - 1;
  17530. }
  17531. }
  17532. system_info_length += mg_str_append(&buffer, end, "{");
  17533. /* Server version */
  17534. {
  17535. const char *version = mg_version();
  17536. mg_snprintf(NULL,
  17537. NULL,
  17538. block,
  17539. sizeof(block),
  17540. "%s\"version\" : \"%s\"",
  17541. eol,
  17542. version);
  17543. system_info_length += mg_str_append(&buffer, end, block);
  17544. }
  17545. /* System info */
  17546. {
  17547. #if defined(_WIN32)
  17548. DWORD dwVersion = 0;
  17549. DWORD dwMajorVersion = 0;
  17550. DWORD dwMinorVersion = 0;
  17551. SYSTEM_INFO si;
  17552. GetSystemInfo(&si);
  17553. #if defined(_MSC_VER)
  17554. #pragma warning(push)
  17555. /* GetVersion was declared deprecated */
  17556. #pragma warning(disable : 4996)
  17557. #endif
  17558. dwVersion = GetVersion();
  17559. #if defined(_MSC_VER)
  17560. #pragma warning(pop)
  17561. #endif
  17562. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17563. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17564. mg_snprintf(NULL,
  17565. NULL,
  17566. block,
  17567. sizeof(block),
  17568. ",%s\"os\" : \"Windows %u.%u\"",
  17569. eol,
  17570. (unsigned)dwMajorVersion,
  17571. (unsigned)dwMinorVersion);
  17572. system_info_length += mg_str_append(&buffer, end, block);
  17573. mg_snprintf(NULL,
  17574. NULL,
  17575. block,
  17576. sizeof(block),
  17577. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17578. eol,
  17579. (unsigned)si.wProcessorArchitecture,
  17580. (unsigned)si.dwNumberOfProcessors,
  17581. (unsigned)si.dwActiveProcessorMask);
  17582. system_info_length += mg_str_append(&buffer, end, block);
  17583. #elif defined(__ZEPHYR__)
  17584. mg_snprintf(NULL,
  17585. NULL,
  17586. block,
  17587. sizeof(block),
  17588. ",%s\"os\" : \"%s %s\"",
  17589. eol,
  17590. "Zephyr OS",
  17591. ZEPHYR_VERSION);
  17592. system_info_length += mg_str_append(&buffer, end, block);
  17593. #else
  17594. struct utsname name;
  17595. memset(&name, 0, sizeof(name));
  17596. uname(&name);
  17597. mg_snprintf(NULL,
  17598. NULL,
  17599. block,
  17600. sizeof(block),
  17601. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17602. eol,
  17603. name.sysname,
  17604. name.version,
  17605. name.release,
  17606. name.machine);
  17607. system_info_length += mg_str_append(&buffer, end, block);
  17608. #endif
  17609. }
  17610. /* Features */
  17611. {
  17612. mg_snprintf(NULL,
  17613. NULL,
  17614. block,
  17615. sizeof(block),
  17616. ",%s\"features\" : %lu"
  17617. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17618. eol,
  17619. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17620. eol,
  17621. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17622. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17623. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17624. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17625. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17626. : "",
  17627. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17628. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17629. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17630. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17631. system_info_length += mg_str_append(&buffer, end, block);
  17632. #if defined(USE_LUA)
  17633. mg_snprintf(NULL,
  17634. NULL,
  17635. block,
  17636. sizeof(block),
  17637. ",%s\"lua_version\" : \"%u (%s)\"",
  17638. eol,
  17639. (unsigned)LUA_VERSION_NUM,
  17640. LUA_RELEASE);
  17641. system_info_length += mg_str_append(&buffer, end, block);
  17642. #endif
  17643. #if defined(USE_DUKTAPE)
  17644. mg_snprintf(NULL,
  17645. NULL,
  17646. block,
  17647. sizeof(block),
  17648. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17649. eol,
  17650. (unsigned)DUK_VERSION / 10000,
  17651. ((unsigned)DUK_VERSION / 100) % 100,
  17652. (unsigned)DUK_VERSION % 100);
  17653. system_info_length += mg_str_append(&buffer, end, block);
  17654. #endif
  17655. }
  17656. /* Build date */
  17657. {
  17658. #if defined(GCC_DIAGNOSTIC)
  17659. #if GCC_VERSION >= 40900
  17660. #pragma GCC diagnostic push
  17661. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17662. #pragma GCC diagnostic ignored "-Wdate-time"
  17663. #endif
  17664. #endif
  17665. mg_snprintf(NULL,
  17666. NULL,
  17667. block,
  17668. sizeof(block),
  17669. ",%s\"build\" : \"%s\"",
  17670. eol,
  17671. __DATE__);
  17672. #if defined(GCC_DIAGNOSTIC)
  17673. #if GCC_VERSION >= 40900
  17674. #pragma GCC diagnostic pop
  17675. #endif
  17676. #endif
  17677. system_info_length += mg_str_append(&buffer, end, block);
  17678. }
  17679. /* Compiler information */
  17680. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17681. {
  17682. #if defined(_MSC_VER)
  17683. mg_snprintf(NULL,
  17684. NULL,
  17685. block,
  17686. sizeof(block),
  17687. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17688. eol,
  17689. (unsigned)_MSC_VER,
  17690. (unsigned)_MSC_FULL_VER);
  17691. system_info_length += mg_str_append(&buffer, end, block);
  17692. #elif defined(__MINGW64__)
  17693. mg_snprintf(NULL,
  17694. NULL,
  17695. block,
  17696. sizeof(block),
  17697. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17698. eol,
  17699. (unsigned)__MINGW64_VERSION_MAJOR,
  17700. (unsigned)__MINGW64_VERSION_MINOR);
  17701. system_info_length += mg_str_append(&buffer, end, block);
  17702. mg_snprintf(NULL,
  17703. NULL,
  17704. block,
  17705. sizeof(block),
  17706. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17707. eol,
  17708. (unsigned)__MINGW32_MAJOR_VERSION,
  17709. (unsigned)__MINGW32_MINOR_VERSION);
  17710. system_info_length += mg_str_append(&buffer, end, block);
  17711. #elif defined(__MINGW32__)
  17712. mg_snprintf(NULL,
  17713. NULL,
  17714. block,
  17715. sizeof(block),
  17716. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17717. eol,
  17718. (unsigned)__MINGW32_MAJOR_VERSION,
  17719. (unsigned)__MINGW32_MINOR_VERSION);
  17720. system_info_length += mg_str_append(&buffer, end, block);
  17721. #elif defined(__clang__)
  17722. mg_snprintf(NULL,
  17723. NULL,
  17724. block,
  17725. sizeof(block),
  17726. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17727. eol,
  17728. __clang_major__,
  17729. __clang_minor__,
  17730. __clang_patchlevel__,
  17731. __clang_version__);
  17732. system_info_length += mg_str_append(&buffer, end, block);
  17733. #elif defined(__GNUC__)
  17734. mg_snprintf(NULL,
  17735. NULL,
  17736. block,
  17737. sizeof(block),
  17738. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17739. eol,
  17740. (unsigned)__GNUC__,
  17741. (unsigned)__GNUC_MINOR__,
  17742. (unsigned)__GNUC_PATCHLEVEL__);
  17743. system_info_length += mg_str_append(&buffer, end, block);
  17744. #elif defined(__INTEL_COMPILER)
  17745. mg_snprintf(NULL,
  17746. NULL,
  17747. block,
  17748. sizeof(block),
  17749. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17750. eol,
  17751. (unsigned)__INTEL_COMPILER);
  17752. system_info_length += mg_str_append(&buffer, end, block);
  17753. #elif defined(__BORLANDC__)
  17754. mg_snprintf(NULL,
  17755. NULL,
  17756. block,
  17757. sizeof(block),
  17758. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17759. eol,
  17760. (unsigned)__BORLANDC__);
  17761. system_info_length += mg_str_append(&buffer, end, block);
  17762. #elif defined(__SUNPRO_C)
  17763. mg_snprintf(NULL,
  17764. NULL,
  17765. block,
  17766. sizeof(block),
  17767. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17768. eol,
  17769. (unsigned)__SUNPRO_C);
  17770. system_info_length += mg_str_append(&buffer, end, block);
  17771. #else
  17772. mg_snprintf(NULL,
  17773. NULL,
  17774. block,
  17775. sizeof(block),
  17776. ",%s\"compiler\" : \"other\"",
  17777. eol);
  17778. system_info_length += mg_str_append(&buffer, end, block);
  17779. #endif
  17780. }
  17781. /* Determine 32/64 bit data mode.
  17782. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17783. {
  17784. mg_snprintf(NULL,
  17785. NULL,
  17786. block,
  17787. sizeof(block),
  17788. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17789. "char:%u/%u, "
  17790. "ptr:%u, size:%u, time:%u\"",
  17791. eol,
  17792. (unsigned)sizeof(short),
  17793. (unsigned)sizeof(int),
  17794. (unsigned)sizeof(long),
  17795. (unsigned)sizeof(long long),
  17796. (unsigned)sizeof(float),
  17797. (unsigned)sizeof(double),
  17798. (unsigned)sizeof(long double),
  17799. (unsigned)sizeof(char),
  17800. (unsigned)sizeof(wchar_t),
  17801. (unsigned)sizeof(void *),
  17802. (unsigned)sizeof(size_t),
  17803. (unsigned)sizeof(time_t));
  17804. system_info_length += mg_str_append(&buffer, end, block);
  17805. }
  17806. /* Terminate string */
  17807. if (append_eoobj) {
  17808. strcat(append_eoobj, eoobj);
  17809. }
  17810. system_info_length += sizeof(eoobj) - 1;
  17811. return (int)system_info_length;
  17812. }
  17813. /* Get context information. It can be printed or stored by the caller.
  17814. * Return the size of available information. */
  17815. int
  17816. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17817. {
  17818. #if defined(USE_SERVER_STATS)
  17819. char *end, *append_eoobj = NULL, block[256];
  17820. size_t context_info_length = 0;
  17821. #if defined(_WIN32)
  17822. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17823. #else
  17824. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17825. #endif
  17826. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17827. if ((buffer == NULL) || (buflen < 1)) {
  17828. buflen = 0;
  17829. end = buffer;
  17830. } else {
  17831. *buffer = 0;
  17832. end = buffer + buflen;
  17833. }
  17834. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17835. /* has enough space to append eoobj */
  17836. append_eoobj = buffer;
  17837. end -= sizeof(eoobj) - 1;
  17838. }
  17839. context_info_length += mg_str_append(&buffer, end, "{");
  17840. if (ms) { /* <-- should be always true */
  17841. /* Memory information */
  17842. mg_snprintf(NULL,
  17843. NULL,
  17844. block,
  17845. sizeof(block),
  17846. "%s\"memory\" : {%s"
  17847. "\"blocks\" : %i,%s"
  17848. "\"used\" : %" INT64_FMT ",%s"
  17849. "\"maxUsed\" : %" INT64_FMT "%s"
  17850. "}",
  17851. eol,
  17852. eol,
  17853. ms->blockCount,
  17854. eol,
  17855. ms->totalMemUsed,
  17856. eol,
  17857. ms->maxMemUsed,
  17858. eol);
  17859. context_info_length += mg_str_append(&buffer, end, block);
  17860. }
  17861. if (ctx) {
  17862. /* Declare all variables at begin of the block, to comply
  17863. * with old C standards. */
  17864. char start_time_str[64] = {0};
  17865. char now_str[64] = {0};
  17866. time_t start_time = ctx->start_time;
  17867. time_t now = time(NULL);
  17868. /* Connections information */
  17869. mg_snprintf(NULL,
  17870. NULL,
  17871. block,
  17872. sizeof(block),
  17873. ",%s\"connections\" : {%s"
  17874. "\"active\" : %i,%s"
  17875. "\"maxActive\" : %i,%s"
  17876. "\"total\" : %" INT64_FMT "%s"
  17877. "}",
  17878. eol,
  17879. eol,
  17880. ctx->active_connections,
  17881. eol,
  17882. ctx->max_active_connections,
  17883. eol,
  17884. ctx->total_connections,
  17885. eol);
  17886. context_info_length += mg_str_append(&buffer, end, block);
  17887. /* Queue information */
  17888. #if !defined(ALTERNATIVE_QUEUE)
  17889. mg_snprintf(NULL,
  17890. NULL,
  17891. block,
  17892. sizeof(block),
  17893. ",%s\"queue\" : {%s"
  17894. "\"length\" : %i,%s"
  17895. "\"filled\" : %i,%s"
  17896. "\"maxFilled\" : %i,%s"
  17897. "\"full\" : %s%s"
  17898. "}",
  17899. eol,
  17900. eol,
  17901. ctx->sq_size,
  17902. eol,
  17903. ctx->sq_head - ctx->sq_tail,
  17904. eol,
  17905. ctx->sq_max_fill,
  17906. eol,
  17907. (ctx->sq_blocked ? "true" : "false"),
  17908. eol);
  17909. context_info_length += mg_str_append(&buffer, end, block);
  17910. #endif
  17911. /* Requests information */
  17912. mg_snprintf(NULL,
  17913. NULL,
  17914. block,
  17915. sizeof(block),
  17916. ",%s\"requests\" : {%s"
  17917. "\"total\" : %" INT64_FMT "%s"
  17918. "}",
  17919. eol,
  17920. eol,
  17921. ctx->total_requests,
  17922. eol);
  17923. context_info_length += mg_str_append(&buffer, end, block);
  17924. /* Data information */
  17925. mg_snprintf(NULL,
  17926. NULL,
  17927. block,
  17928. sizeof(block),
  17929. ",%s\"data\" : {%s"
  17930. "\"read\" : %" INT64_FMT ",%s"
  17931. "\"written\" : %" INT64_FMT "%s"
  17932. "}",
  17933. eol,
  17934. eol,
  17935. ctx->total_data_read,
  17936. eol,
  17937. ctx->total_data_written,
  17938. eol);
  17939. context_info_length += mg_str_append(&buffer, end, block);
  17940. /* Execution time information */
  17941. gmt_time_string(start_time_str,
  17942. sizeof(start_time_str) - 1,
  17943. &start_time);
  17944. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17945. mg_snprintf(NULL,
  17946. NULL,
  17947. block,
  17948. sizeof(block),
  17949. ",%s\"time\" : {%s"
  17950. "\"uptime\" : %.0f,%s"
  17951. "\"start\" : \"%s\",%s"
  17952. "\"now\" : \"%s\"%s"
  17953. "}",
  17954. eol,
  17955. eol,
  17956. difftime(now, start_time),
  17957. eol,
  17958. start_time_str,
  17959. eol,
  17960. now_str,
  17961. eol);
  17962. context_info_length += mg_str_append(&buffer, end, block);
  17963. }
  17964. /* Terminate string */
  17965. if (append_eoobj) {
  17966. strcat(append_eoobj, eoobj);
  17967. }
  17968. context_info_length += sizeof(eoobj) - 1;
  17969. return (int)context_info_length;
  17970. #else
  17971. (void)ctx;
  17972. if ((buffer != NULL) && (buflen > 0)) {
  17973. *buffer = 0;
  17974. }
  17975. return 0;
  17976. #endif
  17977. }
  17978. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17979. /* Get connection information. It can be printed or stored by the caller.
  17980. * Return the size of available information. */
  17981. int
  17982. mg_get_connection_info(const struct mg_context *ctx,
  17983. int idx,
  17984. char *buffer,
  17985. int buflen)
  17986. {
  17987. const struct mg_connection *conn;
  17988. const struct mg_request_info *ri;
  17989. char *end, *append_eoobj = NULL, block[256];
  17990. size_t connection_info_length = 0;
  17991. int state = 0;
  17992. const char *state_str = "unknown";
  17993. #if defined(_WIN32)
  17994. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17995. #else
  17996. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17997. #endif
  17998. if ((buffer == NULL) || (buflen < 1)) {
  17999. buflen = 0;
  18000. end = buffer;
  18001. } else {
  18002. *buffer = 0;
  18003. end = buffer + buflen;
  18004. }
  18005. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18006. /* has enough space to append eoobj */
  18007. append_eoobj = buffer;
  18008. end -= sizeof(eoobj) - 1;
  18009. }
  18010. if ((ctx == NULL) || (idx < 0)) {
  18011. /* Parameter error */
  18012. return 0;
  18013. }
  18014. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18015. /* Out of range */
  18016. return 0;
  18017. }
  18018. /* Take connection [idx]. This connection is not locked in
  18019. * any way, so some other thread might use it. */
  18020. conn = (ctx->worker_connections) + idx;
  18021. /* Initialize output string */
  18022. connection_info_length += mg_str_append(&buffer, end, "{");
  18023. /* Init variables */
  18024. ri = &(conn->request_info);
  18025. #if defined(USE_SERVER_STATS)
  18026. state = conn->conn_state;
  18027. /* State as string */
  18028. switch (state) {
  18029. case 0:
  18030. state_str = "undefined";
  18031. break;
  18032. case 1:
  18033. state_str = "not used";
  18034. break;
  18035. case 2:
  18036. state_str = "init";
  18037. break;
  18038. case 3:
  18039. state_str = "ready";
  18040. break;
  18041. case 4:
  18042. state_str = "processing";
  18043. break;
  18044. case 5:
  18045. state_str = "processed";
  18046. break;
  18047. case 6:
  18048. state_str = "to close";
  18049. break;
  18050. case 7:
  18051. state_str = "closing";
  18052. break;
  18053. case 8:
  18054. state_str = "closed";
  18055. break;
  18056. case 9:
  18057. state_str = "done";
  18058. break;
  18059. }
  18060. #endif
  18061. /* Connection info */
  18062. if ((state >= 3) && (state < 9)) {
  18063. mg_snprintf(NULL,
  18064. NULL,
  18065. block,
  18066. sizeof(block),
  18067. "%s\"connection\" : {%s"
  18068. "\"remote\" : {%s"
  18069. "\"protocol\" : \"%s\",%s"
  18070. "\"addr\" : \"%s\",%s"
  18071. "\"port\" : %u%s"
  18072. "},%s"
  18073. "\"handled_requests\" : %u%s"
  18074. "}",
  18075. eol,
  18076. eol,
  18077. eol,
  18078. get_proto_name(conn),
  18079. eol,
  18080. ri->remote_addr,
  18081. eol,
  18082. ri->remote_port,
  18083. eol,
  18084. eol,
  18085. conn->handled_requests,
  18086. eol);
  18087. connection_info_length += mg_str_append(&buffer, end, block);
  18088. }
  18089. /* Request info */
  18090. if ((state >= 4) && (state < 6)) {
  18091. mg_snprintf(NULL,
  18092. NULL,
  18093. block,
  18094. sizeof(block),
  18095. "%s%s\"request_info\" : {%s"
  18096. "\"method\" : \"%s\",%s"
  18097. "\"uri\" : \"%s\",%s"
  18098. "\"query\" : %s%s%s%s"
  18099. "}",
  18100. (connection_info_length > 1 ? "," : ""),
  18101. eol,
  18102. eol,
  18103. ri->request_method,
  18104. eol,
  18105. ri->request_uri,
  18106. eol,
  18107. ri->query_string ? "\"" : "",
  18108. ri->query_string ? ri->query_string : "null",
  18109. ri->query_string ? "\"" : "",
  18110. eol);
  18111. connection_info_length += mg_str_append(&buffer, end, block);
  18112. }
  18113. /* Execution time information */
  18114. if ((state >= 2) && (state < 9)) {
  18115. char start_time_str[64] = {0};
  18116. char close_time_str[64] = {0};
  18117. time_t start_time = conn->conn_birth_time;
  18118. time_t close_time = 0;
  18119. double time_diff;
  18120. gmt_time_string(start_time_str,
  18121. sizeof(start_time_str) - 1,
  18122. &start_time);
  18123. #if defined(USE_SERVER_STATS)
  18124. close_time = conn->conn_close_time;
  18125. #endif
  18126. if (close_time != 0) {
  18127. time_diff = difftime(close_time, start_time);
  18128. gmt_time_string(close_time_str,
  18129. sizeof(close_time_str) - 1,
  18130. &close_time);
  18131. } else {
  18132. time_t now = time(NULL);
  18133. time_diff = difftime(now, start_time);
  18134. close_time_str[0] = 0; /* or use "now" ? */
  18135. }
  18136. mg_snprintf(NULL,
  18137. NULL,
  18138. block,
  18139. sizeof(block),
  18140. "%s%s\"time\" : {%s"
  18141. "\"uptime\" : %.0f,%s"
  18142. "\"start\" : \"%s\",%s"
  18143. "\"closed\" : \"%s\"%s"
  18144. "}",
  18145. (connection_info_length > 1 ? "," : ""),
  18146. eol,
  18147. eol,
  18148. time_diff,
  18149. eol,
  18150. start_time_str,
  18151. eol,
  18152. close_time_str,
  18153. eol);
  18154. connection_info_length += mg_str_append(&buffer, end, block);
  18155. }
  18156. /* Remote user name */
  18157. if ((ri->remote_user) && (state < 9)) {
  18158. mg_snprintf(NULL,
  18159. NULL,
  18160. block,
  18161. sizeof(block),
  18162. "%s%s\"user\" : {%s"
  18163. "\"name\" : \"%s\",%s"
  18164. "}",
  18165. (connection_info_length > 1 ? "," : ""),
  18166. eol,
  18167. eol,
  18168. ri->remote_user,
  18169. eol);
  18170. connection_info_length += mg_str_append(&buffer, end, block);
  18171. }
  18172. /* Data block */
  18173. if (state >= 3) {
  18174. mg_snprintf(NULL,
  18175. NULL,
  18176. block,
  18177. sizeof(block),
  18178. "%s%s\"data\" : {%s"
  18179. "\"read\" : %" INT64_FMT ",%s"
  18180. "\"written\" : %" INT64_FMT "%s"
  18181. "}",
  18182. (connection_info_length > 1 ? "," : ""),
  18183. eol,
  18184. eol,
  18185. conn->consumed_content,
  18186. eol,
  18187. conn->num_bytes_sent,
  18188. eol);
  18189. connection_info_length += mg_str_append(&buffer, end, block);
  18190. }
  18191. /* State */
  18192. mg_snprintf(NULL,
  18193. NULL,
  18194. block,
  18195. sizeof(block),
  18196. "%s%s\"state\" : \"%s\"",
  18197. (connection_info_length > 1 ? "," : ""),
  18198. eol,
  18199. state_str);
  18200. connection_info_length += mg_str_append(&buffer, end, block);
  18201. /* Terminate string */
  18202. if (append_eoobj) {
  18203. strcat(append_eoobj, eoobj);
  18204. }
  18205. connection_info_length += sizeof(eoobj) - 1;
  18206. return (int)connection_info_length;
  18207. }
  18208. #endif
  18209. /* Initialize this library. This function does not need to be thread safe.
  18210. */
  18211. unsigned
  18212. mg_init_library(unsigned features)
  18213. {
  18214. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18215. unsigned features_inited = features_to_init;
  18216. if (mg_init_library_called <= 0) {
  18217. /* Not initialized yet */
  18218. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18219. return 0;
  18220. }
  18221. }
  18222. mg_global_lock();
  18223. if (mg_init_library_called <= 0) {
  18224. #if defined(_WIN32)
  18225. int file_mutex_init = 1;
  18226. int wsa = 1;
  18227. #else
  18228. int mutexattr_init = 1;
  18229. #endif
  18230. int failed = 1;
  18231. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18232. if (key_create == 0) {
  18233. #if defined(_WIN32)
  18234. file_mutex_init =
  18235. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18236. if (file_mutex_init == 0) {
  18237. /* Start WinSock */
  18238. WSADATA data;
  18239. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18240. }
  18241. #else
  18242. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18243. if (mutexattr_init == 0) {
  18244. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18245. PTHREAD_MUTEX_RECURSIVE);
  18246. }
  18247. #endif
  18248. }
  18249. if (failed) {
  18250. #if defined(_WIN32)
  18251. if (wsa == 0) {
  18252. (void)WSACleanup();
  18253. }
  18254. if (file_mutex_init == 0) {
  18255. (void)pthread_mutex_destroy(&global_log_file_lock);
  18256. }
  18257. #else
  18258. if (mutexattr_init == 0) {
  18259. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18260. }
  18261. #endif
  18262. if (key_create == 0) {
  18263. (void)pthread_key_delete(sTlsKey);
  18264. }
  18265. mg_global_unlock();
  18266. (void)pthread_mutex_destroy(&global_lock_mutex);
  18267. return 0;
  18268. }
  18269. #if defined(USE_LUA)
  18270. lua_init_optional_libraries();
  18271. #endif
  18272. }
  18273. mg_global_unlock();
  18274. #if !defined(NO_SSL)
  18275. if (features_to_init & MG_FEATURES_SSL) {
  18276. if (!mg_ssl_initialized) {
  18277. char ebuf[128];
  18278. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18279. mg_ssl_initialized = 1;
  18280. } else {
  18281. (void)ebuf;
  18282. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18283. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18284. }
  18285. } else {
  18286. /* ssl already initialized */
  18287. }
  18288. }
  18289. #endif
  18290. mg_global_lock();
  18291. if (mg_init_library_called <= 0) {
  18292. mg_init_library_called = 1;
  18293. } else {
  18294. mg_init_library_called++;
  18295. }
  18296. mg_global_unlock();
  18297. return features_inited;
  18298. }
  18299. /* Un-initialize this library. */
  18300. unsigned
  18301. mg_exit_library(void)
  18302. {
  18303. if (mg_init_library_called <= 0) {
  18304. return 0;
  18305. }
  18306. mg_global_lock();
  18307. mg_init_library_called--;
  18308. if (mg_init_library_called == 0) {
  18309. #if !defined(NO_SSL)
  18310. if (mg_ssl_initialized) {
  18311. uninitialize_ssl();
  18312. mg_ssl_initialized = 0;
  18313. }
  18314. #endif
  18315. #if defined(_WIN32)
  18316. (void)WSACleanup();
  18317. (void)pthread_mutex_destroy(&global_log_file_lock);
  18318. #else
  18319. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18320. #endif
  18321. (void)pthread_key_delete(sTlsKey);
  18322. #if defined(USE_LUA)
  18323. lua_exit_optional_libraries();
  18324. #endif
  18325. mg_global_unlock();
  18326. (void)pthread_mutex_destroy(&global_lock_mutex);
  18327. return 1;
  18328. }
  18329. mg_global_unlock();
  18330. return 1;
  18331. }
  18332. /* End of civetweb.c */