civetweb.c 553 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632
  1. /* Copyright (c) 2013-2020 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE 8096
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #else
  209. #define DEBUG_TRACE(fmt, ...) \
  210. do { \
  211. } while (0)
  212. #endif /* DEBUG */
  213. #endif /* DEBUG_TRACE */
  214. #if !defined(DEBUG_ASSERT)
  215. #if defined(DEBUG)
  216. #define DEBUG_ASSERT(cond) \
  217. do { \
  218. if (!(cond)) { \
  219. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  220. exit(2); /* Exit with error */ \
  221. } \
  222. } while (0)
  223. #else
  224. #define DEBUG_ASSERT(cond)
  225. #endif /* DEBUG */
  226. #endif
  227. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  228. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  229. __attribute__((no_instrument_function));
  230. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  231. __attribute__((no_instrument_function));
  232. void
  233. __cyg_profile_func_enter(void *this_fn, void *call_site)
  234. {
  235. if ((void *)this_fn != (void *)printf) {
  236. printf("E %p %p\n", this_fn, call_site);
  237. }
  238. }
  239. void
  240. __cyg_profile_func_exit(void *this_fn, void *call_site)
  241. {
  242. if ((void *)this_fn != (void *)printf) {
  243. printf("X %p %p\n", this_fn, call_site);
  244. }
  245. }
  246. #endif
  247. #if !defined(IGNORE_UNUSED_RESULT)
  248. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  249. #endif
  250. #if defined(__GNUC__) || defined(__MINGW32__)
  251. /* GCC unused function attribute seems fundamentally broken.
  252. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  253. * OR UNUSED" for individual functions failed.
  254. * Either the compiler creates an "unused-function" warning if a
  255. * function is not marked with __attribute__((unused)).
  256. * On the other hand, if the function is marked with this attribute,
  257. * but is used, the compiler raises a completely idiotic
  258. * "used-but-marked-unused" warning - and
  259. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  260. * raises error: unknown option after "#pragma GCC diagnostic".
  261. * Disable this warning completely, until the GCC guys sober up
  262. * again.
  263. */
  264. #pragma GCC diagnostic ignored "-Wunused-function"
  265. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  266. #else
  267. #define FUNCTION_MAY_BE_UNUSED
  268. #endif
  269. /* Some ANSI #includes are not available on Windows CE */
  270. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  271. #include <errno.h>
  272. #include <fcntl.h>
  273. #include <signal.h>
  274. #include <stdlib.h>
  275. #include <sys/stat.h>
  276. #include <sys/types.h>
  277. #endif /* !_WIN32_WCE */
  278. #if defined(__clang__)
  279. /* When using -Weverything, clang does not accept it's own headers
  280. * in a release build configuration. Disable what is too much in
  281. * -Weverything. */
  282. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  283. #endif
  284. #if defined(__GNUC__) || defined(__MINGW32__)
  285. /* Who on earth came to the conclusion, using __DATE__ should rise
  286. * an "expansion of date or time macro is not reproducible"
  287. * warning. That's exactly what was intended by using this macro.
  288. * Just disable this nonsense warning. */
  289. /* And disabling them does not work either:
  290. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  291. * #pragma clang diagnostic ignored "-Wdate-time"
  292. * So we just have to disable ALL warnings for some lines
  293. * of code.
  294. * This seems to be a known GCC bug, not resolved since 2012:
  295. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  296. */
  297. #endif
  298. #if defined(__MACH__) /* Apple OSX section */
  299. #if defined(__clang__)
  300. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  301. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  302. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  303. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  304. #endif
  305. #endif
  306. #define CLOCK_MONOTONIC (1)
  307. #define CLOCK_REALTIME (2)
  308. #include <mach/clock.h>
  309. #include <mach/mach.h>
  310. #include <mach/mach_time.h>
  311. #include <sys/errno.h>
  312. #include <sys/time.h>
  313. /* clock_gettime is not implemented on OSX prior to 10.12 */
  314. static int
  315. _civet_clock_gettime(int clk_id, struct timespec *t)
  316. {
  317. memset(t, 0, sizeof(*t));
  318. if (clk_id == CLOCK_REALTIME) {
  319. struct timeval now;
  320. int rv = gettimeofday(&now, NULL);
  321. if (rv) {
  322. return rv;
  323. }
  324. t->tv_sec = now.tv_sec;
  325. t->tv_nsec = now.tv_usec * 1000;
  326. return 0;
  327. } else if (clk_id == CLOCK_MONOTONIC) {
  328. static uint64_t clock_start_time = 0;
  329. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  330. uint64_t now = mach_absolute_time();
  331. if (clock_start_time == 0) {
  332. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  333. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  334. /* appease "unused variable" warning for release builds */
  335. (void)mach_status;
  336. clock_start_time = now;
  337. }
  338. now = (uint64_t)((double)(now - clock_start_time)
  339. * (double)timebase_ifo.numer
  340. / (double)timebase_ifo.denom);
  341. t->tv_sec = now / 1000000000;
  342. t->tv_nsec = now % 1000000000;
  343. return 0;
  344. }
  345. return -1; /* EINVAL - Clock ID is unknown */
  346. }
  347. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  348. #if defined(__CLOCK_AVAILABILITY)
  349. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  350. * declared but it may be NULL at runtime. So we need to check before using
  351. * it. */
  352. static int
  353. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  354. {
  355. if (clock_gettime) {
  356. return clock_gettime(clk_id, t);
  357. }
  358. return _civet_clock_gettime(clk_id, t);
  359. }
  360. #define clock_gettime _civet_safe_clock_gettime
  361. #else
  362. #define clock_gettime _civet_clock_gettime
  363. #endif
  364. #endif
  365. /********************************************************************/
  366. /* CivetWeb configuration defines */
  367. /********************************************************************/
  368. /* Maximum number of threads that can be configured.
  369. * The number of threads actually created depends on the "num_threads"
  370. * configuration parameter, but this is the upper limit. */
  371. #if !defined(MAX_WORKER_THREADS)
  372. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  373. #endif
  374. /* Timeout interval for select/poll calls.
  375. * The timeouts depend on "*_timeout_ms" configuration values, but long
  376. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  377. * This reduces the time required to stop the server. */
  378. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  379. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  380. #endif
  381. /* Do not try to compress files smaller than this limit. */
  382. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  383. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  384. #endif
  385. #if !defined(PASSWORDS_FILE_NAME)
  386. #define PASSWORDS_FILE_NAME ".htpasswd"
  387. #endif
  388. /* Initial buffer size for all CGI environment variables. In case there is
  389. * not enough space, another block is allocated. */
  390. #if !defined(CGI_ENVIRONMENT_SIZE)
  391. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  392. #endif
  393. /* Maximum number of environment variables. */
  394. #if !defined(MAX_CGI_ENVIR_VARS)
  395. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  396. #endif
  397. /* General purpose buffer size. */
  398. #if !defined(MG_BUF_LEN) /* in bytes */
  399. #define MG_BUF_LEN (1024 * 8)
  400. #endif
  401. /********************************************************************/
  402. /* Helper makros */
  403. #if !defined(ARRAY_SIZE)
  404. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  405. #endif
  406. #include <stdint.h>
  407. /* Standard defines */
  408. #if !defined(INT64_MAX)
  409. #define INT64_MAX (9223372036854775807)
  410. #endif
  411. #define SHUTDOWN_RD (0)
  412. #define SHUTDOWN_WR (1)
  413. #define SHUTDOWN_BOTH (2)
  414. mg_static_assert(MAX_WORKER_THREADS >= 1,
  415. "worker threads must be a positive number");
  416. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  417. "size_t data type size check");
  418. #if defined(_WIN32) /* WINDOWS include block */
  419. #include <malloc.h> /* *alloc( */
  420. #include <stdlib.h> /* *alloc( */
  421. #include <time.h> /* struct timespec */
  422. #include <windows.h>
  423. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  424. #include <ws2tcpip.h>
  425. typedef const char *SOCK_OPT_TYPE;
  426. #if !defined(PATH_MAX)
  427. #define W_PATH_MAX (MAX_PATH)
  428. /* at most three UTF-8 chars per wchar_t */
  429. #define PATH_MAX (W_PATH_MAX * 3)
  430. #else
  431. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  432. #endif
  433. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  434. #if !defined(_IN_PORT_T)
  435. #if !defined(in_port_t)
  436. #define in_port_t u_short
  437. #endif
  438. #endif
  439. #if !defined(_WIN32_WCE)
  440. #include <direct.h>
  441. #include <io.h>
  442. #include <process.h>
  443. #else /* _WIN32_WCE */
  444. #define NO_CGI /* WinCE has no pipes */
  445. #define NO_POPEN /* WinCE has no popen */
  446. typedef long off_t;
  447. #define errno ((int)(GetLastError()))
  448. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  449. #endif /* _WIN32_WCE */
  450. #define MAKEUQUAD(lo, hi) \
  451. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  452. #define RATE_DIFF (10000000) /* 100 nsecs */
  453. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  454. #define SYS2UNIX_TIME(lo, hi) \
  455. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  456. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  457. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  458. * Also use _strtoui64 on modern M$ compilers */
  459. #if defined(_MSC_VER)
  460. #if (_MSC_VER < 1300)
  461. #define STRX(x) #x
  462. #define STR(x) STRX(x)
  463. #define __func__ __FILE__ ":" STR(__LINE__)
  464. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  465. #define strtoll(x, y, z) (_atoi64(x))
  466. #else
  467. #define __func__ __FUNCTION__
  468. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  469. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  470. #endif
  471. #endif /* _MSC_VER */
  472. #define ERRNO ((int)(GetLastError()))
  473. #define NO_SOCKLEN_T
  474. #if defined(_WIN64) || defined(__MINGW64__)
  475. #if !defined(SSL_LIB)
  476. #define SSL_LIB "ssleay64.dll"
  477. #endif
  478. #if !defined(CRYPTO_LIB)
  479. #define CRYPTO_LIB "libeay64.dll"
  480. #endif
  481. #else
  482. #if !defined(SSL_LIB)
  483. #define SSL_LIB "ssleay32.dll"
  484. #endif
  485. #if !defined(CRYPTO_LIB)
  486. #define CRYPTO_LIB "libeay32.dll"
  487. #endif
  488. #endif
  489. #define O_NONBLOCK (0)
  490. #if !defined(W_OK)
  491. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  492. #endif
  493. #define _POSIX_
  494. #define INT64_FMT "I64d"
  495. #define UINT64_FMT "I64u"
  496. #define WINCDECL __cdecl
  497. #define vsnprintf_impl _vsnprintf
  498. #define access _access
  499. #define mg_sleep(x) (Sleep(x))
  500. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  501. #if !defined(popen)
  502. #define popen(x, y) (_popen(x, y))
  503. #endif
  504. #if !defined(pclose)
  505. #define pclose(x) (_pclose(x))
  506. #endif
  507. #define close(x) (_close(x))
  508. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  509. #define RTLD_LAZY (0)
  510. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  511. #define fdopen(x, y) (_fdopen((x), (y)))
  512. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  513. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  514. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  515. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  516. #define sleep(x) (Sleep((x)*1000))
  517. #define rmdir(x) (_rmdir(x))
  518. #if defined(_WIN64) || !defined(__MINGW32__)
  519. /* Only MinGW 32 bit is missing this function */
  520. #define timegm(x) (_mkgmtime(x))
  521. #else
  522. time_t timegm(struct tm *tm);
  523. #define NEED_TIMEGM
  524. #endif
  525. #if !defined(fileno)
  526. #define fileno(x) (_fileno(x))
  527. #endif /* !fileno MINGW #defines fileno */
  528. typedef struct {
  529. CRITICAL_SECTION sec; /* Immovable */
  530. } pthread_mutex_t;
  531. typedef DWORD pthread_key_t;
  532. typedef HANDLE pthread_t;
  533. typedef struct {
  534. pthread_mutex_t threadIdSec;
  535. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  536. } pthread_cond_t;
  537. #if !defined(__clockid_t_defined)
  538. typedef DWORD clockid_t;
  539. #endif
  540. #if !defined(CLOCK_MONOTONIC)
  541. #define CLOCK_MONOTONIC (1)
  542. #endif
  543. #if !defined(CLOCK_REALTIME)
  544. #define CLOCK_REALTIME (2)
  545. #endif
  546. #if !defined(CLOCK_THREAD)
  547. #define CLOCK_THREAD (3)
  548. #endif
  549. #if !defined(CLOCK_PROCESS)
  550. #define CLOCK_PROCESS (4)
  551. #endif
  552. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  553. #define _TIMESPEC_DEFINED
  554. #endif
  555. #if !defined(_TIMESPEC_DEFINED)
  556. struct timespec {
  557. time_t tv_sec; /* seconds */
  558. long tv_nsec; /* nanoseconds */
  559. };
  560. #endif
  561. #if !defined(WIN_PTHREADS_TIME_H)
  562. #define MUST_IMPLEMENT_CLOCK_GETTIME
  563. #endif
  564. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  565. #define clock_gettime mg_clock_gettime
  566. static int
  567. clock_gettime(clockid_t clk_id, struct timespec *tp)
  568. {
  569. FILETIME ft;
  570. ULARGE_INTEGER li, li2;
  571. BOOL ok = FALSE;
  572. double d;
  573. static double perfcnt_per_sec = 0.0;
  574. static BOOL initialized = FALSE;
  575. if (!initialized) {
  576. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  577. perfcnt_per_sec = 1.0 / li.QuadPart;
  578. initialized = TRUE;
  579. }
  580. if (tp) {
  581. memset(tp, 0, sizeof(*tp));
  582. if (clk_id == CLOCK_REALTIME) {
  583. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  584. GetSystemTimeAsFileTime(&ft);
  585. li.LowPart = ft.dwLowDateTime;
  586. li.HighPart = ft.dwHighDateTime;
  587. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  588. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  589. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  590. ok = TRUE;
  591. /* END: CLOCK_REALTIME */
  592. } else if (clk_id == CLOCK_MONOTONIC) {
  593. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  594. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  595. d = li.QuadPart * perfcnt_per_sec;
  596. tp->tv_sec = (time_t)d;
  597. d -= (double)tp->tv_sec;
  598. tp->tv_nsec = (long)(d * 1.0E9);
  599. ok = TRUE;
  600. /* END: CLOCK_MONOTONIC */
  601. } else if (clk_id == CLOCK_THREAD) {
  602. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  603. FILETIME t_create, t_exit, t_kernel, t_user;
  604. if (GetThreadTimes(GetCurrentThread(),
  605. &t_create,
  606. &t_exit,
  607. &t_kernel,
  608. &t_user)) {
  609. li.LowPart = t_user.dwLowDateTime;
  610. li.HighPart = t_user.dwHighDateTime;
  611. li2.LowPart = t_kernel.dwLowDateTime;
  612. li2.HighPart = t_kernel.dwHighDateTime;
  613. li.QuadPart += li2.QuadPart;
  614. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  615. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  616. ok = TRUE;
  617. }
  618. /* END: CLOCK_THREAD */
  619. } else if (clk_id == CLOCK_PROCESS) {
  620. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  621. FILETIME t_create, t_exit, t_kernel, t_user;
  622. if (GetProcessTimes(GetCurrentProcess(),
  623. &t_create,
  624. &t_exit,
  625. &t_kernel,
  626. &t_user)) {
  627. li.LowPart = t_user.dwLowDateTime;
  628. li.HighPart = t_user.dwHighDateTime;
  629. li2.LowPart = t_kernel.dwLowDateTime;
  630. li2.HighPart = t_kernel.dwHighDateTime;
  631. li.QuadPart += li2.QuadPart;
  632. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  633. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  634. ok = TRUE;
  635. }
  636. /* END: CLOCK_PROCESS */
  637. } else {
  638. /* BEGIN: unknown clock */
  639. /* ok = FALSE; already set by init */
  640. /* END: unknown clock */
  641. }
  642. }
  643. return ok ? 0 : -1;
  644. }
  645. #endif
  646. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  647. static int pthread_mutex_lock(pthread_mutex_t *);
  648. static int pthread_mutex_unlock(pthread_mutex_t *);
  649. static void path_to_unicode(const struct mg_connection *conn,
  650. const char *path,
  651. wchar_t *wbuf,
  652. size_t wbuf_len);
  653. /* All file operations need to be rewritten to solve #246. */
  654. struct mg_file;
  655. static const char *
  656. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  657. /* POSIX dirent interface */
  658. struct dirent {
  659. char d_name[PATH_MAX];
  660. };
  661. typedef struct DIR {
  662. HANDLE handle;
  663. WIN32_FIND_DATAW info;
  664. struct dirent result;
  665. } DIR;
  666. #if defined(HAVE_POLL)
  667. #define mg_pollfd pollfd
  668. #else
  669. struct mg_pollfd {
  670. SOCKET fd;
  671. short events;
  672. short revents;
  673. };
  674. #endif
  675. /* Mark required libraries */
  676. #if defined(_MSC_VER)
  677. #pragma comment(lib, "Ws2_32.lib")
  678. #endif
  679. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  680. #include <inttypes.h>
  681. typedef const void *SOCK_OPT_TYPE;
  682. #if defined(ANDROID)
  683. typedef unsigned short int in_port_t;
  684. #endif
  685. #if !defined(__ZEPHYR__)
  686. #include <arpa/inet.h>
  687. #include <ctype.h>
  688. #include <dirent.h>
  689. #include <grp.h>
  690. #include <limits.h>
  691. #include <netdb.h>
  692. #include <netinet/in.h>
  693. #include <netinet/tcp.h>
  694. #include <pthread.h>
  695. #include <pwd.h>
  696. #include <stdarg.h>
  697. #include <stddef.h>
  698. #include <stdio.h>
  699. #include <stdlib.h>
  700. #include <string.h>
  701. #include <sys/poll.h>
  702. #include <sys/socket.h>
  703. #include <sys/time.h>
  704. #include <sys/utsname.h>
  705. #include <sys/wait.h>
  706. #include <time.h>
  707. #include <unistd.h>
  708. #endif
  709. #define vsnprintf_impl vsnprintf
  710. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  711. #include <dlfcn.h>
  712. #endif
  713. #if defined(__MACH__)
  714. #define SSL_LIB "libssl.dylib"
  715. #define CRYPTO_LIB "libcrypto.dylib"
  716. #else
  717. #if !defined(SSL_LIB)
  718. #define SSL_LIB "libssl.so"
  719. #endif
  720. #if !defined(CRYPTO_LIB)
  721. #define CRYPTO_LIB "libcrypto.so"
  722. #endif
  723. #endif
  724. #if !defined(O_BINARY)
  725. #define O_BINARY (0)
  726. #endif /* O_BINARY */
  727. #define closesocket(a) (close(a))
  728. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  729. #define mg_remove(conn, x) (remove(x))
  730. #define mg_sleep(x) (usleep((x)*1000))
  731. #define mg_opendir(conn, x) (opendir(x))
  732. #define mg_closedir(x) (closedir(x))
  733. #define mg_readdir(x) (readdir(x))
  734. #define ERRNO (errno)
  735. #define INVALID_SOCKET (-1)
  736. #define INT64_FMT PRId64
  737. #define UINT64_FMT PRIu64
  738. typedef int SOCKET;
  739. #define WINCDECL
  740. #if defined(__hpux)
  741. /* HPUX 11 does not have monotonic, fall back to realtime */
  742. #if !defined(CLOCK_MONOTONIC)
  743. #define CLOCK_MONOTONIC CLOCK_REALTIME
  744. #endif
  745. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  746. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  747. * the prototypes use int* rather than socklen_t* which matches the
  748. * actual library expectation. When called with the wrong size arg
  749. * accept() returns a zero client inet addr and check_acl() always
  750. * fails. Since socklen_t is widely used below, just force replace
  751. * their typedef with int. - DTL
  752. */
  753. #define socklen_t int
  754. #endif /* hpux */
  755. #define mg_pollfd pollfd
  756. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  757. /* In case our C library is missing "timegm", provide an implementation */
  758. #if defined(NEED_TIMEGM)
  759. static inline int
  760. is_leap(int y)
  761. {
  762. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  763. }
  764. static inline int
  765. count_leap(int y)
  766. {
  767. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  768. }
  769. time_t
  770. timegm(struct tm *tm)
  771. {
  772. static const unsigned short ydays[] = {
  773. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  774. int year = tm->tm_year + 1900;
  775. int mon = tm->tm_mon;
  776. int mday = tm->tm_mday - 1;
  777. int hour = tm->tm_hour;
  778. int min = tm->tm_min;
  779. int sec = tm->tm_sec;
  780. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  781. || (mday >= ydays[mon + 1] - ydays[mon]
  782. + (mon == 1 && is_leap(year) ? 1 : 0))
  783. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  784. return -1;
  785. time_t res = year - 1970;
  786. res *= 365;
  787. res += mday;
  788. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  789. res += count_leap(year);
  790. res *= 24;
  791. res += hour;
  792. res *= 60;
  793. res += min;
  794. res *= 60;
  795. res += sec;
  796. return res;
  797. }
  798. #endif /* NEED_TIMEGM */
  799. /* va_copy should always be a macro, C99 and C++11 - DTL */
  800. #if !defined(va_copy)
  801. #define va_copy(x, y) ((x) = (y))
  802. #endif
  803. #if defined(_WIN32)
  804. /* Create substitutes for POSIX functions in Win32. */
  805. #if defined(GCC_DIAGNOSTIC)
  806. /* Show no warning in case system functions are not used. */
  807. #pragma GCC diagnostic push
  808. #pragma GCC diagnostic ignored "-Wunused-function"
  809. #endif
  810. static pthread_mutex_t global_log_file_lock;
  811. FUNCTION_MAY_BE_UNUSED
  812. static DWORD
  813. pthread_self(void)
  814. {
  815. return GetCurrentThreadId();
  816. }
  817. FUNCTION_MAY_BE_UNUSED
  818. static int
  819. pthread_key_create(
  820. pthread_key_t *key,
  821. void (*_ignored)(void *) /* destructor not supported for Windows */
  822. )
  823. {
  824. (void)_ignored;
  825. if ((key != 0)) {
  826. *key = TlsAlloc();
  827. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  828. }
  829. return -2;
  830. }
  831. FUNCTION_MAY_BE_UNUSED
  832. static int
  833. pthread_key_delete(pthread_key_t key)
  834. {
  835. return TlsFree(key) ? 0 : 1;
  836. }
  837. FUNCTION_MAY_BE_UNUSED
  838. static int
  839. pthread_setspecific(pthread_key_t key, void *value)
  840. {
  841. return TlsSetValue(key, value) ? 0 : 1;
  842. }
  843. FUNCTION_MAY_BE_UNUSED
  844. static void *
  845. pthread_getspecific(pthread_key_t key)
  846. {
  847. return TlsGetValue(key);
  848. }
  849. #if defined(GCC_DIAGNOSTIC)
  850. /* Enable unused function warning again */
  851. #pragma GCC diagnostic pop
  852. #endif
  853. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  854. #else
  855. static pthread_mutexattr_t pthread_mutex_attr;
  856. #endif /* _WIN32 */
  857. #if defined(_WIN32_WCE)
  858. /* Create substitutes for POSIX functions in Win32. */
  859. #if defined(GCC_DIAGNOSTIC)
  860. /* Show no warning in case system functions are not used. */
  861. #pragma GCC diagnostic push
  862. #pragma GCC diagnostic ignored "-Wunused-function"
  863. #endif
  864. FUNCTION_MAY_BE_UNUSED
  865. static time_t
  866. time(time_t *ptime)
  867. {
  868. time_t t;
  869. SYSTEMTIME st;
  870. FILETIME ft;
  871. GetSystemTime(&st);
  872. SystemTimeToFileTime(&st, &ft);
  873. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  874. if (ptime != NULL) {
  875. *ptime = t;
  876. }
  877. return t;
  878. }
  879. FUNCTION_MAY_BE_UNUSED
  880. static struct tm *
  881. localtime_s(const time_t *ptime, struct tm *ptm)
  882. {
  883. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  884. FILETIME ft, lft;
  885. SYSTEMTIME st;
  886. TIME_ZONE_INFORMATION tzinfo;
  887. if (ptm == NULL) {
  888. return NULL;
  889. }
  890. *(int64_t *)&ft = t;
  891. FileTimeToLocalFileTime(&ft, &lft);
  892. FileTimeToSystemTime(&lft, &st);
  893. ptm->tm_year = st.wYear - 1900;
  894. ptm->tm_mon = st.wMonth - 1;
  895. ptm->tm_wday = st.wDayOfWeek;
  896. ptm->tm_mday = st.wDay;
  897. ptm->tm_hour = st.wHour;
  898. ptm->tm_min = st.wMinute;
  899. ptm->tm_sec = st.wSecond;
  900. ptm->tm_yday = 0; /* hope nobody uses this */
  901. ptm->tm_isdst =
  902. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  903. return ptm;
  904. }
  905. FUNCTION_MAY_BE_UNUSED
  906. static struct tm *
  907. gmtime_s(const time_t *ptime, struct tm *ptm)
  908. {
  909. /* FIXME(lsm): fix this. */
  910. return localtime_s(ptime, ptm);
  911. }
  912. static int mg_atomic_inc(volatile int *addr);
  913. static struct tm tm_array[MAX_WORKER_THREADS];
  914. static int tm_index = 0;
  915. FUNCTION_MAY_BE_UNUSED
  916. static struct tm *
  917. localtime(const time_t *ptime)
  918. {
  919. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  920. return localtime_s(ptime, tm_array + i);
  921. }
  922. FUNCTION_MAY_BE_UNUSED
  923. static struct tm *
  924. gmtime(const time_t *ptime)
  925. {
  926. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  927. return gmtime_s(ptime, tm_array + i);
  928. }
  929. FUNCTION_MAY_BE_UNUSED
  930. static size_t
  931. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  932. {
  933. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  934. * for WinCE"); */
  935. return 0;
  936. }
  937. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  938. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  939. #define remove(f) mg_remove(NULL, f)
  940. FUNCTION_MAY_BE_UNUSED
  941. static int
  942. rename(const char *a, const char *b)
  943. {
  944. wchar_t wa[W_PATH_MAX];
  945. wchar_t wb[W_PATH_MAX];
  946. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  947. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  948. return MoveFileW(wa, wb) ? 0 : -1;
  949. }
  950. struct stat {
  951. int64_t st_size;
  952. time_t st_mtime;
  953. };
  954. FUNCTION_MAY_BE_UNUSED
  955. static int
  956. stat(const char *name, struct stat *st)
  957. {
  958. wchar_t wbuf[W_PATH_MAX];
  959. WIN32_FILE_ATTRIBUTE_DATA attr;
  960. time_t creation_time, write_time;
  961. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  962. memset(&attr, 0, sizeof(attr));
  963. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  964. st->st_size =
  965. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  966. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  967. attr.ftLastWriteTime.dwHighDateTime);
  968. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  969. attr.ftCreationTime.dwHighDateTime);
  970. if (creation_time > write_time) {
  971. st->st_mtime = creation_time;
  972. } else {
  973. st->st_mtime = write_time;
  974. }
  975. return 0;
  976. }
  977. #define access(x, a) 1 /* not required anyway */
  978. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  979. /* Values from errno.h in Windows SDK (Visual Studio). */
  980. #define EEXIST 17
  981. #define EACCES 13
  982. #define ENOENT 2
  983. #if defined(GCC_DIAGNOSTIC)
  984. /* Enable unused function warning again */
  985. #pragma GCC diagnostic pop
  986. #endif
  987. #endif /* defined(_WIN32_WCE) */
  988. #if defined(GCC_DIAGNOSTIC)
  989. /* Show no warning in case system functions are not used. */
  990. #pragma GCC diagnostic push
  991. #pragma GCC diagnostic ignored "-Wunused-function"
  992. #endif /* defined(GCC_DIAGNOSTIC) */
  993. #if defined(__clang__)
  994. /* Show no warning in case system functions are not used. */
  995. #pragma clang diagnostic push
  996. #pragma clang diagnostic ignored "-Wunused-function"
  997. #endif
  998. static pthread_mutex_t global_lock_mutex;
  999. FUNCTION_MAY_BE_UNUSED
  1000. static void
  1001. mg_global_lock(void)
  1002. {
  1003. (void)pthread_mutex_lock(&global_lock_mutex);
  1004. }
  1005. FUNCTION_MAY_BE_UNUSED
  1006. static void
  1007. mg_global_unlock(void)
  1008. {
  1009. (void)pthread_mutex_unlock(&global_lock_mutex);
  1010. }
  1011. FUNCTION_MAY_BE_UNUSED
  1012. static int
  1013. mg_atomic_inc(volatile int *addr)
  1014. {
  1015. int ret;
  1016. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1017. /* Depending on the SDK, this function uses either
  1018. * (volatile unsigned int *) or (volatile LONG *),
  1019. * so whatever you use, the other SDK is likely to raise a warning. */
  1020. ret = InterlockedIncrement((volatile long *)addr);
  1021. #elif defined(__GNUC__) \
  1022. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1023. && !defined(NO_ATOMICS)
  1024. ret = __sync_add_and_fetch(addr, 1);
  1025. #else
  1026. mg_global_lock();
  1027. ret = (++(*addr));
  1028. mg_global_unlock();
  1029. #endif
  1030. return ret;
  1031. }
  1032. FUNCTION_MAY_BE_UNUSED
  1033. static int
  1034. mg_atomic_dec(volatile int *addr)
  1035. {
  1036. int ret;
  1037. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1038. /* Depending on the SDK, this function uses either
  1039. * (volatile unsigned int *) or (volatile LONG *),
  1040. * so whatever you use, the other SDK is likely to raise a warning. */
  1041. ret = InterlockedDecrement((volatile long *)addr);
  1042. #elif defined(__GNUC__) \
  1043. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1044. && !defined(NO_ATOMICS)
  1045. ret = __sync_sub_and_fetch(addr, 1);
  1046. #else
  1047. mg_global_lock();
  1048. ret = (--(*addr));
  1049. mg_global_unlock();
  1050. #endif
  1051. return ret;
  1052. }
  1053. #if defined(USE_SERVER_STATS)
  1054. static int64_t
  1055. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1056. {
  1057. int64_t ret;
  1058. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1059. ret = InterlockedAdd64(addr, value);
  1060. #elif defined(__GNUC__) \
  1061. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1062. && !defined(NO_ATOMICS)
  1063. ret = __sync_add_and_fetch(addr, value);
  1064. #else
  1065. mg_global_lock();
  1066. *addr += value;
  1067. ret = (*addr);
  1068. mg_global_unlock();
  1069. #endif
  1070. return ret;
  1071. }
  1072. #endif
  1073. #if defined(GCC_DIAGNOSTIC)
  1074. /* Show no warning in case system functions are not used. */
  1075. #pragma GCC diagnostic pop
  1076. #endif /* defined(GCC_DIAGNOSTIC) */
  1077. #if defined(__clang__)
  1078. /* Show no warning in case system functions are not used. */
  1079. #pragma clang diagnostic pop
  1080. #endif
  1081. #if defined(USE_SERVER_STATS)
  1082. struct mg_memory_stat {
  1083. volatile int64_t totalMemUsed;
  1084. volatile int64_t maxMemUsed;
  1085. volatile int blockCount;
  1086. };
  1087. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1088. static void *
  1089. mg_malloc_ex(size_t size,
  1090. struct mg_context *ctx,
  1091. const char *file,
  1092. unsigned line)
  1093. {
  1094. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1095. void *memory = 0;
  1096. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1097. #if defined(MEMORY_DEBUGGING)
  1098. char mallocStr[256];
  1099. #else
  1100. (void)file;
  1101. (void)line;
  1102. #endif
  1103. if (data) {
  1104. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1105. if (mmem > mstat->maxMemUsed) {
  1106. /* could use atomic compare exchange, but this
  1107. * seems overkill for statistics data */
  1108. mstat->maxMemUsed = mmem;
  1109. }
  1110. mg_atomic_inc(&mstat->blockCount);
  1111. ((uintptr_t *)data)[0] = size;
  1112. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1113. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1114. }
  1115. #if defined(MEMORY_DEBUGGING)
  1116. sprintf(mallocStr,
  1117. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1118. memory,
  1119. (unsigned long)size,
  1120. (unsigned long)mstat->totalMemUsed,
  1121. (unsigned long)mstat->blockCount,
  1122. file,
  1123. line);
  1124. #if defined(_WIN32)
  1125. OutputDebugStringA(mallocStr);
  1126. #else
  1127. DEBUG_TRACE("%s", mallocStr);
  1128. #endif
  1129. #endif
  1130. return memory;
  1131. }
  1132. static void *
  1133. mg_calloc_ex(size_t count,
  1134. size_t size,
  1135. struct mg_context *ctx,
  1136. const char *file,
  1137. unsigned line)
  1138. {
  1139. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1140. if (data) {
  1141. memset(data, 0, size * count);
  1142. }
  1143. return data;
  1144. }
  1145. static void
  1146. mg_free_ex(void *memory, const char *file, unsigned line)
  1147. {
  1148. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1149. #if defined(MEMORY_DEBUGGING)
  1150. char mallocStr[256];
  1151. #else
  1152. (void)file;
  1153. (void)line;
  1154. #endif
  1155. if (memory) {
  1156. uintptr_t size = ((uintptr_t *)data)[0];
  1157. struct mg_memory_stat *mstat =
  1158. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1159. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1160. mg_atomic_dec(&mstat->blockCount);
  1161. #if defined(MEMORY_DEBUGGING)
  1162. sprintf(mallocStr,
  1163. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1164. memory,
  1165. (unsigned long)size,
  1166. (unsigned long)mstat->totalMemUsed,
  1167. (unsigned long)mstat->blockCount,
  1168. file,
  1169. line);
  1170. #if defined(_WIN32)
  1171. OutputDebugStringA(mallocStr);
  1172. #else
  1173. DEBUG_TRACE("%s", mallocStr);
  1174. #endif
  1175. #endif
  1176. free(data);
  1177. }
  1178. }
  1179. static void *
  1180. mg_realloc_ex(void *memory,
  1181. size_t newsize,
  1182. struct mg_context *ctx,
  1183. const char *file,
  1184. unsigned line)
  1185. {
  1186. void *data;
  1187. void *_realloc;
  1188. uintptr_t oldsize;
  1189. #if defined(MEMORY_DEBUGGING)
  1190. char mallocStr[256];
  1191. #else
  1192. (void)file;
  1193. (void)line;
  1194. #endif
  1195. if (newsize) {
  1196. if (memory) {
  1197. /* Reallocate existing block */
  1198. struct mg_memory_stat *mstat;
  1199. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1200. oldsize = ((uintptr_t *)data)[0];
  1201. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1202. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1203. if (_realloc) {
  1204. data = _realloc;
  1205. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1206. #if defined(MEMORY_DEBUGGING)
  1207. sprintf(mallocStr,
  1208. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1209. memory,
  1210. (unsigned long)oldsize,
  1211. (unsigned long)mstat->totalMemUsed,
  1212. (unsigned long)mstat->blockCount,
  1213. file,
  1214. line);
  1215. #if defined(_WIN32)
  1216. OutputDebugStringA(mallocStr);
  1217. #else
  1218. DEBUG_TRACE("%s", mallocStr);
  1219. #endif
  1220. #endif
  1221. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1222. #if defined(MEMORY_DEBUGGING)
  1223. sprintf(mallocStr,
  1224. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1225. memory,
  1226. (unsigned long)newsize,
  1227. (unsigned long)mstat->totalMemUsed,
  1228. (unsigned long)mstat->blockCount,
  1229. file,
  1230. line);
  1231. #if defined(_WIN32)
  1232. OutputDebugStringA(mallocStr);
  1233. #else
  1234. DEBUG_TRACE("%s", mallocStr);
  1235. #endif
  1236. #endif
  1237. *(uintptr_t *)data = newsize;
  1238. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1239. } else {
  1240. #if defined(MEMORY_DEBUGGING)
  1241. #if defined(_WIN32)
  1242. OutputDebugStringA("MEM: realloc failed\n");
  1243. #else
  1244. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1245. #endif
  1246. #endif
  1247. return _realloc;
  1248. }
  1249. } else {
  1250. /* Allocate new block */
  1251. data = mg_malloc_ex(newsize, ctx, file, line);
  1252. }
  1253. } else {
  1254. /* Free existing block */
  1255. data = 0;
  1256. mg_free_ex(memory, file, line);
  1257. }
  1258. return data;
  1259. }
  1260. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1261. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1262. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1263. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1264. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1265. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1266. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1267. #else /* USE_SERVER_STATS */
  1268. static __inline void *
  1269. mg_malloc(size_t a)
  1270. {
  1271. return malloc(a);
  1272. }
  1273. static __inline void *
  1274. mg_calloc(size_t a, size_t b)
  1275. {
  1276. return calloc(a, b);
  1277. }
  1278. static __inline void *
  1279. mg_realloc(void *a, size_t b)
  1280. {
  1281. return realloc(a, b);
  1282. }
  1283. static __inline void
  1284. mg_free(void *a)
  1285. {
  1286. free(a);
  1287. }
  1288. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1289. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1290. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1291. #define mg_free_ctx(a, c) mg_free(a)
  1292. #endif /* USE_SERVER_STATS */
  1293. static void mg_vsnprintf(const struct mg_connection *conn,
  1294. int *truncated,
  1295. char *buf,
  1296. size_t buflen,
  1297. const char *fmt,
  1298. va_list ap);
  1299. static void mg_snprintf(const struct mg_connection *conn,
  1300. int *truncated,
  1301. char *buf,
  1302. size_t buflen,
  1303. PRINTF_FORMAT_STRING(const char *fmt),
  1304. ...) PRINTF_ARGS(5, 6);
  1305. /* This following lines are just meant as a reminder to use the mg-functions
  1306. * for memory management */
  1307. #if defined(malloc)
  1308. #undef malloc
  1309. #endif
  1310. #if defined(calloc)
  1311. #undef calloc
  1312. #endif
  1313. #if defined(realloc)
  1314. #undef realloc
  1315. #endif
  1316. #if defined(free)
  1317. #undef free
  1318. #endif
  1319. #if defined(snprintf)
  1320. #undef snprintf
  1321. #endif
  1322. #if defined(vsnprintf)
  1323. #undef vsnprintf
  1324. #endif
  1325. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1326. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1327. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1328. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1329. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1330. #if defined(_WIN32)
  1331. /* vsnprintf must not be used in any system,
  1332. * but this define only works well for Windows. */
  1333. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1334. #endif
  1335. /* mg_init_library counter */
  1336. static int mg_init_library_called = 0;
  1337. #if !defined(NO_SSL)
  1338. static int mg_ssl_initialized = 0;
  1339. #endif
  1340. static pthread_key_t sTlsKey; /* Thread local storage index */
  1341. static int thread_idx_max = 0;
  1342. #if defined(MG_LEGACY_INTERFACE)
  1343. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1344. #endif
  1345. struct mg_workerTLS {
  1346. int is_master;
  1347. unsigned long thread_idx;
  1348. void *user_ptr;
  1349. #if defined(_WIN32)
  1350. HANDLE pthread_cond_helper_mutex;
  1351. struct mg_workerTLS *next_waiting_thread;
  1352. #endif
  1353. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1354. char txtbuf[4];
  1355. #endif
  1356. };
  1357. #if defined(GCC_DIAGNOSTIC)
  1358. /* Show no warning in case system functions are not used. */
  1359. #pragma GCC diagnostic push
  1360. #pragma GCC diagnostic ignored "-Wunused-function"
  1361. #endif /* defined(GCC_DIAGNOSTIC) */
  1362. #if defined(__clang__)
  1363. /* Show no warning in case system functions are not used. */
  1364. #pragma clang diagnostic push
  1365. #pragma clang diagnostic ignored "-Wunused-function"
  1366. #endif
  1367. /* Get a unique thread ID as unsigned long, independent from the data type
  1368. * of thread IDs defined by the operating system API.
  1369. * If two calls to mg_current_thread_id return the same value, they calls
  1370. * are done from the same thread. If they return different values, they are
  1371. * done from different threads. (Provided this function is used in the same
  1372. * process context and threads are not repeatedly created and deleted, but
  1373. * CivetWeb does not do that).
  1374. * This function must match the signature required for SSL id callbacks:
  1375. * CRYPTO_set_id_callback
  1376. */
  1377. FUNCTION_MAY_BE_UNUSED
  1378. static unsigned long
  1379. mg_current_thread_id(void)
  1380. {
  1381. #if defined(_WIN32)
  1382. return GetCurrentThreadId();
  1383. #else
  1384. #if defined(__clang__)
  1385. #pragma clang diagnostic push
  1386. #pragma clang diagnostic ignored "-Wunreachable-code"
  1387. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1388. * or not, so one of the two conditions will be unreachable by construction.
  1389. * Unfortunately the C standard does not define a way to check this at
  1390. * compile time, since the #if preprocessor conditions can not use the sizeof
  1391. * operator as an argument. */
  1392. #endif
  1393. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1394. /* This is the problematic case for CRYPTO_set_id_callback:
  1395. * The OS pthread_t can not be cast to unsigned long. */
  1396. struct mg_workerTLS *tls =
  1397. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1398. if (tls == NULL) {
  1399. /* SSL called from an unknown thread: Create some thread index.
  1400. */
  1401. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1402. tls->is_master = -2; /* -2 means "3rd party thread" */
  1403. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1404. pthread_setspecific(sTlsKey, tls);
  1405. }
  1406. return tls->thread_idx;
  1407. } else {
  1408. /* pthread_t may be any data type, so a simple cast to unsigned long
  1409. * can rise a warning/error, depending on the platform.
  1410. * Here memcpy is used as an anything-to-anything cast. */
  1411. unsigned long ret = 0;
  1412. pthread_t t = pthread_self();
  1413. memcpy(&ret, &t, sizeof(pthread_t));
  1414. return ret;
  1415. }
  1416. #if defined(__clang__)
  1417. #pragma clang diagnostic pop
  1418. #endif
  1419. #endif
  1420. }
  1421. FUNCTION_MAY_BE_UNUSED
  1422. static uint64_t
  1423. mg_get_current_time_ns(void)
  1424. {
  1425. struct timespec tsnow;
  1426. clock_gettime(CLOCK_REALTIME, &tsnow);
  1427. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1428. }
  1429. #if defined(GCC_DIAGNOSTIC)
  1430. /* Show no warning in case system functions are not used. */
  1431. #pragma GCC diagnostic pop
  1432. #endif /* defined(GCC_DIAGNOSTIC) */
  1433. #if defined(__clang__)
  1434. /* Show no warning in case system functions are not used. */
  1435. #pragma clang diagnostic pop
  1436. #endif
  1437. #if defined(NEED_DEBUG_TRACE_FUNC)
  1438. static void
  1439. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1440. {
  1441. va_list args;
  1442. uint64_t nsnow;
  1443. static uint64_t nslast;
  1444. struct timespec tsnow;
  1445. /* Get some operating system independent thread id */
  1446. unsigned long thread_id = mg_current_thread_id();
  1447. clock_gettime(CLOCK_REALTIME, &tsnow);
  1448. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1449. + ((uint64_t)tsnow.tv_nsec);
  1450. if (!nslast) {
  1451. nslast = nsnow;
  1452. }
  1453. flockfile(stdout);
  1454. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1455. (unsigned long)tsnow.tv_sec,
  1456. (unsigned long)tsnow.tv_nsec,
  1457. nsnow - nslast,
  1458. thread_id,
  1459. func,
  1460. line);
  1461. va_start(args, fmt);
  1462. vprintf(fmt, args);
  1463. va_end(args);
  1464. putchar('\n');
  1465. fflush(stdout);
  1466. funlockfile(stdout);
  1467. nslast = nsnow;
  1468. }
  1469. #endif /* NEED_DEBUG_TRACE_FUNC */
  1470. #define MD5_STATIC static
  1471. #include "md5.inl"
  1472. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1473. #if defined(NO_SOCKLEN_T)
  1474. typedef int socklen_t;
  1475. #endif /* NO_SOCKLEN_T */
  1476. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1477. #if !defined(MSG_NOSIGNAL)
  1478. #define MSG_NOSIGNAL (0)
  1479. #endif
  1480. #if defined(NO_SSL)
  1481. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1482. typedef struct SSL_CTX SSL_CTX;
  1483. #else
  1484. #if defined(NO_SSL_DL)
  1485. #include <openssl/bn.h>
  1486. #include <openssl/conf.h>
  1487. #include <openssl/crypto.h>
  1488. #include <openssl/dh.h>
  1489. #include <openssl/engine.h>
  1490. #include <openssl/err.h>
  1491. #include <openssl/opensslv.h>
  1492. #include <openssl/pem.h>
  1493. #include <openssl/ssl.h>
  1494. #include <openssl/tls1.h>
  1495. #include <openssl/x509.h>
  1496. #if defined(WOLFSSL_VERSION)
  1497. /* Additional defines for WolfSSL, see
  1498. * https://github.com/civetweb/civetweb/issues/583 */
  1499. #include "wolfssl_extras.inl"
  1500. #endif
  1501. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1502. /* If OpenSSL headers are included, automatically select the API version */
  1503. #if !defined(OPENSSL_API_1_1)
  1504. #define OPENSSL_API_1_1
  1505. #endif
  1506. #define OPENSSL_REMOVE_THREAD_STATE()
  1507. #else
  1508. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1509. #endif
  1510. #else
  1511. /* SSL loaded dynamically from DLL.
  1512. * I put the prototypes here to be independent from OpenSSL source
  1513. * installation. */
  1514. typedef struct ssl_st SSL;
  1515. typedef struct ssl_method_st SSL_METHOD;
  1516. typedef struct ssl_ctx_st SSL_CTX;
  1517. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1518. typedef struct x509_name X509_NAME;
  1519. typedef struct asn1_integer ASN1_INTEGER;
  1520. typedef struct bignum BIGNUM;
  1521. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1522. typedef struct evp_md EVP_MD;
  1523. typedef struct x509 X509;
  1524. #define SSL_CTRL_OPTIONS (32)
  1525. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1526. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1527. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1528. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1529. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1530. #define SSL_VERIFY_NONE (0)
  1531. #define SSL_VERIFY_PEER (1)
  1532. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1533. #define SSL_VERIFY_CLIENT_ONCE (4)
  1534. #define SSL_OP_ALL (0x80000BFFul)
  1535. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1536. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1537. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1538. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1539. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1540. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1541. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1542. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1543. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1544. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1545. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1546. #define SSL_CB_HANDSHAKE_START (0x10)
  1547. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1548. #define SSL_ERROR_NONE (0)
  1549. #define SSL_ERROR_SSL (1)
  1550. #define SSL_ERROR_WANT_READ (2)
  1551. #define SSL_ERROR_WANT_WRITE (3)
  1552. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1553. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1554. #define SSL_ERROR_ZERO_RETURN (6)
  1555. #define SSL_ERROR_WANT_CONNECT (7)
  1556. #define SSL_ERROR_WANT_ACCEPT (8)
  1557. #define TLSEXT_TYPE_server_name (0)
  1558. #define TLSEXT_NAMETYPE_host_name (0)
  1559. #define SSL_TLSEXT_ERR_OK (0)
  1560. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1561. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1562. #define SSL_TLSEXT_ERR_NOACK (3)
  1563. struct ssl_func {
  1564. const char *name; /* SSL function name */
  1565. void (*ptr)(void); /* Function pointer */
  1566. };
  1567. #if defined(OPENSSL_API_1_1)
  1568. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1569. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1570. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1571. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1572. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1573. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1574. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1575. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1576. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1577. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1578. #define OPENSSL_init_ssl \
  1579. (*(int (*)(uint64_t opts, \
  1580. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1581. .ptr)
  1582. #define SSL_CTX_use_PrivateKey_file \
  1583. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1584. #define SSL_CTX_use_certificate_file \
  1585. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1586. #define SSL_CTX_set_default_passwd_cb \
  1587. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1588. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1589. #define SSL_CTX_use_certificate_chain_file \
  1590. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1591. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1592. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1593. #define SSL_CTX_set_verify \
  1594. (*(void (*)(SSL_CTX *, \
  1595. int, \
  1596. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1597. .ptr)
  1598. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1599. #define SSL_CTX_load_verify_locations \
  1600. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1601. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1602. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1603. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1604. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1605. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1606. #define SSL_CIPHER_get_name \
  1607. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1608. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1609. #define SSL_CTX_set_session_id_context \
  1610. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1611. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1612. #define SSL_CTX_set_cipher_list \
  1613. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1614. #define SSL_CTX_set_options \
  1615. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1616. #define SSL_CTX_set_info_callback \
  1617. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1618. ssl_sw[32] \
  1619. .ptr)
  1620. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1621. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1622. #define SSL_CTX_callback_ctrl \
  1623. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1624. #define SSL_get_servername \
  1625. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1626. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1627. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1628. #define SSL_CTX_clear_options(ctx, op) \
  1629. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1630. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1631. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1632. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1633. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1634. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1635. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1636. SSL_CTX_callback_ctrl(ctx, \
  1637. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1638. (void (*)(void))cb)
  1639. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1640. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1641. #define SSL_set_tlsext_host_name(ctx, arg) \
  1642. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1643. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1644. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1645. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1646. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1647. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1648. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1649. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1650. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1651. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1652. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1653. #define X509_NAME_oneline \
  1654. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1655. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1656. #define EVP_get_digestbyname \
  1657. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1658. #define EVP_Digest \
  1659. (*(int (*)( \
  1660. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1661. crypto_sw[9] \
  1662. .ptr)
  1663. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1664. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1665. #define ASN1_INTEGER_to_BN \
  1666. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1667. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1668. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1669. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1670. #define OPENSSL_free(a) CRYPTO_free(a)
  1671. #define OPENSSL_REMOVE_THREAD_STATE()
  1672. /* init_ssl_ctx() function updates this array.
  1673. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1674. * of respective functions. The macros above (like SSL_connect()) are really
  1675. * just calling these functions indirectly via the pointer. */
  1676. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1677. {"SSL_accept", NULL},
  1678. {"SSL_connect", NULL},
  1679. {"SSL_read", NULL},
  1680. {"SSL_write", NULL},
  1681. {"SSL_get_error", NULL},
  1682. {"SSL_set_fd", NULL},
  1683. {"SSL_new", NULL},
  1684. {"SSL_CTX_new", NULL},
  1685. {"TLS_server_method", NULL},
  1686. {"OPENSSL_init_ssl", NULL},
  1687. {"SSL_CTX_use_PrivateKey_file", NULL},
  1688. {"SSL_CTX_use_certificate_file", NULL},
  1689. {"SSL_CTX_set_default_passwd_cb", NULL},
  1690. {"SSL_CTX_free", NULL},
  1691. {"SSL_CTX_use_certificate_chain_file", NULL},
  1692. {"TLS_client_method", NULL},
  1693. {"SSL_pending", NULL},
  1694. {"SSL_CTX_set_verify", NULL},
  1695. {"SSL_shutdown", NULL},
  1696. {"SSL_CTX_load_verify_locations", NULL},
  1697. {"SSL_CTX_set_default_verify_paths", NULL},
  1698. {"SSL_CTX_set_verify_depth", NULL},
  1699. {"SSL_get_peer_certificate", NULL},
  1700. {"SSL_get_version", NULL},
  1701. {"SSL_get_current_cipher", NULL},
  1702. {"SSL_CIPHER_get_name", NULL},
  1703. {"SSL_CTX_check_private_key", NULL},
  1704. {"SSL_CTX_set_session_id_context", NULL},
  1705. {"SSL_CTX_ctrl", NULL},
  1706. {"SSL_CTX_set_cipher_list", NULL},
  1707. {"SSL_CTX_set_options", NULL},
  1708. {"SSL_CTX_set_info_callback", NULL},
  1709. {"SSL_get_ex_data", NULL},
  1710. {"SSL_set_ex_data", NULL},
  1711. {"SSL_CTX_callback_ctrl", NULL},
  1712. {"SSL_get_servername", NULL},
  1713. {"SSL_set_SSL_CTX", NULL},
  1714. {"SSL_ctrl", NULL},
  1715. {NULL, NULL}};
  1716. /* Similar array as ssl_sw. These functions could be located in different
  1717. * lib. */
  1718. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1719. {"ERR_error_string", NULL},
  1720. {"CONF_modules_unload", NULL},
  1721. {"X509_free", NULL},
  1722. {"X509_get_subject_name", NULL},
  1723. {"X509_get_issuer_name", NULL},
  1724. {"X509_NAME_oneline", NULL},
  1725. {"X509_get_serialNumber", NULL},
  1726. {"EVP_get_digestbyname", NULL},
  1727. {"EVP_Digest", NULL},
  1728. {"i2d_X509", NULL},
  1729. {"BN_bn2hex", NULL},
  1730. {"ASN1_INTEGER_to_BN", NULL},
  1731. {"BN_free", NULL},
  1732. {"CRYPTO_free", NULL},
  1733. {"ERR_clear_error", NULL},
  1734. {NULL, NULL}};
  1735. #else
  1736. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1737. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1738. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1739. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1740. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1741. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1742. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1743. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1744. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1745. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1746. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1747. #define SSL_CTX_use_PrivateKey_file \
  1748. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1749. #define SSL_CTX_use_certificate_file \
  1750. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1751. #define SSL_CTX_set_default_passwd_cb \
  1752. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1753. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1754. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1755. #define SSL_CTX_use_certificate_chain_file \
  1756. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1757. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1758. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1759. #define SSL_CTX_set_verify \
  1760. (*(void (*)(SSL_CTX *, \
  1761. int, \
  1762. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1763. .ptr)
  1764. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1765. #define SSL_CTX_load_verify_locations \
  1766. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1767. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1768. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1769. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1770. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1771. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1772. #define SSL_CIPHER_get_name \
  1773. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1774. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1775. #define SSL_CTX_set_session_id_context \
  1776. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1777. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1778. #define SSL_CTX_set_cipher_list \
  1779. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1780. #define SSL_CTX_set_info_callback \
  1781. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1782. .ptr)
  1783. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1784. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1785. #define SSL_CTX_callback_ctrl \
  1786. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1787. #define SSL_get_servername \
  1788. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1789. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1790. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1791. #define SSL_CTX_set_options(ctx, op) \
  1792. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1793. #define SSL_CTX_clear_options(ctx, op) \
  1794. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1795. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1796. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1797. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1798. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1799. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1800. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1801. SSL_CTX_callback_ctrl(ctx, \
  1802. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1803. (void (*)(void))cb)
  1804. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1805. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1806. #define SSL_set_tlsext_host_name(ctx, arg) \
  1807. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1808. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1809. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1810. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1811. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1812. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1813. #define CRYPTO_set_locking_callback \
  1814. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1815. #define CRYPTO_set_id_callback \
  1816. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1817. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1818. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1819. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1820. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1821. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1822. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1823. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1824. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1825. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1826. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1827. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1828. #define X509_NAME_oneline \
  1829. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1830. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1831. #define i2c_ASN1_INTEGER \
  1832. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1833. #define EVP_get_digestbyname \
  1834. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1835. #define EVP_Digest \
  1836. (*(int (*)( \
  1837. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1838. crypto_sw[18] \
  1839. .ptr)
  1840. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1841. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1842. #define ASN1_INTEGER_to_BN \
  1843. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1844. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1845. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1846. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1847. #define OPENSSL_free(a) CRYPTO_free(a)
  1848. /* use here ERR_remove_state,
  1849. * while on some platforms function is not included into library due to
  1850. * deprication */
  1851. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1852. /* init_ssl_ctx() function updates this array.
  1853. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1854. * of respective functions. The macros above (like SSL_connect()) are really
  1855. * just calling these functions indirectly via the pointer. */
  1856. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1857. {"SSL_accept", NULL},
  1858. {"SSL_connect", NULL},
  1859. {"SSL_read", NULL},
  1860. {"SSL_write", NULL},
  1861. {"SSL_get_error", NULL},
  1862. {"SSL_set_fd", NULL},
  1863. {"SSL_new", NULL},
  1864. {"SSL_CTX_new", NULL},
  1865. {"SSLv23_server_method", NULL},
  1866. {"SSL_library_init", NULL},
  1867. {"SSL_CTX_use_PrivateKey_file", NULL},
  1868. {"SSL_CTX_use_certificate_file", NULL},
  1869. {"SSL_CTX_set_default_passwd_cb", NULL},
  1870. {"SSL_CTX_free", NULL},
  1871. {"SSL_load_error_strings", NULL},
  1872. {"SSL_CTX_use_certificate_chain_file", NULL},
  1873. {"SSLv23_client_method", NULL},
  1874. {"SSL_pending", NULL},
  1875. {"SSL_CTX_set_verify", NULL},
  1876. {"SSL_shutdown", NULL},
  1877. {"SSL_CTX_load_verify_locations", NULL},
  1878. {"SSL_CTX_set_default_verify_paths", NULL},
  1879. {"SSL_CTX_set_verify_depth", NULL},
  1880. {"SSL_get_peer_certificate", NULL},
  1881. {"SSL_get_version", NULL},
  1882. {"SSL_get_current_cipher", NULL},
  1883. {"SSL_CIPHER_get_name", NULL},
  1884. {"SSL_CTX_check_private_key", NULL},
  1885. {"SSL_CTX_set_session_id_context", NULL},
  1886. {"SSL_CTX_ctrl", NULL},
  1887. {"SSL_CTX_set_cipher_list", NULL},
  1888. {"SSL_CTX_set_info_callback", NULL},
  1889. {"SSL_get_ex_data", NULL},
  1890. {"SSL_set_ex_data", NULL},
  1891. {"SSL_CTX_callback_ctrl", NULL},
  1892. {"SSL_get_servername", NULL},
  1893. {"SSL_set_SSL_CTX", NULL},
  1894. {"SSL_ctrl", NULL},
  1895. {NULL, NULL}};
  1896. /* Similar array as ssl_sw. These functions could be located in different
  1897. * lib. */
  1898. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1899. {"CRYPTO_set_locking_callback", NULL},
  1900. {"CRYPTO_set_id_callback", NULL},
  1901. {"ERR_get_error", NULL},
  1902. {"ERR_error_string", NULL},
  1903. {"ERR_remove_state", NULL},
  1904. {"ERR_free_strings", NULL},
  1905. {"ENGINE_cleanup", NULL},
  1906. {"CONF_modules_unload", NULL},
  1907. {"CRYPTO_cleanup_all_ex_data", NULL},
  1908. {"EVP_cleanup", NULL},
  1909. {"X509_free", NULL},
  1910. {"X509_get_subject_name", NULL},
  1911. {"X509_get_issuer_name", NULL},
  1912. {"X509_NAME_oneline", NULL},
  1913. {"X509_get_serialNumber", NULL},
  1914. {"i2c_ASN1_INTEGER", NULL},
  1915. {"EVP_get_digestbyname", NULL},
  1916. {"EVP_Digest", NULL},
  1917. {"i2d_X509", NULL},
  1918. {"BN_bn2hex", NULL},
  1919. {"ASN1_INTEGER_to_BN", NULL},
  1920. {"BN_free", NULL},
  1921. {"CRYPTO_free", NULL},
  1922. {"ERR_clear_error", NULL},
  1923. {NULL, NULL}};
  1924. #endif /* OPENSSL_API_1_1 */
  1925. #endif /* NO_SSL_DL */
  1926. #endif /* NO_SSL */
  1927. #if !defined(NO_CACHING)
  1928. static const char month_names[][4] = {"Jan",
  1929. "Feb",
  1930. "Mar",
  1931. "Apr",
  1932. "May",
  1933. "Jun",
  1934. "Jul",
  1935. "Aug",
  1936. "Sep",
  1937. "Oct",
  1938. "Nov",
  1939. "Dec"};
  1940. #endif /* !NO_CACHING */
  1941. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1942. * the
  1943. * union u. */
  1944. union usa {
  1945. struct sockaddr sa;
  1946. struct sockaddr_in sin;
  1947. #if defined(USE_IPV6)
  1948. struct sockaddr_in6 sin6;
  1949. #endif
  1950. };
  1951. /* Describes a string (chunk of memory). */
  1952. struct vec {
  1953. const char *ptr;
  1954. size_t len;
  1955. };
  1956. struct mg_file_stat {
  1957. /* File properties filled by mg_stat: */
  1958. uint64_t size;
  1959. time_t last_modified;
  1960. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1961. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1962. * case we need a "Content-Eencoding: gzip" header */
  1963. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1964. };
  1965. struct mg_file_in_memory {
  1966. char *p;
  1967. uint32_t pos;
  1968. char mode;
  1969. };
  1970. struct mg_file_access {
  1971. /* File properties filled by mg_fopen: */
  1972. FILE *fp;
  1973. #if defined(MG_USE_OPEN_FILE)
  1974. /* TODO (low): Remove obsolete "file in memory" implementation.
  1975. * In an "early 2017" discussion at Google groups
  1976. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1977. * we decided to get rid of this feature (after some fade-out
  1978. * phase). */
  1979. const char *membuf;
  1980. #endif
  1981. };
  1982. struct mg_file {
  1983. struct mg_file_stat stat;
  1984. struct mg_file_access access;
  1985. };
  1986. #if defined(MG_USE_OPEN_FILE)
  1987. #define STRUCT_FILE_INITIALIZER \
  1988. { \
  1989. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1990. { \
  1991. (FILE *)NULL, (const char *)NULL \
  1992. } \
  1993. }
  1994. #else
  1995. #define STRUCT_FILE_INITIALIZER \
  1996. { \
  1997. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1998. { \
  1999. (FILE *)NULL \
  2000. } \
  2001. }
  2002. #endif
  2003. /* Describes listening socket, or socket which was accept()-ed by the master
  2004. * thread and queued for future handling by the worker thread. */
  2005. struct socket {
  2006. SOCKET sock; /* Listening socket */
  2007. union usa lsa; /* Local socket address */
  2008. union usa rsa; /* Remote socket address */
  2009. unsigned char is_ssl; /* Is port SSL-ed */
  2010. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2011. * port */
  2012. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2013. };
  2014. /* Enum const for all options must be in sync with
  2015. * static struct mg_option config_options[]
  2016. * This is tested in the unit test (test/private.c)
  2017. * "Private Config Options"
  2018. */
  2019. enum {
  2020. /* Once for each server */
  2021. LISTENING_PORTS,
  2022. NUM_THREADS,
  2023. RUN_AS_USER,
  2024. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2025. * socket option typedef TCP_NODELAY. */
  2026. MAX_REQUEST_SIZE,
  2027. LINGER_TIMEOUT,
  2028. CONNECTION_QUEUE_SIZE,
  2029. MAX_CONNECTIONS,
  2030. #if defined(__linux__)
  2031. ALLOW_SENDFILE_CALL,
  2032. #endif
  2033. #if defined(_WIN32)
  2034. CASE_SENSITIVE_FILES,
  2035. #endif
  2036. THROTTLE,
  2037. ACCESS_LOG_FILE,
  2038. ERROR_LOG_FILE,
  2039. ENABLE_KEEP_ALIVE,
  2040. REQUEST_TIMEOUT,
  2041. KEEP_ALIVE_TIMEOUT,
  2042. #if defined(USE_WEBSOCKET)
  2043. WEBSOCKET_TIMEOUT,
  2044. ENABLE_WEBSOCKET_PING_PONG,
  2045. #endif
  2046. DECODE_URL,
  2047. #if defined(USE_LUA)
  2048. LUA_BACKGROUND_SCRIPT,
  2049. LUA_BACKGROUND_SCRIPT_PARAMS,
  2050. #endif
  2051. #if defined(USE_TIMERS)
  2052. CGI_TIMEOUT,
  2053. #endif
  2054. /* Once for each domain */
  2055. DOCUMENT_ROOT,
  2056. CGI_EXTENSIONS,
  2057. CGI_ENVIRONMENT,
  2058. PUT_DELETE_PASSWORDS_FILE,
  2059. CGI_INTERPRETER,
  2060. PROTECT_URI,
  2061. AUTHENTICATION_DOMAIN,
  2062. ENABLE_AUTH_DOMAIN_CHECK,
  2063. SSI_EXTENSIONS,
  2064. ENABLE_DIRECTORY_LISTING,
  2065. GLOBAL_PASSWORDS_FILE,
  2066. INDEX_FILES,
  2067. ACCESS_CONTROL_LIST,
  2068. EXTRA_MIME_TYPES,
  2069. SSL_CERTIFICATE,
  2070. SSL_CERTIFICATE_CHAIN,
  2071. URL_REWRITE_PATTERN,
  2072. HIDE_FILES,
  2073. SSL_DO_VERIFY_PEER,
  2074. SSL_CA_PATH,
  2075. SSL_CA_FILE,
  2076. SSL_VERIFY_DEPTH,
  2077. SSL_DEFAULT_VERIFY_PATHS,
  2078. SSL_CIPHER_LIST,
  2079. SSL_PROTOCOL_VERSION,
  2080. SSL_SHORT_TRUST,
  2081. #if defined(USE_LUA)
  2082. LUA_PRELOAD_FILE,
  2083. LUA_SCRIPT_EXTENSIONS,
  2084. LUA_SERVER_PAGE_EXTENSIONS,
  2085. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2086. LUA_DEBUG_PARAMS,
  2087. #endif
  2088. #endif
  2089. #if defined(USE_DUKTAPE)
  2090. DUKTAPE_SCRIPT_EXTENSIONS,
  2091. #endif
  2092. #if defined(USE_WEBSOCKET)
  2093. WEBSOCKET_ROOT,
  2094. #endif
  2095. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2096. LUA_WEBSOCKET_EXTENSIONS,
  2097. #endif
  2098. ACCESS_CONTROL_ALLOW_ORIGIN,
  2099. ACCESS_CONTROL_ALLOW_METHODS,
  2100. ACCESS_CONTROL_ALLOW_HEADERS,
  2101. ERROR_PAGES,
  2102. #if !defined(NO_CACHING)
  2103. STATIC_FILE_MAX_AGE,
  2104. STATIC_FILE_CACHE_CONTROL,
  2105. #endif
  2106. #if !defined(NO_SSL)
  2107. STRICT_HTTPS_MAX_AGE,
  2108. #endif
  2109. ADDITIONAL_HEADER,
  2110. ALLOW_INDEX_SCRIPT_SUB_RES,
  2111. #if defined(DAEMONIZE)
  2112. ENABLE_DAEMONIZE,
  2113. #endif
  2114. NUM_OPTIONS
  2115. };
  2116. /* Config option name, config types, default value.
  2117. * Must be in the same order as the enum const above.
  2118. */
  2119. static const struct mg_option config_options[] = {
  2120. /* Once for each server */
  2121. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2122. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2123. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2124. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2125. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2126. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2127. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2128. {"max_connections", MG_CONFIG_TYPE_NUMBER, "100"},
  2129. #if defined(__linux__)
  2130. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2131. #endif
  2132. #if defined(_WIN32)
  2133. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2134. #endif
  2135. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2136. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2137. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2138. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2139. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2140. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2141. #if defined(USE_WEBSOCKET)
  2142. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2143. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2144. #endif
  2145. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2146. #if defined(USE_LUA)
  2147. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2148. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2149. #endif
  2150. #if defined(USE_TIMERS)
  2151. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2152. #endif
  2153. /* Once for each domain */
  2154. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2155. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2156. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2157. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2158. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2159. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2160. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2161. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2162. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2163. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2164. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2165. {"index_files",
  2166. MG_CONFIG_TYPE_STRING_LIST,
  2167. #if defined(USE_LUA)
  2168. "index.xhtml,index.html,index.htm,"
  2169. "index.lp,index.lsp,index.lua,index.cgi,"
  2170. "index.shtml,index.php"},
  2171. #else
  2172. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2173. #endif
  2174. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2175. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2176. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2177. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2178. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2179. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2180. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2181. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2182. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2183. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2184. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2185. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2186. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2187. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2188. #if defined(USE_LUA)
  2189. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2190. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2191. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2192. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2193. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2194. #endif
  2195. #endif
  2196. #if defined(USE_DUKTAPE)
  2197. /* The support for duktape is still in alpha version state.
  2198. * The name of this config option might change. */
  2199. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2200. #endif
  2201. #if defined(USE_WEBSOCKET)
  2202. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2203. #endif
  2204. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2205. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2206. #endif
  2207. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2208. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2209. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2210. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2211. #if !defined(NO_CACHING)
  2212. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2213. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2214. #endif
  2215. #if !defined(NO_SSL)
  2216. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2217. #endif
  2218. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2219. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2220. #if defined(DAEMONIZE)
  2221. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2222. #endif
  2223. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2224. /* Check if the config_options and the corresponding enum have compatible
  2225. * sizes. */
  2226. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2227. == (NUM_OPTIONS + 1),
  2228. "config_options and enum not sync");
  2229. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2230. struct mg_handler_info {
  2231. /* Name/Pattern of the URI. */
  2232. char *uri;
  2233. size_t uri_len;
  2234. /* handler type */
  2235. int handler_type;
  2236. /* Handler for http/https or authorization requests. */
  2237. mg_request_handler handler;
  2238. unsigned int refcount;
  2239. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2240. pthread_cond_t
  2241. refcount_cond; /* Signaled when handler refcount is decremented */
  2242. /* Handler for ws/wss (websocket) requests. */
  2243. mg_websocket_connect_handler connect_handler;
  2244. mg_websocket_ready_handler ready_handler;
  2245. mg_websocket_data_handler data_handler;
  2246. mg_websocket_close_handler close_handler;
  2247. /* accepted subprotocols for ws/wss requests. */
  2248. struct mg_websocket_subprotocols *subprotocols;
  2249. /* Handler for authorization requests */
  2250. mg_authorization_handler auth_handler;
  2251. /* User supplied argument for the handler function. */
  2252. void *cbdata;
  2253. /* next handler in a linked list */
  2254. struct mg_handler_info *next;
  2255. };
  2256. enum {
  2257. CONTEXT_INVALID,
  2258. CONTEXT_SERVER,
  2259. CONTEXT_HTTP_CLIENT,
  2260. CONTEXT_WS_CLIENT
  2261. };
  2262. struct mg_domain_context {
  2263. SSL_CTX *ssl_ctx; /* SSL context */
  2264. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2265. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2266. /* Server nonce */
  2267. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2268. unsigned long nonce_count; /* Used nonces, used for authentication */
  2269. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2270. /* linked list of shared lua websockets */
  2271. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2272. #endif
  2273. /* Linked list of domains */
  2274. struct mg_domain_context *next;
  2275. };
  2276. struct mg_context {
  2277. /* Part 1 - Physical context:
  2278. * This holds threads, ports, timeouts, ...
  2279. * set for the entire server, independent from the
  2280. * addressed hostname.
  2281. */
  2282. /* Connection related */
  2283. int context_type; /* See CONTEXT_* above */
  2284. struct socket *listening_sockets;
  2285. struct mg_pollfd *listening_socket_fds;
  2286. unsigned int num_listening_sockets;
  2287. struct mg_connection *worker_connections; /* The connection struct, pre-
  2288. * allocated for each worker */
  2289. #if defined(USE_SERVER_STATS)
  2290. int active_connections;
  2291. int max_active_connections;
  2292. int64_t total_connections;
  2293. int64_t total_requests;
  2294. int64_t total_data_read;
  2295. int64_t total_data_written;
  2296. #endif
  2297. /* Thread related */
  2298. volatile int stop_flag; /* Should we stop event loop */
  2299. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2300. pthread_t masterthreadid; /* The master thread ID */
  2301. unsigned int
  2302. cfg_worker_threads; /* The number of configured worker threads. */
  2303. pthread_t *worker_threadids; /* The worker thread IDs */
  2304. /* Connection to thread dispatching */
  2305. #if defined(ALTERNATIVE_QUEUE)
  2306. struct socket *client_socks;
  2307. void **client_wait_events;
  2308. #else
  2309. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2310. worker thread */
  2311. volatile int sq_head; /* Head of the socket queue */
  2312. volatile int sq_tail; /* Tail of the socket queue */
  2313. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2314. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2315. volatile int sq_blocked; /* Status information: sq is full */
  2316. int sq_size; /* No of elements in socket queue */
  2317. #if defined(USE_SERVER_STATS)
  2318. int sq_max_fill;
  2319. #endif /* USE_SERVER_STATS */
  2320. #endif /* ALTERNATIVE_QUEUE */
  2321. /* Memory related */
  2322. unsigned int max_request_size; /* The max request size */
  2323. #if defined(USE_SERVER_STATS)
  2324. struct mg_memory_stat ctx_memory;
  2325. #endif
  2326. /* Operating system related */
  2327. char *systemName; /* What operating system is running */
  2328. time_t start_time; /* Server start time, used for authentication
  2329. * and for diagnstics. */
  2330. #if defined(USE_TIMERS)
  2331. struct ttimers *timers;
  2332. #endif
  2333. /* Lua specific: Background operations and shared websockets */
  2334. #if defined(USE_LUA)
  2335. void *lua_background_state;
  2336. #endif
  2337. /* Server nonce */
  2338. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2339. /* Server callbacks */
  2340. struct mg_callbacks callbacks; /* User-defined callback function */
  2341. void *user_data; /* User-defined data */
  2342. /* Part 2 - Logical domain:
  2343. * This holds hostname, TLS certificate, document root, ...
  2344. * set for a domain hosted at the server.
  2345. * There may be multiple domains hosted at one physical server.
  2346. * The default domain "dd" is the first element of a list of
  2347. * domains.
  2348. */
  2349. struct mg_domain_context dd; /* default domain */
  2350. };
  2351. #if defined(USE_SERVER_STATS)
  2352. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2353. static struct mg_memory_stat *
  2354. get_memory_stat(struct mg_context *ctx)
  2355. {
  2356. if (ctx) {
  2357. return &(ctx->ctx_memory);
  2358. }
  2359. return &mg_common_memory;
  2360. }
  2361. #endif
  2362. enum {
  2363. CONNECTION_TYPE_INVALID,
  2364. CONNECTION_TYPE_REQUEST,
  2365. CONNECTION_TYPE_RESPONSE
  2366. };
  2367. struct mg_connection {
  2368. int connection_type; /* see CONNECTION_TYPE_* above */
  2369. struct mg_request_info request_info;
  2370. struct mg_response_info response_info;
  2371. struct mg_context *phys_ctx;
  2372. struct mg_domain_context *dom_ctx;
  2373. #if defined(USE_SERVER_STATS)
  2374. int conn_state; /* 0 = undef, numerical value may change in different
  2375. * versions. For the current definition, see
  2376. * mg_get_connection_info_impl */
  2377. #endif
  2378. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2379. SSL *ssl; /* SSL descriptor */
  2380. struct socket client; /* Connected client */
  2381. time_t conn_birth_time; /* Time (wall clock) when connection was
  2382. * established */
  2383. #if defined(USE_SERVER_STATS)
  2384. time_t conn_close_time; /* Time (wall clock) when connection was
  2385. * closed (or 0 if still open) */
  2386. #endif
  2387. struct timespec req_time; /* Time (since system start) when the request
  2388. * was received */
  2389. int64_t num_bytes_sent; /* Total bytes sent to client */
  2390. int64_t content_len; /* How many bytes of content can be read
  2391. * !is_chunked: Content-Length header value
  2392. * or -1 (until connection closed,
  2393. * not allowed for a request)
  2394. * is_chunked: >= 0, appended gradually
  2395. */
  2396. int64_t consumed_content; /* How many bytes of content have been read */
  2397. int is_chunked; /* Transfer-Encoding is chunked:
  2398. * 0 = not chunked,
  2399. * 1 = chunked, not yet, or some data read,
  2400. * 2 = chunked, has error,
  2401. * 3 = chunked, all data read except trailer,
  2402. * 4 = chunked, all data read
  2403. */
  2404. char *buf; /* Buffer for received data */
  2405. char *path_info; /* PATH_INFO part of the URL */
  2406. int must_close; /* 1 if connection must be closed */
  2407. int accept_gzip; /* 1 if gzip encoding is accepted */
  2408. int in_error_handler; /* 1 if in handler for user defined error
  2409. * pages */
  2410. #if defined(USE_WEBSOCKET)
  2411. int in_websocket_handling; /* 1 if in read_websocket */
  2412. #endif
  2413. int handled_requests; /* Number of requests handled by this connection
  2414. */
  2415. int buf_size; /* Buffer size */
  2416. int request_len; /* Size of the request + headers in a buffer */
  2417. int data_len; /* Total size of data in a buffer */
  2418. int status_code; /* HTTP reply status code, e.g. 200 */
  2419. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2420. * throttle */
  2421. time_t last_throttle_time; /* Last time throttled data was sent */
  2422. int last_throttle_bytes; /* Bytes sent this second */
  2423. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2424. * atomic transmissions for websockets */
  2425. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2426. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2427. #endif
  2428. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2429. * for quick access */
  2430. };
  2431. /* Directory entry */
  2432. struct de {
  2433. struct mg_connection *conn;
  2434. char *file_name;
  2435. struct mg_file_stat file;
  2436. };
  2437. #if defined(USE_WEBSOCKET)
  2438. static int is_websocket_protocol(const struct mg_connection *conn);
  2439. #else
  2440. #define is_websocket_protocol(conn) (0)
  2441. #endif
  2442. #define mg_cry_internal(conn, fmt, ...) \
  2443. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2444. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2445. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2446. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2447. struct mg_context *ctx,
  2448. const char *func,
  2449. unsigned line,
  2450. const char *fmt,
  2451. ...) PRINTF_ARGS(5, 6);
  2452. #if !defined(NO_THREAD_NAME)
  2453. #if defined(_WIN32) && defined(_MSC_VER)
  2454. /* Set the thread name for debugging purposes in Visual Studio
  2455. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2456. */
  2457. #pragma pack(push, 8)
  2458. typedef struct tagTHREADNAME_INFO {
  2459. DWORD dwType; /* Must be 0x1000. */
  2460. LPCSTR szName; /* Pointer to name (in user addr space). */
  2461. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2462. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2463. } THREADNAME_INFO;
  2464. #pragma pack(pop)
  2465. #elif defined(__linux__)
  2466. #include <sys/prctl.h>
  2467. #include <sys/sendfile.h>
  2468. #if defined(ALTERNATIVE_QUEUE)
  2469. #include <sys/eventfd.h>
  2470. #endif /* ALTERNATIVE_QUEUE */
  2471. #if defined(ALTERNATIVE_QUEUE)
  2472. static void *
  2473. event_create(void)
  2474. {
  2475. int evhdl = eventfd(0, EFD_CLOEXEC);
  2476. int *ret;
  2477. if (evhdl == -1) {
  2478. /* Linux uses -1 on error, Windows NULL. */
  2479. /* However, Linux does not return 0 on success either. */
  2480. return 0;
  2481. }
  2482. ret = (int *)mg_malloc(sizeof(int));
  2483. if (ret) {
  2484. *ret = evhdl;
  2485. } else {
  2486. (void)close(evhdl);
  2487. }
  2488. return (void *)ret;
  2489. }
  2490. static int
  2491. event_wait(void *eventhdl)
  2492. {
  2493. uint64_t u;
  2494. int evhdl, s;
  2495. if (!eventhdl) {
  2496. /* error */
  2497. return 0;
  2498. }
  2499. evhdl = *(int *)eventhdl;
  2500. s = (int)read(evhdl, &u, sizeof(u));
  2501. if (s != sizeof(u)) {
  2502. /* error */
  2503. return 0;
  2504. }
  2505. (void)u; /* the value is not required */
  2506. return 1;
  2507. }
  2508. static int
  2509. event_signal(void *eventhdl)
  2510. {
  2511. uint64_t u = 1;
  2512. int evhdl, s;
  2513. if (!eventhdl) {
  2514. /* error */
  2515. return 0;
  2516. }
  2517. evhdl = *(int *)eventhdl;
  2518. s = (int)write(evhdl, &u, sizeof(u));
  2519. if (s != sizeof(u)) {
  2520. /* error */
  2521. return 0;
  2522. }
  2523. return 1;
  2524. }
  2525. static void
  2526. event_destroy(void *eventhdl)
  2527. {
  2528. int evhdl;
  2529. if (!eventhdl) {
  2530. /* error */
  2531. return;
  2532. }
  2533. evhdl = *(int *)eventhdl;
  2534. close(evhdl);
  2535. mg_free(eventhdl);
  2536. }
  2537. #endif
  2538. #endif
  2539. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2540. struct posix_event {
  2541. pthread_mutex_t mutex;
  2542. pthread_cond_t cond;
  2543. int signaled;
  2544. };
  2545. static void *
  2546. event_create(void)
  2547. {
  2548. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2549. if (ret == 0) {
  2550. /* out of memory */
  2551. return 0;
  2552. }
  2553. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2554. /* pthread mutex not available */
  2555. mg_free(ret);
  2556. return 0;
  2557. }
  2558. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2559. /* pthread cond not available */
  2560. pthread_mutex_destroy(&(ret->mutex));
  2561. mg_free(ret);
  2562. return 0;
  2563. }
  2564. ret->signaled = 0;
  2565. return (void *)ret;
  2566. }
  2567. static int
  2568. event_wait(void *eventhdl)
  2569. {
  2570. struct posix_event *ev = (struct posix_event *)eventhdl;
  2571. pthread_mutex_lock(&(ev->mutex));
  2572. while (!ev->signaled) {
  2573. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2574. }
  2575. ev->signaled = 0;
  2576. pthread_mutex_unlock(&(ev->mutex));
  2577. return 1;
  2578. }
  2579. static int
  2580. event_signal(void *eventhdl)
  2581. {
  2582. struct posix_event *ev = (struct posix_event *)eventhdl;
  2583. pthread_mutex_lock(&(ev->mutex));
  2584. pthread_cond_signal(&(ev->cond));
  2585. ev->signaled = 1;
  2586. pthread_mutex_unlock(&(ev->mutex));
  2587. return 1;
  2588. }
  2589. static void
  2590. event_destroy(void *eventhdl)
  2591. {
  2592. struct posix_event *ev = (struct posix_event *)eventhdl;
  2593. pthread_cond_destroy(&(ev->cond));
  2594. pthread_mutex_destroy(&(ev->mutex));
  2595. mg_free(ev);
  2596. }
  2597. #endif
  2598. static void
  2599. mg_set_thread_name(const char *name)
  2600. {
  2601. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2602. mg_snprintf(
  2603. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2604. #if defined(_WIN32)
  2605. #if defined(_MSC_VER)
  2606. /* Windows and Visual Studio Compiler */
  2607. __try {
  2608. THREADNAME_INFO info;
  2609. info.dwType = 0x1000;
  2610. info.szName = threadName;
  2611. info.dwThreadID = ~0U;
  2612. info.dwFlags = 0;
  2613. RaiseException(0x406D1388,
  2614. 0,
  2615. sizeof(info) / sizeof(ULONG_PTR),
  2616. (ULONG_PTR *)&info);
  2617. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2618. }
  2619. #elif defined(__MINGW32__)
  2620. /* No option known to set thread name for MinGW known */
  2621. #endif
  2622. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2623. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2624. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2625. #if defined(__MACH__)
  2626. /* OS X only current thread name can be changed */
  2627. (void)pthread_setname_np(threadName);
  2628. #else
  2629. (void)pthread_setname_np(pthread_self(), threadName);
  2630. #endif
  2631. #elif defined(__linux__)
  2632. /* On Linux we can use the prctl function.
  2633. * When building for Linux Standard Base (LSB) use
  2634. * NO_THREAD_NAME. However, thread names are a big
  2635. * help for debugging, so the stadard is to set them.
  2636. */
  2637. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2638. #endif
  2639. }
  2640. #else /* !defined(NO_THREAD_NAME) */
  2641. void
  2642. mg_set_thread_name(const char *threadName)
  2643. {
  2644. }
  2645. #endif
  2646. #if defined(MG_LEGACY_INTERFACE)
  2647. const char **
  2648. mg_get_valid_option_names(void)
  2649. {
  2650. /* This function is deprecated. Use mg_get_valid_options instead. */
  2651. static const char
  2652. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2653. int i;
  2654. for (i = 0; config_options[i].name != NULL; i++) {
  2655. data[i * 2] = config_options[i].name;
  2656. data[i * 2 + 1] = config_options[i].default_value;
  2657. }
  2658. return data;
  2659. }
  2660. #endif
  2661. const struct mg_option *
  2662. mg_get_valid_options(void)
  2663. {
  2664. return config_options;
  2665. }
  2666. /* Do not open file (used in is_file_in_memory) */
  2667. #define MG_FOPEN_MODE_NONE (0)
  2668. /* Open file for read only access */
  2669. #define MG_FOPEN_MODE_READ (1)
  2670. /* Open file for writing, create and overwrite */
  2671. #define MG_FOPEN_MODE_WRITE (2)
  2672. /* Open file for writing, create and append */
  2673. #define MG_FOPEN_MODE_APPEND (4)
  2674. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2675. * output filep and return 1, otherwise return 0 and don't modify anything.
  2676. */
  2677. static int
  2678. open_file_in_memory(const struct mg_connection *conn,
  2679. const char *path,
  2680. struct mg_file *filep,
  2681. int mode)
  2682. {
  2683. #if defined(MG_USE_OPEN_FILE)
  2684. size_t size = 0;
  2685. const char *buf = NULL;
  2686. if (!conn) {
  2687. return 0;
  2688. }
  2689. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2690. return 0;
  2691. }
  2692. if (conn->phys_ctx->callbacks.open_file) {
  2693. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2694. if (buf != NULL) {
  2695. if (filep == NULL) {
  2696. /* This is a file in memory, but we cannot store the
  2697. * properties
  2698. * now.
  2699. * Called from "is_file_in_memory" function. */
  2700. return 1;
  2701. }
  2702. /* NOTE: override filep->size only on success. Otherwise, it
  2703. * might
  2704. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2705. filep->access.membuf = buf;
  2706. filep->access.fp = NULL;
  2707. /* Size was set by the callback */
  2708. filep->stat.size = size;
  2709. /* Assume the data may change during runtime by setting
  2710. * last_modified = now */
  2711. filep->stat.last_modified = time(NULL);
  2712. filep->stat.is_directory = 0;
  2713. filep->stat.is_gzipped = 0;
  2714. }
  2715. }
  2716. return (buf != NULL);
  2717. #else
  2718. (void)conn;
  2719. (void)path;
  2720. (void)filep;
  2721. (void)mode;
  2722. return 0;
  2723. #endif
  2724. }
  2725. static int
  2726. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2727. {
  2728. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2729. }
  2730. static int
  2731. is_file_opened(const struct mg_file_access *fileacc)
  2732. {
  2733. if (!fileacc) {
  2734. return 0;
  2735. }
  2736. #if defined(MG_USE_OPEN_FILE)
  2737. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2738. #else
  2739. return (fileacc->fp != NULL);
  2740. #endif
  2741. }
  2742. #if !defined(NO_FILESYSTEMS)
  2743. static int mg_stat(const struct mg_connection *conn,
  2744. const char *path,
  2745. struct mg_file_stat *filep);
  2746. /* mg_fopen will open a file either in memory or on the disk.
  2747. * The input parameter path is a string in UTF-8 encoding.
  2748. * The input parameter mode is MG_FOPEN_MODE_*
  2749. * On success, either fp or membuf will be set in the output
  2750. * struct file. All status members will also be set.
  2751. * The function returns 1 on success, 0 on error. */
  2752. static int
  2753. mg_fopen(const struct mg_connection *conn,
  2754. const char *path,
  2755. int mode,
  2756. struct mg_file *filep)
  2757. {
  2758. int found;
  2759. if (!filep) {
  2760. return 0;
  2761. }
  2762. filep->access.fp = NULL;
  2763. #if defined(MG_USE_OPEN_FILE)
  2764. filep->access.membuf = NULL;
  2765. #endif
  2766. if (!is_file_in_memory(conn, path)) {
  2767. /* filep is initialized in mg_stat: all fields with memset to,
  2768. * some fields like size and modification date with values */
  2769. found = mg_stat(conn, path, &(filep->stat));
  2770. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2771. /* file does not exist and will not be created */
  2772. return 0;
  2773. }
  2774. #if defined(_WIN32)
  2775. {
  2776. wchar_t wbuf[W_PATH_MAX];
  2777. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2778. switch (mode) {
  2779. case MG_FOPEN_MODE_READ:
  2780. filep->access.fp = _wfopen(wbuf, L"rb");
  2781. break;
  2782. case MG_FOPEN_MODE_WRITE:
  2783. filep->access.fp = _wfopen(wbuf, L"wb");
  2784. break;
  2785. case MG_FOPEN_MODE_APPEND:
  2786. filep->access.fp = _wfopen(wbuf, L"ab");
  2787. break;
  2788. }
  2789. }
  2790. #else
  2791. /* Linux et al already use unicode. No need to convert. */
  2792. switch (mode) {
  2793. case MG_FOPEN_MODE_READ:
  2794. filep->access.fp = fopen(path, "r");
  2795. break;
  2796. case MG_FOPEN_MODE_WRITE:
  2797. filep->access.fp = fopen(path, "w");
  2798. break;
  2799. case MG_FOPEN_MODE_APPEND:
  2800. filep->access.fp = fopen(path, "a");
  2801. break;
  2802. }
  2803. #endif
  2804. if (!found) {
  2805. /* File did not exist before fopen was called.
  2806. * Maybe it has been created now. Get stat info
  2807. * like creation time now. */
  2808. found = mg_stat(conn, path, &(filep->stat));
  2809. (void)found;
  2810. }
  2811. /* file is on disk */
  2812. return (filep->access.fp != NULL);
  2813. } else {
  2814. #if defined(MG_USE_OPEN_FILE)
  2815. /* is_file_in_memory returned true */
  2816. if (open_file_in_memory(conn, path, filep, mode)) {
  2817. /* file is in memory */
  2818. return (filep->access.membuf != NULL);
  2819. }
  2820. #endif
  2821. }
  2822. /* Open failed */
  2823. return 0;
  2824. }
  2825. /* return 0 on success, just like fclose */
  2826. static int
  2827. mg_fclose(struct mg_file_access *fileacc)
  2828. {
  2829. int ret = -1;
  2830. if (fileacc != NULL) {
  2831. if (fileacc->fp != NULL) {
  2832. ret = fclose(fileacc->fp);
  2833. #if defined(MG_USE_OPEN_FILE)
  2834. } else if (fileacc->membuf != NULL) {
  2835. ret = 0;
  2836. #endif
  2837. }
  2838. /* reset all members of fileacc */
  2839. memset(fileacc, 0, sizeof(*fileacc));
  2840. }
  2841. return ret;
  2842. }
  2843. #endif /* NO_FILESYSTEMS */
  2844. static void
  2845. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2846. {
  2847. for (; *src != '\0' && n > 1; n--) {
  2848. *dst++ = *src++;
  2849. }
  2850. *dst = '\0';
  2851. }
  2852. static int
  2853. lowercase(const char *s)
  2854. {
  2855. return tolower((unsigned char)*s);
  2856. }
  2857. int
  2858. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2859. {
  2860. int diff = 0;
  2861. if (len > 0) {
  2862. do {
  2863. diff = lowercase(s1++) - lowercase(s2++);
  2864. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2865. }
  2866. return diff;
  2867. }
  2868. int
  2869. mg_strcasecmp(const char *s1, const char *s2)
  2870. {
  2871. int diff;
  2872. do {
  2873. diff = lowercase(s1++) - lowercase(s2++);
  2874. } while (diff == 0 && s1[-1] != '\0');
  2875. return diff;
  2876. }
  2877. static char *
  2878. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2879. {
  2880. char *p;
  2881. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2882. * defined */
  2883. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2884. mg_strlcpy(p, ptr, len + 1);
  2885. }
  2886. return p;
  2887. }
  2888. static char *
  2889. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2890. {
  2891. return mg_strndup_ctx(str, strlen(str), ctx);
  2892. }
  2893. static char *
  2894. mg_strdup(const char *str)
  2895. {
  2896. return mg_strndup_ctx(str, strlen(str), NULL);
  2897. }
  2898. static const char *
  2899. mg_strcasestr(const char *big_str, const char *small_str)
  2900. {
  2901. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2902. if (big_len >= small_len) {
  2903. for (i = 0; i <= (big_len - small_len); i++) {
  2904. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2905. return big_str + i;
  2906. }
  2907. }
  2908. }
  2909. return NULL;
  2910. }
  2911. /* Return null terminated string of given maximum length.
  2912. * Report errors if length is exceeded. */
  2913. static void
  2914. mg_vsnprintf(const struct mg_connection *conn,
  2915. int *truncated,
  2916. char *buf,
  2917. size_t buflen,
  2918. const char *fmt,
  2919. va_list ap)
  2920. {
  2921. int n, ok;
  2922. if (buflen == 0) {
  2923. if (truncated) {
  2924. *truncated = 1;
  2925. }
  2926. return;
  2927. }
  2928. #if defined(__clang__)
  2929. #pragma clang diagnostic push
  2930. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2931. /* Using fmt as a non-literal is intended here, since it is mostly called
  2932. * indirectly by mg_snprintf */
  2933. #endif
  2934. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2935. ok = (n >= 0) && ((size_t)n < buflen);
  2936. #if defined(__clang__)
  2937. #pragma clang diagnostic pop
  2938. #endif
  2939. if (ok) {
  2940. if (truncated) {
  2941. *truncated = 0;
  2942. }
  2943. } else {
  2944. if (truncated) {
  2945. *truncated = 1;
  2946. }
  2947. mg_cry_internal(conn,
  2948. "truncating vsnprintf buffer: [%.*s]",
  2949. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2950. buf);
  2951. n = (int)buflen - 1;
  2952. }
  2953. buf[n] = '\0';
  2954. }
  2955. static void
  2956. mg_snprintf(const struct mg_connection *conn,
  2957. int *truncated,
  2958. char *buf,
  2959. size_t buflen,
  2960. const char *fmt,
  2961. ...)
  2962. {
  2963. va_list ap;
  2964. va_start(ap, fmt);
  2965. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2966. va_end(ap);
  2967. }
  2968. static int
  2969. get_option_index(const char *name)
  2970. {
  2971. int i;
  2972. for (i = 0; config_options[i].name != NULL; i++) {
  2973. if (strcmp(config_options[i].name, name) == 0) {
  2974. return i;
  2975. }
  2976. }
  2977. return -1;
  2978. }
  2979. const char *
  2980. mg_get_option(const struct mg_context *ctx, const char *name)
  2981. {
  2982. int i;
  2983. if ((i = get_option_index(name)) == -1) {
  2984. return NULL;
  2985. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2986. return "";
  2987. } else {
  2988. return ctx->dd.config[i];
  2989. }
  2990. }
  2991. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2992. struct mg_context *
  2993. mg_get_context(const struct mg_connection *conn)
  2994. {
  2995. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2996. }
  2997. void *
  2998. mg_get_user_data(const struct mg_context *ctx)
  2999. {
  3000. return (ctx == NULL) ? NULL : ctx->user_data;
  3001. }
  3002. void *
  3003. mg_get_user_context_data(const struct mg_connection *conn)
  3004. {
  3005. return mg_get_user_data(mg_get_context(conn));
  3006. }
  3007. void *
  3008. mg_get_thread_pointer(const struct mg_connection *conn)
  3009. {
  3010. /* both methods should return the same pointer */
  3011. if (conn) {
  3012. /* quick access, in case conn is known */
  3013. return conn->tls_user_ptr;
  3014. } else {
  3015. /* otherwise get pointer from thread local storage (TLS) */
  3016. struct mg_workerTLS *tls =
  3017. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3018. return tls->user_ptr;
  3019. }
  3020. }
  3021. void
  3022. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3023. {
  3024. if (conn != NULL) {
  3025. conn->request_info.conn_data = data;
  3026. }
  3027. }
  3028. void *
  3029. mg_get_user_connection_data(const struct mg_connection *conn)
  3030. {
  3031. if (conn != NULL) {
  3032. return conn->request_info.conn_data;
  3033. }
  3034. return NULL;
  3035. }
  3036. #if defined(MG_LEGACY_INTERFACE)
  3037. /* Deprecated: Use mg_get_server_ports instead. */
  3038. size_t
  3039. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3040. {
  3041. size_t i;
  3042. if (!ctx) {
  3043. return 0;
  3044. }
  3045. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3046. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3047. ports[i] =
  3048. #if defined(USE_IPV6)
  3049. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3050. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3051. :
  3052. #endif
  3053. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3054. }
  3055. return i;
  3056. }
  3057. #endif
  3058. int
  3059. mg_get_server_ports(const struct mg_context *ctx,
  3060. int size,
  3061. struct mg_server_port *ports)
  3062. {
  3063. int i, cnt = 0;
  3064. if (size <= 0) {
  3065. return -1;
  3066. }
  3067. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3068. if (!ctx) {
  3069. return -1;
  3070. }
  3071. if (!ctx->listening_sockets) {
  3072. return -1;
  3073. }
  3074. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3075. ports[cnt].port =
  3076. #if defined(USE_IPV6)
  3077. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3078. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3079. :
  3080. #endif
  3081. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3082. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3083. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3084. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3085. /* IPv4 */
  3086. ports[cnt].protocol = 1;
  3087. cnt++;
  3088. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3089. /* IPv6 */
  3090. ports[cnt].protocol = 3;
  3091. cnt++;
  3092. }
  3093. }
  3094. return cnt;
  3095. }
  3096. static void
  3097. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3098. {
  3099. buf[0] = '\0';
  3100. if (!usa) {
  3101. return;
  3102. }
  3103. if (usa->sa.sa_family == AF_INET) {
  3104. getnameinfo(&usa->sa,
  3105. sizeof(usa->sin),
  3106. buf,
  3107. (unsigned)len,
  3108. NULL,
  3109. 0,
  3110. NI_NUMERICHOST);
  3111. }
  3112. #if defined(USE_IPV6)
  3113. else if (usa->sa.sa_family == AF_INET6) {
  3114. getnameinfo(&usa->sa,
  3115. sizeof(usa->sin6),
  3116. buf,
  3117. (unsigned)len,
  3118. NULL,
  3119. 0,
  3120. NI_NUMERICHOST);
  3121. }
  3122. #endif
  3123. }
  3124. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3125. * included in all responses other than 100, 101, 5xx. */
  3126. static void
  3127. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3128. {
  3129. #if !defined(REENTRANT_TIME)
  3130. struct tm *tm;
  3131. tm = ((t != NULL) ? gmtime(t) : NULL);
  3132. if (tm != NULL) {
  3133. #else
  3134. struct tm _tm;
  3135. struct tm *tm = &_tm;
  3136. if (t != NULL) {
  3137. gmtime_r(t, tm);
  3138. #endif
  3139. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3140. } else {
  3141. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3142. buf[buf_len - 1] = '\0';
  3143. }
  3144. }
  3145. /* difftime for struct timespec. Return value is in seconds. */
  3146. static double
  3147. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3148. {
  3149. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3150. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3151. }
  3152. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3153. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3154. const char *func,
  3155. unsigned line,
  3156. const char *fmt,
  3157. va_list ap);
  3158. #include "external_mg_cry_internal_impl.inl"
  3159. #elif !defined(NO_FILESYSTEMS)
  3160. /* Print error message to the opened error log stream. */
  3161. static void
  3162. mg_cry_internal_impl(const struct mg_connection *conn,
  3163. const char *func,
  3164. unsigned line,
  3165. const char *fmt,
  3166. va_list ap)
  3167. {
  3168. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3169. struct mg_file fi;
  3170. time_t timestamp;
  3171. /* Unused, in the RELEASE build */
  3172. (void)func;
  3173. (void)line;
  3174. #if defined(GCC_DIAGNOSTIC)
  3175. #pragma GCC diagnostic push
  3176. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3177. #endif
  3178. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3179. #if defined(GCC_DIAGNOSTIC)
  3180. #pragma GCC diagnostic pop
  3181. #endif
  3182. buf[sizeof(buf) - 1] = 0;
  3183. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3184. if (!conn) {
  3185. puts(buf);
  3186. return;
  3187. }
  3188. /* Do not lock when getting the callback value, here and below.
  3189. * I suppose this is fine, since function cannot disappear in the
  3190. * same way string option can. */
  3191. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3192. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3193. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3194. if (mg_fopen(conn,
  3195. conn->dom_ctx->config[ERROR_LOG_FILE],
  3196. MG_FOPEN_MODE_APPEND,
  3197. &fi)
  3198. == 0) {
  3199. fi.access.fp = NULL;
  3200. }
  3201. } else {
  3202. fi.access.fp = NULL;
  3203. }
  3204. if (fi.access.fp != NULL) {
  3205. flockfile(fi.access.fp);
  3206. timestamp = time(NULL);
  3207. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3208. fprintf(fi.access.fp,
  3209. "[%010lu] [error] [client %s] ",
  3210. (unsigned long)timestamp,
  3211. src_addr);
  3212. if (conn->request_info.request_method != NULL) {
  3213. fprintf(fi.access.fp,
  3214. "%s %s: ",
  3215. conn->request_info.request_method,
  3216. conn->request_info.request_uri
  3217. ? conn->request_info.request_uri
  3218. : "");
  3219. }
  3220. fprintf(fi.access.fp, "%s", buf);
  3221. fputc('\n', fi.access.fp);
  3222. fflush(fi.access.fp);
  3223. funlockfile(fi.access.fp);
  3224. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3225. * mg_cry here anyway ;-) */
  3226. }
  3227. }
  3228. }
  3229. #else
  3230. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3231. #endif /* Externally provided function */
  3232. /* Construct fake connection structure. Used for logging, if connection
  3233. * is not applicable at the moment of logging. */
  3234. static struct mg_connection *
  3235. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3236. {
  3237. static const struct mg_connection conn_zero = {0};
  3238. *fc = conn_zero;
  3239. fc->phys_ctx = ctx;
  3240. fc->dom_ctx = &(ctx->dd);
  3241. return fc;
  3242. }
  3243. static void
  3244. mg_cry_internal_wrap(const struct mg_connection *conn,
  3245. struct mg_context *ctx,
  3246. const char *func,
  3247. unsigned line,
  3248. const char *fmt,
  3249. ...)
  3250. {
  3251. va_list ap;
  3252. va_start(ap, fmt);
  3253. if (!conn && ctx) {
  3254. struct mg_connection fc;
  3255. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3256. } else {
  3257. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3258. }
  3259. va_end(ap);
  3260. }
  3261. void
  3262. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3263. {
  3264. va_list ap;
  3265. va_start(ap, fmt);
  3266. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3267. va_end(ap);
  3268. }
  3269. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3270. const char *
  3271. mg_version(void)
  3272. {
  3273. return CIVETWEB_VERSION;
  3274. }
  3275. const struct mg_request_info *
  3276. mg_get_request_info(const struct mg_connection *conn)
  3277. {
  3278. if (!conn) {
  3279. return NULL;
  3280. }
  3281. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3282. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3283. char txt[16];
  3284. struct mg_workerTLS *tls =
  3285. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3286. sprintf(txt, "%03i", conn->response_info.status_code);
  3287. if (strlen(txt) == 3) {
  3288. memcpy(tls->txtbuf, txt, 4);
  3289. } else {
  3290. strcpy(tls->txtbuf, "ERR");
  3291. }
  3292. ((struct mg_connection *)conn)->request_info.local_uri =
  3293. ((struct mg_connection *)conn)->request_info.request_uri =
  3294. tls->txtbuf; /* use thread safe buffer */
  3295. ((struct mg_connection *)conn)->request_info.num_headers =
  3296. conn->response_info.num_headers;
  3297. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3298. conn->response_info.http_headers,
  3299. sizeof(conn->response_info.http_headers));
  3300. } else
  3301. #endif
  3302. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3303. return NULL;
  3304. }
  3305. return &conn->request_info;
  3306. }
  3307. const struct mg_response_info *
  3308. mg_get_response_info(const struct mg_connection *conn)
  3309. {
  3310. if (!conn) {
  3311. return NULL;
  3312. }
  3313. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3314. return NULL;
  3315. }
  3316. return &conn->response_info;
  3317. }
  3318. static const char *
  3319. get_proto_name(const struct mg_connection *conn)
  3320. {
  3321. #if defined(__clang__)
  3322. #pragma clang diagnostic push
  3323. #pragma clang diagnostic ignored "-Wunreachable-code"
  3324. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3325. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3326. * unreachable, but splitting into four different #ifdef clauses here is more
  3327. * complicated.
  3328. */
  3329. #endif
  3330. const struct mg_request_info *ri = &conn->request_info;
  3331. const char *proto =
  3332. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3333. : (ri->is_ssl ? "https" : "http"));
  3334. return proto;
  3335. #if defined(__clang__)
  3336. #pragma clang diagnostic pop
  3337. #endif
  3338. }
  3339. int
  3340. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3341. {
  3342. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3343. return -1;
  3344. } else {
  3345. int truncated = 0;
  3346. const struct mg_request_info *ri = &conn->request_info;
  3347. const char *proto = get_proto_name(conn);
  3348. if (ri->local_uri == NULL) {
  3349. return -1;
  3350. }
  3351. if ((ri->request_uri != NULL)
  3352. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3353. /* The request uri is different from the local uri.
  3354. * This is usually if an absolute URI, including server
  3355. * name has been provided. */
  3356. mg_snprintf(conn,
  3357. &truncated,
  3358. buf,
  3359. buflen,
  3360. "%s://%s",
  3361. proto,
  3362. ri->request_uri);
  3363. if (truncated) {
  3364. return -1;
  3365. }
  3366. return 0;
  3367. } else {
  3368. /* The common case is a relative URI, so we have to
  3369. * construct an absolute URI from server name and port */
  3370. #if defined(USE_IPV6)
  3371. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3372. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3373. : htons(conn->client.lsa.sin.sin_port);
  3374. #else
  3375. int port = htons(conn->client.lsa.sin.sin_port);
  3376. #endif
  3377. int def_port = ri->is_ssl ? 443 : 80;
  3378. int auth_domain_check_enabled =
  3379. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3380. && (!mg_strcasecmp(
  3381. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3382. const char *server_domain =
  3383. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3384. char portstr[16];
  3385. char server_ip[48];
  3386. if (port != def_port) {
  3387. sprintf(portstr, ":%u", (unsigned)port);
  3388. } else {
  3389. portstr[0] = 0;
  3390. }
  3391. if (!auth_domain_check_enabled || !server_domain) {
  3392. sockaddr_to_string(server_ip,
  3393. sizeof(server_ip),
  3394. &conn->client.lsa);
  3395. server_domain = server_ip;
  3396. }
  3397. mg_snprintf(conn,
  3398. &truncated,
  3399. buf,
  3400. buflen,
  3401. "%s://%s%s%s",
  3402. proto,
  3403. server_domain,
  3404. portstr,
  3405. ri->local_uri);
  3406. if (truncated) {
  3407. return -1;
  3408. }
  3409. return 0;
  3410. }
  3411. }
  3412. }
  3413. /* Skip the characters until one of the delimiters characters found.
  3414. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3415. * Advance pointer to buffer to the next word. Return found 0-terminated
  3416. * word.
  3417. * Delimiters can be quoted with quotechar. */
  3418. static char *
  3419. skip_quoted(char **buf,
  3420. const char *delimiters,
  3421. const char *whitespace,
  3422. char quotechar)
  3423. {
  3424. char *p, *begin_word, *end_word, *end_whitespace;
  3425. begin_word = *buf;
  3426. end_word = begin_word + strcspn(begin_word, delimiters);
  3427. /* Check for quotechar */
  3428. if (end_word > begin_word) {
  3429. p = end_word - 1;
  3430. while (*p == quotechar) {
  3431. /* While the delimiter is quoted, look for the next delimiter.
  3432. */
  3433. /* This happens, e.g., in calls from parse_auth_header,
  3434. * if the user name contains a " character. */
  3435. /* If there is anything beyond end_word, copy it. */
  3436. if (*end_word != '\0') {
  3437. size_t end_off = strcspn(end_word + 1, delimiters);
  3438. memmove(p, end_word, end_off + 1);
  3439. p += end_off; /* p must correspond to end_word - 1 */
  3440. end_word += end_off + 1;
  3441. } else {
  3442. *p = '\0';
  3443. break;
  3444. }
  3445. }
  3446. for (p++; p < end_word; p++) {
  3447. *p = '\0';
  3448. }
  3449. }
  3450. if (*end_word == '\0') {
  3451. *buf = end_word;
  3452. } else {
  3453. #if defined(GCC_DIAGNOSTIC)
  3454. /* Disable spurious conversion warning for GCC */
  3455. #pragma GCC diagnostic push
  3456. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3457. #endif /* defined(GCC_DIAGNOSTIC) */
  3458. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3459. #if defined(GCC_DIAGNOSTIC)
  3460. #pragma GCC diagnostic pop
  3461. #endif /* defined(GCC_DIAGNOSTIC) */
  3462. for (p = end_word; p < end_whitespace; p++) {
  3463. *p = '\0';
  3464. }
  3465. *buf = end_whitespace;
  3466. }
  3467. return begin_word;
  3468. }
  3469. /* Return HTTP header value, or NULL if not found. */
  3470. static const char *
  3471. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3472. {
  3473. int i;
  3474. for (i = 0; i < num_hdr; i++) {
  3475. if (!mg_strcasecmp(name, hdr[i].name)) {
  3476. return hdr[i].value;
  3477. }
  3478. }
  3479. return NULL;
  3480. }
  3481. #if defined(USE_WEBSOCKET)
  3482. /* Retrieve requested HTTP header multiple values, and return the number of
  3483. * found occurrences */
  3484. static int
  3485. get_req_headers(const struct mg_request_info *ri,
  3486. const char *name,
  3487. const char **output,
  3488. int output_max_size)
  3489. {
  3490. int i;
  3491. int cnt = 0;
  3492. if (ri) {
  3493. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3494. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3495. output[cnt++] = ri->http_headers[i].value;
  3496. }
  3497. }
  3498. }
  3499. return cnt;
  3500. }
  3501. #endif
  3502. const char *
  3503. mg_get_header(const struct mg_connection *conn, const char *name)
  3504. {
  3505. if (!conn) {
  3506. return NULL;
  3507. }
  3508. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3509. return get_header(conn->request_info.http_headers,
  3510. conn->request_info.num_headers,
  3511. name);
  3512. }
  3513. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3514. return get_header(conn->response_info.http_headers,
  3515. conn->response_info.num_headers,
  3516. name);
  3517. }
  3518. return NULL;
  3519. }
  3520. static const char *
  3521. get_http_version(const struct mg_connection *conn)
  3522. {
  3523. if (!conn) {
  3524. return NULL;
  3525. }
  3526. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3527. return conn->request_info.http_version;
  3528. }
  3529. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3530. return conn->response_info.http_version;
  3531. }
  3532. return NULL;
  3533. }
  3534. /* A helper function for traversing a comma separated list of values.
  3535. * It returns a list pointer shifted to the next value, or NULL if the end
  3536. * of the list found.
  3537. * Value is stored in val vector. If value has form "x=y", then eq_val
  3538. * vector is initialized to point to the "y" part, and val vector length
  3539. * is adjusted to point only to "x". */
  3540. static const char *
  3541. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3542. {
  3543. int end;
  3544. reparse:
  3545. if (val == NULL || list == NULL || *list == '\0') {
  3546. /* End of the list */
  3547. return NULL;
  3548. }
  3549. /* Skip over leading LWS */
  3550. while (*list == ' ' || *list == '\t')
  3551. list++;
  3552. val->ptr = list;
  3553. if ((list = strchr(val->ptr, ',')) != NULL) {
  3554. /* Comma found. Store length and shift the list ptr */
  3555. val->len = ((size_t)(list - val->ptr));
  3556. list++;
  3557. } else {
  3558. /* This value is the last one */
  3559. list = val->ptr + strlen(val->ptr);
  3560. val->len = ((size_t)(list - val->ptr));
  3561. }
  3562. /* Adjust length for trailing LWS */
  3563. end = (int)val->len - 1;
  3564. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3565. end--;
  3566. val->len = (size_t)(end) + (size_t)(1);
  3567. if (val->len == 0) {
  3568. /* Ignore any empty entries. */
  3569. goto reparse;
  3570. }
  3571. if (eq_val != NULL) {
  3572. /* Value has form "x=y", adjust pointers and lengths
  3573. * so that val points to "x", and eq_val points to "y". */
  3574. eq_val->len = 0;
  3575. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3576. if (eq_val->ptr != NULL) {
  3577. eq_val->ptr++; /* Skip over '=' character */
  3578. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3579. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3580. }
  3581. }
  3582. return list;
  3583. }
  3584. /* A helper function for checking if a comma separated list of values
  3585. * contains
  3586. * the given option (case insensitvely).
  3587. * 'header' can be NULL, in which case false is returned. */
  3588. static int
  3589. header_has_option(const char *header, const char *option)
  3590. {
  3591. struct vec opt_vec;
  3592. struct vec eq_vec;
  3593. DEBUG_ASSERT(option != NULL);
  3594. DEBUG_ASSERT(option[0] != '\0');
  3595. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3596. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3597. return 1;
  3598. }
  3599. return 0;
  3600. }
  3601. /* Perform case-insensitive match of string against pattern */
  3602. static ptrdiff_t
  3603. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3604. {
  3605. const char *or_str;
  3606. ptrdiff_t i, j, len, res;
  3607. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3608. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3609. return (res > 0) ? res
  3610. : match_prefix(or_str + 1,
  3611. (size_t)((pattern + pattern_len)
  3612. - (or_str + 1)),
  3613. str);
  3614. }
  3615. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3616. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3617. continue;
  3618. } else if (pattern[i] == '$') {
  3619. return (str[j] == '\0') ? j : -1;
  3620. } else if (pattern[i] == '*') {
  3621. i++;
  3622. if (pattern[i] == '*') {
  3623. i++;
  3624. len = strlen(str + j);
  3625. } else {
  3626. len = strcspn(str + j, "/");
  3627. }
  3628. if (i == (ptrdiff_t)pattern_len) {
  3629. return j + len;
  3630. }
  3631. do {
  3632. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3633. } while (res == -1 && len-- > 0);
  3634. return (res == -1) ? -1 : j + res + len;
  3635. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3636. return -1;
  3637. }
  3638. }
  3639. return (ptrdiff_t)j;
  3640. }
  3641. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3642. * This function must tolerate situations when connection info is not
  3643. * set up, for example if request parsing failed. */
  3644. static int
  3645. should_keep_alive(const struct mg_connection *conn)
  3646. {
  3647. const char *http_version;
  3648. const char *header;
  3649. /* First satisfy needs of the server */
  3650. if ((conn == NULL) || conn->must_close) {
  3651. /* Close, if civetweb framework needs to close */
  3652. return 0;
  3653. }
  3654. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3655. /* Close, if keep alive is not enabled */
  3656. return 0;
  3657. }
  3658. /* Check explicit wish of the client */
  3659. header = mg_get_header(conn, "Connection");
  3660. if (header) {
  3661. /* If there is a connection header from the client, obey */
  3662. if (header_has_option(header, "keep-alive")) {
  3663. return 1;
  3664. }
  3665. return 0;
  3666. }
  3667. /* Use default of the standard */
  3668. http_version = get_http_version(conn);
  3669. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3670. /* HTTP 1.1 default is keep alive */
  3671. return 1;
  3672. }
  3673. /* HTTP 1.0 (and earlier) default is to close the connection */
  3674. return 0;
  3675. }
  3676. static int
  3677. should_decode_url(const struct mg_connection *conn)
  3678. {
  3679. if (!conn || !conn->dom_ctx) {
  3680. return 0;
  3681. }
  3682. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3683. }
  3684. static const char *
  3685. suggest_connection_header(const struct mg_connection *conn)
  3686. {
  3687. return should_keep_alive(conn) ? "keep-alive" : "close";
  3688. }
  3689. static int
  3690. send_no_cache_header(struct mg_connection *conn)
  3691. {
  3692. /* Send all current and obsolete cache opt-out directives. */
  3693. return mg_printf(conn,
  3694. "Cache-Control: no-cache, no-store, "
  3695. "must-revalidate, private, max-age=0\r\n"
  3696. "Pragma: no-cache\r\n"
  3697. "Expires: 0\r\n");
  3698. }
  3699. static int
  3700. send_static_cache_header(struct mg_connection *conn)
  3701. {
  3702. #if !defined(NO_CACHING)
  3703. int max_age;
  3704. const char *cache_control =
  3705. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3706. if (cache_control != NULL) {
  3707. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3708. }
  3709. /* Read the server config to check how long a file may be cached.
  3710. * The configuration is in seconds. */
  3711. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3712. if (max_age <= 0) {
  3713. /* 0 means "do not cache". All values <0 are reserved
  3714. * and may be used differently in the future. */
  3715. /* If a file should not be cached, do not only send
  3716. * max-age=0, but also pragmas and Expires headers. */
  3717. return send_no_cache_header(conn);
  3718. }
  3719. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3720. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3721. /* See also https://www.mnot.net/cache_docs/ */
  3722. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3723. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3724. * leap
  3725. * year to 31622400 seconds. For the moment, we just send whatever has
  3726. * been configured, still the behavior for >1 year should be considered
  3727. * as undefined. */
  3728. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3729. #else /* NO_CACHING */
  3730. return send_no_cache_header(conn);
  3731. #endif /* !NO_CACHING */
  3732. }
  3733. static int
  3734. send_additional_header(struct mg_connection *conn)
  3735. {
  3736. int i = 0;
  3737. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3738. #if !defined(NO_SSL)
  3739. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3740. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3741. if (max_age >= 0) {
  3742. i += mg_printf(conn,
  3743. "Strict-Transport-Security: max-age=%u\r\n",
  3744. (unsigned)max_age);
  3745. }
  3746. }
  3747. #endif
  3748. if (header && header[0]) {
  3749. i += mg_printf(conn, "%s\r\n", header);
  3750. }
  3751. return i;
  3752. }
  3753. #if !defined(NO_FILESYSTEMS)
  3754. static void handle_file_based_request(struct mg_connection *conn,
  3755. const char *path,
  3756. struct mg_file *filep);
  3757. #endif /* NO_FILESYSTEMS */
  3758. const char *
  3759. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3760. {
  3761. /* See IANA HTTP status code assignment:
  3762. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3763. */
  3764. switch (response_code) {
  3765. /* RFC2616 Section 10.1 - Informational 1xx */
  3766. case 100:
  3767. return "Continue"; /* RFC2616 Section 10.1.1 */
  3768. case 101:
  3769. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3770. case 102:
  3771. return "Processing"; /* RFC2518 Section 10.1 */
  3772. /* RFC2616 Section 10.2 - Successful 2xx */
  3773. case 200:
  3774. return "OK"; /* RFC2616 Section 10.2.1 */
  3775. case 201:
  3776. return "Created"; /* RFC2616 Section 10.2.2 */
  3777. case 202:
  3778. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3779. case 203:
  3780. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3781. case 204:
  3782. return "No Content"; /* RFC2616 Section 10.2.5 */
  3783. case 205:
  3784. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3785. case 206:
  3786. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3787. case 207:
  3788. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3789. */
  3790. case 208:
  3791. return "Already Reported"; /* RFC5842 Section 7.1 */
  3792. case 226:
  3793. return "IM used"; /* RFC3229 Section 10.4.1 */
  3794. /* RFC2616 Section 10.3 - Redirection 3xx */
  3795. case 300:
  3796. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3797. case 301:
  3798. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3799. case 302:
  3800. return "Found"; /* RFC2616 Section 10.3.3 */
  3801. case 303:
  3802. return "See Other"; /* RFC2616 Section 10.3.4 */
  3803. case 304:
  3804. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3805. case 305:
  3806. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3807. case 307:
  3808. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3809. case 308:
  3810. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3811. /* RFC2616 Section 10.4 - Client Error 4xx */
  3812. case 400:
  3813. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3814. case 401:
  3815. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3816. case 402:
  3817. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3818. case 403:
  3819. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3820. case 404:
  3821. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3822. case 405:
  3823. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3824. case 406:
  3825. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3826. case 407:
  3827. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3828. case 408:
  3829. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3830. case 409:
  3831. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3832. case 410:
  3833. return "Gone"; /* RFC2616 Section 10.4.11 */
  3834. case 411:
  3835. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3836. case 412:
  3837. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3838. case 413:
  3839. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3840. case 414:
  3841. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3842. case 415:
  3843. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3844. case 416:
  3845. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3846. */
  3847. case 417:
  3848. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3849. case 421:
  3850. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3851. case 422:
  3852. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3853. * Section 11.2 */
  3854. case 423:
  3855. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3856. case 424:
  3857. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3858. * Section 11.4 */
  3859. case 426:
  3860. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3861. case 428:
  3862. return "Precondition Required"; /* RFC 6585, Section 3 */
  3863. case 429:
  3864. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3865. case 431:
  3866. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3867. case 451:
  3868. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3869. * Section 3 */
  3870. /* RFC2616 Section 10.5 - Server Error 5xx */
  3871. case 500:
  3872. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3873. case 501:
  3874. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3875. case 502:
  3876. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3877. case 503:
  3878. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3879. case 504:
  3880. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3881. case 505:
  3882. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3883. case 506:
  3884. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3885. case 507:
  3886. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3887. * Section 11.5 */
  3888. case 508:
  3889. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3890. case 510:
  3891. return "Not Extended"; /* RFC 2774, Section 7 */
  3892. case 511:
  3893. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3894. /* Other status codes, not shown in the IANA HTTP status code
  3895. * assignment.
  3896. * E.g., "de facto" standards due to common use, ... */
  3897. case 418:
  3898. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3899. case 419:
  3900. return "Authentication Timeout"; /* common use */
  3901. case 420:
  3902. return "Enhance Your Calm"; /* common use */
  3903. case 440:
  3904. return "Login Timeout"; /* common use */
  3905. case 509:
  3906. return "Bandwidth Limit Exceeded"; /* common use */
  3907. default:
  3908. /* This error code is unknown. This should not happen. */
  3909. if (conn) {
  3910. mg_cry_internal(conn,
  3911. "Unknown HTTP response code: %u",
  3912. response_code);
  3913. }
  3914. /* Return at least a category according to RFC 2616 Section 10. */
  3915. if (response_code >= 100 && response_code < 200) {
  3916. /* Unknown informational status code */
  3917. return "Information";
  3918. }
  3919. if (response_code >= 200 && response_code < 300) {
  3920. /* Unknown success code */
  3921. return "Success";
  3922. }
  3923. if (response_code >= 300 && response_code < 400) {
  3924. /* Unknown redirection code */
  3925. return "Redirection";
  3926. }
  3927. if (response_code >= 400 && response_code < 500) {
  3928. /* Unknown request error code */
  3929. return "Client Error";
  3930. }
  3931. if (response_code >= 500 && response_code < 600) {
  3932. /* Unknown server error code */
  3933. return "Server Error";
  3934. }
  3935. /* Response code not even within reasonable range */
  3936. return "";
  3937. }
  3938. }
  3939. static int
  3940. mg_send_http_error_impl(struct mg_connection *conn,
  3941. int status,
  3942. const char *fmt,
  3943. va_list args)
  3944. {
  3945. char errmsg_buf[MG_BUF_LEN];
  3946. va_list ap;
  3947. int has_body;
  3948. char date[64];
  3949. time_t curtime = time(NULL);
  3950. #if !defined(NO_FILESYSTEMS)
  3951. char path_buf[PATH_MAX];
  3952. int len, i, page_handler_found, scope, truncated;
  3953. const char *error_handler = NULL;
  3954. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3955. const char *error_page_file_ext, *tstr;
  3956. #endif /* NO_FILESYSTEMS */
  3957. int handled_by_callback = 0;
  3958. const char *status_text = mg_get_response_code_text(conn, status);
  3959. if ((conn == NULL) || (fmt == NULL)) {
  3960. return -2;
  3961. }
  3962. /* Set status (for log) */
  3963. conn->status_code = status;
  3964. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3965. has_body = ((status > 199) && (status != 204) && (status != 304));
  3966. /* Prepare message in buf, if required */
  3967. if (has_body
  3968. || (!conn->in_error_handler
  3969. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3970. /* Store error message in errmsg_buf */
  3971. va_copy(ap, args);
  3972. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3973. va_end(ap);
  3974. /* In a debug build, print all html errors */
  3975. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3976. }
  3977. /* If there is a http_error callback, call it.
  3978. * But don't do it recursively, if callback calls mg_send_http_error again.
  3979. */
  3980. if (!conn->in_error_handler
  3981. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3982. /* Mark in_error_handler to avoid recursion and call user callback. */
  3983. conn->in_error_handler = 1;
  3984. handled_by_callback =
  3985. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3986. == 0);
  3987. conn->in_error_handler = 0;
  3988. }
  3989. if (!handled_by_callback) {
  3990. /* Check for recursion */
  3991. if (conn->in_error_handler) {
  3992. DEBUG_TRACE(
  3993. "Recursion when handling error %u - fall back to default",
  3994. status);
  3995. #if !defined(NO_FILESYSTEMS)
  3996. } else {
  3997. /* Send user defined error pages, if defined */
  3998. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3999. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4000. page_handler_found = 0;
  4001. if (error_handler != NULL) {
  4002. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4003. switch (scope) {
  4004. case 1: /* Handler for specific error, e.g. 404 error */
  4005. mg_snprintf(conn,
  4006. &truncated,
  4007. path_buf,
  4008. sizeof(path_buf) - 32,
  4009. "%serror%03u.",
  4010. error_handler,
  4011. status);
  4012. break;
  4013. case 2: /* Handler for error group, e.g., 5xx error
  4014. * handler
  4015. * for all server errors (500-599) */
  4016. mg_snprintf(conn,
  4017. &truncated,
  4018. path_buf,
  4019. sizeof(path_buf) - 32,
  4020. "%serror%01uxx.",
  4021. error_handler,
  4022. status / 100);
  4023. break;
  4024. default: /* Handler for all errors */
  4025. mg_snprintf(conn,
  4026. &truncated,
  4027. path_buf,
  4028. sizeof(path_buf) - 32,
  4029. "%serror.",
  4030. error_handler);
  4031. break;
  4032. }
  4033. /* String truncation in buf may only occur if
  4034. * error_handler is too long. This string is
  4035. * from the config, not from a client. */
  4036. (void)truncated;
  4037. len = (int)strlen(path_buf);
  4038. tstr = strchr(error_page_file_ext, '.');
  4039. while (tstr) {
  4040. for (i = 1;
  4041. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4042. i++) {
  4043. /* buffer overrun is not possible here, since
  4044. * (i < 32) && (len < sizeof(path_buf) - 32)
  4045. * ==> (i + len) < sizeof(path_buf) */
  4046. path_buf[len + i - 1] = tstr[i];
  4047. }
  4048. /* buffer overrun is not possible here, since
  4049. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4050. * ==> (i + len) <= sizeof(path_buf) */
  4051. path_buf[len + i - 1] = 0;
  4052. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4053. DEBUG_TRACE("Check error page %s - found",
  4054. path_buf);
  4055. page_handler_found = 1;
  4056. break;
  4057. }
  4058. DEBUG_TRACE("Check error page %s - not found",
  4059. path_buf);
  4060. tstr = strchr(tstr + i, '.');
  4061. }
  4062. }
  4063. }
  4064. if (page_handler_found) {
  4065. conn->in_error_handler = 1;
  4066. handle_file_based_request(conn, path_buf, &error_page_file);
  4067. conn->in_error_handler = 0;
  4068. return 0;
  4069. }
  4070. #endif /* NO_FILESYSTEMS */
  4071. }
  4072. /* No custom error page. Send default error page. */
  4073. gmt_time_string(date, sizeof(date), &curtime);
  4074. conn->must_close = 1;
  4075. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4076. send_no_cache_header(conn);
  4077. send_additional_header(conn);
  4078. if (has_body) {
  4079. mg_printf(conn,
  4080. "%s",
  4081. "Content-Type: text/plain; charset=utf-8\r\n");
  4082. }
  4083. mg_printf(conn,
  4084. "Date: %s\r\n"
  4085. "Connection: close\r\n\r\n",
  4086. date);
  4087. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4088. if (has_body) {
  4089. /* For other errors, send a generic error message. */
  4090. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4091. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4092. } else {
  4093. /* No body allowed. Close the connection. */
  4094. DEBUG_TRACE("Error %i", status);
  4095. }
  4096. }
  4097. return 0;
  4098. }
  4099. int
  4100. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4101. {
  4102. va_list ap;
  4103. int ret;
  4104. va_start(ap, fmt);
  4105. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4106. va_end(ap);
  4107. return ret;
  4108. }
  4109. int
  4110. mg_send_http_ok(struct mg_connection *conn,
  4111. const char *mime_type,
  4112. long long content_length)
  4113. {
  4114. char date[64];
  4115. time_t curtime = time(NULL);
  4116. if ((mime_type == NULL) || (*mime_type == 0)) {
  4117. /* Parameter error */
  4118. return -2;
  4119. }
  4120. gmt_time_string(date, sizeof(date), &curtime);
  4121. mg_printf(conn,
  4122. "HTTP/1.1 200 OK\r\n"
  4123. "Content-Type: %s\r\n"
  4124. "Date: %s\r\n"
  4125. "Connection: %s\r\n",
  4126. mime_type,
  4127. date,
  4128. suggest_connection_header(conn));
  4129. send_no_cache_header(conn);
  4130. send_additional_header(conn);
  4131. if (content_length < 0) {
  4132. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4133. } else {
  4134. mg_printf(conn,
  4135. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4136. (uint64_t)content_length);
  4137. }
  4138. return 0;
  4139. }
  4140. int
  4141. mg_send_http_redirect(struct mg_connection *conn,
  4142. const char *target_url,
  4143. int redirect_code)
  4144. {
  4145. /* Send a 30x redirect response.
  4146. *
  4147. * Redirect types (status codes):
  4148. *
  4149. * Status | Perm/Temp | Method | Version
  4150. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4151. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4152. * 303 | temporary | always use GET | HTTP/1.1
  4153. * 307 | temporary | always keep method | HTTP/1.1
  4154. * 308 | permanent | always keep method | HTTP/1.1
  4155. */
  4156. const char *redirect_text;
  4157. int ret;
  4158. size_t content_len = 0;
  4159. char reply[MG_BUF_LEN];
  4160. /* In case redirect_code=0, use 307. */
  4161. if (redirect_code == 0) {
  4162. redirect_code = 307;
  4163. }
  4164. /* In case redirect_code is none of the above, return error. */
  4165. if ((redirect_code != 301) && (redirect_code != 302)
  4166. && (redirect_code != 303) && (redirect_code != 307)
  4167. && (redirect_code != 308)) {
  4168. /* Parameter error */
  4169. return -2;
  4170. }
  4171. /* Get proper text for response code */
  4172. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4173. /* If target_url is not defined, redirect to "/". */
  4174. if ((target_url == NULL) || (*target_url == 0)) {
  4175. target_url = "/";
  4176. }
  4177. #if defined(MG_SEND_REDIRECT_BODY)
  4178. /* TODO: condition name? */
  4179. /* Prepare a response body with a hyperlink.
  4180. *
  4181. * According to RFC2616 (and RFC1945 before):
  4182. * Unless the request method was HEAD, the entity of the
  4183. * response SHOULD contain a short hypertext note with a hyperlink to
  4184. * the new URI(s).
  4185. *
  4186. * However, this response body is not useful in M2M communication.
  4187. * Probably the original reason in the RFC was, clients not supporting
  4188. * a 30x HTTP redirect could still show the HTML page and let the user
  4189. * press the link. Since current browsers support 30x HTTP, the additional
  4190. * HTML body does not seem to make sense anymore.
  4191. *
  4192. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4193. * but it only notes:
  4194. * The server's response payload usually contains a short
  4195. * hypertext note with a hyperlink to the new URI(s).
  4196. *
  4197. * Deactivated by default. If you need the 30x body, set the define.
  4198. */
  4199. mg_snprintf(
  4200. conn,
  4201. NULL /* ignore truncation */,
  4202. reply,
  4203. sizeof(reply),
  4204. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4205. redirect_text,
  4206. target_url,
  4207. target_url);
  4208. content_len = strlen(reply);
  4209. #else
  4210. reply[0] = 0;
  4211. #endif
  4212. /* Do not send any additional header. For all other options,
  4213. * including caching, there are suitable defaults. */
  4214. ret = mg_printf(conn,
  4215. "HTTP/1.1 %i %s\r\n"
  4216. "Location: %s\r\n"
  4217. "Content-Length: %u\r\n"
  4218. "Connection: %s\r\n\r\n",
  4219. redirect_code,
  4220. redirect_text,
  4221. target_url,
  4222. (unsigned int)content_len,
  4223. suggest_connection_header(conn));
  4224. /* Send response body */
  4225. if (ret > 0) {
  4226. /* ... unless it is a HEAD request */
  4227. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4228. ret = mg_write(conn, reply, content_len);
  4229. }
  4230. }
  4231. return (ret > 0) ? ret : -1;
  4232. }
  4233. #if defined(_WIN32)
  4234. /* Create substitutes for POSIX functions in Win32. */
  4235. #if defined(GCC_DIAGNOSTIC)
  4236. /* Show no warning in case system functions are not used. */
  4237. #pragma GCC diagnostic push
  4238. #pragma GCC diagnostic ignored "-Wunused-function"
  4239. #endif
  4240. static int
  4241. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4242. {
  4243. (void)unused;
  4244. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4245. InitializeCriticalSection(&mutex->sec);
  4246. return 0;
  4247. }
  4248. static int
  4249. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4250. {
  4251. DeleteCriticalSection(&mutex->sec);
  4252. return 0;
  4253. }
  4254. static int
  4255. pthread_mutex_lock(pthread_mutex_t *mutex)
  4256. {
  4257. EnterCriticalSection(&mutex->sec);
  4258. return 0;
  4259. }
  4260. static int
  4261. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4262. {
  4263. LeaveCriticalSection(&mutex->sec);
  4264. return 0;
  4265. }
  4266. FUNCTION_MAY_BE_UNUSED
  4267. static int
  4268. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4269. {
  4270. (void)unused;
  4271. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4272. cv->waiting_thread = NULL;
  4273. return 0;
  4274. }
  4275. FUNCTION_MAY_BE_UNUSED
  4276. static int
  4277. pthread_cond_timedwait(pthread_cond_t *cv,
  4278. pthread_mutex_t *mutex,
  4279. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4280. {
  4281. struct mg_workerTLS **ptls,
  4282. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4283. int ok;
  4284. int64_t nsnow, nswaitabs, nswaitrel;
  4285. DWORD mswaitrel;
  4286. pthread_mutex_lock(&cv->threadIdSec);
  4287. /* Add this thread to cv's waiting list */
  4288. ptls = &cv->waiting_thread;
  4289. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4290. ;
  4291. tls->next_waiting_thread = NULL;
  4292. *ptls = tls;
  4293. pthread_mutex_unlock(&cv->threadIdSec);
  4294. if (abstime) {
  4295. nsnow = mg_get_current_time_ns();
  4296. nswaitabs =
  4297. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4298. nswaitrel = nswaitabs - nsnow;
  4299. if (nswaitrel < 0) {
  4300. nswaitrel = 0;
  4301. }
  4302. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4303. } else {
  4304. mswaitrel = (DWORD)INFINITE;
  4305. }
  4306. pthread_mutex_unlock(mutex);
  4307. ok = (WAIT_OBJECT_0
  4308. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4309. if (!ok) {
  4310. ok = 1;
  4311. pthread_mutex_lock(&cv->threadIdSec);
  4312. ptls = &cv->waiting_thread;
  4313. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4314. if (*ptls == tls) {
  4315. *ptls = tls->next_waiting_thread;
  4316. ok = 0;
  4317. break;
  4318. }
  4319. }
  4320. pthread_mutex_unlock(&cv->threadIdSec);
  4321. if (ok) {
  4322. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4323. (DWORD)INFINITE);
  4324. }
  4325. }
  4326. /* This thread has been removed from cv's waiting list */
  4327. pthread_mutex_lock(mutex);
  4328. return ok ? 0 : -1;
  4329. }
  4330. FUNCTION_MAY_BE_UNUSED
  4331. static int
  4332. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4333. {
  4334. return pthread_cond_timedwait(cv, mutex, NULL);
  4335. }
  4336. FUNCTION_MAY_BE_UNUSED
  4337. static int
  4338. pthread_cond_signal(pthread_cond_t *cv)
  4339. {
  4340. HANDLE wkup = NULL;
  4341. BOOL ok = FALSE;
  4342. pthread_mutex_lock(&cv->threadIdSec);
  4343. if (cv->waiting_thread) {
  4344. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4345. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4346. ok = SetEvent(wkup);
  4347. DEBUG_ASSERT(ok);
  4348. }
  4349. pthread_mutex_unlock(&cv->threadIdSec);
  4350. return ok ? 0 : 1;
  4351. }
  4352. FUNCTION_MAY_BE_UNUSED
  4353. static int
  4354. pthread_cond_broadcast(pthread_cond_t *cv)
  4355. {
  4356. pthread_mutex_lock(&cv->threadIdSec);
  4357. while (cv->waiting_thread) {
  4358. pthread_cond_signal(cv);
  4359. }
  4360. pthread_mutex_unlock(&cv->threadIdSec);
  4361. return 0;
  4362. }
  4363. FUNCTION_MAY_BE_UNUSED
  4364. static int
  4365. pthread_cond_destroy(pthread_cond_t *cv)
  4366. {
  4367. pthread_mutex_lock(&cv->threadIdSec);
  4368. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4369. pthread_mutex_unlock(&cv->threadIdSec);
  4370. pthread_mutex_destroy(&cv->threadIdSec);
  4371. return 0;
  4372. }
  4373. #if defined(ALTERNATIVE_QUEUE)
  4374. FUNCTION_MAY_BE_UNUSED
  4375. static void *
  4376. event_create(void)
  4377. {
  4378. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4379. }
  4380. FUNCTION_MAY_BE_UNUSED
  4381. static int
  4382. event_wait(void *eventhdl)
  4383. {
  4384. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4385. return (res == WAIT_OBJECT_0);
  4386. }
  4387. FUNCTION_MAY_BE_UNUSED
  4388. static int
  4389. event_signal(void *eventhdl)
  4390. {
  4391. return (int)SetEvent((HANDLE)eventhdl);
  4392. }
  4393. FUNCTION_MAY_BE_UNUSED
  4394. static void
  4395. event_destroy(void *eventhdl)
  4396. {
  4397. CloseHandle((HANDLE)eventhdl);
  4398. }
  4399. #endif
  4400. #if defined(GCC_DIAGNOSTIC)
  4401. /* Enable unused function warning again */
  4402. #pragma GCC diagnostic pop
  4403. #endif
  4404. /* For Windows, change all slashes to backslashes in path names. */
  4405. static void
  4406. change_slashes_to_backslashes(char *path)
  4407. {
  4408. int i;
  4409. for (i = 0; path[i] != '\0'; i++) {
  4410. if (path[i] == '/') {
  4411. path[i] = '\\';
  4412. }
  4413. /* remove double backslash (check i > 0 to preserve UNC paths,
  4414. * like \\server\file.txt) */
  4415. if ((path[i] == '\\') && (i > 0)) {
  4416. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4417. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4418. }
  4419. }
  4420. }
  4421. }
  4422. static int
  4423. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4424. {
  4425. int diff;
  4426. do {
  4427. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4428. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4429. s1++;
  4430. s2++;
  4431. } while ((diff == 0) && (s1[-1] != L'\0'));
  4432. return diff;
  4433. }
  4434. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4435. * wbuf and wbuf_len is a target buffer and its length. */
  4436. static void
  4437. path_to_unicode(const struct mg_connection *conn,
  4438. const char *path,
  4439. wchar_t *wbuf,
  4440. size_t wbuf_len)
  4441. {
  4442. char buf[PATH_MAX], buf2[PATH_MAX];
  4443. wchar_t wbuf2[W_PATH_MAX + 1];
  4444. DWORD long_len, err;
  4445. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4446. mg_strlcpy(buf, path, sizeof(buf));
  4447. change_slashes_to_backslashes(buf);
  4448. /* Convert to Unicode and back. If doubly-converted string does not
  4449. * match the original, something is fishy, reject. */
  4450. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4451. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4452. WideCharToMultiByte(
  4453. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4454. if (strcmp(buf, buf2) != 0) {
  4455. wbuf[0] = L'\0';
  4456. }
  4457. /* Windows file systems are not case sensitive, but you can still use
  4458. * uppercase and lowercase letters (on all modern file systems).
  4459. * The server can check if the URI uses the same upper/lowercase
  4460. * letters an the file system, effectively making Windows servers
  4461. * case sensitive (like Linux servers are). It is still not possible
  4462. * to use two files with the same name in different cases on Windows
  4463. * (like /a and /A) - this would be possible in Linux.
  4464. * As a default, Windows is not case sensitive, but the case sensitive
  4465. * file name check can be activated by an additional configuration. */
  4466. if (conn) {
  4467. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4468. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4469. "yes")) {
  4470. /* Use case sensitive compare function */
  4471. fcompare = wcscmp;
  4472. }
  4473. }
  4474. (void)conn; /* conn is currently unused */
  4475. #if !defined(_WIN32_WCE)
  4476. /* Only accept a full file path, not a Windows short (8.3) path. */
  4477. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4478. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4479. if (long_len == 0) {
  4480. err = GetLastError();
  4481. if (err == ERROR_FILE_NOT_FOUND) {
  4482. /* File does not exist. This is not always a problem here. */
  4483. return;
  4484. }
  4485. }
  4486. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4487. /* Short name is used. */
  4488. wbuf[0] = L'\0';
  4489. }
  4490. #else
  4491. (void)long_len;
  4492. (void)wbuf2;
  4493. (void)err;
  4494. if (strchr(path, '~')) {
  4495. wbuf[0] = L'\0';
  4496. }
  4497. #endif
  4498. }
  4499. #if !defined(NO_FILESYSTEMS)
  4500. static int
  4501. mg_stat(const struct mg_connection *conn,
  4502. const char *path,
  4503. struct mg_file_stat *filep)
  4504. {
  4505. wchar_t wbuf[W_PATH_MAX];
  4506. WIN32_FILE_ATTRIBUTE_DATA info;
  4507. time_t creation_time;
  4508. size_t len;
  4509. if (!filep) {
  4510. return 0;
  4511. }
  4512. memset(filep, 0, sizeof(*filep));
  4513. if (conn && is_file_in_memory(conn, path)) {
  4514. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4515. * memset */
  4516. /* Quick fix (for 1.9.x): */
  4517. /* mg_stat must fill all fields, also for files in memory */
  4518. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4519. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4520. filep->size = tmp_file.stat.size;
  4521. filep->location = 2;
  4522. /* TODO: for 1.10: restructure how files in memory are handled */
  4523. /* The "file in memory" feature is a candidate for deletion.
  4524. * Please join the discussion at
  4525. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4526. */
  4527. filep->last_modified = time(NULL); /* TODO */
  4528. /* last_modified = now ... assumes the file may change during
  4529. * runtime,
  4530. * so every mg_fopen call may return different data */
  4531. /* last_modified = conn->phys_ctx.start_time;
  4532. * May be used it the data does not change during runtime. This
  4533. * allows
  4534. * browser caching. Since we do not know, we have to assume the file
  4535. * in memory may change. */
  4536. return 1;
  4537. }
  4538. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4539. /* Windows happily opens files with some garbage at the end of file name.
  4540. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4541. * "a.cgi", despite one would expect an error back. */
  4542. len = strlen(path);
  4543. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4544. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4545. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4546. filep->last_modified =
  4547. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4548. info.ftLastWriteTime.dwHighDateTime);
  4549. /* On Windows, the file creation time can be higher than the
  4550. * modification time, e.g. when a file is copied.
  4551. * Since the Last-Modified timestamp is used for caching
  4552. * it should be based on the most recent timestamp. */
  4553. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4554. info.ftCreationTime.dwHighDateTime);
  4555. if (creation_time > filep->last_modified) {
  4556. filep->last_modified = creation_time;
  4557. }
  4558. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4559. return 1;
  4560. }
  4561. return 0;
  4562. }
  4563. #endif
  4564. static int
  4565. mg_remove(const struct mg_connection *conn, const char *path)
  4566. {
  4567. wchar_t wbuf[W_PATH_MAX];
  4568. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4569. return DeleteFileW(wbuf) ? 0 : -1;
  4570. }
  4571. static int
  4572. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4573. {
  4574. wchar_t wbuf[W_PATH_MAX];
  4575. (void)mode;
  4576. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4577. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4578. }
  4579. /* Create substitutes for POSIX functions in Win32. */
  4580. #if defined(GCC_DIAGNOSTIC)
  4581. /* Show no warning in case system functions are not used. */
  4582. #pragma GCC diagnostic push
  4583. #pragma GCC diagnostic ignored "-Wunused-function"
  4584. #endif
  4585. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4586. FUNCTION_MAY_BE_UNUSED
  4587. static DIR *
  4588. mg_opendir(const struct mg_connection *conn, const char *name)
  4589. {
  4590. DIR *dir = NULL;
  4591. wchar_t wpath[W_PATH_MAX];
  4592. DWORD attrs;
  4593. if (name == NULL) {
  4594. SetLastError(ERROR_BAD_ARGUMENTS);
  4595. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4596. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4597. } else {
  4598. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4599. attrs = GetFileAttributesW(wpath);
  4600. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4601. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4602. (void)wcscat(wpath, L"\\*");
  4603. dir->handle = FindFirstFileW(wpath, &dir->info);
  4604. dir->result.d_name[0] = '\0';
  4605. } else {
  4606. mg_free(dir);
  4607. dir = NULL;
  4608. }
  4609. }
  4610. return dir;
  4611. }
  4612. FUNCTION_MAY_BE_UNUSED
  4613. static int
  4614. mg_closedir(DIR *dir)
  4615. {
  4616. int result = 0;
  4617. if (dir != NULL) {
  4618. if (dir->handle != INVALID_HANDLE_VALUE)
  4619. result = FindClose(dir->handle) ? 0 : -1;
  4620. mg_free(dir);
  4621. } else {
  4622. result = -1;
  4623. SetLastError(ERROR_BAD_ARGUMENTS);
  4624. }
  4625. return result;
  4626. }
  4627. FUNCTION_MAY_BE_UNUSED
  4628. static struct dirent *
  4629. mg_readdir(DIR *dir)
  4630. {
  4631. struct dirent *result = 0;
  4632. if (dir) {
  4633. if (dir->handle != INVALID_HANDLE_VALUE) {
  4634. result = &dir->result;
  4635. (void)WideCharToMultiByte(CP_UTF8,
  4636. 0,
  4637. dir->info.cFileName,
  4638. -1,
  4639. result->d_name,
  4640. sizeof(result->d_name),
  4641. NULL,
  4642. NULL);
  4643. if (!FindNextFileW(dir->handle, &dir->info)) {
  4644. (void)FindClose(dir->handle);
  4645. dir->handle = INVALID_HANDLE_VALUE;
  4646. }
  4647. } else {
  4648. SetLastError(ERROR_FILE_NOT_FOUND);
  4649. }
  4650. } else {
  4651. SetLastError(ERROR_BAD_ARGUMENTS);
  4652. }
  4653. return result;
  4654. }
  4655. #if !defined(HAVE_POLL)
  4656. #undef POLLIN
  4657. #undef POLLPRI
  4658. #undef POLLOUT
  4659. #define POLLIN (1) /* Data ready - read will not block. */
  4660. #define POLLPRI (2) /* Priority data ready. */
  4661. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4662. FUNCTION_MAY_BE_UNUSED
  4663. static int
  4664. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4665. {
  4666. struct timeval tv;
  4667. fd_set rset;
  4668. fd_set wset;
  4669. unsigned int i;
  4670. int result;
  4671. SOCKET maxfd = 0;
  4672. memset(&tv, 0, sizeof(tv));
  4673. tv.tv_sec = milliseconds / 1000;
  4674. tv.tv_usec = (milliseconds % 1000) * 1000;
  4675. FD_ZERO(&rset);
  4676. FD_ZERO(&wset);
  4677. for (i = 0; i < n; i++) {
  4678. if (pfd[i].events & POLLIN) {
  4679. FD_SET(pfd[i].fd, &rset);
  4680. }
  4681. if (pfd[i].events & POLLOUT) {
  4682. FD_SET(pfd[i].fd, &wset);
  4683. }
  4684. pfd[i].revents = 0;
  4685. if (pfd[i].fd > maxfd) {
  4686. maxfd = pfd[i].fd;
  4687. }
  4688. }
  4689. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4690. for (i = 0; i < n; i++) {
  4691. if (FD_ISSET(pfd[i].fd, &rset)) {
  4692. pfd[i].revents |= POLLIN;
  4693. }
  4694. if (FD_ISSET(pfd[i].fd, &wset)) {
  4695. pfd[i].revents |= POLLOUT;
  4696. }
  4697. }
  4698. }
  4699. /* We should subtract the time used in select from remaining
  4700. * "milliseconds", in particular if called from mg_poll with a
  4701. * timeout quantum.
  4702. * Unfortunately, the remaining time is not stored in "tv" in all
  4703. * implementations, so the result in "tv" must be considered undefined.
  4704. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4705. return result;
  4706. }
  4707. #endif /* HAVE_POLL */
  4708. #if defined(GCC_DIAGNOSTIC)
  4709. /* Enable unused function warning again */
  4710. #pragma GCC diagnostic pop
  4711. #endif
  4712. static void
  4713. set_close_on_exec(SOCKET sock,
  4714. const struct mg_connection *conn /* may be null */,
  4715. struct mg_context *ctx /* may be null */)
  4716. {
  4717. (void)conn; /* Unused. */
  4718. (void)ctx;
  4719. #if defined(_WIN32_WCE)
  4720. (void)sock;
  4721. #else
  4722. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4723. #endif
  4724. }
  4725. int
  4726. mg_start_thread(mg_thread_func_t f, void *p)
  4727. {
  4728. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4729. /* Compile-time option to control stack size, e.g.
  4730. * -DUSE_STACK_SIZE=16384
  4731. */
  4732. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4733. == ((uintptr_t)(-1L)))
  4734. ? -1
  4735. : 0);
  4736. #else
  4737. return (
  4738. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4739. ? -1
  4740. : 0);
  4741. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4742. }
  4743. /* Start a thread storing the thread context. */
  4744. static int
  4745. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4746. void *p,
  4747. pthread_t *threadidptr)
  4748. {
  4749. uintptr_t uip;
  4750. HANDLE threadhandle;
  4751. int result = -1;
  4752. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4753. threadhandle = (HANDLE)uip;
  4754. if ((uip != 0) && (threadidptr != NULL)) {
  4755. *threadidptr = threadhandle;
  4756. result = 0;
  4757. }
  4758. return result;
  4759. }
  4760. /* Wait for a thread to finish. */
  4761. static int
  4762. mg_join_thread(pthread_t threadid)
  4763. {
  4764. int result;
  4765. DWORD dwevent;
  4766. result = -1;
  4767. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4768. if (dwevent == WAIT_FAILED) {
  4769. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4770. } else {
  4771. if (dwevent == WAIT_OBJECT_0) {
  4772. CloseHandle(threadid);
  4773. result = 0;
  4774. }
  4775. }
  4776. return result;
  4777. }
  4778. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4779. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4780. /* Create substitutes for POSIX functions in Win32. */
  4781. #if defined(GCC_DIAGNOSTIC)
  4782. /* Show no warning in case system functions are not used. */
  4783. #pragma GCC diagnostic push
  4784. #pragma GCC diagnostic ignored "-Wunused-function"
  4785. #endif
  4786. FUNCTION_MAY_BE_UNUSED
  4787. static HANDLE
  4788. dlopen(const char *dll_name, int flags)
  4789. {
  4790. wchar_t wbuf[W_PATH_MAX];
  4791. (void)flags;
  4792. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4793. return LoadLibraryW(wbuf);
  4794. }
  4795. FUNCTION_MAY_BE_UNUSED
  4796. static int
  4797. dlclose(void *handle)
  4798. {
  4799. int result;
  4800. if (FreeLibrary((HMODULE)handle) != 0) {
  4801. result = 0;
  4802. } else {
  4803. result = -1;
  4804. }
  4805. return result;
  4806. }
  4807. #if defined(GCC_DIAGNOSTIC)
  4808. /* Enable unused function warning again */
  4809. #pragma GCC diagnostic pop
  4810. #endif
  4811. #endif
  4812. #if !defined(NO_CGI)
  4813. #define SIGKILL (0)
  4814. static int
  4815. kill(pid_t pid, int sig_num)
  4816. {
  4817. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4818. (void)CloseHandle((HANDLE)pid);
  4819. return 0;
  4820. }
  4821. #if !defined(WNOHANG)
  4822. #define WNOHANG (1)
  4823. #endif
  4824. static pid_t
  4825. waitpid(pid_t pid, int *status, int flags)
  4826. {
  4827. DWORD timeout = INFINITE;
  4828. DWORD waitres;
  4829. (void)status; /* Currently not used by any client here */
  4830. if ((flags | WNOHANG) == WNOHANG) {
  4831. timeout = 0;
  4832. }
  4833. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4834. if (waitres == WAIT_OBJECT_0) {
  4835. return pid;
  4836. }
  4837. if (waitres == WAIT_TIMEOUT) {
  4838. return 0;
  4839. }
  4840. return (pid_t)-1;
  4841. }
  4842. static void
  4843. trim_trailing_whitespaces(char *s)
  4844. {
  4845. char *e = s + strlen(s);
  4846. while ((e > s) && isspace((unsigned char)e[-1])) {
  4847. *(--e) = '\0';
  4848. }
  4849. }
  4850. static pid_t
  4851. spawn_process(struct mg_connection *conn,
  4852. const char *prog,
  4853. char *envblk,
  4854. char *envp[],
  4855. int fdin[2],
  4856. int fdout[2],
  4857. int fderr[2],
  4858. const char *dir)
  4859. {
  4860. HANDLE me;
  4861. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4862. cmdline[PATH_MAX], buf[PATH_MAX];
  4863. int truncated;
  4864. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4865. STARTUPINFOA si;
  4866. PROCESS_INFORMATION pi = {0};
  4867. (void)envp;
  4868. memset(&si, 0, sizeof(si));
  4869. si.cb = sizeof(si);
  4870. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4871. si.wShowWindow = SW_HIDE;
  4872. me = GetCurrentProcess();
  4873. DuplicateHandle(me,
  4874. (HANDLE)_get_osfhandle(fdin[0]),
  4875. me,
  4876. &si.hStdInput,
  4877. 0,
  4878. TRUE,
  4879. DUPLICATE_SAME_ACCESS);
  4880. DuplicateHandle(me,
  4881. (HANDLE)_get_osfhandle(fdout[1]),
  4882. me,
  4883. &si.hStdOutput,
  4884. 0,
  4885. TRUE,
  4886. DUPLICATE_SAME_ACCESS);
  4887. DuplicateHandle(me,
  4888. (HANDLE)_get_osfhandle(fderr[1]),
  4889. me,
  4890. &si.hStdError,
  4891. 0,
  4892. TRUE,
  4893. DUPLICATE_SAME_ACCESS);
  4894. /* Mark handles that should not be inherited. See
  4895. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4896. */
  4897. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4898. HANDLE_FLAG_INHERIT,
  4899. 0);
  4900. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4901. HANDLE_FLAG_INHERIT,
  4902. 0);
  4903. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4904. HANDLE_FLAG_INHERIT,
  4905. 0);
  4906. /* If CGI file is a script, try to read the interpreter line */
  4907. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4908. if (interp == NULL) {
  4909. buf[0] = buf[1] = '\0';
  4910. /* Read the first line of the script into the buffer */
  4911. mg_snprintf(
  4912. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4913. if (truncated) {
  4914. pi.hProcess = (pid_t)-1;
  4915. goto spawn_cleanup;
  4916. }
  4917. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4918. #if defined(MG_USE_OPEN_FILE)
  4919. p = (char *)file.access.membuf;
  4920. #else
  4921. p = (char *)NULL;
  4922. #endif
  4923. mg_fgets(buf, sizeof(buf), &file, &p);
  4924. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4925. buf[sizeof(buf) - 1] = '\0';
  4926. }
  4927. if ((buf[0] == '#') && (buf[1] == '!')) {
  4928. trim_trailing_whitespaces(buf + 2);
  4929. } else {
  4930. buf[2] = '\0';
  4931. }
  4932. interp = buf + 2;
  4933. }
  4934. if (interp[0] != '\0') {
  4935. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4936. interp = full_interp;
  4937. }
  4938. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4939. if (interp[0] != '\0') {
  4940. mg_snprintf(conn,
  4941. &truncated,
  4942. cmdline,
  4943. sizeof(cmdline),
  4944. "\"%s\" \"%s\\%s\"",
  4945. interp,
  4946. full_dir,
  4947. prog);
  4948. } else {
  4949. mg_snprintf(conn,
  4950. &truncated,
  4951. cmdline,
  4952. sizeof(cmdline),
  4953. "\"%s\\%s\"",
  4954. full_dir,
  4955. prog);
  4956. }
  4957. if (truncated) {
  4958. pi.hProcess = (pid_t)-1;
  4959. goto spawn_cleanup;
  4960. }
  4961. DEBUG_TRACE("Running [%s]", cmdline);
  4962. if (CreateProcessA(NULL,
  4963. cmdline,
  4964. NULL,
  4965. NULL,
  4966. TRUE,
  4967. CREATE_NEW_PROCESS_GROUP,
  4968. envblk,
  4969. NULL,
  4970. &si,
  4971. &pi)
  4972. == 0) {
  4973. mg_cry_internal(
  4974. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4975. pi.hProcess = (pid_t)-1;
  4976. /* goto spawn_cleanup; */
  4977. }
  4978. spawn_cleanup:
  4979. (void)CloseHandle(si.hStdOutput);
  4980. (void)CloseHandle(si.hStdError);
  4981. (void)CloseHandle(si.hStdInput);
  4982. if (pi.hThread != NULL) {
  4983. (void)CloseHandle(pi.hThread);
  4984. }
  4985. return (pid_t)pi.hProcess;
  4986. }
  4987. #endif /* !NO_CGI */
  4988. static int
  4989. set_blocking_mode(SOCKET sock)
  4990. {
  4991. unsigned long non_blocking = 0;
  4992. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4993. }
  4994. static int
  4995. set_non_blocking_mode(SOCKET sock)
  4996. {
  4997. unsigned long non_blocking = 1;
  4998. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4999. }
  5000. #else
  5001. #if !defined(NO_FILESYSTEMS)
  5002. static int
  5003. mg_stat(const struct mg_connection *conn,
  5004. const char *path,
  5005. struct mg_file_stat *filep)
  5006. {
  5007. struct stat st;
  5008. if (!filep) {
  5009. return 0;
  5010. }
  5011. memset(filep, 0, sizeof(*filep));
  5012. if (conn && is_file_in_memory(conn, path)) {
  5013. /* Quick fix (for 1.9.x): */
  5014. /* mg_stat must fill all fields, also for files in memory */
  5015. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  5016. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  5017. filep->size = tmp_file.stat.size;
  5018. filep->last_modified = time(NULL);
  5019. filep->location = 2;
  5020. /* TODO: remove legacy "files in memory" feature */
  5021. return 1;
  5022. }
  5023. if (0 == stat(path, &st)) {
  5024. filep->size = (uint64_t)(st.st_size);
  5025. filep->last_modified = st.st_mtime;
  5026. filep->is_directory = S_ISDIR(st.st_mode);
  5027. return 1;
  5028. }
  5029. return 0;
  5030. }
  5031. #endif /* NO_FILESYSTEMS */
  5032. static void
  5033. set_close_on_exec(int fd,
  5034. const struct mg_connection *conn /* may be null */,
  5035. struct mg_context *ctx /* may be null */)
  5036. {
  5037. #if defined(__ZEPHYR__)
  5038. (void)fd;
  5039. (void)conn;
  5040. (void)ctx;
  5041. #else
  5042. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5043. if (conn || ctx) {
  5044. struct mg_connection fc;
  5045. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5046. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5047. __func__,
  5048. strerror(ERRNO));
  5049. }
  5050. }
  5051. #endif
  5052. }
  5053. int
  5054. mg_start_thread(mg_thread_func_t func, void *param)
  5055. {
  5056. pthread_t thread_id;
  5057. pthread_attr_t attr;
  5058. int result;
  5059. (void)pthread_attr_init(&attr);
  5060. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5061. #if defined(__ZEPHYR__)
  5062. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5063. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5064. /* Compile-time option to control stack size,
  5065. * e.g. -DUSE_STACK_SIZE=16384 */
  5066. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5067. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5068. result = pthread_create(&thread_id, &attr, func, param);
  5069. pthread_attr_destroy(&attr);
  5070. return result;
  5071. }
  5072. /* Start a thread storing the thread context. */
  5073. static int
  5074. mg_start_thread_with_id(mg_thread_func_t func,
  5075. void *param,
  5076. pthread_t *threadidptr)
  5077. {
  5078. pthread_t thread_id;
  5079. pthread_attr_t attr;
  5080. int result;
  5081. (void)pthread_attr_init(&attr);
  5082. #if defined(__ZEPHYR__)
  5083. pthread_attr_setstack(&attr,
  5084. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5085. ZEPHYR_STACK_SIZE);
  5086. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5087. /* Compile-time option to control stack size,
  5088. * e.g. -DUSE_STACK_SIZE=16384 */
  5089. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5090. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5091. result = pthread_create(&thread_id, &attr, func, param);
  5092. pthread_attr_destroy(&attr);
  5093. if ((result == 0) && (threadidptr != NULL)) {
  5094. *threadidptr = thread_id;
  5095. }
  5096. return result;
  5097. }
  5098. /* Wait for a thread to finish. */
  5099. static int
  5100. mg_join_thread(pthread_t threadid)
  5101. {
  5102. int result;
  5103. result = pthread_join(threadid, NULL);
  5104. return result;
  5105. }
  5106. #if !defined(NO_CGI)
  5107. static pid_t
  5108. spawn_process(struct mg_connection *conn,
  5109. const char *prog,
  5110. char *envblk,
  5111. char *envp[],
  5112. int fdin[2],
  5113. int fdout[2],
  5114. int fderr[2],
  5115. const char *dir)
  5116. {
  5117. pid_t pid;
  5118. const char *interp;
  5119. (void)envblk;
  5120. if ((pid = fork()) == -1) {
  5121. /* Parent */
  5122. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5123. } else if (pid != 0) {
  5124. /* Make sure children close parent-side descriptors.
  5125. * The caller will close the child-side immediately. */
  5126. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5127. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5128. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5129. } else {
  5130. /* Child */
  5131. if (chdir(dir) != 0) {
  5132. mg_cry_internal(
  5133. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5134. } else if (dup2(fdin[0], 0) == -1) {
  5135. mg_cry_internal(conn,
  5136. "%s: dup2(%d, 0): %s",
  5137. __func__,
  5138. fdin[0],
  5139. strerror(ERRNO));
  5140. } else if (dup2(fdout[1], 1) == -1) {
  5141. mg_cry_internal(conn,
  5142. "%s: dup2(%d, 1): %s",
  5143. __func__,
  5144. fdout[1],
  5145. strerror(ERRNO));
  5146. } else if (dup2(fderr[1], 2) == -1) {
  5147. mg_cry_internal(conn,
  5148. "%s: dup2(%d, 2): %s",
  5149. __func__,
  5150. fderr[1],
  5151. strerror(ERRNO));
  5152. } else {
  5153. struct sigaction sa;
  5154. /* Keep stderr and stdout in two different pipes.
  5155. * Stdout will be sent back to the client,
  5156. * stderr should go into a server error log. */
  5157. (void)close(fdin[0]);
  5158. (void)close(fdout[1]);
  5159. (void)close(fderr[1]);
  5160. /* Close write end fdin and read end fdout and fderr */
  5161. (void)close(fdin[1]);
  5162. (void)close(fdout[0]);
  5163. (void)close(fderr[0]);
  5164. /* After exec, all signal handlers are restored to their default
  5165. * values, with one exception of SIGCHLD. According to
  5166. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5167. * will leave unchanged after exec if it was set to be ignored.
  5168. * Restore it to default action. */
  5169. memset(&sa, 0, sizeof(sa));
  5170. sa.sa_handler = SIG_DFL;
  5171. sigaction(SIGCHLD, &sa, NULL);
  5172. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5173. if (interp == NULL) {
  5174. (void)execle(prog, prog, NULL, envp);
  5175. mg_cry_internal(conn,
  5176. "%s: execle(%s): %s",
  5177. __func__,
  5178. prog,
  5179. strerror(ERRNO));
  5180. } else {
  5181. (void)execle(interp, interp, prog, NULL, envp);
  5182. mg_cry_internal(conn,
  5183. "%s: execle(%s %s): %s",
  5184. __func__,
  5185. interp,
  5186. prog,
  5187. strerror(ERRNO));
  5188. }
  5189. }
  5190. exit(EXIT_FAILURE);
  5191. }
  5192. return pid;
  5193. }
  5194. #endif /* !NO_CGI */
  5195. static int
  5196. set_non_blocking_mode(SOCKET sock)
  5197. {
  5198. int flags = fcntl(sock, F_GETFL, 0);
  5199. if (flags < 0) {
  5200. return -1;
  5201. }
  5202. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5203. return -1;
  5204. }
  5205. return 0;
  5206. }
  5207. static int
  5208. set_blocking_mode(SOCKET sock)
  5209. {
  5210. int flags = fcntl(sock, F_GETFL, 0);
  5211. if (flags < 0) {
  5212. return -1;
  5213. }
  5214. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5215. return -1;
  5216. }
  5217. return 0;
  5218. }
  5219. #endif /* _WIN32 / else */
  5220. /* End of initial operating system specific define block. */
  5221. /* Get a random number (independent of C rand function) */
  5222. static uint64_t
  5223. get_random(void)
  5224. {
  5225. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5226. static uint64_t lcg = 0; /* Linear congruential generator */
  5227. uint64_t now = mg_get_current_time_ns();
  5228. if (lfsr == 0) {
  5229. /* lfsr will be only 0 if has not been initialized,
  5230. * so this code is called only once. */
  5231. lfsr = mg_get_current_time_ns();
  5232. lcg = mg_get_current_time_ns();
  5233. } else {
  5234. /* Get the next step of both random number generators. */
  5235. lfsr = (lfsr >> 1)
  5236. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5237. << 63);
  5238. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5239. }
  5240. /* Combining two pseudo-random number generators and a high resolution
  5241. * part
  5242. * of the current server time will make it hard (impossible?) to guess
  5243. * the
  5244. * next number. */
  5245. return (lfsr ^ lcg ^ now);
  5246. }
  5247. static int
  5248. mg_poll(struct mg_pollfd *pfd,
  5249. unsigned int n,
  5250. int milliseconds,
  5251. volatile int *stop_server)
  5252. {
  5253. /* Call poll, but only for a maximum time of a few seconds.
  5254. * This will allow to stop the server after some seconds, instead
  5255. * of having to wait for a long socket timeout. */
  5256. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5257. do {
  5258. int result;
  5259. if (*stop_server) {
  5260. /* Shut down signal */
  5261. return -2;
  5262. }
  5263. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5264. ms_now = milliseconds;
  5265. }
  5266. result = poll(pfd, n, ms_now);
  5267. if (result != 0) {
  5268. /* Poll returned either success (1) or error (-1).
  5269. * Forward both to the caller. */
  5270. return result;
  5271. }
  5272. /* Poll returned timeout (0). */
  5273. if (milliseconds > 0) {
  5274. milliseconds -= ms_now;
  5275. }
  5276. } while (milliseconds != 0);
  5277. /* timeout: return 0 */
  5278. return 0;
  5279. }
  5280. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5281. * descriptor.
  5282. * Return value:
  5283. * >=0 .. number of bytes successfully written
  5284. * -1 .. timeout
  5285. * -2 .. error
  5286. */
  5287. static int
  5288. push_inner(struct mg_context *ctx,
  5289. FILE *fp,
  5290. SOCKET sock,
  5291. SSL *ssl,
  5292. const char *buf,
  5293. int len,
  5294. double timeout)
  5295. {
  5296. uint64_t start = 0, now = 0, timeout_ns = 0;
  5297. int n, err;
  5298. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5299. #if defined(_WIN32)
  5300. typedef int len_t;
  5301. #else
  5302. typedef size_t len_t;
  5303. #endif
  5304. if (timeout > 0) {
  5305. now = mg_get_current_time_ns();
  5306. start = now;
  5307. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5308. }
  5309. if (ctx == NULL) {
  5310. return -2;
  5311. }
  5312. #if defined(NO_SSL)
  5313. if (ssl) {
  5314. return -2;
  5315. }
  5316. #endif
  5317. /* Try to read until it succeeds, fails, times out, or the server
  5318. * shuts down. */
  5319. for (;;) {
  5320. #if !defined(NO_SSL)
  5321. if (ssl != NULL) {
  5322. n = SSL_write(ssl, buf, len);
  5323. if (n <= 0) {
  5324. err = SSL_get_error(ssl, n);
  5325. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5326. err = ERRNO;
  5327. } else if ((err == SSL_ERROR_WANT_READ)
  5328. || (err == SSL_ERROR_WANT_WRITE)) {
  5329. n = 0;
  5330. } else {
  5331. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5332. return -2;
  5333. }
  5334. } else {
  5335. err = 0;
  5336. }
  5337. } else
  5338. #endif
  5339. if (fp != NULL) {
  5340. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5341. if (ferror(fp)) {
  5342. n = -1;
  5343. err = ERRNO;
  5344. } else {
  5345. err = 0;
  5346. }
  5347. } else {
  5348. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5349. err = (n < 0) ? ERRNO : 0;
  5350. #if defined(_WIN32)
  5351. if (err == WSAEWOULDBLOCK) {
  5352. err = 0;
  5353. n = 0;
  5354. }
  5355. #else
  5356. if (err == EWOULDBLOCK) {
  5357. err = 0;
  5358. n = 0;
  5359. }
  5360. #endif
  5361. if (n < 0) {
  5362. /* shutdown of the socket at client side */
  5363. return -2;
  5364. }
  5365. }
  5366. if (ctx->stop_flag) {
  5367. return -2;
  5368. }
  5369. if ((n > 0) || ((n == 0) && (len == 0))) {
  5370. /* some data has been read, or no data was requested */
  5371. return n;
  5372. }
  5373. if (n < 0) {
  5374. /* socket error - check errno */
  5375. DEBUG_TRACE("send() failed, error %d", err);
  5376. /* TODO (mid): error handling depending on the error code.
  5377. * These codes are different between Windows and Linux.
  5378. * Currently there is no problem with failing send calls,
  5379. * if there is a reproducible situation, it should be
  5380. * investigated in detail.
  5381. */
  5382. return -2;
  5383. }
  5384. /* Only in case n=0 (timeout), repeat calling the write function */
  5385. /* If send failed, wait before retry */
  5386. if (fp != NULL) {
  5387. /* For files, just wait a fixed time.
  5388. * Maybe it helps, maybe not. */
  5389. mg_sleep(5);
  5390. } else {
  5391. /* For sockets, wait for the socket using poll */
  5392. struct mg_pollfd pfd[1];
  5393. int pollres;
  5394. pfd[0].fd = sock;
  5395. pfd[0].events = POLLOUT;
  5396. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5397. if (ctx->stop_flag) {
  5398. return -2;
  5399. }
  5400. if (pollres > 0) {
  5401. continue;
  5402. }
  5403. }
  5404. if (timeout > 0) {
  5405. now = mg_get_current_time_ns();
  5406. if ((now - start) > timeout_ns) {
  5407. /* Timeout */
  5408. break;
  5409. }
  5410. }
  5411. }
  5412. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5413. used */
  5414. return -1;
  5415. }
  5416. static int
  5417. push_all(struct mg_context *ctx,
  5418. FILE *fp,
  5419. SOCKET sock,
  5420. SSL *ssl,
  5421. const char *buf,
  5422. int len)
  5423. {
  5424. double timeout = -1.0;
  5425. int n, nwritten = 0;
  5426. if (ctx == NULL) {
  5427. return -1;
  5428. }
  5429. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5430. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5431. }
  5432. while ((len > 0) && (ctx->stop_flag == 0)) {
  5433. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5434. if (n < 0) {
  5435. if (nwritten == 0) {
  5436. nwritten = -1; /* Propagate the error */
  5437. }
  5438. break;
  5439. } else if (n == 0) {
  5440. break; /* No more data to write */
  5441. } else {
  5442. nwritten += n;
  5443. len -= n;
  5444. }
  5445. }
  5446. return nwritten;
  5447. }
  5448. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5449. * Return value:
  5450. * >=0 .. number of bytes successfully read
  5451. * -1 .. timeout
  5452. * -2 .. error
  5453. */
  5454. static int
  5455. pull_inner(FILE *fp,
  5456. struct mg_connection *conn,
  5457. char *buf,
  5458. int len,
  5459. double timeout)
  5460. {
  5461. int nread, err = 0;
  5462. #if defined(_WIN32)
  5463. typedef int len_t;
  5464. #else
  5465. typedef size_t len_t;
  5466. #endif
  5467. #if !defined(NO_SSL)
  5468. int ssl_pending;
  5469. #endif
  5470. /* We need an additional wait loop around this, because in some cases
  5471. * with TLSwe may get data from the socket but not from SSL_read.
  5472. * In this case we need to repeat at least once.
  5473. */
  5474. if (fp != NULL) {
  5475. #if !defined(_WIN32_WCE)
  5476. /* Use read() instead of fread(), because if we're reading from the
  5477. * CGI pipe, fread() may block until IO buffer is filled up. We
  5478. * cannot afford to block and must pass all read bytes immediately
  5479. * to the client. */
  5480. nread = (int)read(fileno(fp), buf, (size_t)len);
  5481. #else
  5482. /* WinCE does not support CGI pipes */
  5483. nread = (int)fread(buf, 1, (size_t)len, fp);
  5484. #endif
  5485. err = (nread < 0) ? ERRNO : 0;
  5486. if ((nread == 0) && (len > 0)) {
  5487. /* Should get data, but got EOL */
  5488. return -2;
  5489. }
  5490. #if !defined(NO_SSL)
  5491. } else if ((conn->ssl != NULL)
  5492. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5493. /* We already know there is no more data buffered in conn->buf
  5494. * but there is more available in the SSL layer. So don't poll
  5495. * conn->client.sock yet. */
  5496. if (ssl_pending > len) {
  5497. ssl_pending = len;
  5498. }
  5499. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5500. if (nread <= 0) {
  5501. err = SSL_get_error(conn->ssl, nread);
  5502. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5503. err = ERRNO;
  5504. } else if ((err == SSL_ERROR_WANT_READ)
  5505. || (err == SSL_ERROR_WANT_WRITE)) {
  5506. nread = 0;
  5507. } else {
  5508. /* All errors should return -2 */
  5509. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5510. return -2;
  5511. }
  5512. ERR_clear_error();
  5513. } else {
  5514. err = 0;
  5515. }
  5516. } else if (conn->ssl != NULL) {
  5517. struct mg_pollfd pfd[1];
  5518. int pollres;
  5519. pfd[0].fd = conn->client.sock;
  5520. pfd[0].events = POLLIN;
  5521. pollres = mg_poll(pfd,
  5522. 1,
  5523. (int)(timeout * 1000.0),
  5524. &(conn->phys_ctx->stop_flag));
  5525. if (conn->phys_ctx->stop_flag) {
  5526. return -2;
  5527. }
  5528. if (pollres > 0) {
  5529. nread = SSL_read(conn->ssl, buf, len);
  5530. if (nread <= 0) {
  5531. err = SSL_get_error(conn->ssl, nread);
  5532. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5533. err = ERRNO;
  5534. } else if ((err == SSL_ERROR_WANT_READ)
  5535. || (err == SSL_ERROR_WANT_WRITE)) {
  5536. nread = 0;
  5537. } else {
  5538. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5539. return -2;
  5540. }
  5541. } else {
  5542. err = 0;
  5543. }
  5544. ERR_clear_error();
  5545. } else if (pollres < 0) {
  5546. /* Error */
  5547. return -2;
  5548. } else {
  5549. /* pollres = 0 means timeout */
  5550. nread = 0;
  5551. }
  5552. #endif
  5553. } else {
  5554. struct mg_pollfd pfd[1];
  5555. int pollres;
  5556. pfd[0].fd = conn->client.sock;
  5557. pfd[0].events = POLLIN;
  5558. pollres = mg_poll(pfd,
  5559. 1,
  5560. (int)(timeout * 1000.0),
  5561. &(conn->phys_ctx->stop_flag));
  5562. if (conn->phys_ctx->stop_flag) {
  5563. return -2;
  5564. }
  5565. if (pollres > 0) {
  5566. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5567. err = (nread < 0) ? ERRNO : 0;
  5568. if (nread <= 0) {
  5569. /* shutdown of the socket at client side */
  5570. return -2;
  5571. }
  5572. } else if (pollres < 0) {
  5573. /* error callint poll */
  5574. return -2;
  5575. } else {
  5576. /* pollres = 0 means timeout */
  5577. nread = 0;
  5578. }
  5579. }
  5580. if (conn->phys_ctx->stop_flag) {
  5581. return -2;
  5582. }
  5583. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5584. /* some data has been read, or no data was requested */
  5585. return nread;
  5586. }
  5587. if (nread < 0) {
  5588. /* socket error - check errno */
  5589. #if defined(_WIN32)
  5590. if (err == WSAEWOULDBLOCK) {
  5591. /* TODO (low): check if this is still required */
  5592. /* standard case if called from close_socket_gracefully */
  5593. return -2;
  5594. } else if (err == WSAETIMEDOUT) {
  5595. /* TODO (low): check if this is still required */
  5596. /* timeout is handled by the while loop */
  5597. return 0;
  5598. } else if (err == WSAECONNABORTED) {
  5599. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5600. return -2;
  5601. } else {
  5602. DEBUG_TRACE("recv() failed, error %d", err);
  5603. return -2;
  5604. }
  5605. #else
  5606. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5607. * if the timeout is reached and if the socket was set to non-
  5608. * blocking in close_socket_gracefully, so we can not distinguish
  5609. * here. We have to wait for the timeout in both cases for now.
  5610. */
  5611. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5612. /* TODO (low): check if this is still required */
  5613. /* EAGAIN/EWOULDBLOCK:
  5614. * standard case if called from close_socket_gracefully
  5615. * => should return -1 */
  5616. /* or timeout occurred
  5617. * => the code must stay in the while loop */
  5618. /* EINTR can be generated on a socket with a timeout set even
  5619. * when SA_RESTART is effective for all relevant signals
  5620. * (see signal(7)).
  5621. * => stay in the while loop */
  5622. } else {
  5623. DEBUG_TRACE("recv() failed, error %d", err);
  5624. return -2;
  5625. }
  5626. #endif
  5627. }
  5628. /* Timeout occurred, but no data available. */
  5629. return -1;
  5630. }
  5631. static int
  5632. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5633. {
  5634. int n, nread = 0;
  5635. double timeout = -1.0;
  5636. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5637. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5638. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5639. }
  5640. if (timeout >= 0.0) {
  5641. start_time = mg_get_current_time_ns();
  5642. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5643. }
  5644. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5645. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5646. if (n == -2) {
  5647. if (nread == 0) {
  5648. nread = -1; /* Propagate the error */
  5649. }
  5650. break;
  5651. } else if (n == -1) {
  5652. /* timeout */
  5653. if (timeout >= 0.0) {
  5654. now = mg_get_current_time_ns();
  5655. if ((now - start_time) <= timeout_ns) {
  5656. continue;
  5657. }
  5658. }
  5659. break;
  5660. } else if (n == 0) {
  5661. break; /* No more data to read */
  5662. } else {
  5663. nread += n;
  5664. len -= n;
  5665. }
  5666. }
  5667. return nread;
  5668. }
  5669. static void
  5670. discard_unread_request_data(struct mg_connection *conn)
  5671. {
  5672. char buf[MG_BUF_LEN];
  5673. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5674. ;
  5675. }
  5676. static int
  5677. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5678. {
  5679. int64_t content_len, n, buffered_len, nread;
  5680. int64_t len64 =
  5681. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5682. * int, we may not read more
  5683. * bytes */
  5684. const char *body;
  5685. if (conn == NULL) {
  5686. return 0;
  5687. }
  5688. /* If Content-Length is not set for a response with body data,
  5689. * we do not know in advance how much data should be read. */
  5690. content_len = conn->content_len;
  5691. if (content_len < 0) {
  5692. /* The body data is completed when the connection is closed. */
  5693. content_len = INT64_MAX;
  5694. }
  5695. nread = 0;
  5696. if (conn->consumed_content < content_len) {
  5697. /* Adjust number of bytes to read. */
  5698. int64_t left_to_read = content_len - conn->consumed_content;
  5699. if (left_to_read < len64) {
  5700. /* Do not read more than the total content length of the
  5701. * request.
  5702. */
  5703. len64 = left_to_read;
  5704. }
  5705. /* Return buffered data */
  5706. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5707. - conn->consumed_content;
  5708. if (buffered_len > 0) {
  5709. if (len64 < buffered_len) {
  5710. buffered_len = len64;
  5711. }
  5712. body = conn->buf + conn->request_len + conn->consumed_content;
  5713. memcpy(buf, body, (size_t)buffered_len);
  5714. len64 -= buffered_len;
  5715. conn->consumed_content += buffered_len;
  5716. nread += buffered_len;
  5717. buf = (char *)buf + buffered_len;
  5718. }
  5719. /* We have returned all buffered data. Read new data from the remote
  5720. * socket.
  5721. */
  5722. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5723. conn->consumed_content += n;
  5724. nread += n;
  5725. } else {
  5726. nread = ((nread > 0) ? nread : n);
  5727. }
  5728. }
  5729. return (int)nread;
  5730. }
  5731. int
  5732. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5733. {
  5734. if (len > INT_MAX) {
  5735. len = INT_MAX;
  5736. }
  5737. if (conn == NULL) {
  5738. return 0;
  5739. }
  5740. if (conn->is_chunked) {
  5741. size_t all_read = 0;
  5742. while (len > 0) {
  5743. if (conn->is_chunked >= 3) {
  5744. /* No more data left to read */
  5745. return 0;
  5746. }
  5747. if (conn->is_chunked != 1) {
  5748. /* Has error */
  5749. return -1;
  5750. }
  5751. if (conn->consumed_content != conn->content_len) {
  5752. /* copy from the current chunk */
  5753. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5754. if (read_ret < 1) {
  5755. /* read error */
  5756. conn->is_chunked = 2;
  5757. return -1;
  5758. }
  5759. all_read += (size_t)read_ret;
  5760. len -= (size_t)read_ret;
  5761. if (conn->consumed_content == conn->content_len) {
  5762. /* Add data bytes in the current chunk have been read,
  5763. * so we are expecting \r\n now. */
  5764. char x[2];
  5765. conn->content_len += 2;
  5766. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5767. || (x[1] != '\n')) {
  5768. /* Protocol violation */
  5769. conn->is_chunked = 2;
  5770. return -1;
  5771. }
  5772. }
  5773. } else {
  5774. /* fetch a new chunk */
  5775. size_t i;
  5776. char lenbuf[64];
  5777. char *end = NULL;
  5778. unsigned long chunkSize = 0;
  5779. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5780. conn->content_len++;
  5781. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5782. lenbuf[i] = 0;
  5783. }
  5784. if ((i > 0) && (lenbuf[i] == '\r')
  5785. && (lenbuf[i - 1] != '\r')) {
  5786. continue;
  5787. }
  5788. if ((i > 1) && (lenbuf[i] == '\n')
  5789. && (lenbuf[i - 1] == '\r')) {
  5790. lenbuf[i + 1] = 0;
  5791. chunkSize = strtoul(lenbuf, &end, 16);
  5792. if (chunkSize == 0) {
  5793. /* regular end of content */
  5794. conn->is_chunked = 3;
  5795. }
  5796. break;
  5797. }
  5798. if (!isxdigit((unsigned char)lenbuf[i])) {
  5799. /* illegal character for chunk length */
  5800. conn->is_chunked = 2;
  5801. return -1;
  5802. }
  5803. }
  5804. if ((end == NULL) || (*end != '\r')) {
  5805. /* chunksize not set correctly */
  5806. conn->is_chunked = 2;
  5807. return -1;
  5808. }
  5809. if (chunkSize == 0) {
  5810. /* try discarding trailer for keep-alive */
  5811. conn->content_len += 2;
  5812. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5813. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5814. conn->is_chunked = 4;
  5815. }
  5816. break;
  5817. }
  5818. /* append a new chunk */
  5819. conn->content_len += chunkSize;
  5820. }
  5821. }
  5822. return (int)all_read;
  5823. }
  5824. return mg_read_inner(conn, buf, len);
  5825. }
  5826. int
  5827. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5828. {
  5829. time_t now;
  5830. int n, total, allowed;
  5831. if (conn == NULL) {
  5832. return 0;
  5833. }
  5834. if (len > INT_MAX) {
  5835. return -1;
  5836. }
  5837. if (conn->throttle > 0) {
  5838. if ((now = time(NULL)) != conn->last_throttle_time) {
  5839. conn->last_throttle_time = now;
  5840. conn->last_throttle_bytes = 0;
  5841. }
  5842. allowed = conn->throttle - conn->last_throttle_bytes;
  5843. if (allowed > (int)len) {
  5844. allowed = (int)len;
  5845. }
  5846. if ((total = push_all(conn->phys_ctx,
  5847. NULL,
  5848. conn->client.sock,
  5849. conn->ssl,
  5850. (const char *)buf,
  5851. allowed))
  5852. == allowed) {
  5853. buf = (const char *)buf + total;
  5854. conn->last_throttle_bytes += total;
  5855. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5856. allowed = (conn->throttle > ((int)len - total))
  5857. ? (int)len - total
  5858. : conn->throttle;
  5859. if ((n = push_all(conn->phys_ctx,
  5860. NULL,
  5861. conn->client.sock,
  5862. conn->ssl,
  5863. (const char *)buf,
  5864. allowed))
  5865. != allowed) {
  5866. break;
  5867. }
  5868. sleep(1);
  5869. conn->last_throttle_bytes = allowed;
  5870. conn->last_throttle_time = time(NULL);
  5871. buf = (const char *)buf + n;
  5872. total += n;
  5873. }
  5874. }
  5875. } else {
  5876. total = push_all(conn->phys_ctx,
  5877. NULL,
  5878. conn->client.sock,
  5879. conn->ssl,
  5880. (const char *)buf,
  5881. (int)len);
  5882. }
  5883. if (total > 0) {
  5884. conn->num_bytes_sent += total;
  5885. }
  5886. return total;
  5887. }
  5888. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5889. int
  5890. mg_send_chunk(struct mg_connection *conn,
  5891. const char *chunk,
  5892. unsigned int chunk_len)
  5893. {
  5894. char lenbuf[16];
  5895. size_t lenbuf_len;
  5896. int ret;
  5897. int t;
  5898. /* First store the length information in a text buffer. */
  5899. sprintf(lenbuf, "%x\r\n", chunk_len);
  5900. lenbuf_len = strlen(lenbuf);
  5901. /* Then send length information, chunk and terminating \r\n. */
  5902. ret = mg_write(conn, lenbuf, lenbuf_len);
  5903. if (ret != (int)lenbuf_len) {
  5904. return -1;
  5905. }
  5906. t = ret;
  5907. ret = mg_write(conn, chunk, chunk_len);
  5908. if (ret != (int)chunk_len) {
  5909. return -1;
  5910. }
  5911. t += ret;
  5912. ret = mg_write(conn, "\r\n", 2);
  5913. if (ret != 2) {
  5914. return -1;
  5915. }
  5916. t += ret;
  5917. return t;
  5918. }
  5919. #if defined(GCC_DIAGNOSTIC)
  5920. /* This block forwards format strings to printf implementations,
  5921. * so we need to disable the format-nonliteral warning. */
  5922. #pragma GCC diagnostic push
  5923. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5924. #endif
  5925. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5926. static int
  5927. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5928. {
  5929. va_list ap_copy;
  5930. size_t size = MG_BUF_LEN / 4;
  5931. int len = -1;
  5932. *buf = NULL;
  5933. while (len < 0) {
  5934. if (*buf) {
  5935. mg_free(*buf);
  5936. }
  5937. size *= 4;
  5938. *buf = (char *)mg_malloc(size);
  5939. if (!*buf) {
  5940. break;
  5941. }
  5942. va_copy(ap_copy, ap);
  5943. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5944. va_end(ap_copy);
  5945. (*buf)[size - 1] = 0;
  5946. }
  5947. return len;
  5948. }
  5949. /* Print message to buffer. If buffer is large enough to hold the message,
  5950. * return buffer. If buffer is to small, allocate large enough buffer on
  5951. * heap,
  5952. * and return allocated buffer. */
  5953. static int
  5954. alloc_vprintf(char **out_buf,
  5955. char *prealloc_buf,
  5956. size_t prealloc_size,
  5957. const char *fmt,
  5958. va_list ap)
  5959. {
  5960. va_list ap_copy;
  5961. int len;
  5962. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5963. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5964. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5965. * Therefore, we make two passes: on first pass, get required message
  5966. * length.
  5967. * On second pass, actually print the message. */
  5968. va_copy(ap_copy, ap);
  5969. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5970. va_end(ap_copy);
  5971. if (len < 0) {
  5972. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5973. * Switch to alternative code path that uses incremental
  5974. * allocations.
  5975. */
  5976. va_copy(ap_copy, ap);
  5977. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5978. va_end(ap_copy);
  5979. } else if ((size_t)(len) >= prealloc_size) {
  5980. /* The pre-allocated buffer not large enough. */
  5981. /* Allocate a new buffer. */
  5982. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5983. if (!*out_buf) {
  5984. /* Allocation failed. Return -1 as "out of memory" error. */
  5985. return -1;
  5986. }
  5987. /* Buffer allocation successful. Store the string there. */
  5988. va_copy(ap_copy, ap);
  5989. IGNORE_UNUSED_RESULT(
  5990. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5991. va_end(ap_copy);
  5992. } else {
  5993. /* The pre-allocated buffer is large enough.
  5994. * Use it to store the string and return the address. */
  5995. va_copy(ap_copy, ap);
  5996. IGNORE_UNUSED_RESULT(
  5997. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5998. va_end(ap_copy);
  5999. *out_buf = prealloc_buf;
  6000. }
  6001. return len;
  6002. }
  6003. #if defined(GCC_DIAGNOSTIC)
  6004. /* Enable format-nonliteral warning again. */
  6005. #pragma GCC diagnostic pop
  6006. #endif
  6007. static int
  6008. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6009. {
  6010. char mem[MG_BUF_LEN];
  6011. char *buf = NULL;
  6012. int len;
  6013. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6014. len = mg_write(conn, buf, (size_t)len);
  6015. }
  6016. if (buf != mem) {
  6017. mg_free(buf);
  6018. }
  6019. return len;
  6020. }
  6021. int
  6022. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6023. {
  6024. va_list ap;
  6025. int result;
  6026. va_start(ap, fmt);
  6027. result = mg_vprintf(conn, fmt, ap);
  6028. va_end(ap);
  6029. return result;
  6030. }
  6031. int
  6032. mg_url_decode(const char *src,
  6033. int src_len,
  6034. char *dst,
  6035. int dst_len,
  6036. int is_form_url_encoded)
  6037. {
  6038. int i, j, a, b;
  6039. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6040. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6041. if ((i < src_len - 2) && (src[i] == '%')
  6042. && isxdigit((unsigned char)src[i + 1])
  6043. && isxdigit((unsigned char)src[i + 2])) {
  6044. a = tolower((unsigned char)src[i + 1]);
  6045. b = tolower((unsigned char)src[i + 2]);
  6046. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6047. i += 2;
  6048. } else if (is_form_url_encoded && (src[i] == '+')) {
  6049. dst[j] = ' ';
  6050. } else {
  6051. dst[j] = src[i];
  6052. }
  6053. }
  6054. dst[j] = '\0'; /* Null-terminate the destination */
  6055. return (i >= src_len) ? j : -1;
  6056. }
  6057. int
  6058. mg_get_var(const char *data,
  6059. size_t data_len,
  6060. const char *name,
  6061. char *dst,
  6062. size_t dst_len)
  6063. {
  6064. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6065. }
  6066. int
  6067. mg_get_var2(const char *data,
  6068. size_t data_len,
  6069. const char *name,
  6070. char *dst,
  6071. size_t dst_len,
  6072. size_t occurrence)
  6073. {
  6074. const char *p, *e, *s;
  6075. size_t name_len;
  6076. int len;
  6077. if ((dst == NULL) || (dst_len == 0)) {
  6078. len = -2;
  6079. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6080. len = -1;
  6081. dst[0] = '\0';
  6082. } else {
  6083. name_len = strlen(name);
  6084. e = data + data_len;
  6085. len = -1;
  6086. dst[0] = '\0';
  6087. /* data is "var1=val1&var2=val2...". Find variable first */
  6088. for (p = data; p + name_len < e; p++) {
  6089. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6090. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6091. /* Point p to variable value */
  6092. p += name_len + 1;
  6093. /* Point s to the end of the value */
  6094. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6095. if (s == NULL) {
  6096. s = e;
  6097. }
  6098. DEBUG_ASSERT(s >= p);
  6099. if (s < p) {
  6100. return -3;
  6101. }
  6102. /* Decode variable into destination buffer */
  6103. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6104. /* Redirect error code from -1 to -2 (destination buffer too
  6105. * small). */
  6106. if (len == -1) {
  6107. len = -2;
  6108. }
  6109. break;
  6110. }
  6111. }
  6112. }
  6113. return len;
  6114. }
  6115. /* HCP24: some changes to compare hole var_name */
  6116. int
  6117. mg_get_cookie(const char *cookie_header,
  6118. const char *var_name,
  6119. char *dst,
  6120. size_t dst_size)
  6121. {
  6122. const char *s, *p, *end;
  6123. int name_len, len = -1;
  6124. if ((dst == NULL) || (dst_size == 0)) {
  6125. return -2;
  6126. }
  6127. dst[0] = '\0';
  6128. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6129. return -1;
  6130. }
  6131. name_len = (int)strlen(var_name);
  6132. end = s + strlen(s);
  6133. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6134. if (s[name_len] == '=') {
  6135. /* HCP24: now check is it a substring or a full cookie name */
  6136. if ((s == cookie_header) || (s[-1] == ' ')) {
  6137. s += name_len + 1;
  6138. if ((p = strchr(s, ' ')) == NULL) {
  6139. p = end;
  6140. }
  6141. if (p[-1] == ';') {
  6142. p--;
  6143. }
  6144. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6145. s++;
  6146. p--;
  6147. }
  6148. if ((size_t)(p - s) < dst_size) {
  6149. len = (int)(p - s);
  6150. mg_strlcpy(dst, s, (size_t)len + 1);
  6151. } else {
  6152. len = -3;
  6153. }
  6154. break;
  6155. }
  6156. }
  6157. }
  6158. return len;
  6159. }
  6160. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6161. static void
  6162. base64_encode(const unsigned char *src, int src_len, char *dst)
  6163. {
  6164. static const char *b64 =
  6165. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6166. int i, j, a, b, c;
  6167. for (i = j = 0; i < src_len; i += 3) {
  6168. a = src[i];
  6169. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6170. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6171. dst[j++] = b64[a >> 2];
  6172. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6173. if (i + 1 < src_len) {
  6174. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6175. }
  6176. if (i + 2 < src_len) {
  6177. dst[j++] = b64[c & 63];
  6178. }
  6179. }
  6180. while (j % 4 != 0) {
  6181. dst[j++] = '=';
  6182. }
  6183. dst[j++] = '\0';
  6184. }
  6185. #endif
  6186. #if defined(USE_LUA)
  6187. static unsigned char
  6188. b64reverse(char letter)
  6189. {
  6190. if ((letter >= 'A') && (letter <= 'Z')) {
  6191. return letter - 'A';
  6192. }
  6193. if ((letter >= 'a') && (letter <= 'z')) {
  6194. return letter - 'a' + 26;
  6195. }
  6196. if ((letter >= '0') && (letter <= '9')) {
  6197. return letter - '0' + 52;
  6198. }
  6199. if (letter == '+') {
  6200. return 62;
  6201. }
  6202. if (letter == '/') {
  6203. return 63;
  6204. }
  6205. if (letter == '=') {
  6206. return 255; /* normal end */
  6207. }
  6208. return 254; /* error */
  6209. }
  6210. static int
  6211. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6212. {
  6213. int i;
  6214. unsigned char a, b, c, d;
  6215. *dst_len = 0;
  6216. for (i = 0; i < src_len; i += 4) {
  6217. a = b64reverse(src[i]);
  6218. if (a >= 254) {
  6219. return i;
  6220. }
  6221. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6222. if (b >= 254) {
  6223. return i + 1;
  6224. }
  6225. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6226. if (c == 254) {
  6227. return i + 2;
  6228. }
  6229. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6230. if (d == 254) {
  6231. return i + 3;
  6232. }
  6233. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6234. if (c != 255) {
  6235. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6236. if (d != 255) {
  6237. dst[(*dst_len)++] = (c << 6) + d;
  6238. }
  6239. }
  6240. }
  6241. return -1;
  6242. }
  6243. #endif
  6244. static int
  6245. is_put_or_delete_method(const struct mg_connection *conn)
  6246. {
  6247. if (conn) {
  6248. const char *s = conn->request_info.request_method;
  6249. return (s != NULL)
  6250. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6251. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6252. }
  6253. return 0;
  6254. }
  6255. #if !defined(NO_FILES)
  6256. static int
  6257. extention_matches_script(
  6258. struct mg_connection *conn, /* in: request (must be valid) */
  6259. const char *filename /* in: filename (must be valid) */
  6260. )
  6261. {
  6262. #if !defined(NO_CGI)
  6263. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6264. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6265. filename)
  6266. > 0) {
  6267. return 1;
  6268. }
  6269. #endif
  6270. #if defined(USE_LUA)
  6271. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6272. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6273. filename)
  6274. > 0) {
  6275. return 1;
  6276. }
  6277. #endif
  6278. #if defined(USE_DUKTAPE)
  6279. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6280. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6281. filename)
  6282. > 0) {
  6283. return 1;
  6284. }
  6285. #endif
  6286. /* filename and conn could be unused, if all preocessor conditions
  6287. * are false (no script language supported). */
  6288. (void)filename;
  6289. (void)conn;
  6290. return 0;
  6291. }
  6292. /* For given directory path, substitute it to valid index file.
  6293. * Return 1 if index file has been found, 0 if not found.
  6294. * If the file is found, it's stats is returned in stp. */
  6295. static int
  6296. substitute_index_file(struct mg_connection *conn,
  6297. char *path,
  6298. size_t path_len,
  6299. struct mg_file_stat *filestat)
  6300. {
  6301. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6302. struct vec filename_vec;
  6303. size_t n = strlen(path);
  6304. int found = 0;
  6305. /* The 'path' given to us points to the directory. Remove all trailing
  6306. * directory separator characters from the end of the path, and
  6307. * then append single directory separator character. */
  6308. while ((n > 0) && (path[n - 1] == '/')) {
  6309. n--;
  6310. }
  6311. path[n] = '/';
  6312. /* Traverse index files list. For each entry, append it to the given
  6313. * path and see if the file exists. If it exists, break the loop */
  6314. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6315. /* Ignore too long entries that may overflow path buffer */
  6316. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6317. continue;
  6318. }
  6319. /* Prepare full path to the index file */
  6320. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6321. /* Does it exist? */
  6322. if (mg_stat(conn, path, filestat)) {
  6323. /* Yes it does, break the loop */
  6324. found = 1;
  6325. break;
  6326. }
  6327. }
  6328. /* If no index file exists, restore directory path */
  6329. if (!found) {
  6330. path[n] = '\0';
  6331. }
  6332. return found;
  6333. }
  6334. #endif
  6335. static void
  6336. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6337. char *filename, /* out: filename */
  6338. size_t filename_buf_len, /* in: size of filename buffer */
  6339. struct mg_file_stat *filestat, /* out: file status structure */
  6340. int *is_found, /* out: file found (directly) */
  6341. int *is_script_resource, /* out: handled by a script? */
  6342. int *is_websocket_request, /* out: websocket connetion? */
  6343. int *is_put_or_delete_request /* out: put/delete a file? */
  6344. )
  6345. {
  6346. char const *accept_encoding;
  6347. #if !defined(NO_FILES)
  6348. const char *uri = conn->request_info.local_uri;
  6349. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6350. const char *rewrite;
  6351. struct vec a, b;
  6352. ptrdiff_t match_len;
  6353. char gz_path[PATH_MAX];
  6354. int truncated;
  6355. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6356. char *tmp_str;
  6357. size_t tmp_str_len, sep_pos;
  6358. int allow_substitute_script_subresources;
  6359. #endif
  6360. #else
  6361. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6362. #endif
  6363. /* Step 1: Set all initially unknown outputs to zero */
  6364. memset(filestat, 0, sizeof(*filestat));
  6365. *filename = 0;
  6366. *is_found = 0;
  6367. *is_script_resource = 0;
  6368. /* Step 2: Check if the request attempts to modify the file system */
  6369. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6370. /* Step 3: Check if it is a websocket request, and modify the document
  6371. * root if required */
  6372. #if defined(USE_WEBSOCKET)
  6373. *is_websocket_request = is_websocket_protocol(conn);
  6374. #if !defined(NO_FILES)
  6375. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6376. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6377. }
  6378. #endif /* !NO_FILES */
  6379. #else /* USE_WEBSOCKET */
  6380. *is_websocket_request = 0;
  6381. #endif /* USE_WEBSOCKET */
  6382. /* Step 4: Check if gzip encoded response is allowed */
  6383. conn->accept_gzip = 0;
  6384. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6385. if (strstr(accept_encoding, "gzip") != NULL) {
  6386. conn->accept_gzip = 1;
  6387. }
  6388. }
  6389. #if !defined(NO_FILES)
  6390. /* Step 5: If there is no root directory, don't look for files. */
  6391. /* Note that root == NULL is a regular use case here. This occurs,
  6392. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6393. * config is not required. */
  6394. if (root == NULL) {
  6395. /* all file related outputs have already been set to 0, just return
  6396. */
  6397. return;
  6398. }
  6399. /* Step 6: Determine the local file path from the root path and the
  6400. * request uri. */
  6401. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6402. * part of the path one byte on the right. */
  6403. mg_snprintf(
  6404. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6405. if (truncated) {
  6406. goto interpret_cleanup;
  6407. }
  6408. /* Step 7: URI rewriting */
  6409. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6410. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6411. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6412. mg_snprintf(conn,
  6413. &truncated,
  6414. filename,
  6415. filename_buf_len - 1,
  6416. "%.*s%s",
  6417. (int)b.len,
  6418. b.ptr,
  6419. uri + match_len);
  6420. break;
  6421. }
  6422. }
  6423. if (truncated) {
  6424. goto interpret_cleanup;
  6425. }
  6426. /* Step 8: Check if the file exists at the server */
  6427. /* Local file path and name, corresponding to requested URI
  6428. * is now stored in "filename" variable. */
  6429. if (mg_stat(conn, filename, filestat)) {
  6430. int uri_len = (int)strlen(uri);
  6431. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6432. /* 8.1: File exists. */
  6433. *is_found = 1;
  6434. /* 8.2: Check if it is a script type. */
  6435. if (extention_matches_script(conn, filename)) {
  6436. /* The request addresses a CGI resource, Lua script or
  6437. * server-side javascript.
  6438. * The URI corresponds to the script itself (like
  6439. * /path/script.cgi), and there is no additional resource
  6440. * path (like /path/script.cgi/something).
  6441. * Requests that modify (replace or delete) a resource, like
  6442. * PUT and DELETE requests, should replace/delete the script
  6443. * file.
  6444. * Requests that read or write from/to a resource, like GET and
  6445. * POST requests, should call the script and return the
  6446. * generated response. */
  6447. *is_script_resource = (!*is_put_or_delete_request);
  6448. }
  6449. /* 8.3: If the request target is a directory, there could be
  6450. * a substitute file (index.html, index.cgi, ...). */
  6451. if (filestat->is_directory && is_uri_end_slash) {
  6452. /* Use a local copy here, since substitute_index_file will
  6453. * change the content of the file status */
  6454. struct mg_file_stat tmp_filestat;
  6455. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6456. if (substitute_index_file(
  6457. conn, filename, filename_buf_len, &tmp_filestat)) {
  6458. /* Substitute file found. Copy stat to the output, then
  6459. * check if the file is a script file */
  6460. *filestat = tmp_filestat;
  6461. if (extention_matches_script(conn, filename)) {
  6462. /* Substitute file is a script file */
  6463. *is_script_resource = 1;
  6464. } else {
  6465. /* Substitute file is a regular file */
  6466. *is_script_resource = 0;
  6467. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6468. }
  6469. }
  6470. /* If there is no substitute file, the server could return
  6471. * a directory listing in a later step */
  6472. }
  6473. return;
  6474. }
  6475. /* Step 9: Check for zipped files: */
  6476. /* If we can't find the actual file, look for the file
  6477. * with the same name but a .gz extension. If we find it,
  6478. * use that and set the gzipped flag in the file struct
  6479. * to indicate that the response need to have the content-
  6480. * encoding: gzip header.
  6481. * We can only do this if the browser declares support. */
  6482. if (conn->accept_gzip) {
  6483. mg_snprintf(
  6484. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6485. if (truncated) {
  6486. goto interpret_cleanup;
  6487. }
  6488. if (mg_stat(conn, gz_path, filestat)) {
  6489. if (filestat) {
  6490. filestat->is_gzipped = 1;
  6491. *is_found = 1;
  6492. }
  6493. /* Currently gz files can not be scripts. */
  6494. return;
  6495. }
  6496. }
  6497. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6498. /* Step 10: Script resources may handle sub-resources */
  6499. /* Support PATH_INFO for CGI scripts. */
  6500. tmp_str_len = strlen(filename);
  6501. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6502. if (!tmp_str) {
  6503. /* Out of memory */
  6504. goto interpret_cleanup;
  6505. }
  6506. memcpy(tmp_str, filename, tmp_str_len + 1);
  6507. /* Check config, if index scripts may have sub-resources */
  6508. allow_substitute_script_subresources =
  6509. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6510. "yes");
  6511. sep_pos = tmp_str_len;
  6512. while (sep_pos > 0) {
  6513. sep_pos--;
  6514. if (tmp_str[sep_pos] == '/') {
  6515. int is_script = 0, does_exist = 0;
  6516. tmp_str[sep_pos] = 0;
  6517. if (tmp_str[0]) {
  6518. is_script = extention_matches_script(conn, tmp_str);
  6519. does_exist = mg_stat(conn, tmp_str, filestat);
  6520. }
  6521. if (does_exist && is_script) {
  6522. filename[sep_pos] = 0;
  6523. memmove(filename + sep_pos + 2,
  6524. filename + sep_pos + 1,
  6525. strlen(filename + sep_pos + 1) + 1);
  6526. conn->path_info = filename + sep_pos + 1;
  6527. filename[sep_pos + 1] = '/';
  6528. *is_script_resource = 1;
  6529. *is_found = 1;
  6530. break;
  6531. }
  6532. if (allow_substitute_script_subresources) {
  6533. if (substitute_index_file(
  6534. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6535. /* some intermediate directory has an index file */
  6536. if (extention_matches_script(conn, tmp_str)) {
  6537. char *tmp_str2;
  6538. DEBUG_TRACE("Substitute script %s serving path %s",
  6539. tmp_str,
  6540. filename);
  6541. /* this index file is a script */
  6542. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6543. conn->phys_ctx);
  6544. mg_snprintf(conn,
  6545. &truncated,
  6546. filename,
  6547. filename_buf_len,
  6548. "%s//%s",
  6549. tmp_str,
  6550. tmp_str2);
  6551. mg_free(tmp_str2);
  6552. if (truncated) {
  6553. mg_free(tmp_str);
  6554. goto interpret_cleanup;
  6555. }
  6556. sep_pos = strlen(tmp_str);
  6557. filename[sep_pos] = 0;
  6558. conn->path_info = filename + sep_pos + 1;
  6559. *is_script_resource = 1;
  6560. *is_found = 1;
  6561. break;
  6562. } else {
  6563. DEBUG_TRACE("Substitute file %s serving path %s",
  6564. tmp_str,
  6565. filename);
  6566. /* non-script files will not have sub-resources */
  6567. filename[sep_pos] = 0;
  6568. conn->path_info = 0;
  6569. *is_script_resource = 0;
  6570. *is_found = 0;
  6571. break;
  6572. }
  6573. }
  6574. }
  6575. tmp_str[sep_pos] = '/';
  6576. }
  6577. }
  6578. mg_free(tmp_str);
  6579. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6580. #endif /* !defined(NO_FILES) */
  6581. return;
  6582. #if !defined(NO_FILES)
  6583. /* Reset all outputs */
  6584. interpret_cleanup:
  6585. memset(filestat, 0, sizeof(*filestat));
  6586. *filename = 0;
  6587. *is_found = 0;
  6588. *is_script_resource = 0;
  6589. *is_websocket_request = 0;
  6590. *is_put_or_delete_request = 0;
  6591. #endif /* !defined(NO_FILES) */
  6592. }
  6593. /* Check whether full request is buffered. Return:
  6594. * -1 if request or response is malformed
  6595. * 0 if request or response is not yet fully buffered
  6596. * >0 actual request length, including last \r\n\r\n */
  6597. static int
  6598. get_http_header_len(const char *buf, int buflen)
  6599. {
  6600. int i;
  6601. for (i = 0; i < buflen; i++) {
  6602. /* Do an unsigned comparison in some conditions below */
  6603. const unsigned char c = (unsigned char)buf[i];
  6604. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6605. && !isprint(c)) {
  6606. /* abort scan as soon as one malformed character is found */
  6607. return -1;
  6608. }
  6609. if (i < buflen - 1) {
  6610. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6611. /* Two newline, no carriage return - not standard compliant,
  6612. * but
  6613. * it
  6614. * should be accepted */
  6615. return i + 2;
  6616. }
  6617. }
  6618. if (i < buflen - 3) {
  6619. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6620. && (buf[i + 3] == '\n')) {
  6621. /* Two \r\n - standard compliant */
  6622. return i + 4;
  6623. }
  6624. }
  6625. }
  6626. return 0;
  6627. }
  6628. #if !defined(NO_CACHING)
  6629. /* Convert month to the month number. Return -1 on error, or month number */
  6630. static int
  6631. get_month_index(const char *s)
  6632. {
  6633. size_t i;
  6634. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6635. if (!strcmp(s, month_names[i])) {
  6636. return (int)i;
  6637. }
  6638. }
  6639. return -1;
  6640. }
  6641. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6642. static time_t
  6643. parse_date_string(const char *datetime)
  6644. {
  6645. char month_str[32] = {0};
  6646. int second, minute, hour, day, month, year;
  6647. time_t result = (time_t)0;
  6648. struct tm tm;
  6649. if ((sscanf(datetime,
  6650. "%d/%3s/%d %d:%d:%d",
  6651. &day,
  6652. month_str,
  6653. &year,
  6654. &hour,
  6655. &minute,
  6656. &second)
  6657. == 6)
  6658. || (sscanf(datetime,
  6659. "%d %3s %d %d:%d:%d",
  6660. &day,
  6661. month_str,
  6662. &year,
  6663. &hour,
  6664. &minute,
  6665. &second)
  6666. == 6)
  6667. || (sscanf(datetime,
  6668. "%*3s, %d %3s %d %d:%d:%d",
  6669. &day,
  6670. month_str,
  6671. &year,
  6672. &hour,
  6673. &minute,
  6674. &second)
  6675. == 6)
  6676. || (sscanf(datetime,
  6677. "%d-%3s-%d %d:%d:%d",
  6678. &day,
  6679. month_str,
  6680. &year,
  6681. &hour,
  6682. &minute,
  6683. &second)
  6684. == 6)) {
  6685. month = get_month_index(month_str);
  6686. if ((month >= 0) && (year >= 1970)) {
  6687. memset(&tm, 0, sizeof(tm));
  6688. tm.tm_year = year - 1900;
  6689. tm.tm_mon = month;
  6690. tm.tm_mday = day;
  6691. tm.tm_hour = hour;
  6692. tm.tm_min = minute;
  6693. tm.tm_sec = second;
  6694. result = timegm(&tm);
  6695. }
  6696. }
  6697. return result;
  6698. }
  6699. #endif /* !NO_CACHING */
  6700. /* Pre-process URIs according to RFC + protect against directory disclosure
  6701. * attacks by removing '..', excessive '/' and '\' characters */
  6702. static void
  6703. remove_dot_segments(char *inout)
  6704. {
  6705. /* Windows backend protection
  6706. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash in
  6707. * URI by slash */
  6708. char *in_copy = mg_strdup(inout);
  6709. char *out_begin = inout;
  6710. char *out_end = inout;
  6711. char *in = in_copy;
  6712. int replaced;
  6713. while (*in) {
  6714. if (*in == '\\') {
  6715. *in = '/';
  6716. }
  6717. in++;
  6718. }
  6719. /* Algorithm "remove_dot_segments" from
  6720. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6721. /* Step 1:
  6722. * The input buffer is initialized.
  6723. * The output buffer is initialized to the empty string.
  6724. */
  6725. in = in_copy;
  6726. /* Step 2:
  6727. * While the input buffer is not empty, loop as follows:
  6728. */
  6729. while (*in) {
  6730. /* Step 2a:
  6731. * If the input buffer begins with a prefix of "../" or "./",
  6732. * then remove that prefix from the input buffer;
  6733. */
  6734. if (!strncmp(in, "../", 3)) {
  6735. in += 3;
  6736. } else if (!strncmp(in, "./", 2)) {
  6737. in += 2;
  6738. }
  6739. /* otherwise */
  6740. /* Step 2b:
  6741. * if the input buffer begins with a prefix of "/./" or "/.",
  6742. * where "." is a complete path segment, then replace that
  6743. * prefix with "/" in the input buffer;
  6744. */
  6745. else if (!strncmp(in, "/./", 3)) {
  6746. in += 2;
  6747. } else if (!strcmp(in, "/.")) {
  6748. in[1] = 0;
  6749. }
  6750. /* otherwise */
  6751. /* Step 2c:
  6752. * if the input buffer begins with a prefix of "/../" or "/..",
  6753. * where ".." is a complete path segment, then replace that
  6754. * prefix with "/" in the input buffer and remove the last
  6755. * segment and its preceding "/" (if any) from the output
  6756. * buffer;
  6757. */
  6758. else if (!strncmp(in, "/../", 4)) {
  6759. in += 3;
  6760. if (out_begin != out_end) {
  6761. /* remove last segment */
  6762. do {
  6763. out_end--;
  6764. *out_end = 0;
  6765. } while ((out_begin != out_end) && (*out_end != '/'));
  6766. }
  6767. } else if (!strcmp(in, "/..")) {
  6768. in[1] = 0;
  6769. if (out_begin != out_end) {
  6770. /* remove last segment */
  6771. do {
  6772. out_end--;
  6773. *out_end = 0;
  6774. } while ((out_begin != out_end) && (*out_end != '/'));
  6775. }
  6776. }
  6777. /* otherwise */
  6778. /* Step 2d:
  6779. * if the input buffer consists only of "." or "..", then remove
  6780. * that from the input buffer;
  6781. */
  6782. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6783. *in = 0;
  6784. }
  6785. /* otherwise */
  6786. /* Step 2e:
  6787. * move the first path segment in the input buffer to the end of
  6788. * the output buffer, including the initial "/" character (if
  6789. * any) and any subsequent characters up to, but not including,
  6790. * the next "/" character or the end of the input buffer.
  6791. */
  6792. else {
  6793. do {
  6794. *out_end = *in;
  6795. out_end++;
  6796. in++;
  6797. } while ((*in != 0) && (*in != '/'));
  6798. }
  6799. }
  6800. /* Step 3:
  6801. * Finally, the output buffer is returned as the result of
  6802. * remove_dot_segments.
  6803. */
  6804. /* Terminate output */
  6805. *out_end = 0;
  6806. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6807. * extension) are identical. Replace all "./" by "/" and remove a "." at the
  6808. * end.
  6809. * Also replace all "//" by "/".
  6810. * Repeat until there is no "./" or "//" anymore.
  6811. */
  6812. do {
  6813. replaced = 0;
  6814. /* replace ./ by / */
  6815. out_end = out_begin;
  6816. while (*out_end) {
  6817. if ((*out_end == '.')
  6818. && ((out_end[1] == '/') || (out_end[1] == 0))) {
  6819. char *r = out_end;
  6820. do {
  6821. r[0] = r[1];
  6822. r++;
  6823. replaced = 1;
  6824. } while (r[0] != 0);
  6825. }
  6826. out_end++;
  6827. }
  6828. /* replace ./ by / */
  6829. out_end = out_begin;
  6830. while (*out_end) {
  6831. if ((out_end[0] == '/') && (out_end[1] == '/')) {
  6832. char *c = out_end;
  6833. while (*c) {
  6834. c[0] = c[1];
  6835. c++;
  6836. }
  6837. replaced = 1;
  6838. }
  6839. out_end++;
  6840. }
  6841. } while (replaced);
  6842. /* Free temporary copies */
  6843. mg_free(in_copy);
  6844. }
  6845. static const struct {
  6846. const char *extension;
  6847. size_t ext_len;
  6848. const char *mime_type;
  6849. } builtin_mime_types[] = {
  6850. /* IANA registered MIME types
  6851. * (http://www.iana.org/assignments/media-types)
  6852. * application types */
  6853. {".doc", 4, "application/msword"},
  6854. {".eps", 4, "application/postscript"},
  6855. {".exe", 4, "application/octet-stream"},
  6856. {".js", 3, "application/javascript"},
  6857. {".json", 5, "application/json"},
  6858. {".pdf", 4, "application/pdf"},
  6859. {".ps", 3, "application/postscript"},
  6860. {".rtf", 4, "application/rtf"},
  6861. {".xhtml", 6, "application/xhtml+xml"},
  6862. {".xsl", 4, "application/xml"},
  6863. {".xslt", 5, "application/xml"},
  6864. /* fonts */
  6865. {".ttf", 4, "application/font-sfnt"},
  6866. {".cff", 4, "application/font-sfnt"},
  6867. {".otf", 4, "application/font-sfnt"},
  6868. {".aat", 4, "application/font-sfnt"},
  6869. {".sil", 4, "application/font-sfnt"},
  6870. {".pfr", 4, "application/font-tdpfr"},
  6871. {".woff", 5, "application/font-woff"},
  6872. /* audio */
  6873. {".mp3", 4, "audio/mpeg"},
  6874. {".oga", 4, "audio/ogg"},
  6875. {".ogg", 4, "audio/ogg"},
  6876. /* image */
  6877. {".gif", 4, "image/gif"},
  6878. {".ief", 4, "image/ief"},
  6879. {".jpeg", 5, "image/jpeg"},
  6880. {".jpg", 4, "image/jpeg"},
  6881. {".jpm", 4, "image/jpm"},
  6882. {".jpx", 4, "image/jpx"},
  6883. {".png", 4, "image/png"},
  6884. {".svg", 4, "image/svg+xml"},
  6885. {".tif", 4, "image/tiff"},
  6886. {".tiff", 5, "image/tiff"},
  6887. /* model */
  6888. {".wrl", 4, "model/vrml"},
  6889. /* text */
  6890. {".css", 4, "text/css"},
  6891. {".csv", 4, "text/csv"},
  6892. {".htm", 4, "text/html"},
  6893. {".html", 5, "text/html"},
  6894. {".sgm", 4, "text/sgml"},
  6895. {".shtm", 5, "text/html"},
  6896. {".shtml", 6, "text/html"},
  6897. {".txt", 4, "text/plain"},
  6898. {".xml", 4, "text/xml"},
  6899. /* video */
  6900. {".mov", 4, "video/quicktime"},
  6901. {".mp4", 4, "video/mp4"},
  6902. {".mpeg", 5, "video/mpeg"},
  6903. {".mpg", 4, "video/mpeg"},
  6904. {".ogv", 4, "video/ogg"},
  6905. {".qt", 3, "video/quicktime"},
  6906. /* not registered types
  6907. * (http://reference.sitepoint.com/html/mime-types-full,
  6908. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6909. {".arj", 4, "application/x-arj-compressed"},
  6910. {".gz", 3, "application/x-gunzip"},
  6911. {".rar", 4, "application/x-arj-compressed"},
  6912. {".swf", 4, "application/x-shockwave-flash"},
  6913. {".tar", 4, "application/x-tar"},
  6914. {".tgz", 4, "application/x-tar-gz"},
  6915. {".torrent", 8, "application/x-bittorrent"},
  6916. {".ppt", 4, "application/x-mspowerpoint"},
  6917. {".xls", 4, "application/x-msexcel"},
  6918. {".zip", 4, "application/x-zip-compressed"},
  6919. {".aac",
  6920. 4,
  6921. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6922. {".aif", 4, "audio/x-aif"},
  6923. {".m3u", 4, "audio/x-mpegurl"},
  6924. {".mid", 4, "audio/x-midi"},
  6925. {".ra", 3, "audio/x-pn-realaudio"},
  6926. {".ram", 4, "audio/x-pn-realaudio"},
  6927. {".wav", 4, "audio/x-wav"},
  6928. {".bmp", 4, "image/bmp"},
  6929. {".ico", 4, "image/x-icon"},
  6930. {".pct", 4, "image/x-pct"},
  6931. {".pict", 5, "image/pict"},
  6932. {".rgb", 4, "image/x-rgb"},
  6933. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6934. {".asf", 4, "video/x-ms-asf"},
  6935. {".avi", 4, "video/x-msvideo"},
  6936. {".m4v", 4, "video/x-m4v"},
  6937. {NULL, 0, NULL}};
  6938. const char *
  6939. mg_get_builtin_mime_type(const char *path)
  6940. {
  6941. const char *ext;
  6942. size_t i, path_len;
  6943. path_len = strlen(path);
  6944. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6945. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6946. if ((path_len > builtin_mime_types[i].ext_len)
  6947. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6948. return builtin_mime_types[i].mime_type;
  6949. }
  6950. }
  6951. return "text/plain";
  6952. }
  6953. /* Look at the "path" extension and figure what mime type it has.
  6954. * Store mime type in the vector. */
  6955. static void
  6956. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6957. {
  6958. struct vec ext_vec, mime_vec;
  6959. const char *list, *ext;
  6960. size_t path_len;
  6961. path_len = strlen(path);
  6962. if ((conn == NULL) || (vec == NULL)) {
  6963. if (vec != NULL) {
  6964. memset(vec, '\0', sizeof(struct vec));
  6965. }
  6966. return;
  6967. }
  6968. /* Scan user-defined mime types first, in case user wants to
  6969. * override default mime types. */
  6970. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6971. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6972. /* ext now points to the path suffix */
  6973. ext = path + path_len - ext_vec.len;
  6974. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6975. *vec = mime_vec;
  6976. return;
  6977. }
  6978. }
  6979. vec->ptr = mg_get_builtin_mime_type(path);
  6980. vec->len = strlen(vec->ptr);
  6981. }
  6982. /* Stringify binary data. Output buffer must be twice as big as input,
  6983. * because each byte takes 2 bytes in string representation */
  6984. static void
  6985. bin2str(char *to, const unsigned char *p, size_t len)
  6986. {
  6987. static const char *hex = "0123456789abcdef";
  6988. for (; len--; p++) {
  6989. *to++ = hex[p[0] >> 4];
  6990. *to++ = hex[p[0] & 0x0f];
  6991. }
  6992. *to = '\0';
  6993. }
  6994. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6995. */
  6996. char *
  6997. mg_md5(char buf[33], ...)
  6998. {
  6999. md5_byte_t hash[16];
  7000. const char *p;
  7001. va_list ap;
  7002. md5_state_t ctx;
  7003. md5_init(&ctx);
  7004. va_start(ap, buf);
  7005. while ((p = va_arg(ap, const char *)) != NULL) {
  7006. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7007. }
  7008. va_end(ap);
  7009. md5_finish(&ctx, hash);
  7010. bin2str(buf, hash, sizeof(hash));
  7011. return buf;
  7012. }
  7013. /* Check the user's password, return 1 if OK */
  7014. static int
  7015. check_password(const char *method,
  7016. const char *ha1,
  7017. const char *uri,
  7018. const char *nonce,
  7019. const char *nc,
  7020. const char *cnonce,
  7021. const char *qop,
  7022. const char *response)
  7023. {
  7024. char ha2[32 + 1], expected_response[32 + 1];
  7025. /* Some of the parameters may be NULL */
  7026. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7027. || (qop == NULL) || (response == NULL)) {
  7028. return 0;
  7029. }
  7030. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7031. if (strlen(response) != 32) {
  7032. return 0;
  7033. }
  7034. mg_md5(ha2, method, ":", uri, NULL);
  7035. mg_md5(expected_response,
  7036. ha1,
  7037. ":",
  7038. nonce,
  7039. ":",
  7040. nc,
  7041. ":",
  7042. cnonce,
  7043. ":",
  7044. qop,
  7045. ":",
  7046. ha2,
  7047. NULL);
  7048. return mg_strcasecmp(response, expected_response) == 0;
  7049. }
  7050. #if !defined(NO_FILESYSTEMS)
  7051. /* Use the global passwords file, if specified by auth_gpass option,
  7052. * or search for .htpasswd in the requested directory. */
  7053. static void
  7054. open_auth_file(struct mg_connection *conn,
  7055. const char *path,
  7056. struct mg_file *filep)
  7057. {
  7058. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7059. char name[PATH_MAX];
  7060. const char *p, *e,
  7061. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7062. int truncated;
  7063. if (gpass != NULL) {
  7064. /* Use global passwords file */
  7065. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7066. #if defined(DEBUG)
  7067. /* Use mg_cry_internal here, since gpass has been configured. */
  7068. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7069. #endif
  7070. }
  7071. /* Important: using local struct mg_file to test path for
  7072. * is_directory flag. If filep is used, mg_stat() makes it
  7073. * appear as if auth file was opened.
  7074. * TODO(mid): Check if this is still required after rewriting
  7075. * mg_stat */
  7076. } else if (mg_stat(conn, path, &filep->stat)
  7077. && filep->stat.is_directory) {
  7078. mg_snprintf(conn,
  7079. &truncated,
  7080. name,
  7081. sizeof(name),
  7082. "%s/%s",
  7083. path,
  7084. PASSWORDS_FILE_NAME);
  7085. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7086. #if defined(DEBUG)
  7087. /* Don't use mg_cry_internal here, but only a trace, since this
  7088. * is
  7089. * a typical case. It will occur for every directory
  7090. * without a password file. */
  7091. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7092. #endif
  7093. }
  7094. } else {
  7095. /* Try to find .htpasswd in requested directory. */
  7096. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7097. if (e[0] == '/') {
  7098. break;
  7099. }
  7100. }
  7101. mg_snprintf(conn,
  7102. &truncated,
  7103. name,
  7104. sizeof(name),
  7105. "%.*s/%s",
  7106. (int)(e - p),
  7107. p,
  7108. PASSWORDS_FILE_NAME);
  7109. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7110. #if defined(DEBUG)
  7111. /* Don't use mg_cry_internal here, but only a trace, since this
  7112. * is
  7113. * a typical case. It will occur for every directory
  7114. * without a password file. */
  7115. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7116. #endif
  7117. }
  7118. }
  7119. }
  7120. }
  7121. #endif /* NO_FILESYSTEMS */
  7122. /* Parsed Authorization header */
  7123. struct ah {
  7124. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7125. };
  7126. /* Return 1 on success. Always initializes the ah structure. */
  7127. static int
  7128. parse_auth_header(struct mg_connection *conn,
  7129. char *buf,
  7130. size_t buf_size,
  7131. struct ah *ah)
  7132. {
  7133. char *name, *value, *s;
  7134. const char *auth_header;
  7135. uint64_t nonce;
  7136. if (!ah || !conn) {
  7137. return 0;
  7138. }
  7139. (void)memset(ah, 0, sizeof(*ah));
  7140. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7141. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7142. return 0;
  7143. }
  7144. /* Make modifiable copy of the auth header */
  7145. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7146. s = buf;
  7147. /* Parse authorization header */
  7148. for (;;) {
  7149. /* Gobble initial spaces */
  7150. while (isspace((unsigned char)*s)) {
  7151. s++;
  7152. }
  7153. name = skip_quoted(&s, "=", " ", 0);
  7154. /* Value is either quote-delimited, or ends at first comma or space.
  7155. */
  7156. if (s[0] == '\"') {
  7157. s++;
  7158. value = skip_quoted(&s, "\"", " ", '\\');
  7159. if (s[0] == ',') {
  7160. s++;
  7161. }
  7162. } else {
  7163. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  7164. * spaces */
  7165. }
  7166. if (*name == '\0') {
  7167. break;
  7168. }
  7169. if (!strcmp(name, "username")) {
  7170. ah->user = value;
  7171. } else if (!strcmp(name, "cnonce")) {
  7172. ah->cnonce = value;
  7173. } else if (!strcmp(name, "response")) {
  7174. ah->response = value;
  7175. } else if (!strcmp(name, "uri")) {
  7176. ah->uri = value;
  7177. } else if (!strcmp(name, "qop")) {
  7178. ah->qop = value;
  7179. } else if (!strcmp(name, "nc")) {
  7180. ah->nc = value;
  7181. } else if (!strcmp(name, "nonce")) {
  7182. ah->nonce = value;
  7183. }
  7184. }
  7185. #if !defined(NO_NONCE_CHECK)
  7186. /* Read the nonce from the response. */
  7187. if (ah->nonce == NULL) {
  7188. return 0;
  7189. }
  7190. s = NULL;
  7191. nonce = strtoull(ah->nonce, &s, 10);
  7192. if ((s == NULL) || (*s != 0)) {
  7193. return 0;
  7194. }
  7195. /* Convert the nonce from the client to a number. */
  7196. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7197. /* The converted number corresponds to the time the nounce has been
  7198. * created. This should not be earlier than the server start. */
  7199. /* Server side nonce check is valuable in all situations but one:
  7200. * if the server restarts frequently, but the client should not see
  7201. * that, so the server should accept nonces from previous starts. */
  7202. /* However, the reasonable default is to not accept a nonce from a
  7203. * previous start, so if anyone changed the access rights between
  7204. * two restarts, a new login is required. */
  7205. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7206. /* nonce is from a previous start of the server and no longer valid
  7207. * (replay attack?) */
  7208. return 0;
  7209. }
  7210. /* Check if the nonce is too high, so it has not (yet) been used by the
  7211. * server. */
  7212. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7213. + conn->dom_ctx->nonce_count)) {
  7214. return 0;
  7215. }
  7216. #else
  7217. (void)nonce;
  7218. #endif
  7219. /* CGI needs it as REMOTE_USER */
  7220. if (ah->user != NULL) {
  7221. conn->request_info.remote_user =
  7222. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7223. } else {
  7224. return 0;
  7225. }
  7226. return 1;
  7227. }
  7228. static const char *
  7229. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7230. {
  7231. #if defined(MG_USE_OPEN_FILE)
  7232. const char *eof;
  7233. size_t len;
  7234. const char *memend;
  7235. #else
  7236. (void)p; /* parameter is unused */
  7237. #endif
  7238. if (!filep) {
  7239. return NULL;
  7240. }
  7241. #if defined(MG_USE_OPEN_FILE)
  7242. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7243. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7244. /* Search for \n from p till the end of stream */
  7245. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7246. if (eof != NULL) {
  7247. eof += 1; /* Include \n */
  7248. } else {
  7249. eof = memend; /* Copy remaining data */
  7250. }
  7251. len =
  7252. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7253. memcpy(buf, *p, len);
  7254. buf[len] = '\0';
  7255. *p += len;
  7256. return len ? eof : NULL;
  7257. } else /* filep->access.fp block below */
  7258. #endif
  7259. if (filep->access.fp != NULL) {
  7260. return fgets(buf, (int)size, filep->access.fp);
  7261. } else {
  7262. return NULL;
  7263. }
  7264. }
  7265. /* Define the initial recursion depth for procesesing htpasswd files that
  7266. * include other htpasswd
  7267. * (or even the same) files. It is not difficult to provide a file or files
  7268. * s.t. they force civetweb
  7269. * to infinitely recurse and then crash.
  7270. */
  7271. #define INITIAL_DEPTH 9
  7272. #if INITIAL_DEPTH <= 0
  7273. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7274. #endif
  7275. #if !defined(NO_FILESYSTEMS)
  7276. struct read_auth_file_struct {
  7277. struct mg_connection *conn;
  7278. struct ah ah;
  7279. const char *domain;
  7280. char buf[256 + 256 + 40];
  7281. const char *f_user;
  7282. const char *f_domain;
  7283. const char *f_ha1;
  7284. };
  7285. static int
  7286. read_auth_file(struct mg_file *filep,
  7287. struct read_auth_file_struct *workdata,
  7288. int depth)
  7289. {
  7290. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7291. int is_authorized = 0;
  7292. struct mg_file fp;
  7293. size_t l;
  7294. if (!filep || !workdata || (0 == depth)) {
  7295. return 0;
  7296. }
  7297. /* Loop over passwords file */
  7298. #if defined(MG_USE_OPEN_FILE)
  7299. p = (char *)filep->access.membuf;
  7300. #endif
  7301. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7302. l = strlen(workdata->buf);
  7303. while (l > 0) {
  7304. if (isspace((unsigned char)workdata->buf[l - 1])
  7305. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7306. l--;
  7307. workdata->buf[l] = 0;
  7308. } else
  7309. break;
  7310. }
  7311. if (l < 1) {
  7312. continue;
  7313. }
  7314. workdata->f_user = workdata->buf;
  7315. if (workdata->f_user[0] == ':') {
  7316. /* user names may not contain a ':' and may not be empty,
  7317. * so lines starting with ':' may be used for a special purpose
  7318. */
  7319. if (workdata->f_user[1] == '#') {
  7320. /* :# is a comment */
  7321. continue;
  7322. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7323. if (mg_fopen(workdata->conn,
  7324. workdata->f_user + 9,
  7325. MG_FOPEN_MODE_READ,
  7326. &fp)) {
  7327. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7328. (void)mg_fclose(
  7329. &fp.access); /* ignore error on read only file */
  7330. /* No need to continue processing files once we have a
  7331. * match, since nothing will reset it back
  7332. * to 0.
  7333. */
  7334. if (is_authorized) {
  7335. return is_authorized;
  7336. }
  7337. } else {
  7338. mg_cry_internal(workdata->conn,
  7339. "%s: cannot open authorization file: %s",
  7340. __func__,
  7341. workdata->buf);
  7342. }
  7343. continue;
  7344. }
  7345. /* everything is invalid for the moment (might change in the
  7346. * future) */
  7347. mg_cry_internal(workdata->conn,
  7348. "%s: syntax error in authorization file: %s",
  7349. __func__,
  7350. workdata->buf);
  7351. continue;
  7352. }
  7353. workdata->f_domain = strchr(workdata->f_user, ':');
  7354. if (workdata->f_domain == NULL) {
  7355. mg_cry_internal(workdata->conn,
  7356. "%s: syntax error in authorization file: %s",
  7357. __func__,
  7358. workdata->buf);
  7359. continue;
  7360. }
  7361. *(char *)(workdata->f_domain) = 0;
  7362. (workdata->f_domain)++;
  7363. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7364. if (workdata->f_ha1 == NULL) {
  7365. mg_cry_internal(workdata->conn,
  7366. "%s: syntax error in authorization file: %s",
  7367. __func__,
  7368. workdata->buf);
  7369. continue;
  7370. }
  7371. *(char *)(workdata->f_ha1) = 0;
  7372. (workdata->f_ha1)++;
  7373. if (!strcmp(workdata->ah.user, workdata->f_user)
  7374. && !strcmp(workdata->domain, workdata->f_domain)) {
  7375. return check_password(workdata->conn->request_info.request_method,
  7376. workdata->f_ha1,
  7377. workdata->ah.uri,
  7378. workdata->ah.nonce,
  7379. workdata->ah.nc,
  7380. workdata->ah.cnonce,
  7381. workdata->ah.qop,
  7382. workdata->ah.response);
  7383. }
  7384. }
  7385. return is_authorized;
  7386. }
  7387. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7388. static int
  7389. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7390. {
  7391. struct read_auth_file_struct workdata;
  7392. char buf[MG_BUF_LEN];
  7393. if (!conn || !conn->dom_ctx) {
  7394. return 0;
  7395. }
  7396. memset(&workdata, 0, sizeof(workdata));
  7397. workdata.conn = conn;
  7398. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7399. return 0;
  7400. }
  7401. if (realm) {
  7402. workdata.domain = realm;
  7403. } else {
  7404. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7405. }
  7406. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7407. }
  7408. /* Public function to check http digest authentication header */
  7409. int
  7410. mg_check_digest_access_authentication(struct mg_connection *conn,
  7411. const char *realm,
  7412. const char *filename)
  7413. {
  7414. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7415. int auth;
  7416. if (!conn || !filename) {
  7417. return -1;
  7418. }
  7419. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7420. return -2;
  7421. }
  7422. auth = authorize(conn, &file, realm);
  7423. mg_fclose(&file.access);
  7424. return auth;
  7425. }
  7426. #endif /* NO_FILESYSTEMS */
  7427. /* Return 1 if request is authorised, 0 otherwise. */
  7428. static int
  7429. check_authorization(struct mg_connection *conn, const char *path)
  7430. {
  7431. #if !defined(NO_FILESYSTEMS)
  7432. char fname[PATH_MAX];
  7433. struct vec uri_vec, filename_vec;
  7434. const char *list;
  7435. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7436. int authorized = 1, truncated;
  7437. if (!conn || !conn->dom_ctx) {
  7438. return 0;
  7439. }
  7440. list = conn->dom_ctx->config[PROTECT_URI];
  7441. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7442. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7443. mg_snprintf(conn,
  7444. &truncated,
  7445. fname,
  7446. sizeof(fname),
  7447. "%.*s",
  7448. (int)filename_vec.len,
  7449. filename_vec.ptr);
  7450. if (truncated
  7451. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7452. mg_cry_internal(conn,
  7453. "%s: cannot open %s: %s",
  7454. __func__,
  7455. fname,
  7456. strerror(errno));
  7457. }
  7458. break;
  7459. }
  7460. }
  7461. if (!is_file_opened(&file.access)) {
  7462. open_auth_file(conn, path, &file);
  7463. }
  7464. if (is_file_opened(&file.access)) {
  7465. authorized = authorize(conn, &file, NULL);
  7466. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7467. }
  7468. return authorized;
  7469. #else
  7470. (void)conn;
  7471. (void)path;
  7472. return 1;
  7473. #endif /* NO_FILESYSTEMS */
  7474. }
  7475. /* Internal function. Assumes conn is valid */
  7476. static void
  7477. send_authorization_request(struct mg_connection *conn, const char *realm)
  7478. {
  7479. char date[64];
  7480. time_t curtime = time(NULL);
  7481. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7482. if (!realm) {
  7483. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7484. }
  7485. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7486. nonce += conn->dom_ctx->nonce_count;
  7487. ++conn->dom_ctx->nonce_count;
  7488. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7489. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7490. conn->status_code = 401;
  7491. conn->must_close = 1;
  7492. gmt_time_string(date, sizeof(date), &curtime);
  7493. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7494. send_no_cache_header(conn);
  7495. send_additional_header(conn);
  7496. mg_printf(conn,
  7497. "Date: %s\r\n"
  7498. "Connection: %s\r\n"
  7499. "Content-Length: 0\r\n"
  7500. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7501. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7502. date,
  7503. suggest_connection_header(conn),
  7504. realm,
  7505. nonce);
  7506. }
  7507. /* Interface function. Parameters are provided by the user, so do
  7508. * at least some basic checks.
  7509. */
  7510. int
  7511. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7512. const char *realm)
  7513. {
  7514. if (conn && conn->dom_ctx) {
  7515. send_authorization_request(conn, realm);
  7516. return 0;
  7517. }
  7518. return -1;
  7519. }
  7520. #if !defined(NO_FILES)
  7521. static int
  7522. is_authorized_for_put(struct mg_connection *conn)
  7523. {
  7524. if (conn) {
  7525. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7526. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7527. int ret = 0;
  7528. if (passfile != NULL
  7529. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7530. ret = authorize(conn, &file, NULL);
  7531. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7532. }
  7533. return ret;
  7534. }
  7535. return 0;
  7536. }
  7537. #endif
  7538. int
  7539. mg_modify_passwords_file(const char *fname,
  7540. const char *domain,
  7541. const char *user,
  7542. const char *pass)
  7543. {
  7544. int found, i;
  7545. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7546. FILE *fp, *fp2;
  7547. found = 0;
  7548. fp = fp2 = NULL;
  7549. /* Regard empty password as no password - remove user record. */
  7550. if ((pass != NULL) && (pass[0] == '\0')) {
  7551. pass = NULL;
  7552. }
  7553. /* Other arguments must not be empty */
  7554. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7555. return 0;
  7556. }
  7557. /* Using the given file format, user name and domain must not contain
  7558. * ':'
  7559. */
  7560. if (strchr(user, ':') != NULL) {
  7561. return 0;
  7562. }
  7563. if (strchr(domain, ':') != NULL) {
  7564. return 0;
  7565. }
  7566. /* Do not allow control characters like newline in user name and domain.
  7567. * Do not allow excessively long names either. */
  7568. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7569. if (iscntrl((unsigned char)user[i])) {
  7570. return 0;
  7571. }
  7572. }
  7573. if (user[i]) {
  7574. return 0;
  7575. }
  7576. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7577. if (iscntrl((unsigned char)domain[i])) {
  7578. return 0;
  7579. }
  7580. }
  7581. if (domain[i]) {
  7582. return 0;
  7583. }
  7584. /* The maximum length of the path to the password file is limited */
  7585. if ((strlen(fname) + 4) >= PATH_MAX) {
  7586. return 0;
  7587. }
  7588. /* Create a temporary file name. Length has been checked before. */
  7589. strcpy(tmp, fname);
  7590. strcat(tmp, ".tmp");
  7591. /* Create the file if does not exist */
  7592. /* Use of fopen here is OK, since fname is only ASCII */
  7593. if ((fp = fopen(fname, "a+")) != NULL) {
  7594. (void)fclose(fp);
  7595. }
  7596. /* Open the given file and temporary file */
  7597. if ((fp = fopen(fname, "r")) == NULL) {
  7598. return 0;
  7599. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7600. fclose(fp);
  7601. return 0;
  7602. }
  7603. /* Copy the stuff to temporary file */
  7604. while (fgets(line, sizeof(line), fp) != NULL) {
  7605. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7606. continue;
  7607. }
  7608. u[255] = 0;
  7609. d[255] = 0;
  7610. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7611. found++;
  7612. if (pass != NULL) {
  7613. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7614. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7615. }
  7616. } else {
  7617. fprintf(fp2, "%s", line);
  7618. }
  7619. }
  7620. /* If new user, just add it */
  7621. if (!found && (pass != NULL)) {
  7622. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7623. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7624. }
  7625. /* Close files */
  7626. fclose(fp);
  7627. fclose(fp2);
  7628. /* Put the temp file in place of real file */
  7629. IGNORE_UNUSED_RESULT(remove(fname));
  7630. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7631. return 1;
  7632. }
  7633. static int
  7634. is_valid_port(unsigned long port)
  7635. {
  7636. return (port <= 0xffff);
  7637. }
  7638. static int
  7639. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7640. {
  7641. struct addrinfo hints, *res, *ressave;
  7642. int func_ret = 0;
  7643. int gai_ret;
  7644. memset(&hints, 0, sizeof(struct addrinfo));
  7645. hints.ai_family = af;
  7646. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7647. if (gai_ret != 0) {
  7648. /* gai_strerror could be used to convert gai_ret to a string */
  7649. /* POSIX return values: see
  7650. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7651. */
  7652. /* Windows return values: see
  7653. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7654. */
  7655. return 0;
  7656. }
  7657. ressave = res;
  7658. while (res) {
  7659. if (dstlen >= (size_t)res->ai_addrlen) {
  7660. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7661. func_ret = 1;
  7662. }
  7663. res = res->ai_next;
  7664. }
  7665. freeaddrinfo(ressave);
  7666. return func_ret;
  7667. }
  7668. static int
  7669. connect_socket(struct mg_context *ctx /* may be NULL */,
  7670. const char *host,
  7671. int port,
  7672. int use_ssl,
  7673. char *ebuf,
  7674. size_t ebuf_len,
  7675. SOCKET *sock /* output: socket, must not be NULL */,
  7676. union usa *sa /* output: socket address, must not be NULL */
  7677. )
  7678. {
  7679. int ip_ver = 0;
  7680. int conn_ret = -1;
  7681. int sockerr = 0;
  7682. *sock = INVALID_SOCKET;
  7683. memset(sa, 0, sizeof(*sa));
  7684. if (ebuf_len > 0) {
  7685. *ebuf = 0;
  7686. }
  7687. if (host == NULL) {
  7688. mg_snprintf(NULL,
  7689. NULL, /* No truncation check for ebuf */
  7690. ebuf,
  7691. ebuf_len,
  7692. "%s",
  7693. "NULL host");
  7694. return 0;
  7695. }
  7696. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7697. mg_snprintf(NULL,
  7698. NULL, /* No truncation check for ebuf */
  7699. ebuf,
  7700. ebuf_len,
  7701. "%s",
  7702. "invalid port");
  7703. return 0;
  7704. }
  7705. #if !defined(NO_SSL)
  7706. #if !defined(NO_SSL_DL)
  7707. #if defined(OPENSSL_API_1_1)
  7708. if (use_ssl && (TLS_client_method == NULL)) {
  7709. mg_snprintf(NULL,
  7710. NULL, /* No truncation check for ebuf */
  7711. ebuf,
  7712. ebuf_len,
  7713. "%s",
  7714. "SSL is not initialized");
  7715. return 0;
  7716. }
  7717. #else
  7718. if (use_ssl && (SSLv23_client_method == NULL)) {
  7719. mg_snprintf(NULL,
  7720. NULL, /* No truncation check for ebuf */
  7721. ebuf,
  7722. ebuf_len,
  7723. "%s",
  7724. "SSL is not initialized");
  7725. return 0;
  7726. }
  7727. #endif /* OPENSSL_API_1_1 */
  7728. #else
  7729. (void)use_ssl;
  7730. #endif /* NO_SSL_DL */
  7731. #else
  7732. (void)use_ssl;
  7733. #endif /* !defined(NO_SSL) */
  7734. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7735. sa->sin.sin_family = AF_INET;
  7736. sa->sin.sin_port = htons((uint16_t)port);
  7737. ip_ver = 4;
  7738. #if defined(USE_IPV6)
  7739. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7740. sa->sin6.sin6_family = AF_INET6;
  7741. sa->sin6.sin6_port = htons((uint16_t)port);
  7742. ip_ver = 6;
  7743. } else if (host[0] == '[') {
  7744. /* While getaddrinfo on Windows will work with [::1],
  7745. * getaddrinfo on Linux only works with ::1 (without []). */
  7746. size_t l = strlen(host + 1);
  7747. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7748. if (h) {
  7749. h[l - 1] = 0;
  7750. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7751. sa->sin6.sin6_family = AF_INET6;
  7752. sa->sin6.sin6_port = htons((uint16_t)port);
  7753. ip_ver = 6;
  7754. }
  7755. mg_free(h);
  7756. }
  7757. #endif
  7758. }
  7759. if (ip_ver == 0) {
  7760. mg_snprintf(NULL,
  7761. NULL, /* No truncation check for ebuf */
  7762. ebuf,
  7763. ebuf_len,
  7764. "%s",
  7765. "host not found");
  7766. return 0;
  7767. }
  7768. if (ip_ver == 4) {
  7769. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7770. }
  7771. #if defined(USE_IPV6)
  7772. else if (ip_ver == 6) {
  7773. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7774. }
  7775. #endif
  7776. if (*sock == INVALID_SOCKET) {
  7777. mg_snprintf(NULL,
  7778. NULL, /* No truncation check for ebuf */
  7779. ebuf,
  7780. ebuf_len,
  7781. "socket(): %s",
  7782. strerror(ERRNO));
  7783. return 0;
  7784. }
  7785. if (0 != set_non_blocking_mode(*sock)) {
  7786. mg_snprintf(NULL,
  7787. NULL, /* No truncation check for ebuf */
  7788. ebuf,
  7789. ebuf_len,
  7790. "Cannot set socket to non-blocking: %s",
  7791. strerror(ERRNO));
  7792. closesocket(*sock);
  7793. *sock = INVALID_SOCKET;
  7794. return 0;
  7795. }
  7796. set_close_on_exec(*sock, NULL, ctx);
  7797. if (ip_ver == 4) {
  7798. /* connected with IPv4 */
  7799. conn_ret = connect(*sock,
  7800. (struct sockaddr *)((void *)&sa->sin),
  7801. sizeof(sa->sin));
  7802. }
  7803. #if defined(USE_IPV6)
  7804. else if (ip_ver == 6) {
  7805. /* connected with IPv6 */
  7806. conn_ret = connect(*sock,
  7807. (struct sockaddr *)((void *)&sa->sin6),
  7808. sizeof(sa->sin6));
  7809. }
  7810. #endif
  7811. if (conn_ret != 0) {
  7812. sockerr = ERRNO;
  7813. }
  7814. #if defined(_WIN32)
  7815. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7816. #else
  7817. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7818. #endif
  7819. /* Data for getsockopt */
  7820. void *psockerr = &sockerr;
  7821. int ret;
  7822. #if defined(_WIN32)
  7823. int len = (int)sizeof(sockerr);
  7824. #else
  7825. socklen_t len = (socklen_t)sizeof(sockerr);
  7826. #endif
  7827. /* Data for poll */
  7828. struct mg_pollfd pfd[1];
  7829. int pollres;
  7830. int ms_wait = 10000; /* 10 second timeout */
  7831. int nonstop = 0;
  7832. /* For a non-blocking socket, the connect sequence is:
  7833. * 1) call connect (will not block)
  7834. * 2) wait until the socket is ready for writing (select or poll)
  7835. * 3) check connection state with getsockopt
  7836. */
  7837. pfd[0].fd = *sock;
  7838. pfd[0].events = POLLOUT;
  7839. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7840. if (pollres != 1) {
  7841. /* Not connected */
  7842. mg_snprintf(NULL,
  7843. NULL, /* No truncation check for ebuf */
  7844. ebuf,
  7845. ebuf_len,
  7846. "connect(%s:%d): timeout",
  7847. host,
  7848. port);
  7849. closesocket(*sock);
  7850. *sock = INVALID_SOCKET;
  7851. return 0;
  7852. }
  7853. #if defined(_WIN32)
  7854. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7855. #else
  7856. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7857. #endif
  7858. if ((ret == 0) && (sockerr == 0)) {
  7859. conn_ret = 0;
  7860. }
  7861. }
  7862. if (conn_ret != 0) {
  7863. /* Not connected */
  7864. mg_snprintf(NULL,
  7865. NULL, /* No truncation check for ebuf */
  7866. ebuf,
  7867. ebuf_len,
  7868. "connect(%s:%d): error %s",
  7869. host,
  7870. port,
  7871. strerror(sockerr));
  7872. closesocket(*sock);
  7873. *sock = INVALID_SOCKET;
  7874. return 0;
  7875. }
  7876. return 1;
  7877. }
  7878. int
  7879. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7880. {
  7881. static const char *dont_escape = "._-$,;~()";
  7882. static const char *hex = "0123456789abcdef";
  7883. char *pos = dst;
  7884. const char *end = dst + dst_len - 1;
  7885. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7886. if (isalnum((unsigned char)*src)
  7887. || (strchr(dont_escape, *src) != NULL)) {
  7888. *pos = *src;
  7889. } else if (pos + 2 < end) {
  7890. pos[0] = '%';
  7891. pos[1] = hex[(unsigned char)*src >> 4];
  7892. pos[2] = hex[(unsigned char)*src & 0xf];
  7893. pos += 2;
  7894. } else {
  7895. break;
  7896. }
  7897. }
  7898. *pos = '\0';
  7899. return (*src == '\0') ? (int)(pos - dst) : -1;
  7900. }
  7901. /* Return 0 on success, non-zero if an error occurs. */
  7902. static int
  7903. print_dir_entry(struct de *de)
  7904. {
  7905. size_t namesize, escsize, i;
  7906. char *href, *esc, *p;
  7907. char size[64], mod[64];
  7908. #if defined(REENTRANT_TIME)
  7909. struct tm _tm;
  7910. struct tm *tm = &_tm;
  7911. #else
  7912. struct tm *tm;
  7913. #endif
  7914. /* Estimate worst case size for encoding and escaping */
  7915. namesize = strlen(de->file_name) + 1;
  7916. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7917. href = (char *)mg_malloc(namesize * 3 + escsize);
  7918. if (href == NULL) {
  7919. return -1;
  7920. }
  7921. mg_url_encode(de->file_name, href, namesize * 3);
  7922. esc = NULL;
  7923. if (escsize > 0) {
  7924. /* HTML escaping needed */
  7925. esc = href + namesize * 3;
  7926. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7927. mg_strlcpy(p, de->file_name + i, 2);
  7928. if (*p == '&') {
  7929. strcpy(p, "&amp;");
  7930. } else if (*p == '<') {
  7931. strcpy(p, "&lt;");
  7932. } else if (*p == '>') {
  7933. strcpy(p, "&gt;");
  7934. }
  7935. }
  7936. }
  7937. if (de->file.is_directory) {
  7938. mg_snprintf(de->conn,
  7939. NULL, /* Buffer is big enough */
  7940. size,
  7941. sizeof(size),
  7942. "%s",
  7943. "[DIRECTORY]");
  7944. } else {
  7945. /* We use (signed) cast below because MSVC 6 compiler cannot
  7946. * convert unsigned __int64 to double. Sigh. */
  7947. if (de->file.size < 1024) {
  7948. mg_snprintf(de->conn,
  7949. NULL, /* Buffer is big enough */
  7950. size,
  7951. sizeof(size),
  7952. "%d",
  7953. (int)de->file.size);
  7954. } else if (de->file.size < 0x100000) {
  7955. mg_snprintf(de->conn,
  7956. NULL, /* Buffer is big enough */
  7957. size,
  7958. sizeof(size),
  7959. "%.1fk",
  7960. (double)de->file.size / 1024.0);
  7961. } else if (de->file.size < 0x40000000) {
  7962. mg_snprintf(de->conn,
  7963. NULL, /* Buffer is big enough */
  7964. size,
  7965. sizeof(size),
  7966. "%.1fM",
  7967. (double)de->file.size / 1048576);
  7968. } else {
  7969. mg_snprintf(de->conn,
  7970. NULL, /* Buffer is big enough */
  7971. size,
  7972. sizeof(size),
  7973. "%.1fG",
  7974. (double)de->file.size / 1073741824);
  7975. }
  7976. }
  7977. /* Note: mg_snprintf will not cause a buffer overflow above.
  7978. * So, string truncation checks are not required here. */
  7979. #if defined(REENTRANT_TIME)
  7980. localtime_r(&de->file.last_modified, tm);
  7981. #else
  7982. tm = localtime(&de->file.last_modified);
  7983. #endif
  7984. if (tm != NULL) {
  7985. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7986. } else {
  7987. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7988. mod[sizeof(mod) - 1] = '\0';
  7989. }
  7990. mg_printf(de->conn,
  7991. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7992. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7993. href,
  7994. de->file.is_directory ? "/" : "",
  7995. esc ? esc : de->file_name,
  7996. de->file.is_directory ? "/" : "",
  7997. mod,
  7998. size);
  7999. mg_free(href);
  8000. return 0;
  8001. }
  8002. /* This function is called from send_directory() and used for
  8003. * sorting directory entries by size, or name, or modification time.
  8004. * On windows, __cdecl specification is needed in case if project is built
  8005. * with __stdcall convention. qsort always requires __cdels callback. */
  8006. static int WINCDECL
  8007. compare_dir_entries(const void *p1, const void *p2)
  8008. {
  8009. if (p1 && p2) {
  8010. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8011. const char *query_string = a->conn->request_info.query_string;
  8012. int cmp_result = 0;
  8013. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8014. query_string = "n";
  8015. }
  8016. if (a->file.is_directory && !b->file.is_directory) {
  8017. return -1; /* Always put directories on top */
  8018. } else if (!a->file.is_directory && b->file.is_directory) {
  8019. return 1; /* Always put directories on top */
  8020. } else if (*query_string == 'n') {
  8021. cmp_result = strcmp(a->file_name, b->file_name);
  8022. } else if (*query_string == 's') {
  8023. cmp_result = (a->file.size == b->file.size)
  8024. ? 0
  8025. : ((a->file.size > b->file.size) ? 1 : -1);
  8026. } else if (*query_string == 'd') {
  8027. cmp_result =
  8028. (a->file.last_modified == b->file.last_modified)
  8029. ? 0
  8030. : ((a->file.last_modified > b->file.last_modified) ? 1
  8031. : -1);
  8032. }
  8033. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8034. }
  8035. return 0;
  8036. }
  8037. static int
  8038. must_hide_file(struct mg_connection *conn, const char *path)
  8039. {
  8040. if (conn && conn->dom_ctx) {
  8041. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8042. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8043. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  8044. || ((pattern != NULL)
  8045. && (match_prefix(pattern, strlen(pattern), path) > 0));
  8046. }
  8047. return 0;
  8048. }
  8049. #if !defined(NO_FILESYSTEMS)
  8050. static int
  8051. scan_directory(struct mg_connection *conn,
  8052. const char *dir,
  8053. void *data,
  8054. int (*cb)(struct de *, void *))
  8055. {
  8056. char path[PATH_MAX];
  8057. struct dirent *dp;
  8058. DIR *dirp;
  8059. struct de de;
  8060. int truncated;
  8061. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8062. return 0;
  8063. } else {
  8064. de.conn = conn;
  8065. while ((dp = mg_readdir(dirp)) != NULL) {
  8066. /* Do not show current dir and hidden files */
  8067. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8068. || must_hide_file(conn, dp->d_name)) {
  8069. continue;
  8070. }
  8071. mg_snprintf(
  8072. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8073. /* If we don't memset stat structure to zero, mtime will have
  8074. * garbage and strftime() will segfault later on in
  8075. * print_dir_entry(). memset is required only if mg_stat()
  8076. * fails. For more details, see
  8077. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8078. memset(&de.file, 0, sizeof(de.file));
  8079. if (truncated) {
  8080. /* If the path is not complete, skip processing. */
  8081. continue;
  8082. }
  8083. if (!mg_stat(conn, path, &de.file)) {
  8084. mg_cry_internal(conn,
  8085. "%s: mg_stat(%s) failed: %s",
  8086. __func__,
  8087. path,
  8088. strerror(ERRNO));
  8089. }
  8090. de.file_name = dp->d_name;
  8091. cb(&de, data);
  8092. }
  8093. (void)mg_closedir(dirp);
  8094. }
  8095. return 1;
  8096. }
  8097. #endif /* NO_FILESYSTEMS */
  8098. #if !defined(NO_FILES)
  8099. static int
  8100. remove_directory(struct mg_connection *conn, const char *dir)
  8101. {
  8102. char path[PATH_MAX];
  8103. struct dirent *dp;
  8104. DIR *dirp;
  8105. struct de de;
  8106. int truncated;
  8107. int ok = 1;
  8108. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8109. return 0;
  8110. } else {
  8111. de.conn = conn;
  8112. while ((dp = mg_readdir(dirp)) != NULL) {
  8113. /* Do not show current dir (but show hidden files as they will
  8114. * also be removed) */
  8115. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8116. continue;
  8117. }
  8118. mg_snprintf(
  8119. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8120. /* If we don't memset stat structure to zero, mtime will have
  8121. * garbage and strftime() will segfault later on in
  8122. * print_dir_entry(). memset is required only if mg_stat()
  8123. * fails. For more details, see
  8124. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8125. memset(&de.file, 0, sizeof(de.file));
  8126. if (truncated) {
  8127. /* Do not delete anything shorter */
  8128. ok = 0;
  8129. continue;
  8130. }
  8131. if (!mg_stat(conn, path, &de.file)) {
  8132. mg_cry_internal(conn,
  8133. "%s: mg_stat(%s) failed: %s",
  8134. __func__,
  8135. path,
  8136. strerror(ERRNO));
  8137. ok = 0;
  8138. }
  8139. if (de.file.is_directory) {
  8140. if (remove_directory(conn, path) == 0) {
  8141. ok = 0;
  8142. }
  8143. } else {
  8144. /* This will fail file is the file is in memory */
  8145. if (mg_remove(conn, path) == 0) {
  8146. ok = 0;
  8147. }
  8148. }
  8149. }
  8150. (void)mg_closedir(dirp);
  8151. IGNORE_UNUSED_RESULT(rmdir(dir));
  8152. }
  8153. return ok;
  8154. }
  8155. #endif
  8156. struct dir_scan_data {
  8157. struct de *entries;
  8158. unsigned int num_entries;
  8159. unsigned int arr_size;
  8160. };
  8161. /* Behaves like realloc(), but frees original pointer on failure */
  8162. static void *
  8163. realloc2(void *ptr, size_t size)
  8164. {
  8165. void *new_ptr = mg_realloc(ptr, size);
  8166. if (new_ptr == NULL) {
  8167. mg_free(ptr);
  8168. }
  8169. return new_ptr;
  8170. }
  8171. #if !defined(NO_FILESYSTEMS)
  8172. static int
  8173. dir_scan_callback(struct de *de, void *data)
  8174. {
  8175. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8176. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8177. dsd->arr_size *= 2;
  8178. dsd->entries =
  8179. (struct de *)realloc2(dsd->entries,
  8180. dsd->arr_size * sizeof(dsd->entries[0]));
  8181. }
  8182. if (dsd->entries == NULL) {
  8183. /* TODO(lsm, low): propagate an error to the caller */
  8184. dsd->num_entries = 0;
  8185. } else {
  8186. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8187. dsd->entries[dsd->num_entries].file = de->file;
  8188. dsd->entries[dsd->num_entries].conn = de->conn;
  8189. dsd->num_entries++;
  8190. }
  8191. return 0;
  8192. }
  8193. static void
  8194. handle_directory_request(struct mg_connection *conn, const char *dir)
  8195. {
  8196. unsigned int i;
  8197. int sort_direction;
  8198. struct dir_scan_data data = {NULL, 0, 128};
  8199. char date[64], *esc, *p;
  8200. const char *title;
  8201. time_t curtime = time(NULL);
  8202. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8203. mg_send_http_error(conn,
  8204. 500,
  8205. "Error: Cannot open directory\nopendir(%s): %s",
  8206. dir,
  8207. strerror(ERRNO));
  8208. return;
  8209. }
  8210. gmt_time_string(date, sizeof(date), &curtime);
  8211. if (!conn) {
  8212. return;
  8213. }
  8214. esc = NULL;
  8215. title = conn->request_info.local_uri;
  8216. if (title[strcspn(title, "&<>")]) {
  8217. /* HTML escaping needed */
  8218. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8219. if (esc) {
  8220. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8221. mg_strlcpy(p, title + i, 2);
  8222. if (*p == '&') {
  8223. strcpy(p, "&amp;");
  8224. } else if (*p == '<') {
  8225. strcpy(p, "&lt;");
  8226. } else if (*p == '>') {
  8227. strcpy(p, "&gt;");
  8228. }
  8229. }
  8230. } else {
  8231. title = "";
  8232. }
  8233. }
  8234. sort_direction = ((conn->request_info.query_string != NULL)
  8235. && (conn->request_info.query_string[0] != '\0')
  8236. && (conn->request_info.query_string[1] == 'd'))
  8237. ? 'a'
  8238. : 'd';
  8239. conn->must_close = 1;
  8240. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8241. send_static_cache_header(conn);
  8242. send_additional_header(conn);
  8243. mg_printf(conn,
  8244. "Date: %s\r\n"
  8245. "Connection: close\r\n"
  8246. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8247. date);
  8248. mg_printf(conn,
  8249. "<html><head><title>Index of %s</title>"
  8250. "<style>th {text-align: left;}</style></head>"
  8251. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8252. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8253. "<th><a href=\"?d%c\">Modified</a></th>"
  8254. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8255. "<tr><td colspan=\"3\"><hr></td></tr>",
  8256. esc ? esc : title,
  8257. esc ? esc : title,
  8258. sort_direction,
  8259. sort_direction,
  8260. sort_direction);
  8261. mg_free(esc);
  8262. /* Print first entry - link to a parent directory */
  8263. mg_printf(conn,
  8264. "<tr><td><a href=\"%s\">%s</a></td>"
  8265. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8266. "..",
  8267. "Parent directory",
  8268. "-",
  8269. "-");
  8270. /* Sort and print directory entries */
  8271. if (data.entries != NULL) {
  8272. qsort(data.entries,
  8273. (size_t)data.num_entries,
  8274. sizeof(data.entries[0]),
  8275. compare_dir_entries);
  8276. for (i = 0; i < data.num_entries; i++) {
  8277. print_dir_entry(&data.entries[i]);
  8278. mg_free(data.entries[i].file_name);
  8279. }
  8280. mg_free(data.entries);
  8281. }
  8282. mg_printf(conn, "%s", "</table></pre></body></html>");
  8283. conn->status_code = 200;
  8284. }
  8285. #endif /* NO_FILESYSTEMS */
  8286. /* Send len bytes from the opened file to the client. */
  8287. static void
  8288. send_file_data(struct mg_connection *conn,
  8289. struct mg_file *filep,
  8290. int64_t offset,
  8291. int64_t len)
  8292. {
  8293. char buf[MG_BUF_LEN];
  8294. int to_read, num_read, num_written;
  8295. int64_t size;
  8296. if (!filep || !conn) {
  8297. return;
  8298. }
  8299. /* Sanity check the offset */
  8300. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8301. : (int64_t)(filep->stat.size);
  8302. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8303. #if defined(MG_USE_OPEN_FILE)
  8304. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8305. /* file stored in memory */
  8306. if (len > size - offset) {
  8307. len = size - offset;
  8308. }
  8309. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8310. } else /* else block below */
  8311. #endif
  8312. if (len > 0 && filep->access.fp != NULL) {
  8313. /* file stored on disk */
  8314. #if defined(__linux__)
  8315. /* sendfile is only available for Linux */
  8316. if ((conn->ssl == 0) && (conn->throttle == 0)
  8317. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8318. "yes"))) {
  8319. off_t sf_offs = (off_t)offset;
  8320. ssize_t sf_sent;
  8321. int sf_file = fileno(filep->access.fp);
  8322. int loop_cnt = 0;
  8323. do {
  8324. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8325. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8326. size_t sf_tosend =
  8327. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8328. sf_sent =
  8329. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8330. if (sf_sent > 0) {
  8331. len -= sf_sent;
  8332. offset += sf_sent;
  8333. } else if (loop_cnt == 0) {
  8334. /* This file can not be sent using sendfile.
  8335. * This might be the case for pseudo-files in the
  8336. * /sys/ and /proc/ file system.
  8337. * Use the regular user mode copy code instead. */
  8338. break;
  8339. } else if (sf_sent == 0) {
  8340. /* No error, but 0 bytes sent. May be EOF? */
  8341. return;
  8342. }
  8343. loop_cnt++;
  8344. } while ((len > 0) && (sf_sent >= 0));
  8345. if (sf_sent > 0) {
  8346. return; /* OK */
  8347. }
  8348. /* sf_sent<0 means error, thus fall back to the classic way */
  8349. /* This is always the case, if sf_file is not a "normal" file,
  8350. * e.g., for sending data from the output of a CGI process. */
  8351. offset = (int64_t)sf_offs;
  8352. }
  8353. #endif
  8354. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8355. mg_cry_internal(conn,
  8356. "%s: fseeko() failed: %s",
  8357. __func__,
  8358. strerror(ERRNO));
  8359. mg_send_http_error(
  8360. conn,
  8361. 500,
  8362. "%s",
  8363. "Error: Unable to access file at requested position.");
  8364. } else {
  8365. while (len > 0) {
  8366. /* Calculate how much to read from the file in the buffer */
  8367. to_read = sizeof(buf);
  8368. if ((int64_t)to_read > len) {
  8369. to_read = (int)len;
  8370. }
  8371. /* Read from file, exit the loop on error */
  8372. if ((num_read =
  8373. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8374. <= 0) {
  8375. break;
  8376. }
  8377. /* Send read bytes to the client, exit the loop on error */
  8378. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8379. != num_read) {
  8380. break;
  8381. }
  8382. /* Both read and were successful, adjust counters */
  8383. len -= num_written;
  8384. }
  8385. }
  8386. }
  8387. }
  8388. static int
  8389. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8390. {
  8391. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8392. }
  8393. static void
  8394. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8395. {
  8396. if ((filestat != NULL) && (buf != NULL)) {
  8397. mg_snprintf(NULL,
  8398. NULL, /* All calls to construct_etag use 64 byte buffer */
  8399. buf,
  8400. buf_len,
  8401. "\"%lx.%" INT64_FMT "\"",
  8402. (unsigned long)filestat->last_modified,
  8403. filestat->size);
  8404. }
  8405. }
  8406. static void
  8407. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8408. {
  8409. if (filep != NULL && filep->fp != NULL) {
  8410. #if defined(_WIN32)
  8411. (void)conn; /* Unused. */
  8412. #else
  8413. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8414. mg_cry_internal(conn,
  8415. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8416. __func__,
  8417. strerror(ERRNO));
  8418. }
  8419. #endif
  8420. }
  8421. }
  8422. #if defined(USE_ZLIB)
  8423. #include "mod_zlib.inl"
  8424. #endif
  8425. #if !defined(NO_FILESYSTEMS)
  8426. static void
  8427. handle_static_file_request(struct mg_connection *conn,
  8428. const char *path,
  8429. struct mg_file *filep,
  8430. const char *mime_type,
  8431. const char *additional_headers)
  8432. {
  8433. char date[64], lm[64], etag[64];
  8434. char range[128]; /* large enough, so there will be no overflow */
  8435. const char *msg = "OK";
  8436. const char *range_hdr;
  8437. time_t curtime = time(NULL);
  8438. int64_t cl, r1, r2;
  8439. struct vec mime_vec;
  8440. int n, truncated;
  8441. char gz_path[PATH_MAX];
  8442. const char *encoding = "";
  8443. const char *origin_hdr;
  8444. const char *cors_orig_cfg;
  8445. const char *cors1, *cors2, *cors3;
  8446. int is_head_request;
  8447. #if defined(USE_ZLIB)
  8448. /* Compression is allowed, unless there is a reason not to use compression.
  8449. * If the file is already compressed, too small or a "range" request was
  8450. * made, on the fly compression is not possible. */
  8451. int allow_on_the_fly_compression = 1;
  8452. #endif
  8453. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8454. return;
  8455. }
  8456. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8457. if (mime_type == NULL) {
  8458. get_mime_type(conn, path, &mime_vec);
  8459. } else {
  8460. mime_vec.ptr = mime_type;
  8461. mime_vec.len = strlen(mime_type);
  8462. }
  8463. if (filep->stat.size > INT64_MAX) {
  8464. mg_send_http_error(conn,
  8465. 500,
  8466. "Error: File size is too large to send\n%" INT64_FMT,
  8467. filep->stat.size);
  8468. return;
  8469. }
  8470. cl = (int64_t)filep->stat.size;
  8471. conn->status_code = 200;
  8472. range[0] = '\0';
  8473. #if defined(USE_ZLIB)
  8474. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8475. * it's important to rewrite the filename after resolving
  8476. * the mime type from it, to preserve the actual file's type */
  8477. if (!conn->accept_gzip) {
  8478. allow_on_the_fly_compression = 0;
  8479. }
  8480. #endif
  8481. /* Check if there is a range header */
  8482. range_hdr = mg_get_header(conn, "Range");
  8483. /* For gzipped files, add *.gz */
  8484. if (filep->stat.is_gzipped) {
  8485. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8486. if (truncated) {
  8487. mg_send_http_error(conn,
  8488. 500,
  8489. "Error: Path of zipped file too long (%s)",
  8490. path);
  8491. return;
  8492. }
  8493. path = gz_path;
  8494. encoding = "Content-Encoding: gzip\r\n";
  8495. #if defined(USE_ZLIB)
  8496. /* File is already compressed. No "on the fly" compression. */
  8497. allow_on_the_fly_compression = 0;
  8498. #endif
  8499. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8500. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8501. struct mg_file_stat file_stat;
  8502. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8503. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8504. && !file_stat.is_directory) {
  8505. file_stat.is_gzipped = 1;
  8506. filep->stat = file_stat;
  8507. cl = (int64_t)filep->stat.size;
  8508. path = gz_path;
  8509. encoding = "Content-Encoding: gzip\r\n";
  8510. #if defined(USE_ZLIB)
  8511. /* File is already compressed. No "on the fly" compression. */
  8512. allow_on_the_fly_compression = 0;
  8513. #endif
  8514. }
  8515. }
  8516. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8517. mg_send_http_error(conn,
  8518. 500,
  8519. "Error: Cannot open file\nfopen(%s): %s",
  8520. path,
  8521. strerror(ERRNO));
  8522. return;
  8523. }
  8524. fclose_on_exec(&filep->access, conn);
  8525. /* If "Range" request was made: parse header, send only selected part
  8526. * of the file. */
  8527. r1 = r2 = 0;
  8528. if ((range_hdr != NULL)
  8529. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8530. && (r2 >= 0)) {
  8531. /* actually, range requests don't play well with a pre-gzipped
  8532. * file (since the range is specified in the uncompressed space) */
  8533. if (filep->stat.is_gzipped) {
  8534. mg_send_http_error(
  8535. conn,
  8536. 416, /* 416 = Range Not Satisfiable */
  8537. "%s",
  8538. "Error: Range requests in gzipped files are not supported");
  8539. (void)mg_fclose(
  8540. &filep->access); /* ignore error on read only file */
  8541. return;
  8542. }
  8543. conn->status_code = 206;
  8544. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8545. mg_snprintf(conn,
  8546. NULL, /* range buffer is big enough */
  8547. range,
  8548. sizeof(range),
  8549. "Content-Range: bytes "
  8550. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8551. r1,
  8552. r1 + cl - 1,
  8553. filep->stat.size);
  8554. msg = "Partial Content";
  8555. #if defined(USE_ZLIB)
  8556. /* Do not compress ranges. */
  8557. allow_on_the_fly_compression = 0;
  8558. #endif
  8559. }
  8560. /* Do not compress small files. Small files do not benefit from file
  8561. * compression, but there is still some overhead. */
  8562. #if defined(USE_ZLIB)
  8563. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8564. /* File is below the size limit. */
  8565. allow_on_the_fly_compression = 0;
  8566. }
  8567. #endif
  8568. /* Standard CORS header */
  8569. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8570. origin_hdr = mg_get_header(conn, "Origin");
  8571. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8572. /* Cross-origin resource sharing (CORS), see
  8573. * http://www.html5rocks.com/en/tutorials/cors/,
  8574. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8575. * -
  8576. * preflight is not supported for files. */
  8577. cors1 = "Access-Control-Allow-Origin: ";
  8578. cors2 = cors_orig_cfg;
  8579. cors3 = "\r\n";
  8580. } else {
  8581. cors1 = cors2 = cors3 = "";
  8582. }
  8583. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8584. * according to
  8585. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8586. gmt_time_string(date, sizeof(date), &curtime);
  8587. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8588. construct_etag(etag, sizeof(etag), &filep->stat);
  8589. /* Send header */
  8590. (void)mg_printf(conn,
  8591. "HTTP/1.1 %d %s\r\n"
  8592. "%s%s%s" /* CORS */
  8593. "Date: %s\r\n"
  8594. "Last-Modified: %s\r\n"
  8595. "Etag: %s\r\n"
  8596. "Content-Type: %.*s\r\n"
  8597. "Connection: %s\r\n",
  8598. conn->status_code,
  8599. msg,
  8600. cors1,
  8601. cors2,
  8602. cors3,
  8603. date,
  8604. lm,
  8605. etag,
  8606. (int)mime_vec.len,
  8607. mime_vec.ptr,
  8608. suggest_connection_header(conn));
  8609. send_static_cache_header(conn);
  8610. send_additional_header(conn);
  8611. #if defined(USE_ZLIB)
  8612. /* On the fly compression allowed */
  8613. if (allow_on_the_fly_compression) {
  8614. /* For on the fly compression, we don't know the content size in
  8615. * advance, so we have to use chunked encoding */
  8616. (void)mg_printf(conn,
  8617. "Content-Encoding: gzip\r\n"
  8618. "Transfer-Encoding: chunked\r\n");
  8619. } else
  8620. #endif
  8621. {
  8622. /* Without on-the-fly compression, we know the content-length
  8623. * and we can use ranges (with on-the-fly compression we cannot).
  8624. * So we send these response headers only in this case. */
  8625. (void)mg_printf(conn,
  8626. "Content-Length: %" INT64_FMT "\r\n"
  8627. "Accept-Ranges: bytes\r\n"
  8628. "%s" /* range */
  8629. "%s" /* encoding */,
  8630. cl,
  8631. range,
  8632. encoding);
  8633. }
  8634. /* The previous code must not add any header starting with X- to make
  8635. * sure no one of the additional_headers is included twice */
  8636. if (additional_headers != NULL) {
  8637. (void)mg_printf(conn,
  8638. "%.*s\r\n\r\n",
  8639. (int)strlen(additional_headers),
  8640. additional_headers);
  8641. } else {
  8642. (void)mg_printf(conn, "\r\n");
  8643. }
  8644. if (!is_head_request) {
  8645. #if defined(USE_ZLIB)
  8646. if (allow_on_the_fly_compression) {
  8647. /* Compress and send */
  8648. send_compressed_data(conn, filep);
  8649. } else
  8650. #endif
  8651. {
  8652. /* Send file directly */
  8653. send_file_data(conn, filep, r1, cl);
  8654. }
  8655. }
  8656. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8657. }
  8658. int
  8659. mg_send_file_body(struct mg_connection *conn, const char *path)
  8660. {
  8661. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8662. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8663. return -1;
  8664. }
  8665. fclose_on_exec(&file.access, conn);
  8666. send_file_data(conn, &file, 0, INT64_MAX);
  8667. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8668. return 0; /* >= 0 for OK */
  8669. }
  8670. #endif /* NO_FILESYSTEMS */
  8671. #if !defined(NO_CACHING)
  8672. /* Return True if we should reply 304 Not Modified. */
  8673. static int
  8674. is_not_modified(const struct mg_connection *conn,
  8675. const struct mg_file_stat *filestat)
  8676. {
  8677. char etag[64];
  8678. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8679. const char *inm = mg_get_header(conn, "If-None-Match");
  8680. construct_etag(etag, sizeof(etag), filestat);
  8681. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8682. || ((ims != NULL)
  8683. && (filestat->last_modified <= parse_date_string(ims)));
  8684. }
  8685. static void
  8686. handle_not_modified_static_file_request(struct mg_connection *conn,
  8687. struct mg_file *filep)
  8688. {
  8689. char date[64], lm[64], etag[64];
  8690. time_t curtime = time(NULL);
  8691. if ((conn == NULL) || (filep == NULL)) {
  8692. return;
  8693. }
  8694. conn->status_code = 304;
  8695. gmt_time_string(date, sizeof(date), &curtime);
  8696. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8697. construct_etag(etag, sizeof(etag), &filep->stat);
  8698. (void)mg_printf(conn,
  8699. "HTTP/1.1 %d %s\r\n"
  8700. "Date: %s\r\n",
  8701. conn->status_code,
  8702. mg_get_response_code_text(conn, conn->status_code),
  8703. date);
  8704. send_static_cache_header(conn);
  8705. send_additional_header(conn);
  8706. (void)mg_printf(conn,
  8707. "Last-Modified: %s\r\n"
  8708. "Etag: %s\r\n"
  8709. "Connection: %s\r\n"
  8710. "\r\n",
  8711. lm,
  8712. etag,
  8713. suggest_connection_header(conn));
  8714. }
  8715. #endif
  8716. #if !defined(NO_FILESYSTEMS)
  8717. void
  8718. mg_send_file(struct mg_connection *conn, const char *path)
  8719. {
  8720. mg_send_mime_file2(conn, path, NULL, NULL);
  8721. }
  8722. void
  8723. mg_send_mime_file(struct mg_connection *conn,
  8724. const char *path,
  8725. const char *mime_type)
  8726. {
  8727. mg_send_mime_file2(conn, path, mime_type, NULL);
  8728. }
  8729. void
  8730. mg_send_mime_file2(struct mg_connection *conn,
  8731. const char *path,
  8732. const char *mime_type,
  8733. const char *additional_headers)
  8734. {
  8735. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8736. if (!conn) {
  8737. /* No conn */
  8738. return;
  8739. }
  8740. if (mg_stat(conn, path, &file.stat)) {
  8741. #if !defined(NO_CACHING)
  8742. if (is_not_modified(conn, &file.stat)) {
  8743. /* Send 304 "Not Modified" - this must not send any body data */
  8744. handle_not_modified_static_file_request(conn, &file);
  8745. } else
  8746. #endif /* NO_CACHING */
  8747. if (file.stat.is_directory) {
  8748. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8749. "yes")) {
  8750. handle_directory_request(conn, path);
  8751. } else {
  8752. mg_send_http_error(conn,
  8753. 403,
  8754. "%s",
  8755. "Error: Directory listing denied");
  8756. }
  8757. } else {
  8758. handle_static_file_request(
  8759. conn, path, &file, mime_type, additional_headers);
  8760. }
  8761. } else {
  8762. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8763. }
  8764. }
  8765. /* For a given PUT path, create all intermediate subdirectories.
  8766. * Return 0 if the path itself is a directory.
  8767. * Return 1 if the path leads to a file.
  8768. * Return -1 for if the path is too long.
  8769. * Return -2 if path can not be created.
  8770. */
  8771. static int
  8772. put_dir(struct mg_connection *conn, const char *path)
  8773. {
  8774. char buf[PATH_MAX];
  8775. const char *s, *p;
  8776. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8777. size_t len;
  8778. int res = 1;
  8779. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8780. len = (size_t)(p - path);
  8781. if (len >= sizeof(buf)) {
  8782. /* path too long */
  8783. res = -1;
  8784. break;
  8785. }
  8786. memcpy(buf, path, len);
  8787. buf[len] = '\0';
  8788. /* Try to create intermediate directory */
  8789. DEBUG_TRACE("mkdir(%s)", buf);
  8790. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8791. /* path does not exixt and can not be created */
  8792. res = -2;
  8793. break;
  8794. }
  8795. /* Is path itself a directory? */
  8796. if (p[1] == '\0') {
  8797. res = 0;
  8798. }
  8799. }
  8800. return res;
  8801. }
  8802. static void
  8803. remove_bad_file(const struct mg_connection *conn, const char *path)
  8804. {
  8805. int r = mg_remove(conn, path);
  8806. if (r != 0) {
  8807. mg_cry_internal(conn,
  8808. "%s: Cannot remove invalid file %s",
  8809. __func__,
  8810. path);
  8811. }
  8812. }
  8813. long long
  8814. mg_store_body(struct mg_connection *conn, const char *path)
  8815. {
  8816. char buf[MG_BUF_LEN];
  8817. long long len = 0;
  8818. int ret, n;
  8819. struct mg_file fi;
  8820. if (conn->consumed_content != 0) {
  8821. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8822. return -11;
  8823. }
  8824. ret = put_dir(conn, path);
  8825. if (ret < 0) {
  8826. /* -1 for path too long,
  8827. * -2 for path can not be created. */
  8828. return ret;
  8829. }
  8830. if (ret != 1) {
  8831. /* Return 0 means, path itself is a directory. */
  8832. return 0;
  8833. }
  8834. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8835. return -12;
  8836. }
  8837. ret = mg_read(conn, buf, sizeof(buf));
  8838. while (ret > 0) {
  8839. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8840. if (n != ret) {
  8841. (void)mg_fclose(
  8842. &fi.access); /* File is bad and will be removed anyway. */
  8843. remove_bad_file(conn, path);
  8844. return -13;
  8845. }
  8846. len += ret;
  8847. ret = mg_read(conn, buf, sizeof(buf));
  8848. }
  8849. /* File is open for writing. If fclose fails, there was probably an
  8850. * error flushing the buffer to disk, so the file on disk might be
  8851. * broken. Delete it and return an error to the caller. */
  8852. if (mg_fclose(&fi.access) != 0) {
  8853. remove_bad_file(conn, path);
  8854. return -14;
  8855. }
  8856. return len;
  8857. }
  8858. #endif /* NO_FILESYSTEMS */
  8859. /* Parse a buffer:
  8860. * Forward the string pointer till the end of a word, then
  8861. * terminate it and forward till the begin of the next word.
  8862. */
  8863. static int
  8864. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8865. {
  8866. /* Forward until a space is found - use isgraph here */
  8867. /* See http://www.cplusplus.com/reference/cctype/ */
  8868. while (isgraph((unsigned char)**ppw)) {
  8869. (*ppw)++;
  8870. }
  8871. /* Check end of word */
  8872. if (eol) {
  8873. /* must be a end of line */
  8874. if ((**ppw != '\r') && (**ppw != '\n')) {
  8875. return -1;
  8876. }
  8877. } else {
  8878. /* must be a end of a word, but not a line */
  8879. if (**ppw != ' ') {
  8880. return -1;
  8881. }
  8882. }
  8883. /* Terminate and forward to the next word */
  8884. do {
  8885. **ppw = 0;
  8886. (*ppw)++;
  8887. } while (isspace((unsigned char)**ppw));
  8888. /* Check after term */
  8889. if (!eol) {
  8890. /* if it's not the end of line, there must be a next word */
  8891. if (!isgraph((unsigned char)**ppw)) {
  8892. return -1;
  8893. }
  8894. }
  8895. /* ok */
  8896. return 1;
  8897. }
  8898. /* Parse HTTP headers from the given buffer, advance buf pointer
  8899. * to the point where parsing stopped.
  8900. * All parameters must be valid pointers (not NULL).
  8901. * Return <0 on error. */
  8902. static int
  8903. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8904. {
  8905. int i;
  8906. int num_headers = 0;
  8907. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8908. char *dp = *buf;
  8909. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8910. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8911. dp++;
  8912. }
  8913. if (dp == *buf) {
  8914. /* End of headers reached. */
  8915. break;
  8916. }
  8917. if (*dp != ':') {
  8918. /* This is not a valid field. */
  8919. return -1;
  8920. }
  8921. /* End of header key (*dp == ':') */
  8922. /* Truncate here and set the key name */
  8923. *dp = 0;
  8924. hdr[i].name = *buf;
  8925. /* Skip all spaces */
  8926. do {
  8927. dp++;
  8928. } while ((*dp == ' ') || (*dp == '\t'));
  8929. /* The rest of the line is the value */
  8930. hdr[i].value = dp;
  8931. /* Find end of line */
  8932. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8933. dp++;
  8934. };
  8935. /* eliminate \r */
  8936. if (*dp == '\r') {
  8937. *dp = 0;
  8938. dp++;
  8939. if (*dp != '\n') {
  8940. /* This is not a valid line. */
  8941. return -1;
  8942. }
  8943. }
  8944. /* here *dp is either 0 or '\n' */
  8945. /* in any case, we have a new header */
  8946. num_headers = i + 1;
  8947. if (*dp) {
  8948. *dp = 0;
  8949. dp++;
  8950. *buf = dp;
  8951. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8952. /* This is the end of the header */
  8953. break;
  8954. }
  8955. } else {
  8956. *buf = dp;
  8957. break;
  8958. }
  8959. }
  8960. return num_headers;
  8961. }
  8962. struct mg_http_method_info {
  8963. const char *name;
  8964. int request_has_body;
  8965. int response_has_body;
  8966. int is_safe;
  8967. int is_idempotent;
  8968. int is_cacheable;
  8969. };
  8970. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8971. static struct mg_http_method_info http_methods[] = {
  8972. /* HTTP (RFC 2616) */
  8973. {"GET", 0, 1, 1, 1, 1},
  8974. {"POST", 1, 1, 0, 0, 0},
  8975. {"PUT", 1, 0, 0, 1, 0},
  8976. {"DELETE", 0, 0, 0, 1, 0},
  8977. {"HEAD", 0, 0, 1, 1, 1},
  8978. {"OPTIONS", 0, 0, 1, 1, 0},
  8979. {"CONNECT", 1, 1, 0, 0, 0},
  8980. /* TRACE method (RFC 2616) is not supported for security reasons */
  8981. /* PATCH method (RFC 5789) */
  8982. {"PATCH", 1, 0, 0, 0, 0},
  8983. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8984. /* WEBDAV (RFC 2518) */
  8985. {"PROPFIND", 0, 1, 1, 1, 0},
  8986. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8987. * Some PROPFIND results MAY be cached, with care,
  8988. * as there is no cache validation mechanism for
  8989. * most properties. This method is both safe and
  8990. * idempotent (see Section 9.1 of [RFC2616]). */
  8991. {"MKCOL", 0, 0, 0, 1, 0},
  8992. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8993. * When MKCOL is invoked without a request body,
  8994. * the newly created collection SHOULD have no
  8995. * members. A MKCOL request message may contain
  8996. * a message body. The precise behavior of a MKCOL
  8997. * request when the body is present is undefined,
  8998. * ... ==> We do not support MKCOL with body data.
  8999. * This method is idempotent, but not safe (see
  9000. * Section 9.1 of [RFC2616]). Responses to this
  9001. * method MUST NOT be cached. */
  9002. /* Unsupported WEBDAV Methods: */
  9003. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9004. /* + 11 methods from RFC 3253 */
  9005. /* ORDERPATCH (RFC 3648) */
  9006. /* ACL (RFC 3744) */
  9007. /* SEARCH (RFC 5323) */
  9008. /* + MicroSoft extensions
  9009. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9010. /* REPORT method (RFC 3253) */
  9011. {"REPORT", 1, 1, 1, 1, 1},
  9012. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9013. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9014. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9015. * to be useful for REST in case a "GET request with body" is
  9016. * required. */
  9017. {NULL, 0, 0, 0, 0, 0}
  9018. /* end of list */
  9019. };
  9020. static const struct mg_http_method_info *
  9021. get_http_method_info(const char *method)
  9022. {
  9023. /* Check if the method is known to the server. The list of all known
  9024. * HTTP methods can be found here at
  9025. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9026. */
  9027. const struct mg_http_method_info *m = http_methods;
  9028. while (m->name) {
  9029. if (!strcmp(m->name, method)) {
  9030. return m;
  9031. }
  9032. m++;
  9033. }
  9034. return NULL;
  9035. }
  9036. static int
  9037. is_valid_http_method(const char *method)
  9038. {
  9039. return (get_http_method_info(method) != NULL);
  9040. }
  9041. /* Parse HTTP request, fill in mg_request_info structure.
  9042. * This function modifies the buffer by NUL-terminating
  9043. * HTTP request components, header names and header values.
  9044. * Parameters:
  9045. * buf (in/out): pointer to the HTTP header to parse and split
  9046. * len (in): length of HTTP header buffer
  9047. * re (out): parsed header as mg_request_info
  9048. * buf and ri must be valid pointers (not NULL), len>0.
  9049. * Returns <0 on error. */
  9050. static int
  9051. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9052. {
  9053. int request_length;
  9054. int init_skip = 0;
  9055. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9056. * remote_port */
  9057. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9058. NULL;
  9059. ri->num_headers = 0;
  9060. /* RFC says that all initial whitespaces should be ingored */
  9061. /* This included all leading \r and \n (isspace) */
  9062. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9063. while ((len > 0) && isspace((unsigned char)*buf)) {
  9064. buf++;
  9065. len--;
  9066. init_skip++;
  9067. }
  9068. if (len == 0) {
  9069. /* Incomplete request */
  9070. return 0;
  9071. }
  9072. /* Control characters are not allowed, including zero */
  9073. if (iscntrl((unsigned char)*buf)) {
  9074. return -1;
  9075. }
  9076. /* Find end of HTTP header */
  9077. request_length = get_http_header_len(buf, len);
  9078. if (request_length <= 0) {
  9079. return request_length;
  9080. }
  9081. buf[request_length - 1] = '\0';
  9082. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9083. return -1;
  9084. }
  9085. /* The first word has to be the HTTP method */
  9086. ri->request_method = buf;
  9087. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9088. return -1;
  9089. }
  9090. /* Check for a valid http method */
  9091. if (!is_valid_http_method(ri->request_method)) {
  9092. return -1;
  9093. }
  9094. /* The second word is the URI */
  9095. ri->request_uri = buf;
  9096. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9097. return -1;
  9098. }
  9099. /* Next would be the HTTP version */
  9100. ri->http_version = buf;
  9101. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9102. return -1;
  9103. }
  9104. /* Check for a valid HTTP version key */
  9105. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9106. /* Invalid request */
  9107. return -1;
  9108. }
  9109. ri->http_version += 5;
  9110. /* Parse all HTTP headers */
  9111. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9112. if (ri->num_headers < 0) {
  9113. /* Error while parsing headers */
  9114. return -1;
  9115. }
  9116. return request_length + init_skip;
  9117. }
  9118. static int
  9119. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9120. {
  9121. int response_length;
  9122. int init_skip = 0;
  9123. char *tmp, *tmp2;
  9124. long l;
  9125. /* Initialize elements. */
  9126. ri->http_version = ri->status_text = NULL;
  9127. ri->num_headers = ri->status_code = 0;
  9128. /* RFC says that all initial whitespaces should be ingored */
  9129. /* This included all leading \r and \n (isspace) */
  9130. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9131. while ((len > 0) && isspace((unsigned char)*buf)) {
  9132. buf++;
  9133. len--;
  9134. init_skip++;
  9135. }
  9136. if (len == 0) {
  9137. /* Incomplete request */
  9138. return 0;
  9139. }
  9140. /* Control characters are not allowed, including zero */
  9141. if (iscntrl((unsigned char)*buf)) {
  9142. return -1;
  9143. }
  9144. /* Find end of HTTP header */
  9145. response_length = get_http_header_len(buf, len);
  9146. if (response_length <= 0) {
  9147. return response_length;
  9148. }
  9149. buf[response_length - 1] = '\0';
  9150. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9151. return -1;
  9152. }
  9153. /* The first word is the HTTP version */
  9154. /* Check for a valid HTTP version key */
  9155. if (strncmp(buf, "HTTP/", 5) != 0) {
  9156. /* Invalid request */
  9157. return -1;
  9158. }
  9159. buf += 5;
  9160. if (!isgraph((unsigned char)buf[0])) {
  9161. /* Invalid request */
  9162. return -1;
  9163. }
  9164. ri->http_version = buf;
  9165. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9166. return -1;
  9167. }
  9168. /* The second word is the status as a number */
  9169. tmp = buf;
  9170. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9171. return -1;
  9172. }
  9173. l = strtol(tmp, &tmp2, 10);
  9174. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9175. /* Everything else but a 3 digit code is invalid */
  9176. return -1;
  9177. }
  9178. ri->status_code = (int)l;
  9179. /* The rest of the line is the status text */
  9180. ri->status_text = buf;
  9181. /* Find end of status text */
  9182. /* isgraph or isspace = isprint */
  9183. while (isprint((unsigned char)*buf)) {
  9184. buf++;
  9185. }
  9186. if ((*buf != '\r') && (*buf != '\n')) {
  9187. return -1;
  9188. }
  9189. /* Terminate string and forward buf to next line */
  9190. do {
  9191. *buf = 0;
  9192. buf++;
  9193. } while (isspace((unsigned char)*buf));
  9194. /* Parse all HTTP headers */
  9195. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9196. if (ri->num_headers < 0) {
  9197. /* Error while parsing headers */
  9198. return -1;
  9199. }
  9200. return response_length + init_skip;
  9201. }
  9202. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9203. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9204. * buffer (which marks the end of HTTP request). Buffer buf may already
  9205. * have some data. The length of the data is stored in nread.
  9206. * Upon every read operation, increase nread by the number of bytes read. */
  9207. static int
  9208. read_message(FILE *fp,
  9209. struct mg_connection *conn,
  9210. char *buf,
  9211. int bufsiz,
  9212. int *nread)
  9213. {
  9214. int request_len, n = 0;
  9215. struct timespec last_action_time;
  9216. double request_timeout;
  9217. if (!conn) {
  9218. return 0;
  9219. }
  9220. memset(&last_action_time, 0, sizeof(last_action_time));
  9221. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9222. /* value of request_timeout is in seconds, config in milliseconds */
  9223. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9224. } else {
  9225. request_timeout = -1.0;
  9226. }
  9227. if (conn->handled_requests > 0) {
  9228. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9229. request_timeout =
  9230. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9231. }
  9232. }
  9233. request_len = get_http_header_len(buf, *nread);
  9234. while (request_len == 0) {
  9235. /* Full request not yet received */
  9236. if (conn->phys_ctx->stop_flag != 0) {
  9237. /* Server is to be stopped. */
  9238. return -1;
  9239. }
  9240. if (*nread >= bufsiz) {
  9241. /* Request too long */
  9242. return -2;
  9243. }
  9244. n = pull_inner(
  9245. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9246. if (n == -2) {
  9247. /* Receive error */
  9248. return -1;
  9249. }
  9250. /* update clock after every read request */
  9251. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9252. if (n > 0) {
  9253. *nread += n;
  9254. request_len = get_http_header_len(buf, *nread);
  9255. } else {
  9256. request_len = 0;
  9257. }
  9258. if ((request_len == 0) && (request_timeout >= 0)) {
  9259. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9260. > request_timeout) {
  9261. /* Timeout */
  9262. return -1;
  9263. }
  9264. }
  9265. }
  9266. return request_len;
  9267. }
  9268. #if !defined(NO_CGI) || !defined(NO_FILES)
  9269. static int
  9270. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9271. {
  9272. const char *expect;
  9273. char buf[MG_BUF_LEN];
  9274. int success = 0;
  9275. if (!conn) {
  9276. return 0;
  9277. }
  9278. expect = mg_get_header(conn, "Expect");
  9279. DEBUG_ASSERT(fp != NULL);
  9280. if (!fp) {
  9281. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9282. return 0;
  9283. }
  9284. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9285. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9286. */
  9287. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9288. } else {
  9289. if (expect != NULL) {
  9290. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9291. conn->status_code = 100;
  9292. } else {
  9293. conn->status_code = 200;
  9294. }
  9295. DEBUG_ASSERT(conn->consumed_content == 0);
  9296. if (conn->consumed_content != 0) {
  9297. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9298. return 0;
  9299. }
  9300. for (;;) {
  9301. int nread = mg_read(conn, buf, sizeof(buf));
  9302. if (nread <= 0) {
  9303. success = (nread == 0);
  9304. break;
  9305. }
  9306. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9307. break;
  9308. }
  9309. }
  9310. /* Each error code path in this function must send an error */
  9311. if (!success) {
  9312. /* NOTE: Maybe some data has already been sent. */
  9313. /* TODO (low): If some data has been sent, a correct error
  9314. * reply can no longer be sent, so just close the connection */
  9315. mg_send_http_error(conn, 500, "%s", "");
  9316. }
  9317. }
  9318. return success;
  9319. }
  9320. #endif
  9321. #if defined(USE_TIMERS)
  9322. #define TIMER_API static
  9323. #include "timer.inl"
  9324. #endif /* USE_TIMERS */
  9325. #if !defined(NO_CGI)
  9326. /* This structure helps to create an environment for the spawned CGI
  9327. * program.
  9328. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9329. * last element must be NULL.
  9330. * However, on Windows there is a requirement that all these
  9331. * VARIABLE=VALUE\0
  9332. * strings must reside in a contiguous buffer. The end of the buffer is
  9333. * marked by two '\0' characters.
  9334. * We satisfy both worlds: we create an envp array (which is vars), all
  9335. * entries are actually pointers inside buf. */
  9336. struct cgi_environment {
  9337. struct mg_connection *conn;
  9338. /* Data block */
  9339. char *buf; /* Environment buffer */
  9340. size_t buflen; /* Space available in buf */
  9341. size_t bufused; /* Space taken in buf */
  9342. /* Index block */
  9343. char **var; /* char **envp */
  9344. size_t varlen; /* Number of variables available in var */
  9345. size_t varused; /* Number of variables stored in var */
  9346. };
  9347. static void addenv(struct cgi_environment *env,
  9348. PRINTF_FORMAT_STRING(const char *fmt),
  9349. ...) PRINTF_ARGS(2, 3);
  9350. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9351. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9352. static void
  9353. addenv(struct cgi_environment *env, const char *fmt, ...)
  9354. {
  9355. size_t i, n, space;
  9356. int truncated = 0;
  9357. char *added;
  9358. va_list ap;
  9359. if ((env->varlen - env->varused) < 2) {
  9360. mg_cry_internal(env->conn,
  9361. "%s: Cannot register CGI variable [%s]",
  9362. __func__,
  9363. fmt);
  9364. return;
  9365. }
  9366. /* Calculate how much space is left in the buffer */
  9367. space = (env->buflen - env->bufused);
  9368. do {
  9369. /* Space for "\0\0" is always needed. */
  9370. if (space <= 2) {
  9371. /* Allocate new buffer */
  9372. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9373. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9374. if (!added) {
  9375. /* Out of memory */
  9376. mg_cry_internal(
  9377. env->conn,
  9378. "%s: Cannot allocate memory for CGI variable [%s]",
  9379. __func__,
  9380. fmt);
  9381. return;
  9382. }
  9383. /* Retarget pointers */
  9384. env->buf = added;
  9385. env->buflen = n;
  9386. for (i = 0, n = 0; i < env->varused; i++) {
  9387. env->var[i] = added + n;
  9388. n += strlen(added + n) + 1;
  9389. }
  9390. space = (env->buflen - env->bufused);
  9391. }
  9392. /* Make a pointer to the free space int the buffer */
  9393. added = env->buf + env->bufused;
  9394. /* Copy VARIABLE=VALUE\0 string into the free space */
  9395. va_start(ap, fmt);
  9396. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9397. va_end(ap);
  9398. /* Do not add truncated strings to the environment */
  9399. if (truncated) {
  9400. /* Reallocate the buffer */
  9401. space = 0;
  9402. }
  9403. } while (truncated);
  9404. /* Calculate number of bytes added to the environment */
  9405. n = strlen(added) + 1;
  9406. env->bufused += n;
  9407. /* Append a pointer to the added string into the envp array */
  9408. env->var[env->varused] = added;
  9409. env->varused++;
  9410. }
  9411. /* Return 0 on success, non-zero if an error occurs. */
  9412. static int
  9413. prepare_cgi_environment(struct mg_connection *conn,
  9414. const char *prog,
  9415. struct cgi_environment *env)
  9416. {
  9417. const char *s;
  9418. struct vec var_vec;
  9419. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9420. int i, truncated, uri_len;
  9421. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9422. return -1;
  9423. }
  9424. env->conn = conn;
  9425. env->buflen = CGI_ENVIRONMENT_SIZE;
  9426. env->bufused = 0;
  9427. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9428. if (env->buf == NULL) {
  9429. mg_cry_internal(conn,
  9430. "%s: Not enough memory for environmental buffer",
  9431. __func__);
  9432. return -1;
  9433. }
  9434. env->varlen = MAX_CGI_ENVIR_VARS;
  9435. env->varused = 0;
  9436. env->var =
  9437. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9438. if (env->var == NULL) {
  9439. mg_cry_internal(conn,
  9440. "%s: Not enough memory for environmental variables",
  9441. __func__);
  9442. mg_free(env->buf);
  9443. return -1;
  9444. }
  9445. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9446. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9447. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9448. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9449. /* Prepare the environment block */
  9450. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9451. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9452. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9453. #if defined(USE_IPV6)
  9454. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9455. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9456. } else
  9457. #endif
  9458. {
  9459. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9460. }
  9461. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9462. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9463. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9464. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9465. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9466. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9467. /* SCRIPT_NAME */
  9468. uri_len = (int)strlen(conn->request_info.local_uri);
  9469. if (conn->path_info == NULL) {
  9470. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9471. /* URI: /path_to_script/script.cgi */
  9472. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9473. } else {
  9474. /* URI: /path_to_script/ ... using index.cgi */
  9475. const char *index_file = strrchr(prog, '/');
  9476. if (index_file) {
  9477. addenv(env,
  9478. "SCRIPT_NAME=%s%s",
  9479. conn->request_info.local_uri,
  9480. index_file + 1);
  9481. }
  9482. }
  9483. } else {
  9484. /* URI: /path_to_script/script.cgi/path_info */
  9485. addenv(env,
  9486. "SCRIPT_NAME=%.*s",
  9487. uri_len - (int)strlen(conn->path_info),
  9488. conn->request_info.local_uri);
  9489. }
  9490. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9491. if (conn->path_info == NULL) {
  9492. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9493. } else {
  9494. addenv(env,
  9495. "PATH_TRANSLATED=%s%s",
  9496. conn->dom_ctx->config[DOCUMENT_ROOT],
  9497. conn->path_info);
  9498. }
  9499. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9500. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9501. addenv(env, "CONTENT_TYPE=%s", s);
  9502. }
  9503. if (conn->request_info.query_string != NULL) {
  9504. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9505. }
  9506. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9507. addenv(env, "CONTENT_LENGTH=%s", s);
  9508. }
  9509. if ((s = getenv("PATH")) != NULL) {
  9510. addenv(env, "PATH=%s", s);
  9511. }
  9512. if (conn->path_info != NULL) {
  9513. addenv(env, "PATH_INFO=%s", conn->path_info);
  9514. }
  9515. if (conn->status_code > 0) {
  9516. /* CGI error handler should show the status code */
  9517. addenv(env, "STATUS=%d", conn->status_code);
  9518. }
  9519. #if defined(_WIN32)
  9520. if ((s = getenv("COMSPEC")) != NULL) {
  9521. addenv(env, "COMSPEC=%s", s);
  9522. }
  9523. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9524. addenv(env, "SYSTEMROOT=%s", s);
  9525. }
  9526. if ((s = getenv("SystemDrive")) != NULL) {
  9527. addenv(env, "SystemDrive=%s", s);
  9528. }
  9529. if ((s = getenv("ProgramFiles")) != NULL) {
  9530. addenv(env, "ProgramFiles=%s", s);
  9531. }
  9532. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9533. addenv(env, "ProgramFiles(x86)=%s", s);
  9534. }
  9535. #else
  9536. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9537. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9538. }
  9539. #endif /* _WIN32 */
  9540. if ((s = getenv("PERLLIB")) != NULL) {
  9541. addenv(env, "PERLLIB=%s", s);
  9542. }
  9543. if (conn->request_info.remote_user != NULL) {
  9544. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9545. addenv(env, "%s", "AUTH_TYPE=Digest");
  9546. }
  9547. /* Add all headers as HTTP_* variables */
  9548. for (i = 0; i < conn->request_info.num_headers; i++) {
  9549. (void)mg_snprintf(conn,
  9550. &truncated,
  9551. http_var_name,
  9552. sizeof(http_var_name),
  9553. "HTTP_%s",
  9554. conn->request_info.http_headers[i].name);
  9555. if (truncated) {
  9556. mg_cry_internal(conn,
  9557. "%s: HTTP header variable too long [%s]",
  9558. __func__,
  9559. conn->request_info.http_headers[i].name);
  9560. continue;
  9561. }
  9562. /* Convert variable name into uppercase, and change - to _ */
  9563. for (p = http_var_name; *p != '\0'; p++) {
  9564. if (*p == '-') {
  9565. *p = '_';
  9566. }
  9567. *p = (char)toupper((unsigned char)*p);
  9568. }
  9569. addenv(env,
  9570. "%s=%s",
  9571. http_var_name,
  9572. conn->request_info.http_headers[i].value);
  9573. }
  9574. /* Add user-specified variables */
  9575. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9576. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9577. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9578. }
  9579. env->var[env->varused] = NULL;
  9580. env->buf[env->bufused] = '\0';
  9581. return 0;
  9582. }
  9583. /* Data for CGI process control: PID and number of references */
  9584. struct process_control_data {
  9585. pid_t pid;
  9586. int references;
  9587. };
  9588. static int
  9589. abort_process(void *data)
  9590. {
  9591. /* Waitpid checks for child status and won't work for a pid that does not
  9592. * identify a child of the current process. Thus, if the pid is reused,
  9593. * we will not affect a different process. */
  9594. struct process_control_data *proc = (struct process_control_data *)data;
  9595. int status = 0;
  9596. int refs;
  9597. pid_t ret_pid;
  9598. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9599. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9600. /* Stop child process */
  9601. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9602. kill(proc->pid, SIGABRT);
  9603. /* Wait until process is terminated (don't leave zombies) */
  9604. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9605. ;
  9606. } else {
  9607. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9608. }
  9609. /* Dec reference counter */
  9610. refs = mg_atomic_dec(&proc->references);
  9611. if (refs == 0) {
  9612. /* no more references - free data */
  9613. mg_free(data);
  9614. }
  9615. return 0;
  9616. }
  9617. /* Local (static) function assumes all arguments are valid. */
  9618. static void
  9619. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9620. {
  9621. char *buf;
  9622. size_t buflen;
  9623. int headers_len, data_len, i, truncated;
  9624. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9625. const char *status, *status_text, *connection_state;
  9626. char *pbuf, dir[PATH_MAX], *p;
  9627. struct mg_request_info ri;
  9628. struct cgi_environment blk;
  9629. FILE *in = NULL, *out = NULL, *err = NULL;
  9630. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9631. pid_t pid = (pid_t)-1;
  9632. struct process_control_data *proc = NULL;
  9633. #if defined(USE_TIMERS)
  9634. double cgi_timeout = -1.0;
  9635. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9636. /* Get timeout in seconds */
  9637. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9638. }
  9639. #endif
  9640. buf = NULL;
  9641. buflen = conn->phys_ctx->max_request_size;
  9642. i = prepare_cgi_environment(conn, prog, &blk);
  9643. if (i != 0) {
  9644. blk.buf = NULL;
  9645. blk.var = NULL;
  9646. goto done;
  9647. }
  9648. /* CGI must be executed in its own directory. 'dir' must point to the
  9649. * directory containing executable program, 'p' must point to the
  9650. * executable program name relative to 'dir'. */
  9651. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9652. if (truncated) {
  9653. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9654. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9655. goto done;
  9656. }
  9657. if ((p = strrchr(dir, '/')) != NULL) {
  9658. *p++ = '\0';
  9659. } else {
  9660. dir[0] = '.';
  9661. dir[1] = '\0';
  9662. p = (char *)prog;
  9663. }
  9664. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9665. status = strerror(ERRNO);
  9666. mg_cry_internal(
  9667. conn,
  9668. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9669. prog,
  9670. status);
  9671. mg_send_http_error(conn,
  9672. 500,
  9673. "Error: Cannot create CGI pipe: %s",
  9674. status);
  9675. goto done;
  9676. }
  9677. proc = (struct process_control_data *)
  9678. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9679. if (proc == NULL) {
  9680. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9681. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9682. goto done;
  9683. }
  9684. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9685. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9686. if (pid == (pid_t)-1) {
  9687. status = strerror(ERRNO);
  9688. mg_cry_internal(
  9689. conn,
  9690. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9691. prog,
  9692. status);
  9693. mg_send_http_error(conn,
  9694. 500,
  9695. "Error: Cannot spawn CGI process [%s]: %s",
  9696. prog,
  9697. status);
  9698. mg_free(proc);
  9699. proc = NULL;
  9700. goto done;
  9701. }
  9702. /* Store data in shared process_control_data */
  9703. proc->pid = pid;
  9704. proc->references = 1;
  9705. #if defined(USE_TIMERS)
  9706. if (cgi_timeout > 0.0) {
  9707. proc->references = 2;
  9708. // Start a timer for CGI
  9709. timer_add(conn->phys_ctx,
  9710. cgi_timeout /* in seconds */,
  9711. 0.0,
  9712. 1,
  9713. abort_process,
  9714. (void *)proc);
  9715. }
  9716. #endif
  9717. /* Parent closes only one side of the pipes.
  9718. * If we don't mark them as closed, close() attempt before
  9719. * return from this function throws an exception on Windows.
  9720. * Windows does not like when closed descriptor is closed again. */
  9721. (void)close(fdin[0]);
  9722. (void)close(fdout[1]);
  9723. (void)close(fderr[1]);
  9724. fdin[0] = fdout[1] = fderr[1] = -1;
  9725. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9726. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9727. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9728. status = strerror(ERRNO);
  9729. mg_cry_internal(conn,
  9730. "Error: CGI program \"%s\": Can not open fd: %s",
  9731. prog,
  9732. status);
  9733. mg_send_http_error(conn,
  9734. 500,
  9735. "Error: CGI can not open fd\nfdopen: %s",
  9736. status);
  9737. goto done;
  9738. }
  9739. setbuf(in, NULL);
  9740. setbuf(out, NULL);
  9741. setbuf(err, NULL);
  9742. fout.access.fp = out;
  9743. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9744. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9745. conn->content_len);
  9746. /* This is a POST/PUT request, or another request with body data. */
  9747. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9748. /* Error sending the body data */
  9749. mg_cry_internal(
  9750. conn,
  9751. "Error: CGI program \"%s\": Forward body data failed",
  9752. prog);
  9753. goto done;
  9754. }
  9755. }
  9756. /* Close so child gets an EOF. */
  9757. fclose(in);
  9758. in = NULL;
  9759. fdin[1] = -1;
  9760. /* Now read CGI reply into a buffer. We need to set correct
  9761. * status code, thus we need to see all HTTP headers first.
  9762. * Do not send anything back to client, until we buffer in all
  9763. * HTTP headers. */
  9764. data_len = 0;
  9765. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9766. if (buf == NULL) {
  9767. mg_send_http_error(conn,
  9768. 500,
  9769. "Error: Not enough memory for CGI buffer (%u bytes)",
  9770. (unsigned int)buflen);
  9771. mg_cry_internal(
  9772. conn,
  9773. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9774. "bytes)",
  9775. prog,
  9776. (unsigned int)buflen);
  9777. goto done;
  9778. }
  9779. DEBUG_TRACE("CGI: %s", "wait for response");
  9780. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9781. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9782. if (headers_len <= 0) {
  9783. /* Could not parse the CGI response. Check if some error message on
  9784. * stderr. */
  9785. i = pull_all(err, conn, buf, (int)buflen);
  9786. if (i > 0) {
  9787. /* CGI program explicitly sent an error */
  9788. /* Write the error message to the internal log */
  9789. mg_cry_internal(conn,
  9790. "Error: CGI program \"%s\" sent error "
  9791. "message: [%.*s]",
  9792. prog,
  9793. i,
  9794. buf);
  9795. /* Don't send the error message back to the client */
  9796. mg_send_http_error(conn,
  9797. 500,
  9798. "Error: CGI program \"%s\" failed.",
  9799. prog);
  9800. } else {
  9801. /* CGI program did not explicitly send an error, but a broken
  9802. * respon header */
  9803. mg_cry_internal(conn,
  9804. "Error: CGI program sent malformed or too big "
  9805. "(>%u bytes) HTTP headers: [%.*s]",
  9806. (unsigned)buflen,
  9807. data_len,
  9808. buf);
  9809. mg_send_http_error(conn,
  9810. 500,
  9811. "Error: CGI program sent malformed or too big "
  9812. "(>%u bytes) HTTP headers: [%.*s]",
  9813. (unsigned)buflen,
  9814. data_len,
  9815. buf);
  9816. }
  9817. /* in both cases, abort processing CGI */
  9818. goto done;
  9819. }
  9820. pbuf = buf;
  9821. buf[headers_len - 1] = '\0';
  9822. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9823. /* Make up and send the status line */
  9824. status_text = "OK";
  9825. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9826. != NULL) {
  9827. conn->status_code = atoi(status);
  9828. status_text = status;
  9829. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9830. status_text++;
  9831. }
  9832. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9833. != NULL) {
  9834. conn->status_code = 307;
  9835. } else {
  9836. conn->status_code = 200;
  9837. }
  9838. connection_state =
  9839. get_header(ri.http_headers, ri.num_headers, "Connection");
  9840. if (!header_has_option(connection_state, "keep-alive")) {
  9841. conn->must_close = 1;
  9842. }
  9843. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9844. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9845. /* Send headers */
  9846. for (i = 0; i < ri.num_headers; i++) {
  9847. DEBUG_TRACE("CGI header: %s: %s",
  9848. ri.http_headers[i].name,
  9849. ri.http_headers[i].value);
  9850. mg_printf(conn,
  9851. "%s: %s\r\n",
  9852. ri.http_headers[i].name,
  9853. ri.http_headers[i].value);
  9854. }
  9855. mg_write(conn, "\r\n", 2);
  9856. /* Send chunk of data that may have been read after the headers */
  9857. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9858. /* Read the rest of CGI output and send to the client */
  9859. DEBUG_TRACE("CGI: %s", "forward all data");
  9860. send_file_data(conn, &fout, 0, INT64_MAX);
  9861. DEBUG_TRACE("CGI: %s", "all data sent");
  9862. done:
  9863. mg_free(blk.var);
  9864. mg_free(blk.buf);
  9865. if (pid != (pid_t)-1) {
  9866. abort_process((void *)proc);
  9867. }
  9868. if (fdin[0] != -1) {
  9869. close(fdin[0]);
  9870. }
  9871. if (fdout[1] != -1) {
  9872. close(fdout[1]);
  9873. }
  9874. if (fderr[1] != -1) {
  9875. close(fderr[1]);
  9876. }
  9877. if (in != NULL) {
  9878. fclose(in);
  9879. } else if (fdin[1] != -1) {
  9880. close(fdin[1]);
  9881. }
  9882. if (out != NULL) {
  9883. fclose(out);
  9884. } else if (fdout[0] != -1) {
  9885. close(fdout[0]);
  9886. }
  9887. if (err != NULL) {
  9888. fclose(err);
  9889. } else if (fderr[0] != -1) {
  9890. close(fderr[0]);
  9891. }
  9892. mg_free(buf);
  9893. }
  9894. #endif /* !NO_CGI */
  9895. #if !defined(NO_FILES)
  9896. static void
  9897. mkcol(struct mg_connection *conn, const char *path)
  9898. {
  9899. int rc, body_len;
  9900. struct de de;
  9901. char date[64];
  9902. time_t curtime = time(NULL);
  9903. if (conn == NULL) {
  9904. return;
  9905. }
  9906. /* TODO (mid): Check the mg_send_http_error situations in this function
  9907. */
  9908. memset(&de.file, 0, sizeof(de.file));
  9909. if (!mg_stat(conn, path, &de.file)) {
  9910. mg_cry_internal(conn,
  9911. "%s: mg_stat(%s) failed: %s",
  9912. __func__,
  9913. path,
  9914. strerror(ERRNO));
  9915. }
  9916. if (de.file.last_modified) {
  9917. /* TODO (mid): This check does not seem to make any sense ! */
  9918. /* TODO (mid): Add a webdav unit test first, before changing
  9919. * anything here. */
  9920. mg_send_http_error(
  9921. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9922. return;
  9923. }
  9924. body_len = conn->data_len - conn->request_len;
  9925. if (body_len > 0) {
  9926. mg_send_http_error(
  9927. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9928. return;
  9929. }
  9930. rc = mg_mkdir(conn, path, 0755);
  9931. if (rc == 0) {
  9932. conn->status_code = 201;
  9933. gmt_time_string(date, sizeof(date), &curtime);
  9934. mg_printf(conn,
  9935. "HTTP/1.1 %d Created\r\n"
  9936. "Date: %s\r\n",
  9937. conn->status_code,
  9938. date);
  9939. send_static_cache_header(conn);
  9940. send_additional_header(conn);
  9941. mg_printf(conn,
  9942. "Content-Length: 0\r\n"
  9943. "Connection: %s\r\n\r\n",
  9944. suggest_connection_header(conn));
  9945. } else {
  9946. if (errno == EEXIST) {
  9947. mg_send_http_error(
  9948. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9949. } else if (errno == EACCES) {
  9950. mg_send_http_error(
  9951. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9952. } else if (errno == ENOENT) {
  9953. mg_send_http_error(
  9954. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9955. } else {
  9956. mg_send_http_error(
  9957. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9958. }
  9959. }
  9960. }
  9961. static void
  9962. put_file(struct mg_connection *conn, const char *path)
  9963. {
  9964. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9965. const char *range;
  9966. int64_t r1, r2;
  9967. int rc;
  9968. char date[64];
  9969. time_t curtime = time(NULL);
  9970. if (conn == NULL) {
  9971. return;
  9972. }
  9973. if (mg_stat(conn, path, &file.stat)) {
  9974. /* File already exists */
  9975. conn->status_code = 200;
  9976. if (file.stat.is_directory) {
  9977. /* This is an already existing directory,
  9978. * so there is nothing to do for the server. */
  9979. rc = 0;
  9980. } else {
  9981. /* File exists and is not a directory. */
  9982. /* Can it be replaced? */
  9983. #if defined(MG_USE_OPEN_FILE)
  9984. if (file.access.membuf != NULL) {
  9985. /* This is an "in-memory" file, that can not be replaced */
  9986. mg_send_http_error(conn,
  9987. 405,
  9988. "Error: Put not possible\nReplacing %s "
  9989. "is not supported",
  9990. path);
  9991. return;
  9992. }
  9993. #endif
  9994. /* Check if the server may write this file */
  9995. if (access(path, W_OK) == 0) {
  9996. /* Access granted */
  9997. conn->status_code = 200;
  9998. rc = 1;
  9999. } else {
  10000. mg_send_http_error(
  10001. conn,
  10002. 403,
  10003. "Error: Put not possible\nReplacing %s is not allowed",
  10004. path);
  10005. return;
  10006. }
  10007. }
  10008. } else {
  10009. /* File should be created */
  10010. conn->status_code = 201;
  10011. rc = put_dir(conn, path);
  10012. }
  10013. if (rc == 0) {
  10014. /* put_dir returns 0 if path is a directory */
  10015. gmt_time_string(date, sizeof(date), &curtime);
  10016. mg_printf(conn,
  10017. "HTTP/1.1 %d %s\r\n",
  10018. conn->status_code,
  10019. mg_get_response_code_text(NULL, conn->status_code));
  10020. send_no_cache_header(conn);
  10021. send_additional_header(conn);
  10022. mg_printf(conn,
  10023. "Date: %s\r\n"
  10024. "Content-Length: 0\r\n"
  10025. "Connection: %s\r\n\r\n",
  10026. date,
  10027. suggest_connection_header(conn));
  10028. /* Request to create a directory has been fulfilled successfully.
  10029. * No need to put a file. */
  10030. return;
  10031. }
  10032. if (rc == -1) {
  10033. /* put_dir returns -1 if the path is too long */
  10034. mg_send_http_error(conn,
  10035. 414,
  10036. "Error: Path too long\nput_dir(%s): %s",
  10037. path,
  10038. strerror(ERRNO));
  10039. return;
  10040. }
  10041. if (rc == -2) {
  10042. /* put_dir returns -2 if the directory can not be created */
  10043. mg_send_http_error(conn,
  10044. 500,
  10045. "Error: Can not create directory\nput_dir(%s): %s",
  10046. path,
  10047. strerror(ERRNO));
  10048. return;
  10049. }
  10050. /* A file should be created or overwritten. */
  10051. /* Currently CivetWeb does not nead read+write access. */
  10052. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10053. || file.access.fp == NULL) {
  10054. (void)mg_fclose(&file.access);
  10055. mg_send_http_error(conn,
  10056. 500,
  10057. "Error: Can not create file\nfopen(%s): %s",
  10058. path,
  10059. strerror(ERRNO));
  10060. return;
  10061. }
  10062. fclose_on_exec(&file.access, conn);
  10063. range = mg_get_header(conn, "Content-Range");
  10064. r1 = r2 = 0;
  10065. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10066. conn->status_code = 206; /* Partial content */
  10067. fseeko(file.access.fp, r1, SEEK_SET);
  10068. }
  10069. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10070. /* forward_body_data failed.
  10071. * The error code has already been sent to the client,
  10072. * and conn->status_code is already set. */
  10073. (void)mg_fclose(&file.access);
  10074. return;
  10075. }
  10076. if (mg_fclose(&file.access) != 0) {
  10077. /* fclose failed. This might have different reasons, but a likely
  10078. * one is "no space on disk", http 507. */
  10079. conn->status_code = 507;
  10080. }
  10081. gmt_time_string(date, sizeof(date), &curtime);
  10082. mg_printf(conn,
  10083. "HTTP/1.1 %d %s\r\n",
  10084. conn->status_code,
  10085. mg_get_response_code_text(NULL, conn->status_code));
  10086. send_no_cache_header(conn);
  10087. send_additional_header(conn);
  10088. mg_printf(conn,
  10089. "Date: %s\r\n"
  10090. "Content-Length: 0\r\n"
  10091. "Connection: %s\r\n\r\n",
  10092. date,
  10093. suggest_connection_header(conn));
  10094. }
  10095. static void
  10096. delete_file(struct mg_connection *conn, const char *path)
  10097. {
  10098. struct de de;
  10099. memset(&de.file, 0, sizeof(de.file));
  10100. if (!mg_stat(conn, path, &de.file)) {
  10101. /* mg_stat returns 0 if the file does not exist */
  10102. mg_send_http_error(conn,
  10103. 404,
  10104. "Error: Cannot delete file\nFile %s not found",
  10105. path);
  10106. return;
  10107. }
  10108. #if 0 /* Ignore if a file in memory is inside a folder */
  10109. if (de.access.membuf != NULL) {
  10110. /* the file is cached in memory */
  10111. mg_send_http_error(
  10112. conn,
  10113. 405,
  10114. "Error: Delete not possible\nDeleting %s is not supported",
  10115. path);
  10116. return;
  10117. }
  10118. #endif
  10119. if (de.file.is_directory) {
  10120. if (remove_directory(conn, path)) {
  10121. /* Delete is successful: Return 204 without content. */
  10122. mg_send_http_error(conn, 204, "%s", "");
  10123. } else {
  10124. /* Delete is not successful: Return 500 (Server error). */
  10125. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10126. }
  10127. return;
  10128. }
  10129. /* This is an existing file (not a directory).
  10130. * Check if write permission is granted. */
  10131. if (access(path, W_OK) != 0) {
  10132. /* File is read only */
  10133. mg_send_http_error(
  10134. conn,
  10135. 403,
  10136. "Error: Delete not possible\nDeleting %s is not allowed",
  10137. path);
  10138. return;
  10139. }
  10140. /* Try to delete it. */
  10141. if (mg_remove(conn, path) == 0) {
  10142. /* Delete was successful: Return 204 without content. */
  10143. mg_send_http_error(conn, 204, "%s", "");
  10144. } else {
  10145. /* Delete not successful (file locked). */
  10146. mg_send_http_error(conn,
  10147. 423,
  10148. "Error: Cannot delete file\nremove(%s): %s",
  10149. path,
  10150. strerror(ERRNO));
  10151. }
  10152. }
  10153. #endif /* !NO_FILES */
  10154. #if !defined(NO_FILESYSTEMS)
  10155. static void
  10156. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10157. static void
  10158. do_ssi_include(struct mg_connection *conn,
  10159. const char *ssi,
  10160. char *tag,
  10161. int include_level)
  10162. {
  10163. char file_name[MG_BUF_LEN], path[512], *p;
  10164. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10165. size_t len;
  10166. int truncated = 0;
  10167. if (conn == NULL) {
  10168. return;
  10169. }
  10170. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10171. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10172. * always < MG_BUF_LEN. */
  10173. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10174. /* File name is relative to the webserver root */
  10175. file_name[511] = 0;
  10176. (void)mg_snprintf(conn,
  10177. &truncated,
  10178. path,
  10179. sizeof(path),
  10180. "%s/%s",
  10181. conn->dom_ctx->config[DOCUMENT_ROOT],
  10182. file_name);
  10183. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10184. /* File name is relative to the webserver working directory
  10185. * or it is absolute system path */
  10186. file_name[511] = 0;
  10187. (void)
  10188. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10189. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10190. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10191. /* File name is relative to the currect document */
  10192. file_name[511] = 0;
  10193. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10194. if (!truncated) {
  10195. if ((p = strrchr(path, '/')) != NULL) {
  10196. p[1] = '\0';
  10197. }
  10198. len = strlen(path);
  10199. (void)mg_snprintf(conn,
  10200. &truncated,
  10201. path + len,
  10202. sizeof(path) - len,
  10203. "%s",
  10204. file_name);
  10205. }
  10206. } else {
  10207. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10208. return;
  10209. }
  10210. if (truncated) {
  10211. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10212. return;
  10213. }
  10214. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10215. mg_cry_internal(conn,
  10216. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10217. tag,
  10218. path,
  10219. strerror(ERRNO));
  10220. } else {
  10221. fclose_on_exec(&file.access, conn);
  10222. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10223. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10224. path)
  10225. > 0) {
  10226. send_ssi_file(conn, path, &file, include_level + 1);
  10227. } else {
  10228. send_file_data(conn, &file, 0, INT64_MAX);
  10229. }
  10230. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10231. }
  10232. }
  10233. #if !defined(NO_POPEN)
  10234. static void
  10235. do_ssi_exec(struct mg_connection *conn, char *tag)
  10236. {
  10237. char cmd[1024] = "";
  10238. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10239. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10240. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10241. } else {
  10242. cmd[1023] = 0;
  10243. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10244. mg_cry_internal(conn,
  10245. "Cannot SSI #exec: [%s]: %s",
  10246. cmd,
  10247. strerror(ERRNO));
  10248. } else {
  10249. send_file_data(conn, &file, 0, INT64_MAX);
  10250. pclose(file.access.fp);
  10251. }
  10252. }
  10253. }
  10254. #endif /* !NO_POPEN */
  10255. static int
  10256. mg_fgetc(struct mg_file *filep, int offset)
  10257. {
  10258. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10259. if (filep == NULL) {
  10260. return EOF;
  10261. }
  10262. #if defined(MG_USE_OPEN_FILE)
  10263. if ((filep->access.membuf != NULL) && (offset >= 0)
  10264. && (((unsigned int)(offset)) < filep->stat.size)) {
  10265. return ((const unsigned char *)filep->access.membuf)[offset];
  10266. } else /* else block below */
  10267. #endif
  10268. if (filep->access.fp != NULL) {
  10269. return fgetc(filep->access.fp);
  10270. } else {
  10271. return EOF;
  10272. }
  10273. }
  10274. static void
  10275. send_ssi_file(struct mg_connection *conn,
  10276. const char *path,
  10277. struct mg_file *filep,
  10278. int include_level)
  10279. {
  10280. char buf[MG_BUF_LEN];
  10281. int ch, offset, len, in_tag, in_ssi_tag;
  10282. if (include_level > 10) {
  10283. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10284. return;
  10285. }
  10286. in_tag = in_ssi_tag = len = offset = 0;
  10287. /* Read file, byte by byte, and look for SSI include tags */
  10288. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10289. if (in_tag) {
  10290. /* We are in a tag, either SSI tag or html tag */
  10291. if (ch == '>') {
  10292. /* Tag is closing */
  10293. buf[len++] = '>';
  10294. if (in_ssi_tag) {
  10295. /* Handle SSI tag */
  10296. buf[len] = 0;
  10297. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10298. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10299. #if !defined(NO_POPEN)
  10300. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10301. do_ssi_exec(conn, buf + 9);
  10302. #endif /* !NO_POPEN */
  10303. } else {
  10304. mg_cry_internal(conn,
  10305. "%s: unknown SSI "
  10306. "command: \"%s\"",
  10307. path,
  10308. buf);
  10309. }
  10310. len = 0;
  10311. in_ssi_tag = in_tag = 0;
  10312. } else {
  10313. /* Not an SSI tag */
  10314. /* Flush buffer */
  10315. (void)mg_write(conn, buf, (size_t)len);
  10316. len = 0;
  10317. in_tag = 0;
  10318. }
  10319. } else {
  10320. /* Tag is still open */
  10321. buf[len++] = (char)(ch & 0xff);
  10322. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10323. /* All SSI tags start with <!--# */
  10324. in_ssi_tag = 1;
  10325. }
  10326. if ((len + 2) > (int)sizeof(buf)) {
  10327. /* Tag to long for buffer */
  10328. mg_cry_internal(conn, "%s: tag is too large", path);
  10329. return;
  10330. }
  10331. }
  10332. } else {
  10333. /* We are not in a tag yet. */
  10334. if (ch == '<') {
  10335. /* Tag is opening */
  10336. in_tag = 1;
  10337. if (len > 0) {
  10338. /* Flush current buffer.
  10339. * Buffer is filled with "len" bytes. */
  10340. (void)mg_write(conn, buf, (size_t)len);
  10341. }
  10342. /* Store the < */
  10343. len = 1;
  10344. buf[0] = '<';
  10345. } else {
  10346. /* No Tag */
  10347. /* Add data to buffer */
  10348. buf[len++] = (char)(ch & 0xff);
  10349. /* Flush if buffer is full */
  10350. if (len == (int)sizeof(buf)) {
  10351. mg_write(conn, buf, (size_t)len);
  10352. len = 0;
  10353. }
  10354. }
  10355. }
  10356. }
  10357. /* Send the rest of buffered data */
  10358. if (len > 0) {
  10359. mg_write(conn, buf, (size_t)len);
  10360. }
  10361. }
  10362. static void
  10363. handle_ssi_file_request(struct mg_connection *conn,
  10364. const char *path,
  10365. struct mg_file *filep)
  10366. {
  10367. char date[64];
  10368. time_t curtime = time(NULL);
  10369. const char *cors_orig_cfg;
  10370. const char *cors1, *cors2, *cors3;
  10371. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10372. return;
  10373. }
  10374. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10375. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10376. /* Cross-origin resource sharing (CORS). */
  10377. cors1 = "Access-Control-Allow-Origin: ";
  10378. cors2 = cors_orig_cfg;
  10379. cors3 = "\r\n";
  10380. } else {
  10381. cors1 = cors2 = cors3 = "";
  10382. }
  10383. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10384. /* File exists (precondition for calling this function),
  10385. * but can not be opened by the server. */
  10386. mg_send_http_error(conn,
  10387. 500,
  10388. "Error: Cannot read file\nfopen(%s): %s",
  10389. path,
  10390. strerror(ERRNO));
  10391. } else {
  10392. conn->must_close = 1;
  10393. gmt_time_string(date, sizeof(date), &curtime);
  10394. fclose_on_exec(&filep->access, conn);
  10395. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10396. send_no_cache_header(conn);
  10397. send_additional_header(conn);
  10398. mg_printf(conn,
  10399. "%s%s%s"
  10400. "Date: %s\r\n"
  10401. "Content-Type: text/html\r\n"
  10402. "Connection: %s\r\n\r\n",
  10403. cors1,
  10404. cors2,
  10405. cors3,
  10406. date,
  10407. suggest_connection_header(conn));
  10408. send_ssi_file(conn, path, filep, 0);
  10409. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10410. }
  10411. }
  10412. #endif /* NO_FILESYSTEMS */
  10413. #if !defined(NO_FILES)
  10414. static void
  10415. send_options(struct mg_connection *conn)
  10416. {
  10417. char date[64];
  10418. time_t curtime = time(NULL);
  10419. if (!conn) {
  10420. return;
  10421. }
  10422. conn->status_code = 200;
  10423. conn->must_close = 1;
  10424. gmt_time_string(date, sizeof(date), &curtime);
  10425. /* We do not set a "Cache-Control" header here, but leave the default.
  10426. * Since browsers do not send an OPTIONS request, we can not test the
  10427. * effect anyway. */
  10428. mg_printf(conn,
  10429. "HTTP/1.1 200 OK\r\n"
  10430. "Date: %s\r\n"
  10431. "Connection: %s\r\n"
  10432. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10433. "PROPFIND, MKCOL\r\n"
  10434. "DAV: 1\r\n",
  10435. date,
  10436. suggest_connection_header(conn));
  10437. send_additional_header(conn);
  10438. mg_printf(conn, "\r\n");
  10439. }
  10440. /* Writes PROPFIND properties for a collection element */
  10441. static int
  10442. print_props(struct mg_connection *conn,
  10443. const char *uri,
  10444. const char *name,
  10445. struct mg_file_stat *filep)
  10446. {
  10447. size_t href_size, i, j;
  10448. int len;
  10449. char *href, mtime[64];
  10450. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10451. return 0;
  10452. }
  10453. /* Estimate worst case size for encoding */
  10454. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10455. href = (char *)mg_malloc(href_size);
  10456. if (href == NULL) {
  10457. return 0;
  10458. }
  10459. len = mg_url_encode(uri, href, href_size);
  10460. if (len >= 0) {
  10461. /* Append an extra string */
  10462. mg_url_encode(name, href + len, href_size - (size_t)len);
  10463. }
  10464. /* Directory separator should be preserved. */
  10465. for (i = j = 0; href[i]; j++) {
  10466. if (!strncmp(href + i, "%2f", 3)) {
  10467. href[j] = '/';
  10468. i += 3;
  10469. } else {
  10470. href[j] = href[i++];
  10471. }
  10472. }
  10473. href[j] = '\0';
  10474. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10475. mg_printf(conn,
  10476. "<d:response>"
  10477. "<d:href>%s</d:href>"
  10478. "<d:propstat>"
  10479. "<d:prop>"
  10480. "<d:resourcetype>%s</d:resourcetype>"
  10481. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10482. "<d:getlastmodified>%s</d:getlastmodified>"
  10483. "</d:prop>"
  10484. "<d:status>HTTP/1.1 200 OK</d:status>"
  10485. "</d:propstat>"
  10486. "</d:response>\n",
  10487. href,
  10488. filep->is_directory ? "<d:collection/>" : "",
  10489. filep->size,
  10490. mtime);
  10491. mg_free(href);
  10492. return 1;
  10493. }
  10494. static int
  10495. print_dav_dir_entry(struct de *de, void *data)
  10496. {
  10497. struct mg_connection *conn = (struct mg_connection *)data;
  10498. if (!de || !conn
  10499. || !print_props(
  10500. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10501. return -1;
  10502. }
  10503. return 0;
  10504. }
  10505. static void
  10506. handle_propfind(struct mg_connection *conn,
  10507. const char *path,
  10508. struct mg_file_stat *filep)
  10509. {
  10510. const char *depth = mg_get_header(conn, "Depth");
  10511. char date[64];
  10512. time_t curtime = time(NULL);
  10513. gmt_time_string(date, sizeof(date), &curtime);
  10514. if (!conn || !path || !filep || !conn->dom_ctx) {
  10515. return;
  10516. }
  10517. conn->must_close = 1;
  10518. conn->status_code = 207;
  10519. mg_printf(conn,
  10520. "HTTP/1.1 207 Multi-Status\r\n"
  10521. "Date: %s\r\n",
  10522. date);
  10523. send_static_cache_header(conn);
  10524. send_additional_header(conn);
  10525. mg_printf(conn,
  10526. "Connection: %s\r\n"
  10527. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10528. suggest_connection_header(conn));
  10529. mg_printf(conn,
  10530. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10531. "<d:multistatus xmlns:d='DAV:'>\n");
  10532. /* Print properties for the requested resource itself */
  10533. print_props(conn, conn->request_info.local_uri, "", filep);
  10534. /* If it is a directory, print directory entries too if Depth is not 0
  10535. */
  10536. if (filep->is_directory
  10537. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10538. "yes")
  10539. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10540. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10541. }
  10542. mg_printf(conn, "%s\n", "</d:multistatus>");
  10543. }
  10544. #endif
  10545. void
  10546. mg_lock_connection(struct mg_connection *conn)
  10547. {
  10548. if (conn) {
  10549. (void)pthread_mutex_lock(&conn->mutex);
  10550. }
  10551. }
  10552. void
  10553. mg_unlock_connection(struct mg_connection *conn)
  10554. {
  10555. if (conn) {
  10556. (void)pthread_mutex_unlock(&conn->mutex);
  10557. }
  10558. }
  10559. void
  10560. mg_lock_context(struct mg_context *ctx)
  10561. {
  10562. if (ctx) {
  10563. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10564. }
  10565. }
  10566. void
  10567. mg_unlock_context(struct mg_context *ctx)
  10568. {
  10569. if (ctx) {
  10570. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10571. }
  10572. }
  10573. #if defined(USE_LUA)
  10574. #include "mod_lua.inl"
  10575. #endif /* USE_LUA */
  10576. #if defined(USE_DUKTAPE)
  10577. #include "mod_duktape.inl"
  10578. #endif /* USE_DUKTAPE */
  10579. #if defined(USE_WEBSOCKET)
  10580. #if !defined(NO_SSL_DL)
  10581. #define SHA_API static
  10582. #include "sha1.inl"
  10583. #endif
  10584. static int
  10585. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10586. {
  10587. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10588. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10589. SHA_CTX sha_ctx;
  10590. int truncated;
  10591. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10592. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10593. if (truncated) {
  10594. conn->must_close = 1;
  10595. return 0;
  10596. }
  10597. DEBUG_TRACE("%s", "Send websocket handshake");
  10598. SHA1_Init(&sha_ctx);
  10599. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10600. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10601. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10602. mg_printf(conn,
  10603. "HTTP/1.1 101 Switching Protocols\r\n"
  10604. "Upgrade: websocket\r\n"
  10605. "Connection: Upgrade\r\n"
  10606. "Sec-WebSocket-Accept: %s\r\n",
  10607. b64_sha);
  10608. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10609. mg_printf(conn,
  10610. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10611. conn->request_info.acceptedWebSocketSubprotocol);
  10612. } else {
  10613. mg_printf(conn, "%s", "\r\n");
  10614. }
  10615. return 1;
  10616. }
  10617. #if !defined(MG_MAX_UNANSWERED_PING)
  10618. /* Configuration of the maximum number of websocket PINGs that might
  10619. * stay unanswered before the connection is considered broken.
  10620. * Note: The name of this define may still change (until it is
  10621. * defined as a compile parameter in a documentation).
  10622. */
  10623. #define MG_MAX_UNANSWERED_PING (5)
  10624. #endif
  10625. static void
  10626. read_websocket(struct mg_connection *conn,
  10627. mg_websocket_data_handler ws_data_handler,
  10628. void *callback_data)
  10629. {
  10630. /* Pointer to the beginning of the portion of the incoming websocket
  10631. * message queue.
  10632. * The original websocket upgrade request is never removed, so the queue
  10633. * begins after it. */
  10634. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10635. int n, error, exit_by_callback;
  10636. int ret;
  10637. /* body_len is the length of the entire queue in bytes
  10638. * len is the length of the current message
  10639. * data_len is the length of the current message's data payload
  10640. * header_len is the length of the current message's header */
  10641. size_t i, len, mask_len = 0, header_len, body_len;
  10642. uint64_t data_len = 0;
  10643. /* "The masking key is a 32-bit value chosen at random by the client."
  10644. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10645. */
  10646. unsigned char mask[4];
  10647. /* data points to the place where the message is stored when passed to
  10648. * the websocket_data callback. This is either mem on the stack, or a
  10649. * dynamically allocated buffer if it is too large. */
  10650. unsigned char mem[4096];
  10651. unsigned char mop; /* mask flag and opcode */
  10652. /* Variables used for connection monitoring */
  10653. double timeout = -1.0;
  10654. int enable_ping_pong = 0;
  10655. int ping_count = 0;
  10656. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10657. enable_ping_pong =
  10658. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10659. "yes");
  10660. }
  10661. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10662. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10663. }
  10664. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10665. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10666. }
  10667. /* Enter data processing loop */
  10668. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10669. conn->request_info.remote_addr,
  10670. conn->request_info.remote_port);
  10671. conn->in_websocket_handling = 1;
  10672. mg_set_thread_name("wsock");
  10673. /* Loop continuously, reading messages from the socket, invoking the
  10674. * callback, and waiting repeatedly until an error occurs. */
  10675. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10676. header_len = 0;
  10677. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10678. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10679. len = buf[1] & 127;
  10680. mask_len = (buf[1] & 128) ? 4 : 0;
  10681. if ((len < 126) && (body_len >= mask_len)) {
  10682. /* inline 7-bit length field */
  10683. data_len = len;
  10684. header_len = 2 + mask_len;
  10685. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10686. /* 16-bit length field */
  10687. header_len = 4 + mask_len;
  10688. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10689. } else if (body_len >= (10 + mask_len)) {
  10690. /* 64-bit length field */
  10691. uint32_t l1, l2;
  10692. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10693. memcpy(&l2, &buf[6], 4);
  10694. header_len = 10 + mask_len;
  10695. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10696. if (data_len > (uint64_t)0x7FFF0000ul) {
  10697. /* no can do */
  10698. mg_cry_internal(
  10699. conn,
  10700. "%s",
  10701. "websocket out of memory; closing connection");
  10702. break;
  10703. }
  10704. }
  10705. }
  10706. if ((header_len > 0) && (body_len >= header_len)) {
  10707. /* Allocate space to hold websocket payload */
  10708. unsigned char *data = mem;
  10709. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10710. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10711. conn->phys_ctx);
  10712. if (data == NULL) {
  10713. /* Allocation failed, exit the loop and then close the
  10714. * connection */
  10715. mg_cry_internal(
  10716. conn,
  10717. "%s",
  10718. "websocket out of memory; closing connection");
  10719. break;
  10720. }
  10721. }
  10722. /* Copy the mask before we shift the queue and destroy it */
  10723. if (mask_len > 0) {
  10724. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10725. } else {
  10726. memset(mask, 0, sizeof(mask));
  10727. }
  10728. /* Read frame payload from the first message in the queue into
  10729. * data and advance the queue by moving the memory in place. */
  10730. DEBUG_ASSERT(body_len >= header_len);
  10731. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10732. mop = buf[0]; /* current mask and opcode */
  10733. /* Overflow case */
  10734. len = body_len - header_len;
  10735. memcpy(data, buf + header_len, len);
  10736. error = 0;
  10737. while ((uint64_t)len < data_len) {
  10738. n = pull_inner(NULL,
  10739. conn,
  10740. (char *)(data + len),
  10741. (int)(data_len - len),
  10742. timeout);
  10743. if (n <= -2) {
  10744. error = 1;
  10745. break;
  10746. } else if (n > 0) {
  10747. len += (size_t)n;
  10748. } else {
  10749. /* Timeout: should retry */
  10750. /* TODO: retry condition */
  10751. }
  10752. }
  10753. if (error) {
  10754. mg_cry_internal(
  10755. conn,
  10756. "%s",
  10757. "Websocket pull failed; closing connection");
  10758. if (data != mem) {
  10759. mg_free(data);
  10760. }
  10761. break;
  10762. }
  10763. conn->data_len = conn->request_len;
  10764. } else {
  10765. mop = buf[0]; /* current mask and opcode, overwritten by
  10766. * memmove() */
  10767. /* Length of the message being read at the front of the
  10768. * queue. Cast to 31 bit is OK, since we limited
  10769. * data_len before. */
  10770. len = (size_t)data_len + header_len;
  10771. /* Copy the data payload into the data pointer for the
  10772. * callback. Cast to 31 bit is OK, since we
  10773. * limited data_len */
  10774. memcpy(data, buf + header_len, (size_t)data_len);
  10775. /* Move the queue forward len bytes */
  10776. memmove(buf, buf + len, body_len - len);
  10777. /* Mark the queue as advanced */
  10778. conn->data_len -= (int)len;
  10779. }
  10780. /* Apply mask if necessary */
  10781. if (mask_len > 0) {
  10782. for (i = 0; i < (size_t)data_len; i++) {
  10783. data[i] ^= mask[i & 3];
  10784. }
  10785. }
  10786. exit_by_callback = 0;
  10787. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10788. /* filter PONG messages */
  10789. DEBUG_TRACE("PONG from %s:%u",
  10790. conn->request_info.remote_addr,
  10791. conn->request_info.remote_port);
  10792. /* No unanwered PINGs left */
  10793. ping_count = 0;
  10794. } else if (enable_ping_pong
  10795. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10796. /* reply PING messages */
  10797. DEBUG_TRACE("Reply PING from %s:%u",
  10798. conn->request_info.remote_addr,
  10799. conn->request_info.remote_port);
  10800. ret = mg_websocket_write(conn,
  10801. MG_WEBSOCKET_OPCODE_PONG,
  10802. (char *)data,
  10803. (size_t)data_len);
  10804. if (ret <= 0) {
  10805. /* Error: send failed */
  10806. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10807. break;
  10808. }
  10809. } else {
  10810. /* Exit the loop if callback signals to exit (server side),
  10811. * or "connection close" opcode received (client side). */
  10812. if ((ws_data_handler != NULL)
  10813. && !ws_data_handler(conn,
  10814. mop,
  10815. (char *)data,
  10816. (size_t)data_len,
  10817. callback_data)) {
  10818. exit_by_callback = 1;
  10819. }
  10820. }
  10821. /* It a buffer has been allocated, free it again */
  10822. if (data != mem) {
  10823. mg_free(data);
  10824. }
  10825. if (exit_by_callback) {
  10826. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10827. conn->request_info.remote_addr,
  10828. conn->request_info.remote_port);
  10829. break;
  10830. }
  10831. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10832. /* Opcode == 8, connection close */
  10833. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10834. conn->request_info.remote_addr,
  10835. conn->request_info.remote_port);
  10836. break;
  10837. }
  10838. /* Not breaking the loop, process next websocket frame. */
  10839. } else {
  10840. /* Read from the socket into the next available location in the
  10841. * message queue. */
  10842. n = pull_inner(NULL,
  10843. conn,
  10844. conn->buf + conn->data_len,
  10845. conn->buf_size - conn->data_len,
  10846. timeout);
  10847. if (n <= -2) {
  10848. /* Error, no bytes read */
  10849. DEBUG_TRACE("PULL from %s:%u failed",
  10850. conn->request_info.remote_addr,
  10851. conn->request_info.remote_port);
  10852. break;
  10853. }
  10854. if (n > 0) {
  10855. conn->data_len += n;
  10856. /* Reset open PING count */
  10857. ping_count = 0;
  10858. } else {
  10859. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10860. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10861. /* Stop sending PING */
  10862. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10863. "- closing connection",
  10864. ping_count,
  10865. conn->request_info.remote_addr,
  10866. conn->request_info.remote_port);
  10867. break;
  10868. }
  10869. if (enable_ping_pong) {
  10870. /* Send Websocket PING message */
  10871. DEBUG_TRACE("PING to %s:%u",
  10872. conn->request_info.remote_addr,
  10873. conn->request_info.remote_port);
  10874. ret = mg_websocket_write(conn,
  10875. MG_WEBSOCKET_OPCODE_PING,
  10876. NULL,
  10877. 0);
  10878. if (ret <= 0) {
  10879. /* Error: send failed */
  10880. DEBUG_TRACE("Send PING failed (%i)", ret);
  10881. break;
  10882. }
  10883. ping_count++;
  10884. }
  10885. }
  10886. /* Timeout: should retry */
  10887. /* TODO: get timeout def */
  10888. }
  10889. }
  10890. }
  10891. /* Leave data processing loop */
  10892. mg_set_thread_name("worker");
  10893. conn->in_websocket_handling = 0;
  10894. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10895. conn->request_info.remote_addr,
  10896. conn->request_info.remote_port);
  10897. }
  10898. static int
  10899. mg_websocket_write_exec(struct mg_connection *conn,
  10900. int opcode,
  10901. const char *data,
  10902. size_t dataLen,
  10903. uint32_t masking_key)
  10904. {
  10905. unsigned char header[14];
  10906. size_t headerLen;
  10907. int retval;
  10908. #if defined(GCC_DIAGNOSTIC)
  10909. /* Disable spurious conversion warning for GCC */
  10910. #pragma GCC diagnostic push
  10911. #pragma GCC diagnostic ignored "-Wconversion"
  10912. #endif
  10913. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10914. #if defined(GCC_DIAGNOSTIC)
  10915. #pragma GCC diagnostic pop
  10916. #endif
  10917. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10918. if (dataLen < 126) {
  10919. /* inline 7-bit length field */
  10920. header[1] = (unsigned char)dataLen;
  10921. headerLen = 2;
  10922. } else if (dataLen <= 0xFFFF) {
  10923. /* 16-bit length field */
  10924. uint16_t len = htons((uint16_t)dataLen);
  10925. header[1] = 126;
  10926. memcpy(header + 2, &len, 2);
  10927. headerLen = 4;
  10928. } else {
  10929. /* 64-bit length field */
  10930. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10931. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10932. header[1] = 127;
  10933. memcpy(header + 2, &len1, 4);
  10934. memcpy(header + 6, &len2, 4);
  10935. headerLen = 10;
  10936. }
  10937. if (masking_key) {
  10938. /* add mask */
  10939. header[1] |= 0x80;
  10940. memcpy(header + headerLen, &masking_key, 4);
  10941. headerLen += 4;
  10942. }
  10943. /* Note that POSIX/Winsock's send() is threadsafe
  10944. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10945. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10946. * push(), although that is only a problem if the packet is large or
  10947. * outgoing buffer is full). */
  10948. /* TODO: Check if this lock should be moved to user land.
  10949. * Currently the server sets this lock for websockets, but
  10950. * not for any other connection. It must be set for every
  10951. * conn read/written by more than one thread, no matter if
  10952. * it is a websocket or regular connection. */
  10953. (void)mg_lock_connection(conn);
  10954. retval = mg_write(conn, header, headerLen);
  10955. if (retval != (int)headerLen) {
  10956. /* Did not send complete header */
  10957. retval = -1;
  10958. } else {
  10959. if (dataLen > 0) {
  10960. retval = mg_write(conn, data, dataLen);
  10961. }
  10962. /* if dataLen == 0, the header length (2) is returned */
  10963. }
  10964. /* TODO: Remove this unlock as well, when lock is removed. */
  10965. mg_unlock_connection(conn);
  10966. return retval;
  10967. }
  10968. int
  10969. mg_websocket_write(struct mg_connection *conn,
  10970. int opcode,
  10971. const char *data,
  10972. size_t dataLen)
  10973. {
  10974. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10975. }
  10976. static void
  10977. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10978. {
  10979. size_t i = 0;
  10980. i = 0;
  10981. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10982. /* Convert in 32 bit words, if data is 4 byte aligned */
  10983. while (i < (in_len - 3)) {
  10984. *(uint32_t *)(void *)(out + i) =
  10985. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10986. i += 4;
  10987. }
  10988. }
  10989. if (i != in_len) {
  10990. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10991. while (i < in_len) {
  10992. *(uint8_t *)(void *)(out + i) =
  10993. *(uint8_t *)(void *)(in + i)
  10994. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10995. i++;
  10996. }
  10997. }
  10998. }
  10999. int
  11000. mg_websocket_client_write(struct mg_connection *conn,
  11001. int opcode,
  11002. const char *data,
  11003. size_t dataLen)
  11004. {
  11005. int retval = -1;
  11006. char *masked_data =
  11007. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11008. uint32_t masking_key = 0;
  11009. if (masked_data == NULL) {
  11010. /* Return -1 in an error case */
  11011. mg_cry_internal(conn,
  11012. "%s",
  11013. "Cannot allocate buffer for masked websocket response: "
  11014. "Out of memory");
  11015. return -1;
  11016. }
  11017. do {
  11018. /* Get a masking key - but not 0 */
  11019. masking_key = (uint32_t)get_random();
  11020. } while (masking_key == 0);
  11021. mask_data(data, dataLen, masking_key, masked_data);
  11022. retval = mg_websocket_write_exec(
  11023. conn, opcode, masked_data, dataLen, masking_key);
  11024. mg_free(masked_data);
  11025. return retval;
  11026. }
  11027. static void
  11028. handle_websocket_request(struct mg_connection *conn,
  11029. const char *path,
  11030. int is_callback_resource,
  11031. struct mg_websocket_subprotocols *subprotocols,
  11032. mg_websocket_connect_handler ws_connect_handler,
  11033. mg_websocket_ready_handler ws_ready_handler,
  11034. mg_websocket_data_handler ws_data_handler,
  11035. mg_websocket_close_handler ws_close_handler,
  11036. void *cbData)
  11037. {
  11038. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11039. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11040. ptrdiff_t lua_websock = 0;
  11041. #if !defined(USE_LUA)
  11042. (void)path;
  11043. #endif
  11044. /* Step 1: Check websocket protocol version. */
  11045. /* Step 1.1: Check Sec-WebSocket-Key. */
  11046. if (!websock_key) {
  11047. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11048. * requires a Sec-WebSocket-Key header.
  11049. */
  11050. /* It could be the hixie draft version
  11051. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11052. */
  11053. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11054. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11055. char key3[8];
  11056. if ((key1 != NULL) && (key2 != NULL)) {
  11057. /* This version uses 8 byte body data in a GET request */
  11058. conn->content_len = 8;
  11059. if (8 == mg_read(conn, key3, 8)) {
  11060. /* This is the hixie version */
  11061. mg_send_http_error(conn,
  11062. 426,
  11063. "%s",
  11064. "Protocol upgrade to RFC 6455 required");
  11065. return;
  11066. }
  11067. }
  11068. /* This is an unknown version */
  11069. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11070. return;
  11071. }
  11072. /* Step 1.2: Check websocket protocol version. */
  11073. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11074. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11075. /* Reject wrong versions */
  11076. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11077. return;
  11078. }
  11079. /* Step 1.3: Could check for "Host", but we do not really nead this
  11080. * value for anything, so just ignore it. */
  11081. /* Step 2: If a callback is responsible, call it. */
  11082. if (is_callback_resource) {
  11083. /* Step 2.1 check and select subprotocol */
  11084. const char *protocols[64]; // max 64 headers
  11085. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11086. "Sec-WebSocket-Protocol",
  11087. protocols,
  11088. 64);
  11089. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11090. int cnt = 0;
  11091. int idx;
  11092. unsigned long len;
  11093. const char *sep, *curSubProtocol,
  11094. *acceptedWebSocketSubprotocol = NULL;
  11095. /* look for matching subprotocol */
  11096. do {
  11097. const char *protocol = protocols[cnt];
  11098. do {
  11099. sep = strchr(protocol, ',');
  11100. curSubProtocol = protocol;
  11101. len = sep ? (unsigned long)(sep - protocol)
  11102. : (unsigned long)strlen(protocol);
  11103. while (sep && isspace((unsigned char)*++sep))
  11104. ; // ignore leading whitespaces
  11105. protocol = sep;
  11106. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11107. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11108. && (strncmp(curSubProtocol,
  11109. subprotocols->subprotocols[idx],
  11110. len)
  11111. == 0)) {
  11112. acceptedWebSocketSubprotocol =
  11113. subprotocols->subprotocols[idx];
  11114. break;
  11115. }
  11116. }
  11117. } while (sep && !acceptedWebSocketSubprotocol);
  11118. } while (++cnt < nbSubprotocolHeader
  11119. && !acceptedWebSocketSubprotocol);
  11120. conn->request_info.acceptedWebSocketSubprotocol =
  11121. acceptedWebSocketSubprotocol;
  11122. } else if (nbSubprotocolHeader > 0) {
  11123. /* keep legacy behavior */
  11124. const char *protocol = protocols[0];
  11125. /* The protocol is a comma separated list of names. */
  11126. /* The server must only return one value from this list. */
  11127. /* First check if it is a list or just a single value. */
  11128. const char *sep = strrchr(protocol, ',');
  11129. if (sep == NULL) {
  11130. /* Just a single protocol -> accept it. */
  11131. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11132. } else {
  11133. /* Multiple protocols -> accept the last one. */
  11134. /* This is just a quick fix if the client offers multiple
  11135. * protocols. The handler should have a list of accepted
  11136. * protocols on his own
  11137. * and use it to select one protocol among those the client
  11138. * has
  11139. * offered.
  11140. */
  11141. while (isspace((unsigned char)*++sep)) {
  11142. ; /* ignore leading whitespaces */
  11143. }
  11144. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11145. }
  11146. }
  11147. if ((ws_connect_handler != NULL)
  11148. && (ws_connect_handler(conn, cbData) != 0)) {
  11149. /* C callback has returned non-zero, do not proceed with
  11150. * handshake.
  11151. */
  11152. /* Note that C callbacks are no longer called when Lua is
  11153. * responsible, so C can no longer filter callbacks for Lua. */
  11154. return;
  11155. }
  11156. }
  11157. #if defined(USE_LUA)
  11158. /* Step 3: No callback. Check if Lua is responsible. */
  11159. else {
  11160. /* Step 3.1: Check if Lua is responsible. */
  11161. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11162. lua_websock = match_prefix(
  11163. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11164. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11165. path);
  11166. }
  11167. if (lua_websock) {
  11168. /* Step 3.2: Lua is responsible: call it. */
  11169. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11170. if (!conn->lua_websocket_state) {
  11171. /* Lua rejected the new client */
  11172. return;
  11173. }
  11174. }
  11175. }
  11176. #endif
  11177. /* Step 4: Check if there is a responsible websocket handler. */
  11178. if (!is_callback_resource && !lua_websock) {
  11179. /* There is no callback, and Lua is not responsible either. */
  11180. /* Reply with a 404 Not Found. We are still at a standard
  11181. * HTTP request here, before the websocket handshake, so
  11182. * we can still send standard HTTP error replies. */
  11183. mg_send_http_error(conn, 404, "%s", "Not found");
  11184. return;
  11185. }
  11186. /* Step 5: The websocket connection has been accepted */
  11187. if (!send_websocket_handshake(conn, websock_key)) {
  11188. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11189. return;
  11190. }
  11191. /* Step 6: Call the ready handler */
  11192. if (is_callback_resource) {
  11193. if (ws_ready_handler != NULL) {
  11194. ws_ready_handler(conn, cbData);
  11195. }
  11196. #if defined(USE_LUA)
  11197. } else if (lua_websock) {
  11198. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11199. /* the ready handler returned false */
  11200. return;
  11201. }
  11202. #endif
  11203. }
  11204. /* Step 7: Enter the read loop */
  11205. if (is_callback_resource) {
  11206. read_websocket(conn, ws_data_handler, cbData);
  11207. #if defined(USE_LUA)
  11208. } else if (lua_websock) {
  11209. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11210. #endif
  11211. }
  11212. /* Step 8: Call the close handler */
  11213. if (ws_close_handler) {
  11214. ws_close_handler(conn, cbData);
  11215. }
  11216. }
  11217. static int
  11218. is_websocket_protocol(const struct mg_connection *conn)
  11219. {
  11220. const char *upgrade, *connection;
  11221. /* A websocket protocoll has the following HTTP headers:
  11222. *
  11223. * Connection: Upgrade
  11224. * Upgrade: Websocket
  11225. */
  11226. upgrade = mg_get_header(conn, "Upgrade");
  11227. if (upgrade == NULL) {
  11228. return 0; /* fail early, don't waste time checking other header
  11229. * fields
  11230. */
  11231. }
  11232. DEBUG_TRACE("Upgrade: %s", upgrade);
  11233. if (!mg_strcasestr(upgrade, "websocket")) {
  11234. return 0;
  11235. }
  11236. connection = mg_get_header(conn, "Connection");
  11237. if (connection == NULL) {
  11238. return 0;
  11239. }
  11240. if (!mg_strcasestr(connection, "upgrade")) {
  11241. return 0;
  11242. }
  11243. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11244. * "Sec-WebSocket-Version" are also required.
  11245. * Don't check them here, since even an unsupported websocket protocol
  11246. * request still IS a websocket request (in contrast to a standard HTTP
  11247. * request). It will fail later in handle_websocket_request.
  11248. */
  11249. return 1;
  11250. }
  11251. #endif /* !USE_WEBSOCKET */
  11252. static int
  11253. isbyte(int n)
  11254. {
  11255. return (n >= 0) && (n <= 255);
  11256. }
  11257. static int
  11258. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11259. {
  11260. int n, a, b, c, d, slash = 32, len = 0;
  11261. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11262. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11263. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11264. && (slash < 33)) {
  11265. len = n;
  11266. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11267. | (uint32_t)d;
  11268. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11269. }
  11270. return len;
  11271. }
  11272. static int
  11273. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11274. {
  11275. int throttle = 0;
  11276. struct vec vec, val;
  11277. uint32_t net, mask;
  11278. char mult;
  11279. double v;
  11280. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11281. mult = ',';
  11282. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11283. || (v < 0)
  11284. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11285. && (mult != ','))) {
  11286. continue;
  11287. }
  11288. v *= (lowercase(&mult) == 'k')
  11289. ? 1024
  11290. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11291. if (vec.len == 1 && vec.ptr[0] == '*') {
  11292. throttle = (int)v;
  11293. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11294. if ((remote_ip & mask) == net) {
  11295. throttle = (int)v;
  11296. }
  11297. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11298. throttle = (int)v;
  11299. }
  11300. }
  11301. return throttle;
  11302. }
  11303. static uint32_t
  11304. get_remote_ip(const struct mg_connection *conn)
  11305. {
  11306. if (!conn) {
  11307. return 0;
  11308. }
  11309. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11310. }
  11311. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11312. #include "handle_form.inl"
  11313. #if defined(MG_LEGACY_INTERFACE)
  11314. /* Implement the deprecated mg_upload function by calling the new
  11315. * mg_handle_form_request function. While mg_upload could only handle
  11316. * HTML forms sent as POST request in multipart/form-data format
  11317. * containing only file input elements, mg_handle_form_request can
  11318. * handle all form input elements and all standard request methods. */
  11319. struct mg_upload_user_data {
  11320. struct mg_connection *conn;
  11321. const char *destination_dir;
  11322. int num_uploaded_files;
  11323. };
  11324. /* Helper function for deprecated mg_upload. */
  11325. static int
  11326. mg_upload_field_found(const char *key,
  11327. const char *filename,
  11328. char *path,
  11329. size_t pathlen,
  11330. void *user_data)
  11331. {
  11332. int truncated = 0;
  11333. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11334. (void)key;
  11335. if (!filename) {
  11336. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11337. return FORM_FIELD_STORAGE_ABORT;
  11338. }
  11339. mg_snprintf(fud->conn,
  11340. &truncated,
  11341. path,
  11342. pathlen - 1,
  11343. "%s/%s",
  11344. fud->destination_dir,
  11345. filename);
  11346. if (truncated) {
  11347. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11348. return FORM_FIELD_STORAGE_ABORT;
  11349. }
  11350. return FORM_FIELD_STORAGE_STORE;
  11351. }
  11352. /* Helper function for deprecated mg_upload. */
  11353. static int
  11354. mg_upload_field_get(const char *key,
  11355. const char *value,
  11356. size_t value_size,
  11357. void *user_data)
  11358. {
  11359. /* Function should never be called */
  11360. (void)key;
  11361. (void)value;
  11362. (void)value_size;
  11363. (void)user_data;
  11364. return 0;
  11365. }
  11366. /* Helper function for deprecated mg_upload. */
  11367. static int
  11368. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11369. {
  11370. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11371. (void)file_size;
  11372. fud->num_uploaded_files++;
  11373. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11374. return 0;
  11375. }
  11376. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11377. int
  11378. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11379. {
  11380. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11381. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11382. mg_upload_field_get,
  11383. mg_upload_field_stored,
  11384. 0};
  11385. int ret;
  11386. fdh.user_data = (void *)&fud;
  11387. ret = mg_handle_form_request(conn, &fdh);
  11388. if (ret < 0) {
  11389. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11390. }
  11391. return fud.num_uploaded_files;
  11392. }
  11393. #endif
  11394. static int
  11395. get_first_ssl_listener_index(const struct mg_context *ctx)
  11396. {
  11397. unsigned int i;
  11398. int idx = -1;
  11399. if (ctx) {
  11400. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11401. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11402. }
  11403. }
  11404. return idx;
  11405. }
  11406. /* Return host (without port) */
  11407. /* Use mg_free to free the result */
  11408. static const char *
  11409. alloc_get_host(struct mg_connection *conn)
  11410. {
  11411. char buf[1025];
  11412. size_t buflen = sizeof(buf);
  11413. const char *host_header = get_header(conn->request_info.http_headers,
  11414. conn->request_info.num_headers,
  11415. "Host");
  11416. char *host;
  11417. if (host_header != NULL) {
  11418. char *pos;
  11419. /* Create a local copy of the "Host" header, since it might be
  11420. * modified here. */
  11421. mg_strlcpy(buf, host_header, buflen);
  11422. buf[buflen - 1] = '\0';
  11423. host = buf;
  11424. while (isspace((unsigned char)*host)) {
  11425. host++;
  11426. }
  11427. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11428. * is found. */
  11429. if (*host == '[') {
  11430. pos = strchr(host, ']');
  11431. if (!pos) {
  11432. /* Malformed hostname starts with '[', but no ']' found */
  11433. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11434. return NULL;
  11435. }
  11436. /* terminate after ']' */
  11437. pos[1] = 0;
  11438. } else {
  11439. /* Otherwise, a ':' separates hostname and port number */
  11440. pos = strchr(host, ':');
  11441. if (pos != NULL) {
  11442. *pos = '\0';
  11443. }
  11444. }
  11445. if (conn->ssl) {
  11446. /* This is a HTTPS connection, maybe we have a hostname
  11447. * from SNI (set in ssl_servername_callback). */
  11448. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11449. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11450. /* We are not using the default domain */
  11451. if (mg_strcasecmp(host, sslhost)) {
  11452. /* Mismatch between SNI domain and HTTP domain */
  11453. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11454. sslhost,
  11455. host);
  11456. return NULL;
  11457. }
  11458. }
  11459. DEBUG_TRACE("HTTPS Host: %s", host);
  11460. } else {
  11461. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11462. while (dom) {
  11463. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11464. /* Found matching domain */
  11465. DEBUG_TRACE("HTTP domain %s found",
  11466. dom->config[AUTHENTICATION_DOMAIN]);
  11467. /* TODO: Check if this is a HTTP or HTTPS domain */
  11468. conn->dom_ctx = dom;
  11469. break;
  11470. }
  11471. dom = dom->next;
  11472. }
  11473. DEBUG_TRACE("HTTP Host: %s", host);
  11474. }
  11475. } else {
  11476. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11477. host = buf;
  11478. DEBUG_TRACE("IP: %s", host);
  11479. }
  11480. return mg_strdup_ctx(host, conn->phys_ctx);
  11481. }
  11482. static void
  11483. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11484. {
  11485. char target_url[MG_BUF_LEN];
  11486. int truncated = 0;
  11487. conn->must_close = 1;
  11488. /* Send host, port, uri and (if it exists) ?query_string */
  11489. if (conn->host) {
  11490. /* Use "308 Permanent Redirect" */
  11491. int redirect_code = 308;
  11492. /* Create target URL */
  11493. mg_snprintf(
  11494. conn,
  11495. &truncated,
  11496. target_url,
  11497. sizeof(target_url),
  11498. "https://%s:%d%s%s%s",
  11499. conn->host,
  11500. #if defined(USE_IPV6)
  11501. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11502. == AF_INET6)
  11503. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11504. .lsa.sin6.sin6_port)
  11505. :
  11506. #endif
  11507. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11508. .lsa.sin.sin_port),
  11509. conn->request_info.local_uri,
  11510. (conn->request_info.query_string == NULL) ? "" : "?",
  11511. (conn->request_info.query_string == NULL)
  11512. ? ""
  11513. : conn->request_info.query_string);
  11514. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11515. * is used as buffer size) */
  11516. if (truncated) {
  11517. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11518. return;
  11519. }
  11520. /* Use redirect helper function */
  11521. mg_send_http_redirect(conn, target_url, redirect_code);
  11522. }
  11523. }
  11524. static void
  11525. handler_info_acquire(struct mg_handler_info *handler_info)
  11526. {
  11527. pthread_mutex_lock(&handler_info->refcount_mutex);
  11528. handler_info->refcount++;
  11529. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11530. }
  11531. static void
  11532. handler_info_release(struct mg_handler_info *handler_info)
  11533. {
  11534. pthread_mutex_lock(&handler_info->refcount_mutex);
  11535. handler_info->refcount--;
  11536. pthread_cond_signal(&handler_info->refcount_cond);
  11537. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11538. }
  11539. static void
  11540. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11541. {
  11542. pthread_mutex_lock(&handler_info->refcount_mutex);
  11543. while (handler_info->refcount) {
  11544. pthread_cond_wait(&handler_info->refcount_cond,
  11545. &handler_info->refcount_mutex);
  11546. }
  11547. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11548. }
  11549. static void
  11550. mg_set_handler_type(struct mg_context *phys_ctx,
  11551. struct mg_domain_context *dom_ctx,
  11552. const char *uri,
  11553. int handler_type,
  11554. int is_delete_request,
  11555. mg_request_handler handler,
  11556. struct mg_websocket_subprotocols *subprotocols,
  11557. mg_websocket_connect_handler connect_handler,
  11558. mg_websocket_ready_handler ready_handler,
  11559. mg_websocket_data_handler data_handler,
  11560. mg_websocket_close_handler close_handler,
  11561. mg_authorization_handler auth_handler,
  11562. void *cbdata)
  11563. {
  11564. struct mg_handler_info *tmp_rh, **lastref;
  11565. size_t urilen = strlen(uri);
  11566. if (handler_type == WEBSOCKET_HANDLER) {
  11567. DEBUG_ASSERT(handler == NULL);
  11568. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11569. || ready_handler != NULL || data_handler != NULL
  11570. || close_handler != NULL);
  11571. DEBUG_ASSERT(auth_handler == NULL);
  11572. if (handler != NULL) {
  11573. return;
  11574. }
  11575. if (!is_delete_request && (connect_handler == NULL)
  11576. && (ready_handler == NULL) && (data_handler == NULL)
  11577. && (close_handler == NULL)) {
  11578. return;
  11579. }
  11580. if (auth_handler != NULL) {
  11581. return;
  11582. }
  11583. } else if (handler_type == REQUEST_HANDLER) {
  11584. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11585. && data_handler == NULL && close_handler == NULL);
  11586. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11587. DEBUG_ASSERT(auth_handler == NULL);
  11588. if ((connect_handler != NULL) || (ready_handler != NULL)
  11589. || (data_handler != NULL) || (close_handler != NULL)) {
  11590. return;
  11591. }
  11592. if (!is_delete_request && (handler == NULL)) {
  11593. return;
  11594. }
  11595. if (auth_handler != NULL) {
  11596. return;
  11597. }
  11598. } else { /* AUTH_HANDLER */
  11599. DEBUG_ASSERT(handler == NULL);
  11600. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11601. && data_handler == NULL && close_handler == NULL);
  11602. DEBUG_ASSERT(auth_handler != NULL);
  11603. if (handler != NULL) {
  11604. return;
  11605. }
  11606. if ((connect_handler != NULL) || (ready_handler != NULL)
  11607. || (data_handler != NULL) || (close_handler != NULL)) {
  11608. return;
  11609. }
  11610. if (!is_delete_request && (auth_handler == NULL)) {
  11611. return;
  11612. }
  11613. }
  11614. if (!phys_ctx || !dom_ctx) {
  11615. return;
  11616. }
  11617. mg_lock_context(phys_ctx);
  11618. /* first try to find an existing handler */
  11619. lastref = &(dom_ctx->handlers);
  11620. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11621. if (tmp_rh->handler_type == handler_type) {
  11622. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11623. if (!is_delete_request) {
  11624. /* update existing handler */
  11625. if (handler_type == REQUEST_HANDLER) {
  11626. /* Wait for end of use before updating */
  11627. handler_info_wait_unused(tmp_rh);
  11628. /* Ok, the handler is no more use -> Update it */
  11629. tmp_rh->handler = handler;
  11630. } else if (handler_type == WEBSOCKET_HANDLER) {
  11631. tmp_rh->subprotocols = subprotocols;
  11632. tmp_rh->connect_handler = connect_handler;
  11633. tmp_rh->ready_handler = ready_handler;
  11634. tmp_rh->data_handler = data_handler;
  11635. tmp_rh->close_handler = close_handler;
  11636. } else { /* AUTH_HANDLER */
  11637. tmp_rh->auth_handler = auth_handler;
  11638. }
  11639. tmp_rh->cbdata = cbdata;
  11640. } else {
  11641. /* remove existing handler */
  11642. if (handler_type == REQUEST_HANDLER) {
  11643. /* Wait for end of use before removing */
  11644. handler_info_wait_unused(tmp_rh);
  11645. /* Ok, the handler is no more used -> Destroy resources
  11646. */
  11647. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11648. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11649. }
  11650. *lastref = tmp_rh->next;
  11651. mg_free(tmp_rh->uri);
  11652. mg_free(tmp_rh);
  11653. }
  11654. mg_unlock_context(phys_ctx);
  11655. return;
  11656. }
  11657. }
  11658. lastref = &(tmp_rh->next);
  11659. }
  11660. if (is_delete_request) {
  11661. /* no handler to set, this was a remove request to a non-existing
  11662. * handler */
  11663. mg_unlock_context(phys_ctx);
  11664. return;
  11665. }
  11666. tmp_rh =
  11667. (struct mg_handler_info *)mg_calloc_ctx(1,
  11668. sizeof(struct mg_handler_info),
  11669. phys_ctx);
  11670. if (tmp_rh == NULL) {
  11671. mg_unlock_context(phys_ctx);
  11672. mg_cry_ctx_internal(phys_ctx,
  11673. "%s",
  11674. "Cannot create new request handler struct, OOM");
  11675. return;
  11676. }
  11677. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11678. if (!tmp_rh->uri) {
  11679. mg_unlock_context(phys_ctx);
  11680. mg_free(tmp_rh);
  11681. mg_cry_ctx_internal(phys_ctx,
  11682. "%s",
  11683. "Cannot create new request handler struct, OOM");
  11684. return;
  11685. }
  11686. tmp_rh->uri_len = urilen;
  11687. if (handler_type == REQUEST_HANDLER) {
  11688. /* Init refcount mutex and condition */
  11689. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11690. mg_unlock_context(phys_ctx);
  11691. mg_free(tmp_rh);
  11692. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11693. return;
  11694. }
  11695. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11696. mg_unlock_context(phys_ctx);
  11697. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11698. mg_free(tmp_rh);
  11699. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11700. return;
  11701. }
  11702. tmp_rh->refcount = 0;
  11703. tmp_rh->handler = handler;
  11704. } else if (handler_type == WEBSOCKET_HANDLER) {
  11705. tmp_rh->subprotocols = subprotocols;
  11706. tmp_rh->connect_handler = connect_handler;
  11707. tmp_rh->ready_handler = ready_handler;
  11708. tmp_rh->data_handler = data_handler;
  11709. tmp_rh->close_handler = close_handler;
  11710. } else { /* AUTH_HANDLER */
  11711. tmp_rh->auth_handler = auth_handler;
  11712. }
  11713. tmp_rh->cbdata = cbdata;
  11714. tmp_rh->handler_type = handler_type;
  11715. tmp_rh->next = NULL;
  11716. *lastref = tmp_rh;
  11717. mg_unlock_context(phys_ctx);
  11718. }
  11719. void
  11720. mg_set_request_handler(struct mg_context *ctx,
  11721. const char *uri,
  11722. mg_request_handler handler,
  11723. void *cbdata)
  11724. {
  11725. mg_set_handler_type(ctx,
  11726. &(ctx->dd),
  11727. uri,
  11728. REQUEST_HANDLER,
  11729. handler == NULL,
  11730. handler,
  11731. NULL,
  11732. NULL,
  11733. NULL,
  11734. NULL,
  11735. NULL,
  11736. NULL,
  11737. cbdata);
  11738. }
  11739. void
  11740. mg_set_websocket_handler(struct mg_context *ctx,
  11741. const char *uri,
  11742. mg_websocket_connect_handler connect_handler,
  11743. mg_websocket_ready_handler ready_handler,
  11744. mg_websocket_data_handler data_handler,
  11745. mg_websocket_close_handler close_handler,
  11746. void *cbdata)
  11747. {
  11748. mg_set_websocket_handler_with_subprotocols(ctx,
  11749. uri,
  11750. NULL,
  11751. connect_handler,
  11752. ready_handler,
  11753. data_handler,
  11754. close_handler,
  11755. cbdata);
  11756. }
  11757. void
  11758. mg_set_websocket_handler_with_subprotocols(
  11759. struct mg_context *ctx,
  11760. const char *uri,
  11761. struct mg_websocket_subprotocols *subprotocols,
  11762. mg_websocket_connect_handler connect_handler,
  11763. mg_websocket_ready_handler ready_handler,
  11764. mg_websocket_data_handler data_handler,
  11765. mg_websocket_close_handler close_handler,
  11766. void *cbdata)
  11767. {
  11768. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11769. && (data_handler == NULL)
  11770. && (close_handler == NULL);
  11771. mg_set_handler_type(ctx,
  11772. &(ctx->dd),
  11773. uri,
  11774. WEBSOCKET_HANDLER,
  11775. is_delete_request,
  11776. NULL,
  11777. subprotocols,
  11778. connect_handler,
  11779. ready_handler,
  11780. data_handler,
  11781. close_handler,
  11782. NULL,
  11783. cbdata);
  11784. }
  11785. void
  11786. mg_set_auth_handler(struct mg_context *ctx,
  11787. const char *uri,
  11788. mg_authorization_handler handler,
  11789. void *cbdata)
  11790. {
  11791. mg_set_handler_type(ctx,
  11792. &(ctx->dd),
  11793. uri,
  11794. AUTH_HANDLER,
  11795. handler == NULL,
  11796. NULL,
  11797. NULL,
  11798. NULL,
  11799. NULL,
  11800. NULL,
  11801. NULL,
  11802. handler,
  11803. cbdata);
  11804. }
  11805. static int
  11806. get_request_handler(struct mg_connection *conn,
  11807. int handler_type,
  11808. mg_request_handler *handler,
  11809. struct mg_websocket_subprotocols **subprotocols,
  11810. mg_websocket_connect_handler *connect_handler,
  11811. mg_websocket_ready_handler *ready_handler,
  11812. mg_websocket_data_handler *data_handler,
  11813. mg_websocket_close_handler *close_handler,
  11814. mg_authorization_handler *auth_handler,
  11815. void **cbdata,
  11816. struct mg_handler_info **handler_info)
  11817. {
  11818. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11819. if (request_info) {
  11820. const char *uri = request_info->local_uri;
  11821. size_t urilen = strlen(uri);
  11822. struct mg_handler_info *tmp_rh;
  11823. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11824. return 0;
  11825. }
  11826. mg_lock_context(conn->phys_ctx);
  11827. /* first try for an exact match */
  11828. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11829. tmp_rh = tmp_rh->next) {
  11830. if (tmp_rh->handler_type == handler_type) {
  11831. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11832. if (handler_type == WEBSOCKET_HANDLER) {
  11833. *subprotocols = tmp_rh->subprotocols;
  11834. *connect_handler = tmp_rh->connect_handler;
  11835. *ready_handler = tmp_rh->ready_handler;
  11836. *data_handler = tmp_rh->data_handler;
  11837. *close_handler = tmp_rh->close_handler;
  11838. } else if (handler_type == REQUEST_HANDLER) {
  11839. *handler = tmp_rh->handler;
  11840. /* Acquire handler and give it back */
  11841. handler_info_acquire(tmp_rh);
  11842. *handler_info = tmp_rh;
  11843. } else { /* AUTH_HANDLER */
  11844. *auth_handler = tmp_rh->auth_handler;
  11845. }
  11846. *cbdata = tmp_rh->cbdata;
  11847. mg_unlock_context(conn->phys_ctx);
  11848. return 1;
  11849. }
  11850. }
  11851. }
  11852. /* next try for a partial match, we will accept uri/something */
  11853. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11854. tmp_rh = tmp_rh->next) {
  11855. if (tmp_rh->handler_type == handler_type) {
  11856. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11857. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11858. if (handler_type == WEBSOCKET_HANDLER) {
  11859. *subprotocols = tmp_rh->subprotocols;
  11860. *connect_handler = tmp_rh->connect_handler;
  11861. *ready_handler = tmp_rh->ready_handler;
  11862. *data_handler = tmp_rh->data_handler;
  11863. *close_handler = tmp_rh->close_handler;
  11864. } else if (handler_type == REQUEST_HANDLER) {
  11865. *handler = tmp_rh->handler;
  11866. /* Acquire handler and give it back */
  11867. handler_info_acquire(tmp_rh);
  11868. *handler_info = tmp_rh;
  11869. } else { /* AUTH_HANDLER */
  11870. *auth_handler = tmp_rh->auth_handler;
  11871. }
  11872. *cbdata = tmp_rh->cbdata;
  11873. mg_unlock_context(conn->phys_ctx);
  11874. return 1;
  11875. }
  11876. }
  11877. }
  11878. /* finally try for pattern match */
  11879. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11880. tmp_rh = tmp_rh->next) {
  11881. if (tmp_rh->handler_type == handler_type) {
  11882. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11883. if (handler_type == WEBSOCKET_HANDLER) {
  11884. *subprotocols = tmp_rh->subprotocols;
  11885. *connect_handler = tmp_rh->connect_handler;
  11886. *ready_handler = tmp_rh->ready_handler;
  11887. *data_handler = tmp_rh->data_handler;
  11888. *close_handler = tmp_rh->close_handler;
  11889. } else if (handler_type == REQUEST_HANDLER) {
  11890. *handler = tmp_rh->handler;
  11891. /* Acquire handler and give it back */
  11892. handler_info_acquire(tmp_rh);
  11893. *handler_info = tmp_rh;
  11894. } else { /* AUTH_HANDLER */
  11895. *auth_handler = tmp_rh->auth_handler;
  11896. }
  11897. *cbdata = tmp_rh->cbdata;
  11898. mg_unlock_context(conn->phys_ctx);
  11899. return 1;
  11900. }
  11901. }
  11902. }
  11903. mg_unlock_context(conn->phys_ctx);
  11904. }
  11905. return 0; /* none found */
  11906. }
  11907. /* Check if the script file is in a path, allowed for script files.
  11908. * This can be used if uploading files is possible not only for the server
  11909. * admin, and the upload mechanism does not check the file extension.
  11910. */
  11911. static int
  11912. is_in_script_path(const struct mg_connection *conn, const char *path)
  11913. {
  11914. /* TODO (Feature): Add config value for allowed script path.
  11915. * Default: All allowed. */
  11916. (void)conn;
  11917. (void)path;
  11918. return 1;
  11919. }
  11920. #if defined(USE_WEBSOCKET) \
  11921. && (defined(MG_LEGACY_INTERFACE) || defined(MG_EXPERIMENTAL_INTERFACES))
  11922. static int
  11923. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11924. void *cbdata)
  11925. {
  11926. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11927. if (pcallbacks->websocket_connect) {
  11928. return pcallbacks->websocket_connect(conn);
  11929. }
  11930. /* No handler set - assume "OK" */
  11931. return 0;
  11932. }
  11933. static void
  11934. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11935. {
  11936. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11937. if (pcallbacks->websocket_ready) {
  11938. pcallbacks->websocket_ready(conn);
  11939. }
  11940. }
  11941. static int
  11942. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11943. int bits,
  11944. char *data,
  11945. size_t len,
  11946. void *cbdata)
  11947. {
  11948. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11949. if (pcallbacks->websocket_data) {
  11950. return pcallbacks->websocket_data(conn, bits, data, len);
  11951. }
  11952. /* No handler set - assume "OK" */
  11953. return 1;
  11954. }
  11955. static void
  11956. deprecated_websocket_close_wrapper(const struct mg_connection *conn,
  11957. void *cbdata)
  11958. {
  11959. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11960. if (pcallbacks->connection_close) {
  11961. pcallbacks->connection_close(conn);
  11962. }
  11963. }
  11964. #endif
  11965. /* This is the heart of the Civetweb's logic.
  11966. * This function is called when the request is read, parsed and validated,
  11967. * and Civetweb must decide what action to take: serve a file, or
  11968. * a directory, or call embedded function, etcetera. */
  11969. static void
  11970. handle_request(struct mg_connection *conn)
  11971. {
  11972. struct mg_request_info *ri = &conn->request_info;
  11973. char path[PATH_MAX];
  11974. int uri_len, ssl_index;
  11975. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11976. is_put_or_delete_request = 0, is_callback_resource = 0;
  11977. int i;
  11978. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11979. mg_request_handler callback_handler = NULL;
  11980. struct mg_handler_info *handler_info = NULL;
  11981. struct mg_websocket_subprotocols *subprotocols;
  11982. mg_websocket_connect_handler ws_connect_handler = NULL;
  11983. mg_websocket_ready_handler ws_ready_handler = NULL;
  11984. mg_websocket_data_handler ws_data_handler = NULL;
  11985. mg_websocket_close_handler ws_close_handler = NULL;
  11986. void *callback_data = NULL;
  11987. mg_authorization_handler auth_handler = NULL;
  11988. void *auth_callback_data = NULL;
  11989. int handler_type;
  11990. time_t curtime = time(NULL);
  11991. char date[64];
  11992. path[0] = 0;
  11993. /* 1. get the request url */
  11994. /* 1.1. split into url and query string */
  11995. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11996. != NULL) {
  11997. *((char *)conn->request_info.query_string++) = '\0';
  11998. }
  11999. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12000. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12001. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12002. if (ssl_index >= 0) {
  12003. redirect_to_https_port(conn, ssl_index);
  12004. } else {
  12005. /* A http to https forward port has been specified,
  12006. * but no https port to forward to. */
  12007. mg_send_http_error(conn,
  12008. 503,
  12009. "%s",
  12010. "Error: SSL forward not configured properly");
  12011. mg_cry_internal(conn,
  12012. "%s",
  12013. "Can not redirect to SSL, no SSL port available");
  12014. }
  12015. return;
  12016. }
  12017. uri_len = (int)strlen(ri->local_uri);
  12018. /* 1.3. decode url (if config says so) */
  12019. if (should_decode_url(conn)) {
  12020. mg_url_decode(
  12021. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12022. }
  12023. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12024. * not possible */
  12025. remove_dot_segments((char *)ri->local_uri);
  12026. /* step 1. completed, the url is known now */
  12027. uri_len = (int)strlen(ri->local_uri);
  12028. DEBUG_TRACE("URL: %s", ri->local_uri);
  12029. /* 2. if this ip has limited speed, set it for this connection */
  12030. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12031. get_remote_ip(conn),
  12032. ri->local_uri);
  12033. /* 3. call a "handle everything" callback, if registered */
  12034. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12035. /* Note that since V1.7 the "begin_request" function is called
  12036. * before an authorization check. If an authorization check is
  12037. * required, use a request_handler instead. */
  12038. i = conn->phys_ctx->callbacks.begin_request(conn);
  12039. if (i > 0) {
  12040. /* callback already processed the request. Store the
  12041. return value as a status code for the access log. */
  12042. conn->status_code = i;
  12043. discard_unread_request_data(conn);
  12044. return;
  12045. } else if (i == 0) {
  12046. /* civetweb should process the request */
  12047. } else {
  12048. /* unspecified - may change with the next version */
  12049. return;
  12050. }
  12051. }
  12052. /* request not yet handled by a handler or redirect, so the request
  12053. * is processed here */
  12054. /* 4. Check for CORS preflight requests and handle them (if configured).
  12055. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12056. */
  12057. if (!strcmp(ri->request_method, "OPTIONS")) {
  12058. /* Send a response to CORS preflights only if
  12059. * access_control_allow_methods is not NULL and not an empty string.
  12060. * In this case, scripts can still handle CORS. */
  12061. const char *cors_meth_cfg =
  12062. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12063. const char *cors_orig_cfg =
  12064. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12065. const char *cors_origin =
  12066. get_header(ri->http_headers, ri->num_headers, "Origin");
  12067. const char *cors_acrm = get_header(ri->http_headers,
  12068. ri->num_headers,
  12069. "Access-Control-Request-Method");
  12070. /* Todo: check if cors_origin is in cors_orig_cfg.
  12071. * Or, let the client check this. */
  12072. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12073. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12074. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12075. /* This is a valid CORS preflight, and the server is configured
  12076. * to
  12077. * handle it automatically. */
  12078. const char *cors_acrh =
  12079. get_header(ri->http_headers,
  12080. ri->num_headers,
  12081. "Access-Control-Request-Headers");
  12082. gmt_time_string(date, sizeof(date), &curtime);
  12083. mg_printf(conn,
  12084. "HTTP/1.1 200 OK\r\n"
  12085. "Date: %s\r\n"
  12086. "Access-Control-Allow-Origin: %s\r\n"
  12087. "Access-Control-Allow-Methods: %s\r\n"
  12088. "Content-Length: 0\r\n"
  12089. "Connection: %s\r\n",
  12090. date,
  12091. cors_orig_cfg,
  12092. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12093. suggest_connection_header(conn));
  12094. if (cors_acrh != NULL) {
  12095. /* CORS request is asking for additional headers */
  12096. const char *cors_hdr_cfg =
  12097. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12098. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12099. /* Allow only if access_control_allow_headers is
  12100. * not NULL and not an empty string. If this
  12101. * configuration is set to *, allow everything.
  12102. * Otherwise this configuration must be a list
  12103. * of allowed HTTP header names. */
  12104. mg_printf(conn,
  12105. "Access-Control-Allow-Headers: %s\r\n",
  12106. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12107. : cors_hdr_cfg));
  12108. }
  12109. }
  12110. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12111. mg_printf(conn, "\r\n");
  12112. return;
  12113. }
  12114. }
  12115. /* 5. interpret the url to find out how the request must be handled
  12116. */
  12117. /* 5.1. first test, if the request targets the regular http(s)://
  12118. * protocol namespace or the websocket ws(s):// protocol namespace.
  12119. */
  12120. is_websocket_request = is_websocket_protocol(conn);
  12121. #if defined(USE_WEBSOCKET)
  12122. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12123. #else
  12124. handler_type = REQUEST_HANDLER;
  12125. #endif /* defined(USE_WEBSOCKET) */
  12126. /* 5.2. check if the request will be handled by a callback */
  12127. if (get_request_handler(conn,
  12128. handler_type,
  12129. &callback_handler,
  12130. &subprotocols,
  12131. &ws_connect_handler,
  12132. &ws_ready_handler,
  12133. &ws_data_handler,
  12134. &ws_close_handler,
  12135. NULL,
  12136. &callback_data,
  12137. &handler_info)) {
  12138. /* 5.2.1. A callback will handle this request. All requests
  12139. * handled
  12140. * by a callback have to be considered as requests to a script
  12141. * resource. */
  12142. is_callback_resource = 1;
  12143. is_script_resource = 1;
  12144. is_put_or_delete_request = is_put_or_delete_method(conn);
  12145. } else {
  12146. no_callback_resource:
  12147. /* 5.2.2. No callback is responsible for this request. The URI
  12148. * addresses a file based resource (static content or Lua/cgi
  12149. * scripts in the file system). */
  12150. is_callback_resource = 0;
  12151. interpret_uri(conn,
  12152. path,
  12153. sizeof(path),
  12154. &file.stat,
  12155. &is_found,
  12156. &is_script_resource,
  12157. &is_websocket_request,
  12158. &is_put_or_delete_request);
  12159. }
  12160. /* 6. authorization check */
  12161. /* 6.1. a custom authorization handler is installed */
  12162. if (get_request_handler(conn,
  12163. AUTH_HANDLER,
  12164. NULL,
  12165. NULL,
  12166. NULL,
  12167. NULL,
  12168. NULL,
  12169. NULL,
  12170. &auth_handler,
  12171. &auth_callback_data,
  12172. NULL)) {
  12173. if (!auth_handler(conn, auth_callback_data)) {
  12174. return;
  12175. }
  12176. } else if (is_put_or_delete_request && !is_script_resource
  12177. && !is_callback_resource) {
  12178. /* 6.2. this request is a PUT/DELETE to a real file */
  12179. /* 6.2.1. thus, the server must have real files */
  12180. #if defined(NO_FILES)
  12181. if (1) {
  12182. #else
  12183. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12184. #endif
  12185. /* This server does not have any real files, thus the
  12186. * PUT/DELETE methods are not valid. */
  12187. mg_send_http_error(conn,
  12188. 405,
  12189. "%s method not allowed",
  12190. conn->request_info.request_method);
  12191. return;
  12192. }
  12193. #if !defined(NO_FILES)
  12194. /* 6.2.2. Check if put authorization for static files is
  12195. * available.
  12196. */
  12197. if (!is_authorized_for_put(conn)) {
  12198. send_authorization_request(conn, NULL);
  12199. return;
  12200. }
  12201. #endif
  12202. } else {
  12203. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12204. * or it is a PUT or DELETE request to a resource that does not
  12205. * correspond to a file. Check authorization. */
  12206. if (!check_authorization(conn, path)) {
  12207. send_authorization_request(conn, NULL);
  12208. return;
  12209. }
  12210. }
  12211. /* request is authorized or does not need authorization */
  12212. /* 7. check if there are request handlers for this uri */
  12213. if (is_callback_resource) {
  12214. if (!is_websocket_request) {
  12215. i = callback_handler(conn, callback_data);
  12216. /* Callback handler will not be used anymore. Release it */
  12217. handler_info_release(handler_info);
  12218. if (i > 0) {
  12219. /* Do nothing, callback has served the request. Store
  12220. * then return value as status code for the log and discard
  12221. * all data from the client not used by the callback. */
  12222. conn->status_code = i;
  12223. discard_unread_request_data(conn);
  12224. } else {
  12225. /* The handler did NOT handle the request. */
  12226. /* Some proper reactions would be:
  12227. * a) close the connections without sending anything
  12228. * b) send a 404 not found
  12229. * c) try if there is a file matching the URI
  12230. * It would be possible to do a, b or c in the callback
  12231. * implementation, and return 1 - we cannot do anything
  12232. * here, that is not possible in the callback.
  12233. *
  12234. * TODO: What would be the best reaction here?
  12235. * (Note: The reaction may change, if there is a better
  12236. *idea.)
  12237. */
  12238. /* For the moment, use option c: We look for a proper file,
  12239. * but since a file request is not always a script resource,
  12240. * the authorization check might be different. */
  12241. interpret_uri(conn,
  12242. path,
  12243. sizeof(path),
  12244. &file.stat,
  12245. &is_found,
  12246. &is_script_resource,
  12247. &is_websocket_request,
  12248. &is_put_or_delete_request);
  12249. callback_handler = NULL;
  12250. /* Here we are at a dead end:
  12251. * According to URI matching, a callback should be
  12252. * responsible for handling the request,
  12253. * we called it, but the callback declared itself
  12254. * not responsible.
  12255. * We use a goto here, to get out of this dead end,
  12256. * and continue with the default handling.
  12257. * A goto here is simpler and better to understand
  12258. * than some curious loop. */
  12259. goto no_callback_resource;
  12260. }
  12261. } else {
  12262. #if defined(USE_WEBSOCKET)
  12263. handle_websocket_request(conn,
  12264. path,
  12265. is_callback_resource,
  12266. subprotocols,
  12267. ws_connect_handler,
  12268. ws_ready_handler,
  12269. ws_data_handler,
  12270. ws_close_handler,
  12271. callback_data);
  12272. #endif
  12273. }
  12274. return;
  12275. }
  12276. /* 8. handle websocket requests */
  12277. #if defined(USE_WEBSOCKET)
  12278. if (is_websocket_request) {
  12279. if (is_script_resource) {
  12280. if (is_in_script_path(conn, path)) {
  12281. /* Websocket Lua script */
  12282. handle_websocket_request(conn,
  12283. path,
  12284. 0 /* Lua Script */,
  12285. NULL,
  12286. NULL,
  12287. NULL,
  12288. NULL,
  12289. NULL,
  12290. conn->phys_ctx->user_data);
  12291. } else {
  12292. /* Script was in an illegal path */
  12293. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12294. }
  12295. } else {
  12296. #if defined(MG_LEGACY_INTERFACE)
  12297. handle_websocket_request(
  12298. conn,
  12299. path,
  12300. !is_script_resource /* could be deprecated global callback */,
  12301. NULL,
  12302. deprecated_websocket_connect_wrapper,
  12303. deprecated_websocket_ready_wrapper,
  12304. deprecated_websocket_data_wrapper,
  12305. NULL,
  12306. conn->phys_ctx->callbacks);
  12307. #else
  12308. mg_send_http_error(conn, 404, "%s", "Not found");
  12309. #endif
  12310. }
  12311. return;
  12312. } else
  12313. #endif
  12314. #if defined(NO_FILES)
  12315. /* 9a. In case the server uses only callbacks, this uri is
  12316. * unknown.
  12317. * Then, all request handling ends here. */
  12318. mg_send_http_error(conn, 404, "%s", "Not Found");
  12319. #else
  12320. /* 9b. This request is either for a static file or resource handled
  12321. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12322. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12323. mg_send_http_error(conn, 404, "%s", "Not Found");
  12324. return;
  12325. }
  12326. /* 10. Request is handled by a script */
  12327. if (is_script_resource) {
  12328. handle_file_based_request(conn, path, &file);
  12329. return;
  12330. }
  12331. /* 11. Handle put/delete/mkcol requests */
  12332. if (is_put_or_delete_request) {
  12333. /* 11.1. PUT method */
  12334. if (!strcmp(ri->request_method, "PUT")) {
  12335. put_file(conn, path);
  12336. return;
  12337. }
  12338. /* 11.2. DELETE method */
  12339. if (!strcmp(ri->request_method, "DELETE")) {
  12340. delete_file(conn, path);
  12341. return;
  12342. }
  12343. /* 11.3. MKCOL method */
  12344. if (!strcmp(ri->request_method, "MKCOL")) {
  12345. mkcol(conn, path);
  12346. return;
  12347. }
  12348. /* 11.4. PATCH method
  12349. * This method is not supported for static resources,
  12350. * only for scripts (Lua, CGI) and callbacks. */
  12351. mg_send_http_error(conn,
  12352. 405,
  12353. "%s method not allowed",
  12354. conn->request_info.request_method);
  12355. return;
  12356. }
  12357. /* 11. File does not exist, or it was configured that it should be
  12358. * hidden */
  12359. if (!is_found || (must_hide_file(conn, path))) {
  12360. mg_send_http_error(conn, 404, "%s", "Not found");
  12361. return;
  12362. }
  12363. /* 12. Directory uris should end with a slash */
  12364. if (file.stat.is_directory && (uri_len > 0)
  12365. && (ri->local_uri[uri_len - 1] != '/')) {
  12366. gmt_time_string(date, sizeof(date), &curtime);
  12367. mg_printf(conn,
  12368. "HTTP/1.1 301 Moved Permanently\r\n"
  12369. "Location: %s/\r\n"
  12370. "Date: %s\r\n"
  12371. /* "Cache-Control: private\r\n" (= default) */
  12372. "Content-Length: 0\r\n"
  12373. "Connection: %s\r\n",
  12374. ri->request_uri,
  12375. date,
  12376. suggest_connection_header(conn));
  12377. send_additional_header(conn);
  12378. mg_printf(conn, "\r\n");
  12379. return;
  12380. }
  12381. /* 13. Handle other methods than GET/HEAD */
  12382. /* 13.1. Handle PROPFIND */
  12383. if (!strcmp(ri->request_method, "PROPFIND")) {
  12384. handle_propfind(conn, path, &file.stat);
  12385. return;
  12386. }
  12387. /* 13.2. Handle OPTIONS for files */
  12388. if (!strcmp(ri->request_method, "OPTIONS")) {
  12389. /* This standard handler is only used for real files.
  12390. * Scripts should support the OPTIONS method themselves, to allow a
  12391. * maximum flexibility.
  12392. * Lua and CGI scripts may fully support CORS this way (including
  12393. * preflights). */
  12394. send_options(conn);
  12395. return;
  12396. }
  12397. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12398. if ((0 != strcmp(ri->request_method, "GET"))
  12399. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12400. mg_send_http_error(conn,
  12401. 405,
  12402. "%s method not allowed",
  12403. conn->request_info.request_method);
  12404. return;
  12405. }
  12406. /* 14. directories */
  12407. if (file.stat.is_directory) {
  12408. /* Substitute files have already been handled above. */
  12409. /* Here we can either generate and send a directory listing,
  12410. * or send an "access denied" error. */
  12411. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12412. "yes")) {
  12413. handle_directory_request(conn, path);
  12414. } else {
  12415. mg_send_http_error(conn,
  12416. 403,
  12417. "%s",
  12418. "Error: Directory listing denied");
  12419. }
  12420. return;
  12421. }
  12422. /* 15. read a normal file with GET or HEAD */
  12423. handle_file_based_request(conn, path, &file);
  12424. #endif /* !defined(NO_FILES) */
  12425. }
  12426. #if !defined(NO_FILESYSTEMS)
  12427. static void
  12428. handle_file_based_request(struct mg_connection *conn,
  12429. const char *path,
  12430. struct mg_file *file)
  12431. {
  12432. if (!conn || !conn->dom_ctx) {
  12433. return;
  12434. }
  12435. if (0) {
  12436. #if defined(USE_LUA)
  12437. } else if (match_prefix(
  12438. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12439. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12440. path)
  12441. > 0) {
  12442. if (is_in_script_path(conn, path)) {
  12443. /* Lua server page: an SSI like page containing mostly plain
  12444. * html
  12445. * code
  12446. * plus some tags with server generated contents. */
  12447. handle_lsp_request(conn, path, file, NULL);
  12448. } else {
  12449. /* Script was in an illegal path */
  12450. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12451. }
  12452. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12453. strlen(
  12454. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12455. path)
  12456. > 0) {
  12457. if (is_in_script_path(conn, path)) {
  12458. /* Lua in-server module script: a CGI like script used to
  12459. * generate
  12460. * the
  12461. * entire reply. */
  12462. mg_exec_lua_script(conn, path, NULL);
  12463. } else {
  12464. /* Script was in an illegal path */
  12465. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12466. }
  12467. #endif
  12468. #if defined(USE_DUKTAPE)
  12469. } else if (match_prefix(
  12470. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12471. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12472. path)
  12473. > 0) {
  12474. if (is_in_script_path(conn, path)) {
  12475. /* Call duktape to generate the page */
  12476. mg_exec_duktape_script(conn, path);
  12477. } else {
  12478. /* Script was in an illegal path */
  12479. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12480. }
  12481. #endif
  12482. #if !defined(NO_CGI)
  12483. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12484. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12485. path)
  12486. > 0) {
  12487. if (is_in_script_path(conn, path)) {
  12488. /* CGI scripts may support all HTTP methods */
  12489. handle_cgi_request(conn, path);
  12490. } else {
  12491. /* Script was in an illegal path */
  12492. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12493. }
  12494. #endif /* !NO_CGI */
  12495. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12496. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12497. path)
  12498. > 0) {
  12499. if (is_in_script_path(conn, path)) {
  12500. handle_ssi_file_request(conn, path, file);
  12501. } else {
  12502. /* Script was in an illegal path */
  12503. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12504. }
  12505. #if !defined(NO_CACHING)
  12506. } else if ((!conn->in_error_handler)
  12507. && is_not_modified(conn, &file->stat)) {
  12508. /* Send 304 "Not Modified" - this must not send any body data */
  12509. handle_not_modified_static_file_request(conn, file);
  12510. #endif /* !NO_CACHING */
  12511. } else {
  12512. handle_static_file_request(conn, path, file, NULL, NULL);
  12513. }
  12514. }
  12515. #endif /* NO_FILESYSTEMS */
  12516. static void
  12517. close_all_listening_sockets(struct mg_context *ctx)
  12518. {
  12519. unsigned int i;
  12520. if (!ctx) {
  12521. return;
  12522. }
  12523. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12524. closesocket(ctx->listening_sockets[i].sock);
  12525. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12526. }
  12527. mg_free(ctx->listening_sockets);
  12528. ctx->listening_sockets = NULL;
  12529. mg_free(ctx->listening_socket_fds);
  12530. ctx->listening_socket_fds = NULL;
  12531. }
  12532. /* Valid listening port specification is: [ip_address:]port[s]
  12533. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12534. * Examples for IPv6: [::]:80, [::1]:80,
  12535. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12536. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12537. * In order to bind to both, IPv4 and IPv6, you can either add
  12538. * both ports using 8080,[::]:8080, or the short form +8080.
  12539. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12540. * one only accepting IPv4 the other only IPv6. +8080 creates
  12541. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12542. * environment, they might work differently, or might not work
  12543. * at all - it must be tested what options work best in the
  12544. * relevant network environment.
  12545. */
  12546. static int
  12547. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12548. {
  12549. unsigned int a, b, c, d, port;
  12550. int ch, len;
  12551. const char *cb;
  12552. char *endptr;
  12553. #if defined(USE_IPV6)
  12554. char buf[100] = {0};
  12555. #endif
  12556. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12557. * Also, all-zeroes in the socket address means binding to all addresses
  12558. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12559. memset(so, 0, sizeof(*so));
  12560. so->lsa.sin.sin_family = AF_INET;
  12561. *ip_version = 0;
  12562. /* Initialize port and len as invalid. */
  12563. port = 0;
  12564. len = 0;
  12565. /* Test for different ways to format this string */
  12566. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12567. == 5) {
  12568. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12569. so->lsa.sin.sin_addr.s_addr =
  12570. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12571. so->lsa.sin.sin_port = htons((uint16_t)port);
  12572. *ip_version = 4;
  12573. #if defined(USE_IPV6)
  12574. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12575. && mg_inet_pton(
  12576. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12577. /* IPv6 address, examples: see above */
  12578. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12579. */
  12580. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12581. *ip_version = 6;
  12582. #endif
  12583. } else if ((vec->ptr[0] == '+')
  12584. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12585. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12586. /* Add 1 to len for the + character we skipped before */
  12587. len++;
  12588. #if defined(USE_IPV6)
  12589. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12590. so->lsa.sin6.sin6_family = AF_INET6;
  12591. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12592. *ip_version = 4 + 6;
  12593. #else
  12594. /* Bind to IPv4 only, since IPv6 is not built in. */
  12595. so->lsa.sin.sin_port = htons((uint16_t)port);
  12596. *ip_version = 4;
  12597. #endif
  12598. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12599. && vec->ptr != endptr) {
  12600. len = endptr - vec->ptr;
  12601. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12602. so->lsa.sin.sin_port = htons((uint16_t)port);
  12603. *ip_version = 4;
  12604. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12605. /* String could be a hostname. This check algotithm
  12606. * will only work for RFC 952 compliant hostnames,
  12607. * starting with a letter, containing only letters,
  12608. * digits and hyphen ('-'). Newer specs may allow
  12609. * more, but this is not guaranteed here, since it
  12610. * may interfere with rules for port option lists. */
  12611. /* According to RFC 1035, hostnames are restricted to 255 characters
  12612. * in total (63 between two dots). */
  12613. char hostname[256];
  12614. size_t hostnlen = (size_t)(cb - vec->ptr);
  12615. if (hostnlen >= sizeof(hostname)) {
  12616. /* This would be invalid in any case */
  12617. *ip_version = 0;
  12618. return 0;
  12619. }
  12620. memcpy(hostname, vec->ptr, hostnlen);
  12621. hostname[hostnlen] = 0;
  12622. if (mg_inet_pton(
  12623. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12624. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12625. *ip_version = 4;
  12626. so->lsa.sin.sin_family = AF_INET;
  12627. so->lsa.sin.sin_port = htons((uint16_t)port);
  12628. len += (int)(hostnlen + 1);
  12629. } else {
  12630. port = 0;
  12631. len = 0;
  12632. }
  12633. #if defined(USE_IPV6)
  12634. } else if (mg_inet_pton(AF_INET6,
  12635. vec->ptr,
  12636. &so->lsa.sin6,
  12637. sizeof(so->lsa.sin6))) {
  12638. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12639. *ip_version = 6;
  12640. so->lsa.sin6.sin6_family = AF_INET6;
  12641. so->lsa.sin.sin_port = htons((uint16_t)port);
  12642. len += (int)(hostnlen + 1);
  12643. } else {
  12644. port = 0;
  12645. len = 0;
  12646. }
  12647. #endif
  12648. }
  12649. } else {
  12650. /* Parsing failure. */
  12651. }
  12652. /* sscanf and the option splitting code ensure the following condition
  12653. */
  12654. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12655. *ip_version = 0;
  12656. return 0;
  12657. }
  12658. ch = vec->ptr[len]; /* Next character after the port number */
  12659. so->is_ssl = (ch == 's');
  12660. so->ssl_redir = (ch == 'r');
  12661. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12662. if (is_valid_port(port)
  12663. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12664. return 1;
  12665. }
  12666. /* Reset ip_version to 0 if there is an error */
  12667. *ip_version = 0;
  12668. return 0;
  12669. }
  12670. /* Is there any SSL port in use? */
  12671. static int
  12672. is_ssl_port_used(const char *ports)
  12673. {
  12674. if (ports) {
  12675. /* There are several different allowed syntax variants:
  12676. * - "80" for a single port using every network interface
  12677. * - "localhost:80" for a single port using only localhost
  12678. * - "80,localhost:8080" for two ports, one bound to localhost
  12679. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12680. * to IPv4 localhost, one to IPv6 localhost
  12681. * - "+80" use port 80 for IPv4 and IPv6
  12682. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12683. * for both: IPv4 and IPv4
  12684. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12685. * additionally port 8080 bound to localhost connections
  12686. *
  12687. * If we just look for 's' anywhere in the string, "localhost:80"
  12688. * will be detected as SSL (false positive).
  12689. * Looking for 's' after a digit may cause false positives in
  12690. * "my24service:8080".
  12691. * Looking from 's' backward if there are only ':' and numbers
  12692. * before will not work for "24service:8080" (non SSL, port 8080)
  12693. * or "24s" (SSL, port 24).
  12694. *
  12695. * Remark: Initially hostnames were not allowed to start with a
  12696. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12697. * Section 2.1).
  12698. *
  12699. * To get this correct, the entire string must be parsed as a whole,
  12700. * reading it as a list element for element and parsing with an
  12701. * algorithm equivalent to parse_port_string.
  12702. *
  12703. * In fact, we use local interface names here, not arbitrary hostnames,
  12704. * so in most cases the only name will be "localhost".
  12705. *
  12706. * So, for now, we use this simple algorithm, that may still return
  12707. * a false positive in bizarre cases.
  12708. */
  12709. int i;
  12710. int portslen = (int)strlen(ports);
  12711. char prevIsNumber = 0;
  12712. for (i = 0; i < portslen; i++) {
  12713. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12714. return 1;
  12715. }
  12716. if (ports[i] >= '0' && ports[i] <= '9') {
  12717. prevIsNumber = 1;
  12718. } else {
  12719. prevIsNumber = 0;
  12720. }
  12721. }
  12722. }
  12723. return 0;
  12724. }
  12725. static int
  12726. set_ports_option(struct mg_context *phys_ctx)
  12727. {
  12728. const char *list;
  12729. int on = 1;
  12730. #if defined(USE_IPV6)
  12731. int off = 0;
  12732. #endif
  12733. struct vec vec;
  12734. struct socket so, *ptr;
  12735. struct mg_pollfd *pfd;
  12736. union usa usa;
  12737. socklen_t len;
  12738. int ip_version;
  12739. int portsTotal = 0;
  12740. int portsOk = 0;
  12741. const char *opt_txt;
  12742. long opt_max_connections;
  12743. if (!phys_ctx) {
  12744. return 0;
  12745. }
  12746. memset(&so, 0, sizeof(so));
  12747. memset(&usa, 0, sizeof(usa));
  12748. len = sizeof(usa);
  12749. list = phys_ctx->dd.config[LISTENING_PORTS];
  12750. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12751. portsTotal++;
  12752. if (!parse_port_string(&vec, &so, &ip_version)) {
  12753. mg_cry_ctx_internal(
  12754. phys_ctx,
  12755. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12756. (int)vec.len,
  12757. vec.ptr,
  12758. portsTotal,
  12759. "[IP_ADDRESS:]PORT[s|r]");
  12760. continue;
  12761. }
  12762. #if !defined(NO_SSL)
  12763. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12764. mg_cry_ctx_internal(phys_ctx,
  12765. "Cannot add SSL socket (entry %i)",
  12766. portsTotal);
  12767. continue;
  12768. }
  12769. #endif
  12770. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12771. == INVALID_SOCKET) {
  12772. mg_cry_ctx_internal(phys_ctx,
  12773. "cannot create socket (entry %i)",
  12774. portsTotal);
  12775. continue;
  12776. }
  12777. #if defined(_WIN32)
  12778. /* Windows SO_REUSEADDR lets many procs binds to a
  12779. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12780. * if someone already has the socket -- DTL */
  12781. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12782. * Windows might need a few seconds before
  12783. * the same port can be used again in the
  12784. * same process, so a short Sleep may be
  12785. * required between mg_stop and mg_start.
  12786. */
  12787. if (setsockopt(so.sock,
  12788. SOL_SOCKET,
  12789. SO_EXCLUSIVEADDRUSE,
  12790. (SOCK_OPT_TYPE)&on,
  12791. sizeof(on))
  12792. != 0) {
  12793. /* Set reuse option, but don't abort on errors. */
  12794. mg_cry_ctx_internal(
  12795. phys_ctx,
  12796. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12797. portsTotal);
  12798. }
  12799. #else
  12800. if (setsockopt(so.sock,
  12801. SOL_SOCKET,
  12802. SO_REUSEADDR,
  12803. (SOCK_OPT_TYPE)&on,
  12804. sizeof(on))
  12805. != 0) {
  12806. /* Set reuse option, but don't abort on errors. */
  12807. mg_cry_ctx_internal(
  12808. phys_ctx,
  12809. "cannot set socket option SO_REUSEADDR (entry %i)",
  12810. portsTotal);
  12811. }
  12812. #endif
  12813. if (ip_version > 4) {
  12814. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12815. #if defined(USE_IPV6)
  12816. if (ip_version > 6) {
  12817. if (so.lsa.sa.sa_family == AF_INET6
  12818. && setsockopt(so.sock,
  12819. IPPROTO_IPV6,
  12820. IPV6_V6ONLY,
  12821. (void *)&off,
  12822. sizeof(off))
  12823. != 0) {
  12824. /* Set IPv6 only option, but don't abort on errors. */
  12825. mg_cry_ctx_internal(
  12826. phys_ctx,
  12827. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12828. portsTotal);
  12829. }
  12830. } else {
  12831. if (so.lsa.sa.sa_family == AF_INET6
  12832. && setsockopt(so.sock,
  12833. IPPROTO_IPV6,
  12834. IPV6_V6ONLY,
  12835. (void *)&on,
  12836. sizeof(on))
  12837. != 0) {
  12838. /* Set IPv6 only option, but don't abort on errors. */
  12839. mg_cry_ctx_internal(
  12840. phys_ctx,
  12841. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12842. portsTotal);
  12843. }
  12844. }
  12845. #else
  12846. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12847. closesocket(so.sock);
  12848. so.sock = INVALID_SOCKET;
  12849. continue;
  12850. #endif
  12851. }
  12852. if (so.lsa.sa.sa_family == AF_INET) {
  12853. len = sizeof(so.lsa.sin);
  12854. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12855. mg_cry_ctx_internal(phys_ctx,
  12856. "cannot bind to %.*s: %d (%s)",
  12857. (int)vec.len,
  12858. vec.ptr,
  12859. (int)ERRNO,
  12860. strerror(errno));
  12861. closesocket(so.sock);
  12862. so.sock = INVALID_SOCKET;
  12863. continue;
  12864. }
  12865. }
  12866. #if defined(USE_IPV6)
  12867. else if (so.lsa.sa.sa_family == AF_INET6) {
  12868. len = sizeof(so.lsa.sin6);
  12869. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12870. mg_cry_ctx_internal(phys_ctx,
  12871. "cannot bind to IPv6 %.*s: %d (%s)",
  12872. (int)vec.len,
  12873. vec.ptr,
  12874. (int)ERRNO,
  12875. strerror(errno));
  12876. closesocket(so.sock);
  12877. so.sock = INVALID_SOCKET;
  12878. continue;
  12879. }
  12880. }
  12881. #endif
  12882. else {
  12883. mg_cry_ctx_internal(
  12884. phys_ctx,
  12885. "cannot bind: address family not supported (entry %i)",
  12886. portsTotal);
  12887. closesocket(so.sock);
  12888. so.sock = INVALID_SOCKET;
  12889. continue;
  12890. }
  12891. opt_txt = phys_ctx->dd.config[MAX_CONNECTIONS];
  12892. opt_max_connections = strtol(opt_txt, NULL, 10);
  12893. if ((opt_max_connections > INT_MAX) || (opt_max_connections < 1)) {
  12894. mg_cry_ctx_internal(phys_ctx,
  12895. "max_connections value \"%s\" is invalid",
  12896. opt_txt);
  12897. continue;
  12898. }
  12899. if (listen(so.sock, (int)opt_max_connections) != 0) {
  12900. mg_cry_ctx_internal(phys_ctx,
  12901. "cannot listen to %.*s: %d (%s)",
  12902. (int)vec.len,
  12903. vec.ptr,
  12904. (int)ERRNO,
  12905. strerror(errno));
  12906. closesocket(so.sock);
  12907. so.sock = INVALID_SOCKET;
  12908. continue;
  12909. }
  12910. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12911. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12912. int err = (int)ERRNO;
  12913. mg_cry_ctx_internal(phys_ctx,
  12914. "call to getsockname failed %.*s: %d (%s)",
  12915. (int)vec.len,
  12916. vec.ptr,
  12917. err,
  12918. strerror(errno));
  12919. closesocket(so.sock);
  12920. so.sock = INVALID_SOCKET;
  12921. continue;
  12922. }
  12923. /* Update lsa port in case of random free ports */
  12924. #if defined(USE_IPV6)
  12925. if (so.lsa.sa.sa_family == AF_INET6) {
  12926. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12927. } else
  12928. #endif
  12929. {
  12930. so.lsa.sin.sin_port = usa.sin.sin_port;
  12931. }
  12932. if ((ptr = (struct socket *)
  12933. mg_realloc_ctx(phys_ctx->listening_sockets,
  12934. (phys_ctx->num_listening_sockets + 1)
  12935. * sizeof(phys_ctx->listening_sockets[0]),
  12936. phys_ctx))
  12937. == NULL) {
  12938. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12939. closesocket(so.sock);
  12940. so.sock = INVALID_SOCKET;
  12941. continue;
  12942. }
  12943. if ((pfd = (struct mg_pollfd *)
  12944. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12945. (phys_ctx->num_listening_sockets + 1)
  12946. * sizeof(phys_ctx->listening_socket_fds[0]),
  12947. phys_ctx))
  12948. == NULL) {
  12949. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12950. closesocket(so.sock);
  12951. so.sock = INVALID_SOCKET;
  12952. mg_free(ptr);
  12953. continue;
  12954. }
  12955. set_close_on_exec(so.sock, NULL, phys_ctx);
  12956. phys_ctx->listening_sockets = ptr;
  12957. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12958. phys_ctx->listening_socket_fds = pfd;
  12959. phys_ctx->num_listening_sockets++;
  12960. portsOk++;
  12961. }
  12962. if (portsOk != portsTotal) {
  12963. close_all_listening_sockets(phys_ctx);
  12964. portsOk = 0;
  12965. }
  12966. return portsOk;
  12967. }
  12968. static const char *
  12969. header_val(const struct mg_connection *conn, const char *header)
  12970. {
  12971. const char *header_value;
  12972. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12973. return "-";
  12974. } else {
  12975. return header_value;
  12976. }
  12977. }
  12978. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12979. static void log_access(const struct mg_connection *conn);
  12980. #include "external_log_access.inl"
  12981. #elif !defined(NO_FILESYSTEMS)
  12982. static void
  12983. log_access(const struct mg_connection *conn)
  12984. {
  12985. const struct mg_request_info *ri;
  12986. struct mg_file fi;
  12987. char date[64], src_addr[IP_ADDR_STR_LEN];
  12988. struct tm *tm;
  12989. const char *referer;
  12990. const char *user_agent;
  12991. char buf[4096];
  12992. if (!conn || !conn->dom_ctx) {
  12993. return;
  12994. }
  12995. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12996. if (mg_fopen(conn,
  12997. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12998. MG_FOPEN_MODE_APPEND,
  12999. &fi)
  13000. == 0) {
  13001. fi.access.fp = NULL;
  13002. }
  13003. } else {
  13004. fi.access.fp = NULL;
  13005. }
  13006. /* Log is written to a file and/or a callback. If both are not set,
  13007. * executing the rest of the function is pointless. */
  13008. if ((fi.access.fp == NULL)
  13009. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13010. return;
  13011. }
  13012. tm = localtime(&conn->conn_birth_time);
  13013. if (tm != NULL) {
  13014. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13015. } else {
  13016. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13017. date[sizeof(date) - 1] = '\0';
  13018. }
  13019. ri = &conn->request_info;
  13020. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13021. referer = header_val(conn, "Referer");
  13022. user_agent = header_val(conn, "User-Agent");
  13023. mg_snprintf(conn,
  13024. NULL, /* Ignore truncation in access log */
  13025. buf,
  13026. sizeof(buf),
  13027. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13028. src_addr,
  13029. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13030. date,
  13031. ri->request_method ? ri->request_method : "-",
  13032. ri->request_uri ? ri->request_uri : "-",
  13033. ri->query_string ? "?" : "",
  13034. ri->query_string ? ri->query_string : "",
  13035. ri->http_version,
  13036. conn->status_code,
  13037. conn->num_bytes_sent,
  13038. referer,
  13039. user_agent);
  13040. if (conn->phys_ctx->callbacks.log_access) {
  13041. conn->phys_ctx->callbacks.log_access(conn, buf);
  13042. }
  13043. if (fi.access.fp) {
  13044. int ok = 1;
  13045. flockfile(fi.access.fp);
  13046. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13047. ok = 0;
  13048. }
  13049. if (fflush(fi.access.fp) != 0) {
  13050. ok = 0;
  13051. }
  13052. funlockfile(fi.access.fp);
  13053. if (mg_fclose(&fi.access) != 0) {
  13054. ok = 0;
  13055. }
  13056. if (!ok) {
  13057. mg_cry_internal(conn,
  13058. "Error writing log file %s",
  13059. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13060. }
  13061. }
  13062. }
  13063. #else
  13064. #error Must either enable filesystems or provide a custom log_access implementation
  13065. #endif /* Externally provided function */
  13066. /* Verify given socket address against the ACL.
  13067. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13068. */
  13069. static int
  13070. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  13071. {
  13072. int allowed, flag;
  13073. uint32_t net, mask;
  13074. struct vec vec;
  13075. if (phys_ctx) {
  13076. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13077. /* If any ACL is set, deny by default */
  13078. allowed = (list == NULL) ? '+' : '-';
  13079. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13080. flag = vec.ptr[0];
  13081. if ((flag != '+' && flag != '-')
  13082. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  13083. mg_cry_ctx_internal(phys_ctx,
  13084. "%s: subnet must be [+|-]x.x.x.x[/x]",
  13085. __func__);
  13086. return -1;
  13087. }
  13088. if (net == (remote_ip & mask)) {
  13089. allowed = flag;
  13090. }
  13091. }
  13092. return allowed == '+';
  13093. }
  13094. return -1;
  13095. }
  13096. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13097. static int
  13098. set_uid_option(struct mg_context *phys_ctx)
  13099. {
  13100. int success = 0;
  13101. if (phys_ctx) {
  13102. /* We are currently running as curr_uid. */
  13103. const uid_t curr_uid = getuid();
  13104. /* If set, we want to run as run_as_user. */
  13105. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13106. const struct passwd *to_pw = NULL;
  13107. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13108. /* run_as_user does not exist on the system. We can't proceed
  13109. * further. */
  13110. mg_cry_ctx_internal(phys_ctx,
  13111. "%s: unknown user [%s]",
  13112. __func__,
  13113. run_as_user);
  13114. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13115. /* There was either no request to change user, or we're already
  13116. * running as run_as_user. Nothing else to do.
  13117. */
  13118. success = 1;
  13119. } else {
  13120. /* Valid change request. */
  13121. if (setgid(to_pw->pw_gid) == -1) {
  13122. mg_cry_ctx_internal(phys_ctx,
  13123. "%s: setgid(%s): %s",
  13124. __func__,
  13125. run_as_user,
  13126. strerror(errno));
  13127. } else if (setgroups(0, NULL) == -1) {
  13128. mg_cry_ctx_internal(phys_ctx,
  13129. "%s: setgroups(): %s",
  13130. __func__,
  13131. strerror(errno));
  13132. } else if (setuid(to_pw->pw_uid) == -1) {
  13133. mg_cry_ctx_internal(phys_ctx,
  13134. "%s: setuid(%s): %s",
  13135. __func__,
  13136. run_as_user,
  13137. strerror(errno));
  13138. } else {
  13139. success = 1;
  13140. }
  13141. }
  13142. }
  13143. return success;
  13144. }
  13145. #endif /* !_WIN32 */
  13146. static void
  13147. tls_dtor(void *key)
  13148. {
  13149. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13150. /* key == pthread_getspecific(sTlsKey); */
  13151. if (tls) {
  13152. if (tls->is_master == 2) {
  13153. tls->is_master = -3; /* Mark memory as dead */
  13154. mg_free(tls);
  13155. }
  13156. }
  13157. pthread_setspecific(sTlsKey, NULL);
  13158. }
  13159. #if !defined(NO_SSL)
  13160. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13161. struct mg_domain_context *dom_ctx,
  13162. const char *pem,
  13163. const char *chain);
  13164. static const char *ssl_error(void);
  13165. static int
  13166. refresh_trust(struct mg_connection *conn)
  13167. {
  13168. static int reload_lock = 0;
  13169. static long int data_check = 0;
  13170. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  13171. struct stat cert_buf;
  13172. long int t;
  13173. const char *pem;
  13174. const char *chain;
  13175. int should_verify_peer;
  13176. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13177. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13178. * refresh_trust still can not work. */
  13179. return 0;
  13180. }
  13181. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13182. if (chain == NULL) {
  13183. /* pem is not NULL here */
  13184. chain = pem;
  13185. }
  13186. if (*chain == 0) {
  13187. chain = NULL;
  13188. }
  13189. t = data_check;
  13190. if (stat(pem, &cert_buf) != -1) {
  13191. t = (long int)cert_buf.st_mtime;
  13192. }
  13193. if (data_check != t) {
  13194. data_check = t;
  13195. should_verify_peer = 0;
  13196. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13197. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13198. == 0) {
  13199. should_verify_peer = 1;
  13200. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13201. "optional")
  13202. == 0) {
  13203. should_verify_peer = 1;
  13204. }
  13205. }
  13206. if (should_verify_peer) {
  13207. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13208. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13209. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13210. ca_file,
  13211. ca_path)
  13212. != 1) {
  13213. mg_cry_ctx_internal(
  13214. conn->phys_ctx,
  13215. "SSL_CTX_load_verify_locations error: %s "
  13216. "ssl_verify_peer requires setting "
  13217. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13218. "present in "
  13219. "the .conf file?",
  13220. ssl_error());
  13221. return 0;
  13222. }
  13223. }
  13224. if (1 == mg_atomic_inc(p_reload_lock)) {
  13225. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13226. == 0) {
  13227. return 0;
  13228. }
  13229. *p_reload_lock = 0;
  13230. }
  13231. }
  13232. /* lock while cert is reloading */
  13233. while (*p_reload_lock) {
  13234. sleep(1);
  13235. }
  13236. return 1;
  13237. }
  13238. #if defined(OPENSSL_API_1_1)
  13239. #else
  13240. static pthread_mutex_t *ssl_mutexes;
  13241. #endif /* OPENSSL_API_1_1 */
  13242. static int
  13243. sslize(struct mg_connection *conn,
  13244. SSL_CTX *s,
  13245. int (*func)(SSL *),
  13246. volatile int *stop_server,
  13247. const struct mg_client_options *client_options)
  13248. {
  13249. int ret, err;
  13250. int short_trust;
  13251. unsigned timeout = 1024;
  13252. unsigned i;
  13253. if (!conn) {
  13254. return 0;
  13255. }
  13256. short_trust =
  13257. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13258. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13259. if (short_trust) {
  13260. int trust_ret = refresh_trust(conn);
  13261. if (!trust_ret) {
  13262. return trust_ret;
  13263. }
  13264. }
  13265. conn->ssl = SSL_new(s);
  13266. if (conn->ssl == NULL) {
  13267. return 0;
  13268. }
  13269. SSL_set_app_data(conn->ssl, (char *)conn);
  13270. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13271. if (ret != 1) {
  13272. err = SSL_get_error(conn->ssl, ret);
  13273. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13274. SSL_free(conn->ssl);
  13275. conn->ssl = NULL;
  13276. OPENSSL_REMOVE_THREAD_STATE();
  13277. return 0;
  13278. }
  13279. if (client_options) {
  13280. if (client_options->host_name) {
  13281. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13282. }
  13283. }
  13284. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13285. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13286. /* NOTE: The loop below acts as a back-off, so we can end
  13287. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13288. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13289. }
  13290. /* SSL functions may fail and require to be called again:
  13291. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13292. * Here "func" could be SSL_connect or SSL_accept. */
  13293. for (i = 0; i <= timeout; i += 50) {
  13294. ret = func(conn->ssl);
  13295. if (ret != 1) {
  13296. err = SSL_get_error(conn->ssl, ret);
  13297. if ((err == SSL_ERROR_WANT_CONNECT)
  13298. || (err == SSL_ERROR_WANT_ACCEPT)
  13299. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13300. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13301. if (*stop_server) {
  13302. /* Don't wait if the server is going to be stopped. */
  13303. break;
  13304. }
  13305. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13306. /* Simply retry the function call. */
  13307. mg_sleep(50);
  13308. } else {
  13309. /* Need to retry the function call "later".
  13310. * See https://linux.die.net/man/3/ssl_get_error
  13311. * This is typical for non-blocking sockets. */
  13312. struct mg_pollfd pfd;
  13313. int pollres;
  13314. pfd.fd = conn->client.sock;
  13315. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13316. || (err == SSL_ERROR_WANT_WRITE))
  13317. ? POLLOUT
  13318. : POLLIN;
  13319. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13320. if (pollres < 0) {
  13321. /* Break if error occured (-1)
  13322. * or server shutdown (-2) */
  13323. break;
  13324. }
  13325. }
  13326. } else if (err == SSL_ERROR_SYSCALL) {
  13327. /* This is an IO error. Look at errno. */
  13328. err = errno;
  13329. mg_cry_internal(conn, "SSL syscall error %i", err);
  13330. break;
  13331. } else {
  13332. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13333. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13334. break;
  13335. }
  13336. ERR_clear_error();
  13337. } else {
  13338. /* success */
  13339. break;
  13340. }
  13341. }
  13342. if (ret != 1) {
  13343. SSL_free(conn->ssl);
  13344. conn->ssl = NULL;
  13345. OPENSSL_REMOVE_THREAD_STATE();
  13346. return 0;
  13347. }
  13348. return 1;
  13349. }
  13350. /* Return OpenSSL error message (from CRYPTO lib) */
  13351. static const char *
  13352. ssl_error(void)
  13353. {
  13354. unsigned long err;
  13355. err = ERR_get_error();
  13356. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13357. }
  13358. static int
  13359. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13360. {
  13361. int i;
  13362. const char hexdigit[] = "0123456789abcdef";
  13363. if ((memlen <= 0) || (buflen <= 0)) {
  13364. return 0;
  13365. }
  13366. if (buflen < (3 * memlen)) {
  13367. return 0;
  13368. }
  13369. for (i = 0; i < memlen; i++) {
  13370. if (i > 0) {
  13371. buf[3 * i - 1] = ' ';
  13372. }
  13373. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13374. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13375. }
  13376. buf[3 * memlen - 1] = 0;
  13377. return 1;
  13378. }
  13379. static void
  13380. ssl_get_client_cert_info(struct mg_connection *conn)
  13381. {
  13382. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13383. if (cert) {
  13384. char str_subject[1024];
  13385. char str_issuer[1024];
  13386. char str_finger[1024];
  13387. unsigned char buf[256];
  13388. char *str_serial = NULL;
  13389. unsigned int ulen;
  13390. int ilen;
  13391. unsigned char *tmp_buf;
  13392. unsigned char *tmp_p;
  13393. /* Handle to algorithm used for fingerprint */
  13394. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13395. /* Get Subject and issuer */
  13396. X509_NAME *subj = X509_get_subject_name(cert);
  13397. X509_NAME *iss = X509_get_issuer_name(cert);
  13398. /* Get serial number */
  13399. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13400. /* Translate serial number to a hex string */
  13401. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13402. str_serial = BN_bn2hex(serial_bn);
  13403. BN_free(serial_bn);
  13404. /* Translate subject and issuer to a string */
  13405. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13406. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13407. /* Calculate SHA1 fingerprint and store as a hex string */
  13408. ulen = 0;
  13409. /* ASN1_digest is deprecated. Do the calculation manually,
  13410. * using EVP_Digest. */
  13411. ilen = i2d_X509(cert, NULL);
  13412. tmp_buf = (ilen > 0)
  13413. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13414. conn->phys_ctx)
  13415. : NULL;
  13416. if (tmp_buf) {
  13417. tmp_p = tmp_buf;
  13418. (void)i2d_X509(cert, &tmp_p);
  13419. if (!EVP_Digest(
  13420. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13421. ulen = 0;
  13422. }
  13423. mg_free(tmp_buf);
  13424. }
  13425. if (!hexdump2string(
  13426. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13427. *str_finger = 0;
  13428. }
  13429. conn->request_info.client_cert = (struct mg_client_cert *)
  13430. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13431. if (conn->request_info.client_cert) {
  13432. conn->request_info.client_cert->peer_cert = (void *)cert;
  13433. conn->request_info.client_cert->subject =
  13434. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13435. conn->request_info.client_cert->issuer =
  13436. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13437. conn->request_info.client_cert->serial =
  13438. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13439. conn->request_info.client_cert->finger =
  13440. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13441. } else {
  13442. mg_cry_internal(conn,
  13443. "%s",
  13444. "Out of memory: Cannot allocate memory for client "
  13445. "certificate");
  13446. }
  13447. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13448. * see https://linux.die.net/man/3/bn_bn2hex */
  13449. OPENSSL_free(str_serial);
  13450. }
  13451. }
  13452. #if defined(OPENSSL_API_1_1)
  13453. #else
  13454. static void
  13455. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13456. {
  13457. (void)line;
  13458. (void)file;
  13459. if (mode & 1) {
  13460. /* 1 is CRYPTO_LOCK */
  13461. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13462. } else {
  13463. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13464. }
  13465. }
  13466. #endif /* OPENSSL_API_1_1 */
  13467. #if !defined(NO_SSL_DL)
  13468. static void *
  13469. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13470. {
  13471. union {
  13472. void *p;
  13473. void (*fp)(void);
  13474. } u;
  13475. void *dll_handle;
  13476. struct ssl_func *fp;
  13477. int ok;
  13478. int truncated = 0;
  13479. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13480. mg_snprintf(NULL,
  13481. NULL, /* No truncation check for ebuf */
  13482. ebuf,
  13483. ebuf_len,
  13484. "%s: cannot load %s",
  13485. __func__,
  13486. dll_name);
  13487. return NULL;
  13488. }
  13489. ok = 1;
  13490. for (fp = sw; fp->name != NULL; fp++) {
  13491. #if defined(_WIN32)
  13492. /* GetProcAddress() returns pointer to function */
  13493. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13494. #else
  13495. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13496. * pointers to function pointers. We need to use a union to make a
  13497. * cast. */
  13498. u.p = dlsym(dll_handle, fp->name);
  13499. #endif /* _WIN32 */
  13500. if (u.fp == NULL) {
  13501. if (ok) {
  13502. mg_snprintf(NULL,
  13503. &truncated,
  13504. ebuf,
  13505. ebuf_len,
  13506. "%s: %s: cannot find %s",
  13507. __func__,
  13508. dll_name,
  13509. fp->name);
  13510. ok = 0;
  13511. } else {
  13512. size_t cur_len = strlen(ebuf);
  13513. if (!truncated) {
  13514. mg_snprintf(NULL,
  13515. &truncated,
  13516. ebuf + cur_len,
  13517. ebuf_len - cur_len - 3,
  13518. ", %s",
  13519. fp->name);
  13520. if (truncated) {
  13521. /* If truncated, add "..." */
  13522. strcat(ebuf, "...");
  13523. }
  13524. }
  13525. }
  13526. /* Debug:
  13527. * printf("Missing function: %s\n", fp->name); */
  13528. } else {
  13529. fp->ptr = u.fp;
  13530. }
  13531. }
  13532. if (!ok) {
  13533. (void)dlclose(dll_handle);
  13534. return NULL;
  13535. }
  13536. return dll_handle;
  13537. }
  13538. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13539. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13540. #endif /* NO_SSL_DL */
  13541. #if defined(SSL_ALREADY_INITIALIZED)
  13542. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13543. #else
  13544. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13545. #endif
  13546. static int
  13547. initialize_ssl(char *ebuf, size_t ebuf_len)
  13548. {
  13549. #if defined(OPENSSL_API_1_1)
  13550. if (ebuf_len > 0) {
  13551. ebuf[0] = 0;
  13552. }
  13553. #if !defined(NO_SSL_DL)
  13554. if (!cryptolib_dll_handle) {
  13555. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13556. if (!cryptolib_dll_handle) {
  13557. mg_snprintf(NULL,
  13558. NULL, /* No truncation check for ebuf */
  13559. ebuf,
  13560. ebuf_len,
  13561. "%s: error loading library %s",
  13562. __func__,
  13563. CRYPTO_LIB);
  13564. DEBUG_TRACE("%s", ebuf);
  13565. return 0;
  13566. }
  13567. }
  13568. #endif /* NO_SSL_DL */
  13569. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13570. return 1;
  13571. }
  13572. #else /* not OPENSSL_API_1_1 */
  13573. int i, num_locks;
  13574. size_t size;
  13575. if (ebuf_len > 0) {
  13576. ebuf[0] = 0;
  13577. }
  13578. #if !defined(NO_SSL_DL)
  13579. if (!cryptolib_dll_handle) {
  13580. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13581. if (!cryptolib_dll_handle) {
  13582. mg_snprintf(NULL,
  13583. NULL, /* No truncation check for ebuf */
  13584. ebuf,
  13585. ebuf_len,
  13586. "%s: error loading library %s",
  13587. __func__,
  13588. CRYPTO_LIB);
  13589. DEBUG_TRACE("%s", ebuf);
  13590. return 0;
  13591. }
  13592. }
  13593. #endif /* NO_SSL_DL */
  13594. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13595. return 1;
  13596. }
  13597. /* Initialize locking callbacks, needed for thread safety.
  13598. * http://www.openssl.org/support/faq.html#PROG1
  13599. */
  13600. num_locks = CRYPTO_num_locks();
  13601. if (num_locks < 0) {
  13602. num_locks = 0;
  13603. }
  13604. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13605. /* allocate mutex array, if required */
  13606. if (num_locks == 0) {
  13607. /* No mutex array required */
  13608. ssl_mutexes = NULL;
  13609. } else {
  13610. /* Mutex array required - allocate it */
  13611. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13612. /* Check OOM */
  13613. if (ssl_mutexes == NULL) {
  13614. mg_snprintf(NULL,
  13615. NULL, /* No truncation check for ebuf */
  13616. ebuf,
  13617. ebuf_len,
  13618. "%s: cannot allocate mutexes: %s",
  13619. __func__,
  13620. ssl_error());
  13621. DEBUG_TRACE("%s", ebuf);
  13622. return 0;
  13623. }
  13624. /* initialize mutex array */
  13625. for (i = 0; i < num_locks; i++) {
  13626. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13627. mg_snprintf(NULL,
  13628. NULL, /* No truncation check for ebuf */
  13629. ebuf,
  13630. ebuf_len,
  13631. "%s: error initializing mutex %i of %i",
  13632. __func__,
  13633. i,
  13634. num_locks);
  13635. DEBUG_TRACE("%s", ebuf);
  13636. mg_free(ssl_mutexes);
  13637. return 0;
  13638. }
  13639. }
  13640. }
  13641. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13642. CRYPTO_set_id_callback(&mg_current_thread_id);
  13643. #endif /* OPENSSL_API_1_1 */
  13644. #if !defined(NO_SSL_DL)
  13645. if (!ssllib_dll_handle) {
  13646. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13647. if (!ssllib_dll_handle) {
  13648. #if !defined(OPENSSL_API_1_1)
  13649. mg_free(ssl_mutexes);
  13650. #endif
  13651. DEBUG_TRACE("%s", ebuf);
  13652. return 0;
  13653. }
  13654. }
  13655. #endif /* NO_SSL_DL */
  13656. #if defined(OPENSSL_API_1_1)
  13657. /* Initialize SSL library */
  13658. OPENSSL_init_ssl(0, NULL);
  13659. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13660. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13661. NULL);
  13662. #else
  13663. /* Initialize SSL library */
  13664. SSL_library_init();
  13665. SSL_load_error_strings();
  13666. #endif
  13667. return 1;
  13668. }
  13669. static int
  13670. ssl_use_pem_file(struct mg_context *phys_ctx,
  13671. struct mg_domain_context *dom_ctx,
  13672. const char *pem,
  13673. const char *chain)
  13674. {
  13675. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13676. mg_cry_ctx_internal(phys_ctx,
  13677. "%s: cannot open certificate file %s: %s",
  13678. __func__,
  13679. pem,
  13680. ssl_error());
  13681. return 0;
  13682. }
  13683. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13684. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13685. mg_cry_ctx_internal(phys_ctx,
  13686. "%s: cannot open private key file %s: %s",
  13687. __func__,
  13688. pem,
  13689. ssl_error());
  13690. return 0;
  13691. }
  13692. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13693. mg_cry_ctx_internal(phys_ctx,
  13694. "%s: certificate and private key do not match: %s",
  13695. __func__,
  13696. pem);
  13697. return 0;
  13698. }
  13699. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13700. * chain files that contain private keys and certificates in
  13701. * SSL_CTX_use_certificate_chain_file.
  13702. * The CivetWeb-Server used pem-Files that contained both information.
  13703. * In order to make wolfSSL work, it is split in two files.
  13704. * One file that contains key and certificate used by the server and
  13705. * an optional chain file for the ssl stack.
  13706. */
  13707. if (chain) {
  13708. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13709. mg_cry_ctx_internal(phys_ctx,
  13710. "%s: cannot use certificate chain file %s: %s",
  13711. __func__,
  13712. chain,
  13713. ssl_error());
  13714. return 0;
  13715. }
  13716. }
  13717. return 1;
  13718. }
  13719. #if defined(OPENSSL_API_1_1)
  13720. static unsigned long
  13721. ssl_get_protocol(int version_id)
  13722. {
  13723. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13724. if (version_id > 0)
  13725. ret |= SSL_OP_NO_SSLv2;
  13726. if (version_id > 1)
  13727. ret |= SSL_OP_NO_SSLv3;
  13728. if (version_id > 2)
  13729. ret |= SSL_OP_NO_TLSv1;
  13730. if (version_id > 3)
  13731. ret |= SSL_OP_NO_TLSv1_1;
  13732. if (version_id > 4)
  13733. ret |= SSL_OP_NO_TLSv1_2;
  13734. #if defined(SSL_OP_NO_TLSv1_3)
  13735. if (version_id > 5)
  13736. ret |= SSL_OP_NO_TLSv1_3;
  13737. #endif
  13738. return ret;
  13739. }
  13740. #else
  13741. static long
  13742. ssl_get_protocol(int version_id)
  13743. {
  13744. long ret = (long)SSL_OP_ALL;
  13745. if (version_id > 0)
  13746. ret |= SSL_OP_NO_SSLv2;
  13747. if (version_id > 1)
  13748. ret |= SSL_OP_NO_SSLv3;
  13749. if (version_id > 2)
  13750. ret |= SSL_OP_NO_TLSv1;
  13751. if (version_id > 3)
  13752. ret |= SSL_OP_NO_TLSv1_1;
  13753. if (version_id > 4)
  13754. ret |= SSL_OP_NO_TLSv1_2;
  13755. #if defined(SSL_OP_NO_TLSv1_3)
  13756. if (version_id > 5)
  13757. ret |= SSL_OP_NO_TLSv1_3;
  13758. #endif
  13759. return ret;
  13760. }
  13761. #endif /* OPENSSL_API_1_1 */
  13762. /* SSL callback documentation:
  13763. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13764. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13765. * https://linux.die.net/man/3/ssl_set_info_callback */
  13766. /* Note: There is no "const" for the first argument in the documentation
  13767. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13768. * / OpenSSL compatibility layers have it. Having a different definition will
  13769. * cause a warning in C and an error in C++. Use "const SSL *", while
  13770. * automatical conversion from "SSL *" works for all compilers, but not other
  13771. * way around */
  13772. static void
  13773. ssl_info_callback(const SSL *ssl, int what, int ret)
  13774. {
  13775. (void)ret;
  13776. if (what & SSL_CB_HANDSHAKE_START) {
  13777. SSL_get_app_data(ssl);
  13778. }
  13779. if (what & SSL_CB_HANDSHAKE_DONE) {
  13780. /* TODO: check for openSSL 1.1 */
  13781. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13782. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13783. }
  13784. }
  13785. static int
  13786. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13787. {
  13788. struct mg_context *ctx = (struct mg_context *)arg;
  13789. struct mg_domain_context *dom =
  13790. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13791. #if defined(GCC_DIAGNOSTIC)
  13792. #pragma GCC diagnostic push
  13793. #pragma GCC diagnostic ignored "-Wcast-align"
  13794. #endif /* defined(GCC_DIAGNOSTIC) */
  13795. /* We used an aligned pointer in SSL_set_app_data */
  13796. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13797. #if defined(GCC_DIAGNOSTIC)
  13798. #pragma GCC diagnostic pop
  13799. #endif /* defined(GCC_DIAGNOSTIC) */
  13800. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13801. (void)ad;
  13802. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13803. DEBUG_TRACE("%s", "internal error - assertion failed");
  13804. return SSL_TLSEXT_ERR_NOACK;
  13805. }
  13806. /* Old clients (Win XP) will not support SNI. Then, there
  13807. * is no server name available in the request - we can
  13808. * only work with the default certificate.
  13809. * Multiple HTTPS hosts on one IP+port are only possible
  13810. * with a certificate containing all alternative names.
  13811. */
  13812. if ((servername == NULL) || (*servername == 0)) {
  13813. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13814. conn->dom_ctx = &(ctx->dd);
  13815. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13816. return SSL_TLSEXT_ERR_NOACK;
  13817. }
  13818. DEBUG_TRACE("TLS connection to host %s", servername);
  13819. while (dom) {
  13820. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13821. /* Found matching domain */
  13822. DEBUG_TRACE("TLS domain %s found",
  13823. dom->config[AUTHENTICATION_DOMAIN]);
  13824. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13825. conn->dom_ctx = dom;
  13826. return SSL_TLSEXT_ERR_OK;
  13827. }
  13828. dom = dom->next;
  13829. }
  13830. /* Default domain */
  13831. DEBUG_TRACE("TLS default domain %s used",
  13832. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13833. conn->dom_ctx = &(ctx->dd);
  13834. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13835. return SSL_TLSEXT_ERR_OK;
  13836. }
  13837. /* Setup SSL CTX as required by CivetWeb */
  13838. static int
  13839. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13840. struct mg_domain_context *dom_ctx,
  13841. const char *pem,
  13842. const char *chain)
  13843. {
  13844. int callback_ret;
  13845. int should_verify_peer;
  13846. int peer_certificate_optional;
  13847. const char *ca_path;
  13848. const char *ca_file;
  13849. int use_default_verify_paths;
  13850. int verify_depth;
  13851. struct timespec now_mt;
  13852. md5_byte_t ssl_context_id[16];
  13853. md5_state_t md5state;
  13854. int protocol_ver;
  13855. #if defined(OPENSSL_API_1_1)
  13856. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13857. mg_cry_ctx_internal(phys_ctx,
  13858. "SSL_CTX_new (server) error: %s",
  13859. ssl_error());
  13860. return 0;
  13861. }
  13862. #else
  13863. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13864. mg_cry_ctx_internal(phys_ctx,
  13865. "SSL_CTX_new (server) error: %s",
  13866. ssl_error());
  13867. return 0;
  13868. }
  13869. #endif /* OPENSSL_API_1_1 */
  13870. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13871. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13872. | SSL_OP_NO_TLSv1_1);
  13873. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13874. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13875. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13876. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13877. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13878. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13879. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13880. #if defined(SSL_OP_NO_RENEGOTIATION)
  13881. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13882. #endif
  13883. #if !defined(NO_SSL_DL)
  13884. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13885. #endif /* NO_SSL_DL */
  13886. /* In SSL documentation examples callback defined without const specifier
  13887. * 'void (*)(SSL *, int, int)' See:
  13888. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13889. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13890. * But in the source code const SSL is used:
  13891. * 'void (*)(const SSL *, int, int)' See:
  13892. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13893. * Problem about wrong documentation described, but not resolved:
  13894. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13895. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13896. * But when compiled with modern C++ compiler, correct const should be
  13897. * provided
  13898. */
  13899. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13900. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13901. ssl_servername_callback);
  13902. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13903. /* If a callback has been specified, call it. */
  13904. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13905. ? 0
  13906. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13907. phys_ctx->user_data));
  13908. /* If callback returns 0, civetweb sets up the SSL certificate.
  13909. * If it returns 1, civetweb assumes the calback already did this.
  13910. * If it returns -1, initializing ssl fails. */
  13911. if (callback_ret < 0) {
  13912. mg_cry_ctx_internal(phys_ctx,
  13913. "SSL callback returned error: %i",
  13914. callback_ret);
  13915. return 0;
  13916. }
  13917. if (callback_ret > 0) {
  13918. /* Callback did everything. */
  13919. return 1;
  13920. }
  13921. /* If a domain callback has been specified, call it. */
  13922. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  13923. ? 0
  13924. : (phys_ctx->callbacks.init_ssl_domain(
  13925. dom_ctx->config[AUTHENTICATION_DOMAIN],
  13926. dom_ctx->ssl_ctx,
  13927. phys_ctx->user_data));
  13928. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  13929. * If it returns 1, civetweb assumes the calback already did this.
  13930. * If it returns -1, initializing ssl fails. */
  13931. if (callback_ret < 0) {
  13932. mg_cry_ctx_internal(phys_ctx,
  13933. "Domain SSL callback returned error: %i",
  13934. callback_ret);
  13935. return 0;
  13936. }
  13937. if (callback_ret > 0) {
  13938. /* Domain callback did everything. */
  13939. return 1;
  13940. }
  13941. /* Use some combination of start time, domain and port as a SSL
  13942. * context ID. This should be unique on the current machine. */
  13943. md5_init(&md5state);
  13944. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13945. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13946. md5_append(&md5state,
  13947. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13948. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13949. md5_append(&md5state,
  13950. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13951. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13952. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13953. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13954. md5_finish(&md5state, ssl_context_id);
  13955. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13956. (unsigned char *)ssl_context_id,
  13957. sizeof(ssl_context_id));
  13958. if (pem != NULL) {
  13959. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13960. return 0;
  13961. }
  13962. }
  13963. /* Should we support client certificates? */
  13964. /* Default is "no". */
  13965. should_verify_peer = 0;
  13966. peer_certificate_optional = 0;
  13967. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13968. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13969. /* Yes, they are mandatory */
  13970. should_verify_peer = 1;
  13971. peer_certificate_optional = 0;
  13972. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13973. "optional")
  13974. == 0) {
  13975. /* Yes, they are optional */
  13976. should_verify_peer = 1;
  13977. peer_certificate_optional = 1;
  13978. }
  13979. }
  13980. use_default_verify_paths =
  13981. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13982. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13983. == 0);
  13984. if (should_verify_peer) {
  13985. ca_path = dom_ctx->config[SSL_CA_PATH];
  13986. ca_file = dom_ctx->config[SSL_CA_FILE];
  13987. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13988. != 1) {
  13989. mg_cry_ctx_internal(phys_ctx,
  13990. "SSL_CTX_load_verify_locations error: %s "
  13991. "ssl_verify_peer requires setting "
  13992. "either ssl_ca_path or ssl_ca_file. "
  13993. "Is any of them present in the "
  13994. ".conf file?",
  13995. ssl_error());
  13996. return 0;
  13997. }
  13998. if (peer_certificate_optional) {
  13999. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14000. } else {
  14001. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14002. SSL_VERIFY_PEER
  14003. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14004. NULL);
  14005. }
  14006. if (use_default_verify_paths
  14007. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14008. mg_cry_ctx_internal(phys_ctx,
  14009. "SSL_CTX_set_default_verify_paths error: %s",
  14010. ssl_error());
  14011. return 0;
  14012. }
  14013. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14014. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14015. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14016. }
  14017. }
  14018. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14019. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14020. dom_ctx->config[SSL_CIPHER_LIST])
  14021. != 1) {
  14022. mg_cry_ctx_internal(phys_ctx,
  14023. "SSL_CTX_set_cipher_list error: %s",
  14024. ssl_error());
  14025. }
  14026. }
  14027. return 1;
  14028. }
  14029. /* Check if SSL is required.
  14030. * If so, dynamically load SSL library
  14031. * and set up ctx->ssl_ctx pointer. */
  14032. static int
  14033. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14034. {
  14035. void *ssl_ctx = 0;
  14036. int callback_ret;
  14037. const char *pem;
  14038. const char *chain;
  14039. char ebuf[128];
  14040. if (!phys_ctx) {
  14041. return 0;
  14042. }
  14043. if (!dom_ctx) {
  14044. dom_ctx = &(phys_ctx->dd);
  14045. }
  14046. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14047. /* No SSL port is set. No need to setup SSL. */
  14048. return 1;
  14049. }
  14050. /* Check for external SSL_CTX */
  14051. callback_ret =
  14052. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14053. ? 0
  14054. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14055. phys_ctx->user_data));
  14056. if (callback_ret < 0) {
  14057. mg_cry_ctx_internal(phys_ctx,
  14058. "external_ssl_ctx callback returned error: %i",
  14059. callback_ret);
  14060. return 0;
  14061. } else if (callback_ret > 0) {
  14062. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14063. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14064. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14065. return 0;
  14066. }
  14067. return 1;
  14068. }
  14069. /* Check for external domain SSL_CTX */
  14070. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14071. ? 0
  14072. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14073. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14074. &ssl_ctx,
  14075. phys_ctx->user_data));
  14076. if (callback_ret < 0) {
  14077. mg_cry_ctx_internal(
  14078. phys_ctx,
  14079. "external_ssl_ctx_domain callback returned error: %i",
  14080. callback_ret);
  14081. return 0;
  14082. } else if (callback_ret > 0) {
  14083. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14084. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14085. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14086. return 0;
  14087. }
  14088. return 1;
  14089. }
  14090. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return 0,
  14091. * CivetWeb should continue initializing SSL */
  14092. /* If PEM file is not specified and the init_ssl callbacks
  14093. * are not specified, setup will fail. */
  14094. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14095. && (phys_ctx->callbacks.init_ssl == NULL)
  14096. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14097. /* No certificate and no init_ssl callbacks:
  14098. * Essential data to set up TLS is missing.
  14099. */
  14100. mg_cry_ctx_internal(phys_ctx,
  14101. "Initializing SSL failed: -%s is not set",
  14102. config_options[SSL_CERTIFICATE].name);
  14103. return 0;
  14104. }
  14105. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14106. if (chain == NULL) {
  14107. chain = pem;
  14108. }
  14109. if ((chain != NULL) && (*chain == 0)) {
  14110. chain = NULL;
  14111. }
  14112. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14113. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14114. return 0;
  14115. }
  14116. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14117. }
  14118. static void
  14119. uninitialize_ssl(void)
  14120. {
  14121. #if defined(OPENSSL_API_1_1)
  14122. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14123. /* Shutdown according to
  14124. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14125. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14126. */
  14127. CONF_modules_unload(1);
  14128. #else
  14129. int i;
  14130. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14131. /* Shutdown according to
  14132. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14133. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14134. */
  14135. CRYPTO_set_locking_callback(NULL);
  14136. CRYPTO_set_id_callback(NULL);
  14137. ENGINE_cleanup();
  14138. CONF_modules_unload(1);
  14139. ERR_free_strings();
  14140. EVP_cleanup();
  14141. CRYPTO_cleanup_all_ex_data();
  14142. OPENSSL_REMOVE_THREAD_STATE();
  14143. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14144. pthread_mutex_destroy(&ssl_mutexes[i]);
  14145. }
  14146. mg_free(ssl_mutexes);
  14147. ssl_mutexes = NULL;
  14148. #endif /* OPENSSL_API_1_1 */
  14149. }
  14150. }
  14151. #endif /* !NO_SSL */
  14152. #if !defined(NO_FILESYSTEMS)
  14153. static int
  14154. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14155. {
  14156. if (phys_ctx) {
  14157. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14158. const char *path;
  14159. struct mg_connection fc;
  14160. if (!dom_ctx) {
  14161. dom_ctx = &(phys_ctx->dd);
  14162. }
  14163. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14164. if ((path != NULL)
  14165. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14166. mg_cry_ctx_internal(phys_ctx,
  14167. "Cannot open %s: %s",
  14168. path,
  14169. strerror(ERRNO));
  14170. return 0;
  14171. }
  14172. return 1;
  14173. }
  14174. return 0;
  14175. }
  14176. #endif /* NO_FILESYSTEMS */
  14177. static int
  14178. set_acl_option(struct mg_context *phys_ctx)
  14179. {
  14180. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  14181. }
  14182. static void
  14183. reset_per_request_attributes(struct mg_connection *conn)
  14184. {
  14185. if (!conn) {
  14186. return;
  14187. }
  14188. conn->connection_type =
  14189. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  14190. conn->num_bytes_sent = conn->consumed_content = 0;
  14191. conn->path_info = NULL;
  14192. conn->status_code = -1;
  14193. conn->content_len = -1;
  14194. conn->is_chunked = 0;
  14195. conn->must_close = 0;
  14196. conn->request_len = 0;
  14197. conn->throttle = 0;
  14198. conn->accept_gzip = 0;
  14199. conn->response_info.content_length = conn->request_info.content_length = -1;
  14200. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14201. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14202. conn->response_info.status_text = NULL;
  14203. conn->response_info.status_code = 0;
  14204. conn->request_info.remote_user = NULL;
  14205. conn->request_info.request_method = NULL;
  14206. conn->request_info.request_uri = NULL;
  14207. conn->request_info.local_uri = NULL;
  14208. #if defined(MG_LEGACY_INTERFACE)
  14209. /* Legacy before split into local_uri and request_uri */
  14210. conn->request_info.uri = NULL;
  14211. #endif
  14212. }
  14213. static int
  14214. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14215. {
  14216. if (setsockopt(sock,
  14217. IPPROTO_TCP,
  14218. TCP_NODELAY,
  14219. (SOCK_OPT_TYPE)&nodelay_on,
  14220. sizeof(nodelay_on))
  14221. != 0) {
  14222. /* Error */
  14223. return 1;
  14224. }
  14225. /* OK */
  14226. return 0;
  14227. }
  14228. #if !defined(__ZEPHYR__)
  14229. static void
  14230. close_socket_gracefully(struct mg_connection *conn)
  14231. {
  14232. #if defined(_WIN32)
  14233. char buf[MG_BUF_LEN];
  14234. int n;
  14235. #endif
  14236. struct linger linger;
  14237. int error_code = 0;
  14238. int linger_timeout = -2;
  14239. socklen_t opt_len = sizeof(error_code);
  14240. if (!conn) {
  14241. return;
  14242. }
  14243. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14244. * "Note that enabling a nonzero timeout on a nonblocking socket
  14245. * is not recommended.", so set it to blocking now */
  14246. set_blocking_mode(conn->client.sock);
  14247. /* Send FIN to the client */
  14248. shutdown(conn->client.sock, SHUTDOWN_WR);
  14249. #if defined(_WIN32)
  14250. /* Read and discard pending incoming data. If we do not do that and
  14251. * close
  14252. * the socket, the data in the send buffer may be discarded. This
  14253. * behaviour is seen on Windows, when client keeps sending data
  14254. * when server decides to close the connection; then when client
  14255. * does recv() it gets no data back. */
  14256. do {
  14257. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14258. } while (n > 0);
  14259. #endif
  14260. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14261. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14262. }
  14263. /* Set linger option according to configuration */
  14264. if (linger_timeout >= 0) {
  14265. /* Set linger option to avoid socket hanging out after close. This
  14266. * prevent ephemeral port exhaust problem under high QPS. */
  14267. linger.l_onoff = 1;
  14268. #if defined(_MSC_VER)
  14269. #pragma warning(push)
  14270. #pragma warning(disable : 4244)
  14271. #endif
  14272. #if defined(GCC_DIAGNOSTIC)
  14273. #pragma GCC diagnostic push
  14274. #pragma GCC diagnostic ignored "-Wconversion"
  14275. #endif
  14276. /* Data type of linger structure elements may differ,
  14277. * so we don't know what cast we need here.
  14278. * Disable type conversion warnings. */
  14279. linger.l_linger = (linger_timeout + 999) / 1000;
  14280. #if defined(GCC_DIAGNOSTIC)
  14281. #pragma GCC diagnostic pop
  14282. #endif
  14283. #if defined(_MSC_VER)
  14284. #pragma warning(pop)
  14285. #endif
  14286. } else {
  14287. linger.l_onoff = 0;
  14288. linger.l_linger = 0;
  14289. }
  14290. if (linger_timeout < -1) {
  14291. /* Default: don't configure any linger */
  14292. } else if (getsockopt(conn->client.sock,
  14293. SOL_SOCKET,
  14294. SO_ERROR,
  14295. #if defined(_WIN32) /* WinSock uses different data type here */
  14296. (char *)&error_code,
  14297. #else
  14298. &error_code,
  14299. #endif
  14300. &opt_len)
  14301. != 0) {
  14302. /* Cannot determine if socket is already closed. This should
  14303. * not occur and never did in a test. Log an error message
  14304. * and continue. */
  14305. mg_cry_internal(conn,
  14306. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14307. __func__,
  14308. strerror(ERRNO));
  14309. #if defined(_WIN32)
  14310. } else if (error_code == WSAECONNRESET) {
  14311. #else
  14312. } else if (error_code == ECONNRESET) {
  14313. #endif
  14314. /* Socket already closed by client/peer, close socket without linger
  14315. */
  14316. } else {
  14317. /* Set linger timeout */
  14318. if (setsockopt(conn->client.sock,
  14319. SOL_SOCKET,
  14320. SO_LINGER,
  14321. (char *)&linger,
  14322. sizeof(linger))
  14323. != 0) {
  14324. mg_cry_internal(
  14325. conn,
  14326. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14327. __func__,
  14328. linger.l_onoff,
  14329. linger.l_linger,
  14330. strerror(ERRNO));
  14331. }
  14332. }
  14333. /* Now we know that our FIN is ACK-ed, safe to close */
  14334. closesocket(conn->client.sock);
  14335. conn->client.sock = INVALID_SOCKET;
  14336. }
  14337. #endif
  14338. static void
  14339. close_connection(struct mg_connection *conn)
  14340. {
  14341. #if defined(USE_SERVER_STATS)
  14342. conn->conn_state = 6; /* to close */
  14343. #endif
  14344. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14345. if (conn->lua_websocket_state) {
  14346. lua_websocket_close(conn, conn->lua_websocket_state);
  14347. conn->lua_websocket_state = NULL;
  14348. }
  14349. #endif
  14350. mg_lock_connection(conn);
  14351. /* Set close flag, so keep-alive loops will stop */
  14352. conn->must_close = 1;
  14353. /* call the connection_close callback if assigned */
  14354. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14355. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14356. conn->phys_ctx->callbacks.connection_close(conn);
  14357. }
  14358. }
  14359. /* Reset user data, after close callback is called.
  14360. * Do not reuse it. If the user needs a destructor,
  14361. * it must be done in the connection_close callback. */
  14362. mg_set_user_connection_data(conn, NULL);
  14363. #if defined(USE_SERVER_STATS)
  14364. conn->conn_state = 7; /* closing */
  14365. #endif
  14366. #if !defined(NO_SSL)
  14367. if (conn->ssl != NULL) {
  14368. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14369. */
  14370. SSL_shutdown(conn->ssl);
  14371. SSL_free(conn->ssl);
  14372. OPENSSL_REMOVE_THREAD_STATE();
  14373. conn->ssl = NULL;
  14374. }
  14375. #endif
  14376. if (conn->client.sock != INVALID_SOCKET) {
  14377. #if defined(__ZEPHYR__)
  14378. closesocket(conn->client.sock);
  14379. #else
  14380. close_socket_gracefully(conn);
  14381. #endif
  14382. conn->client.sock = INVALID_SOCKET;
  14383. }
  14384. if (conn->host) {
  14385. mg_free((void *)conn->host);
  14386. conn->host = NULL;
  14387. }
  14388. mg_unlock_connection(conn);
  14389. #if defined(USE_SERVER_STATS)
  14390. conn->conn_state = 8; /* closed */
  14391. #endif
  14392. }
  14393. void
  14394. mg_close_connection(struct mg_connection *conn)
  14395. {
  14396. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14397. return;
  14398. }
  14399. #if defined(USE_WEBSOCKET)
  14400. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14401. if (conn->in_websocket_handling) {
  14402. /* Set close flag, so the server thread can exit. */
  14403. conn->must_close = 1;
  14404. return;
  14405. }
  14406. }
  14407. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14408. unsigned int i;
  14409. /* client context: loops must end */
  14410. conn->phys_ctx->stop_flag = 1;
  14411. conn->must_close = 1;
  14412. /* We need to get the client thread out of the select/recv call
  14413. * here. */
  14414. /* Since we use a sleep quantum of some seconds to check for recv
  14415. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14416. /* join worker thread */
  14417. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14418. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14419. }
  14420. }
  14421. #endif /* defined(USE_WEBSOCKET) */
  14422. close_connection(conn);
  14423. #if !defined(NO_SSL)
  14424. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14425. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14426. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14427. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14428. }
  14429. #endif
  14430. #if defined(USE_WEBSOCKET)
  14431. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14432. mg_free(conn->phys_ctx->worker_threadids);
  14433. (void)pthread_mutex_destroy(&conn->mutex);
  14434. mg_free(conn);
  14435. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14436. mg_free(conn);
  14437. }
  14438. #else
  14439. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14440. mg_free(conn);
  14441. }
  14442. #endif /* defined(USE_WEBSOCKET) */
  14443. }
  14444. static struct mg_connection *
  14445. mg_connect_client_impl(const struct mg_client_options *client_options,
  14446. int use_ssl,
  14447. char *ebuf,
  14448. size_t ebuf_len)
  14449. {
  14450. struct mg_connection *conn = NULL;
  14451. SOCKET sock;
  14452. union usa sa;
  14453. struct sockaddr *psa;
  14454. socklen_t len;
  14455. unsigned max_req_size =
  14456. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14457. /* Size of structures, aligned to 8 bytes */
  14458. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14459. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14460. conn =
  14461. (struct mg_connection *)mg_calloc(1,
  14462. conn_size + ctx_size + max_req_size);
  14463. if (conn == NULL) {
  14464. mg_snprintf(NULL,
  14465. NULL, /* No truncation check for ebuf */
  14466. ebuf,
  14467. ebuf_len,
  14468. "calloc(): %s",
  14469. strerror(ERRNO));
  14470. return NULL;
  14471. }
  14472. #if defined(GCC_DIAGNOSTIC)
  14473. #pragma GCC diagnostic push
  14474. #pragma GCC diagnostic ignored "-Wcast-align"
  14475. #endif /* defined(GCC_DIAGNOSTIC) */
  14476. /* conn_size is aligned to 8 bytes */
  14477. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14478. #if defined(GCC_DIAGNOSTIC)
  14479. #pragma GCC diagnostic pop
  14480. #endif /* defined(GCC_DIAGNOSTIC) */
  14481. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14482. conn->buf_size = (int)max_req_size;
  14483. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14484. conn->dom_ctx = &(conn->phys_ctx->dd);
  14485. if (!connect_socket(conn->phys_ctx,
  14486. client_options->host,
  14487. client_options->port,
  14488. use_ssl,
  14489. ebuf,
  14490. ebuf_len,
  14491. &sock,
  14492. &sa)) {
  14493. /* ebuf is set by connect_socket,
  14494. * free all memory and return NULL; */
  14495. mg_free(conn);
  14496. return NULL;
  14497. }
  14498. #if !defined(NO_SSL)
  14499. #if defined(OPENSSL_API_1_1)
  14500. if (use_ssl
  14501. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14502. == NULL) {
  14503. mg_snprintf(NULL,
  14504. NULL, /* No truncation check for ebuf */
  14505. ebuf,
  14506. ebuf_len,
  14507. "SSL_CTX_new error: %s",
  14508. ssl_error());
  14509. closesocket(sock);
  14510. mg_free(conn);
  14511. return NULL;
  14512. }
  14513. #else
  14514. if (use_ssl
  14515. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14516. == NULL) {
  14517. mg_snprintf(NULL,
  14518. NULL, /* No truncation check for ebuf */
  14519. ebuf,
  14520. ebuf_len,
  14521. "SSL_CTX_new error: %s",
  14522. ssl_error());
  14523. closesocket(sock);
  14524. mg_free(conn);
  14525. return NULL;
  14526. }
  14527. #endif /* OPENSSL_API_1_1 */
  14528. #endif /* NO_SSL */
  14529. #if defined(USE_IPV6)
  14530. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14531. : sizeof(conn->client.rsa.sin6);
  14532. psa = (sa.sa.sa_family == AF_INET)
  14533. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14534. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14535. #else
  14536. len = sizeof(conn->client.rsa.sin);
  14537. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14538. #endif
  14539. conn->client.sock = sock;
  14540. conn->client.lsa = sa;
  14541. if (getsockname(sock, psa, &len) != 0) {
  14542. mg_cry_internal(conn,
  14543. "%s: getsockname() failed: %s",
  14544. __func__,
  14545. strerror(ERRNO));
  14546. }
  14547. conn->client.is_ssl = use_ssl ? 1 : 0;
  14548. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14549. mg_snprintf(NULL,
  14550. NULL, /* No truncation check for ebuf */
  14551. ebuf,
  14552. ebuf_len,
  14553. "Can not create mutex");
  14554. #if !defined(NO_SSL)
  14555. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14556. #endif
  14557. closesocket(sock);
  14558. mg_free(conn);
  14559. return NULL;
  14560. }
  14561. #if !defined(NO_SSL)
  14562. if (use_ssl) {
  14563. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14564. * SSL_CTX_set_verify call is needed to switch off server
  14565. * certificate checking, which is off by default in OpenSSL and
  14566. * on in yaSSL. */
  14567. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14568. * SSL_VERIFY_PEER, verify_ssl_server); */
  14569. if (client_options->client_cert) {
  14570. if (!ssl_use_pem_file(conn->phys_ctx,
  14571. conn->dom_ctx,
  14572. client_options->client_cert,
  14573. NULL)) {
  14574. mg_snprintf(NULL,
  14575. NULL, /* No truncation check for ebuf */
  14576. ebuf,
  14577. ebuf_len,
  14578. "Can not use SSL client certificate");
  14579. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14580. closesocket(sock);
  14581. mg_free(conn);
  14582. return NULL;
  14583. }
  14584. }
  14585. if (client_options->server_cert) {
  14586. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14587. client_options->server_cert,
  14588. NULL)
  14589. != 1) {
  14590. mg_cry_internal(conn,
  14591. "SSL_CTX_load_verify_locations error: %s ",
  14592. ssl_error());
  14593. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14594. closesocket(sock);
  14595. mg_free(conn);
  14596. return NULL;
  14597. }
  14598. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14599. } else {
  14600. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14601. }
  14602. if (!sslize(conn,
  14603. conn->dom_ctx->ssl_ctx,
  14604. SSL_connect,
  14605. &(conn->phys_ctx->stop_flag),
  14606. client_options)) {
  14607. mg_snprintf(NULL,
  14608. NULL, /* No truncation check for ebuf */
  14609. ebuf,
  14610. ebuf_len,
  14611. "SSL connection error");
  14612. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14613. closesocket(sock);
  14614. mg_free(conn);
  14615. return NULL;
  14616. }
  14617. }
  14618. #endif
  14619. return conn;
  14620. }
  14621. CIVETWEB_API struct mg_connection *
  14622. mg_connect_client_secure(const struct mg_client_options *client_options,
  14623. char *error_buffer,
  14624. size_t error_buffer_size)
  14625. {
  14626. return mg_connect_client_impl(client_options,
  14627. 1,
  14628. error_buffer,
  14629. error_buffer_size);
  14630. }
  14631. struct mg_connection *
  14632. mg_connect_client(const char *host,
  14633. int port,
  14634. int use_ssl,
  14635. char *error_buffer,
  14636. size_t error_buffer_size)
  14637. {
  14638. struct mg_client_options opts;
  14639. memset(&opts, 0, sizeof(opts));
  14640. opts.host = host;
  14641. opts.port = port;
  14642. return mg_connect_client_impl(&opts,
  14643. use_ssl,
  14644. error_buffer,
  14645. error_buffer_size);
  14646. }
  14647. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14648. struct mg_connection *
  14649. mg_connect_client2(const char *host,
  14650. const char *protocol,
  14651. int port,
  14652. const char *path,
  14653. struct mg_init_data *init,
  14654. struct mg_error_data *error)
  14655. {
  14656. int is_ssl, is_ws;
  14657. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14658. if (error != NULL) {
  14659. error->code = 0;
  14660. if (error->text_buffer_size > 0) {
  14661. *error->text = 0;
  14662. }
  14663. }
  14664. if ((host == NULL) || (protocol == NULL)) {
  14665. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14666. mg_snprintf(NULL,
  14667. NULL, /* No truncation check for error buffers */
  14668. error->text,
  14669. error->text_buffer_size,
  14670. "%s",
  14671. "Invalid parameters");
  14672. }
  14673. return NULL;
  14674. }
  14675. /* check all known protocolls */
  14676. if (!mg_strcasecmp(protocol, "http")) {
  14677. is_ssl = 0;
  14678. is_ws = 0;
  14679. } else if (!mg_strcasecmp(protocol, "https")) {
  14680. is_ssl = 1;
  14681. is_ws = 0;
  14682. #if defined(USE_WEBSOCKET)
  14683. } else if (!mg_strcasecmp(protocol, "ws")) {
  14684. is_ssl = 0;
  14685. is_ws = 1;
  14686. } else if (!mg_strcasecmp(protocol, "wss")) {
  14687. is_ssl = 1;
  14688. is_ws = 1;
  14689. #endif
  14690. } else {
  14691. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14692. mg_snprintf(NULL,
  14693. NULL, /* No truncation check for error buffers */
  14694. error->text,
  14695. error->text_buffer_size,
  14696. "Protocol %s not supported",
  14697. protocol);
  14698. }
  14699. return NULL;
  14700. }
  14701. /* TODO: The current implementation here just calls the old implementations,
  14702. * without using any new options. This is just a first step to test the new
  14703. * interfaces. */
  14704. #if defined(USE_WEBSOCKET)
  14705. if (is_ws) {
  14706. /* TODO: implement all options */
  14707. return mg_connect_websocket_client(host,
  14708. port,
  14709. is_ssl,
  14710. error->text,
  14711. error->text_buffer_size,
  14712. (path ? path : ""),
  14713. NULL /* TODO: origin */,
  14714. deprecated_websocket_data_wrapper,
  14715. deprecated_websocket_close_wrapper,
  14716. (void *)init->callbacks);
  14717. }
  14718. #endif
  14719. /* TODO: all additional options */
  14720. struct mg_client_options opts;
  14721. memset(&opts, 0, sizeof(opts));
  14722. opts.host = host;
  14723. opts.port = port;
  14724. return mg_connect_client_impl(&opts,
  14725. is_ssl,
  14726. error->text,
  14727. error->text_buffer_size);
  14728. }
  14729. #endif
  14730. static const struct {
  14731. const char *proto;
  14732. size_t proto_len;
  14733. unsigned default_port;
  14734. } abs_uri_protocols[] = {{"http://", 7, 80},
  14735. {"https://", 8, 443},
  14736. {"ws://", 5, 80},
  14737. {"wss://", 6, 443},
  14738. {NULL, 0, 0}};
  14739. /* Check if the uri is valid.
  14740. * return 0 for invalid uri,
  14741. * return 1 for *,
  14742. * return 2 for relative uri,
  14743. * return 3 for absolute uri without port,
  14744. * return 4 for absolute uri with port */
  14745. static int
  14746. get_uri_type(const char *uri)
  14747. {
  14748. int i;
  14749. const char *hostend, *portbegin;
  14750. char *portend;
  14751. unsigned long port;
  14752. /* According to the HTTP standard
  14753. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14754. * URI can be an asterisk (*) or should start with slash (relative uri),
  14755. * or it should start with the protocol (absolute uri). */
  14756. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14757. /* asterisk */
  14758. return 1;
  14759. }
  14760. /* Valid URIs according to RFC 3986
  14761. * (https://www.ietf.org/rfc/rfc3986.txt)
  14762. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14763. * and unreserved characters A-Z a-z 0-9 and -._~
  14764. * and % encoded symbols.
  14765. */
  14766. for (i = 0; uri[i] != 0; i++) {
  14767. if (uri[i] < 33) {
  14768. /* control characters and spaces are invalid */
  14769. return 0;
  14770. }
  14771. if (uri[i] > 126) {
  14772. /* non-ascii characters must be % encoded */
  14773. return 0;
  14774. } else {
  14775. switch (uri[i]) {
  14776. case '"': /* 34 */
  14777. case '<': /* 60 */
  14778. case '>': /* 62 */
  14779. case '\\': /* 92 */
  14780. case '^': /* 94 */
  14781. case '`': /* 96 */
  14782. case '{': /* 123 */
  14783. case '|': /* 124 */
  14784. case '}': /* 125 */
  14785. return 0;
  14786. default:
  14787. /* character is ok */
  14788. break;
  14789. }
  14790. }
  14791. }
  14792. /* A relative uri starts with a / character */
  14793. if (uri[0] == '/') {
  14794. /* relative uri */
  14795. return 2;
  14796. }
  14797. /* It could be an absolute uri: */
  14798. /* This function only checks if the uri is valid, not if it is
  14799. * addressing the current server. So civetweb can also be used
  14800. * as a proxy server. */
  14801. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14802. if (mg_strncasecmp(uri,
  14803. abs_uri_protocols[i].proto,
  14804. abs_uri_protocols[i].proto_len)
  14805. == 0) {
  14806. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14807. if (!hostend) {
  14808. return 0;
  14809. }
  14810. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14811. if (!portbegin) {
  14812. return 3;
  14813. }
  14814. port = strtoul(portbegin + 1, &portend, 10);
  14815. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14816. return 0;
  14817. }
  14818. return 4;
  14819. }
  14820. }
  14821. return 0;
  14822. }
  14823. /* Return NULL or the relative uri at the current server */
  14824. static const char *
  14825. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14826. {
  14827. const char *server_domain;
  14828. size_t server_domain_len;
  14829. size_t request_domain_len = 0;
  14830. unsigned long port = 0;
  14831. int i, auth_domain_check_enabled;
  14832. const char *hostbegin = NULL;
  14833. const char *hostend = NULL;
  14834. const char *portbegin;
  14835. char *portend;
  14836. auth_domain_check_enabled =
  14837. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14838. /* DNS is case insensitive, so use case insensitive string compare here
  14839. */
  14840. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14841. if (mg_strncasecmp(uri,
  14842. abs_uri_protocols[i].proto,
  14843. abs_uri_protocols[i].proto_len)
  14844. == 0) {
  14845. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14846. hostend = strchr(hostbegin, '/');
  14847. if (!hostend) {
  14848. return 0;
  14849. }
  14850. portbegin = strchr(hostbegin, ':');
  14851. if ((!portbegin) || (portbegin > hostend)) {
  14852. port = abs_uri_protocols[i].default_port;
  14853. request_domain_len = (size_t)(hostend - hostbegin);
  14854. } else {
  14855. port = strtoul(portbegin + 1, &portend, 10);
  14856. if ((portend != hostend) || (port <= 0)
  14857. || !is_valid_port(port)) {
  14858. return 0;
  14859. }
  14860. request_domain_len = (size_t)(portbegin - hostbegin);
  14861. }
  14862. /* protocol found, port set */
  14863. break;
  14864. }
  14865. }
  14866. if (!port) {
  14867. /* port remains 0 if the protocol is not found */
  14868. return 0;
  14869. }
  14870. /* Check if the request is directed to a different server. */
  14871. /* First check if the port is the same (IPv4 and IPv6). */
  14872. #if defined(USE_IPV6)
  14873. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14874. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14875. /* Request is directed to a different port */
  14876. return 0;
  14877. }
  14878. } else
  14879. #endif
  14880. {
  14881. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14882. /* Request is directed to a different port */
  14883. return 0;
  14884. }
  14885. }
  14886. /* Finally check if the server corresponds to the authentication
  14887. * domain of the server (the server domain).
  14888. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14889. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14890. * but do not allow substrings (like
  14891. * http://notmydomain.com/path/file.ext
  14892. * or http://mydomain.com.fake/path/file.ext).
  14893. */
  14894. if (auth_domain_check_enabled) {
  14895. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14896. server_domain_len = strlen(server_domain);
  14897. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14898. return 0;
  14899. }
  14900. if ((request_domain_len == server_domain_len)
  14901. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14902. /* Request is directed to this server - full name match. */
  14903. } else {
  14904. if (request_domain_len < (server_domain_len + 2)) {
  14905. /* Request is directed to another server: The server name
  14906. * is longer than the request name.
  14907. * Drop this case here to avoid overflows in the
  14908. * following checks. */
  14909. return 0;
  14910. }
  14911. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14912. /* Request is directed to another server: It could be a
  14913. * substring
  14914. * like notmyserver.com */
  14915. return 0;
  14916. }
  14917. if (0
  14918. != memcmp(server_domain,
  14919. hostbegin + request_domain_len - server_domain_len,
  14920. server_domain_len)) {
  14921. /* Request is directed to another server:
  14922. * The server name is different. */
  14923. return 0;
  14924. }
  14925. }
  14926. }
  14927. return hostend;
  14928. }
  14929. static int
  14930. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14931. {
  14932. if (ebuf_len > 0) {
  14933. ebuf[0] = '\0';
  14934. }
  14935. *err = 0;
  14936. reset_per_request_attributes(conn);
  14937. if (!conn) {
  14938. mg_snprintf(conn,
  14939. NULL, /* No truncation check for ebuf */
  14940. ebuf,
  14941. ebuf_len,
  14942. "%s",
  14943. "Internal error");
  14944. *err = 500;
  14945. return 0;
  14946. }
  14947. /* Set the time the request was received. This value should be used for
  14948. * timeouts. */
  14949. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14950. conn->request_len =
  14951. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14952. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14953. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14954. mg_snprintf(conn,
  14955. NULL, /* No truncation check for ebuf */
  14956. ebuf,
  14957. ebuf_len,
  14958. "%s",
  14959. "Invalid message size");
  14960. *err = 500;
  14961. return 0;
  14962. }
  14963. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14964. mg_snprintf(conn,
  14965. NULL, /* No truncation check for ebuf */
  14966. ebuf,
  14967. ebuf_len,
  14968. "%s",
  14969. "Message too large");
  14970. *err = 413;
  14971. return 0;
  14972. }
  14973. if (conn->request_len <= 0) {
  14974. if (conn->data_len > 0) {
  14975. mg_snprintf(conn,
  14976. NULL, /* No truncation check for ebuf */
  14977. ebuf,
  14978. ebuf_len,
  14979. "%s",
  14980. "Malformed message");
  14981. *err = 400;
  14982. } else {
  14983. /* Server did not recv anything -> just close the connection */
  14984. conn->must_close = 1;
  14985. mg_snprintf(conn,
  14986. NULL, /* No truncation check for ebuf */
  14987. ebuf,
  14988. ebuf_len,
  14989. "%s",
  14990. "No data received");
  14991. *err = 0;
  14992. }
  14993. return 0;
  14994. }
  14995. return 1;
  14996. }
  14997. static int
  14998. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14999. {
  15000. const char *cl;
  15001. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15002. return 0;
  15003. }
  15004. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15005. <= 0) {
  15006. mg_snprintf(conn,
  15007. NULL, /* No truncation check for ebuf */
  15008. ebuf,
  15009. ebuf_len,
  15010. "%s",
  15011. "Bad request");
  15012. *err = 400;
  15013. return 0;
  15014. }
  15015. /* Message is a valid request */
  15016. /* Is there a "host" ? */
  15017. if (conn->host != NULL) {
  15018. mg_free((void *)conn->host);
  15019. }
  15020. conn->host = alloc_get_host(conn);
  15021. if (!conn->host) {
  15022. mg_snprintf(conn,
  15023. NULL, /* No truncation check for ebuf */
  15024. ebuf,
  15025. ebuf_len,
  15026. "%s",
  15027. "Bad request: Host mismatch");
  15028. *err = 400;
  15029. return 0;
  15030. }
  15031. if (((cl = get_header(conn->request_info.http_headers,
  15032. conn->request_info.num_headers,
  15033. "Transfer-Encoding"))
  15034. != NULL)
  15035. && mg_strcasecmp(cl, "identity")) {
  15036. if (mg_strcasecmp(cl, "chunked")) {
  15037. mg_snprintf(conn,
  15038. NULL, /* No truncation check for ebuf */
  15039. ebuf,
  15040. ebuf_len,
  15041. "%s",
  15042. "Bad request");
  15043. *err = 400;
  15044. return 0;
  15045. }
  15046. conn->is_chunked = 1;
  15047. conn->content_len = 0; /* not yet read */
  15048. } else if ((cl = get_header(conn->request_info.http_headers,
  15049. conn->request_info.num_headers,
  15050. "Content-Length"))
  15051. != NULL) {
  15052. /* Request has content length set */
  15053. char *endptr = NULL;
  15054. conn->content_len = strtoll(cl, &endptr, 10);
  15055. if ((endptr == cl) || (conn->content_len < 0)) {
  15056. mg_snprintf(conn,
  15057. NULL, /* No truncation check for ebuf */
  15058. ebuf,
  15059. ebuf_len,
  15060. "%s",
  15061. "Bad request");
  15062. *err = 411;
  15063. return 0;
  15064. }
  15065. /* Publish the content length back to the request info. */
  15066. conn->request_info.content_length = conn->content_len;
  15067. } else {
  15068. /* There is no exception, see RFC7230. */
  15069. conn->content_len = 0;
  15070. }
  15071. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  15072. return 1;
  15073. }
  15074. /* conn is assumed to be valid in this internal function */
  15075. static int
  15076. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15077. {
  15078. const char *cl;
  15079. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15080. return 0;
  15081. }
  15082. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15083. <= 0) {
  15084. mg_snprintf(conn,
  15085. NULL, /* No truncation check for ebuf */
  15086. ebuf,
  15087. ebuf_len,
  15088. "%s",
  15089. "Bad response");
  15090. *err = 400;
  15091. return 0;
  15092. }
  15093. /* Message is a valid response */
  15094. if (((cl = get_header(conn->response_info.http_headers,
  15095. conn->response_info.num_headers,
  15096. "Transfer-Encoding"))
  15097. != NULL)
  15098. && mg_strcasecmp(cl, "identity")) {
  15099. if (mg_strcasecmp(cl, "chunked")) {
  15100. mg_snprintf(conn,
  15101. NULL, /* No truncation check for ebuf */
  15102. ebuf,
  15103. ebuf_len,
  15104. "%s",
  15105. "Bad request");
  15106. *err = 400;
  15107. return 0;
  15108. }
  15109. conn->is_chunked = 1;
  15110. conn->content_len = 0; /* not yet read */
  15111. } else if ((cl = get_header(conn->response_info.http_headers,
  15112. conn->response_info.num_headers,
  15113. "Content-Length"))
  15114. != NULL) {
  15115. char *endptr = NULL;
  15116. conn->content_len = strtoll(cl, &endptr, 10);
  15117. if ((endptr == cl) || (conn->content_len < 0)) {
  15118. mg_snprintf(conn,
  15119. NULL, /* No truncation check for ebuf */
  15120. ebuf,
  15121. ebuf_len,
  15122. "%s",
  15123. "Bad request");
  15124. *err = 411;
  15125. return 0;
  15126. }
  15127. /* Publish the content length back to the response info. */
  15128. conn->response_info.content_length = conn->content_len;
  15129. /* TODO: check if it is still used in response_info */
  15130. conn->request_info.content_length = conn->content_len;
  15131. /* TODO: we should also consider HEAD method */
  15132. if (conn->response_info.status_code == 304) {
  15133. conn->content_len = 0;
  15134. }
  15135. } else {
  15136. /* TODO: we should also consider HEAD method */
  15137. if (((conn->response_info.status_code >= 100)
  15138. && (conn->response_info.status_code <= 199))
  15139. || (conn->response_info.status_code == 204)
  15140. || (conn->response_info.status_code == 304)) {
  15141. conn->content_len = 0;
  15142. } else {
  15143. conn->content_len = -1; /* unknown content length */
  15144. }
  15145. }
  15146. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  15147. return 1;
  15148. }
  15149. int
  15150. mg_get_response(struct mg_connection *conn,
  15151. char *ebuf,
  15152. size_t ebuf_len,
  15153. int timeout)
  15154. {
  15155. int err, ret;
  15156. char txt[32]; /* will not overflow */
  15157. char *save_timeout;
  15158. char *new_timeout;
  15159. if (ebuf_len > 0) {
  15160. ebuf[0] = '\0';
  15161. }
  15162. if (!conn) {
  15163. mg_snprintf(conn,
  15164. NULL, /* No truncation check for ebuf */
  15165. ebuf,
  15166. ebuf_len,
  15167. "%s",
  15168. "Parameter error");
  15169. return -1;
  15170. }
  15171. /* Reset the previous responses */
  15172. conn->data_len = 0;
  15173. /* Implementation of API function for HTTP clients */
  15174. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15175. if (timeout >= 0) {
  15176. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15177. new_timeout = txt;
  15178. } else {
  15179. new_timeout = NULL;
  15180. }
  15181. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15182. ret = get_response(conn, ebuf, ebuf_len, &err);
  15183. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15184. #if defined(MG_LEGACY_INTERFACE)
  15185. /* TODO: 1) uri is deprecated;
  15186. * 2) here, ri.uri is the http response code */
  15187. conn->request_info.uri = conn->request_info.request_uri;
  15188. #endif
  15189. conn->request_info.local_uri = conn->request_info.request_uri;
  15190. /* TODO (mid): Define proper return values - maybe return length?
  15191. * For the first test use <0 for error and >0 for OK */
  15192. return (ret == 0) ? -1 : +1;
  15193. }
  15194. struct mg_connection *
  15195. mg_download(const char *host,
  15196. int port,
  15197. int use_ssl,
  15198. char *ebuf,
  15199. size_t ebuf_len,
  15200. const char *fmt,
  15201. ...)
  15202. {
  15203. struct mg_connection *conn;
  15204. va_list ap;
  15205. int i;
  15206. int reqerr;
  15207. if (ebuf_len > 0) {
  15208. ebuf[0] = '\0';
  15209. }
  15210. va_start(ap, fmt);
  15211. /* open a connection */
  15212. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15213. if (conn != NULL) {
  15214. i = mg_vprintf(conn, fmt, ap);
  15215. if (i <= 0) {
  15216. mg_snprintf(conn,
  15217. NULL, /* No truncation check for ebuf */
  15218. ebuf,
  15219. ebuf_len,
  15220. "%s",
  15221. "Error sending request");
  15222. } else {
  15223. /* make sure the buffer is clear */
  15224. conn->data_len = 0;
  15225. get_response(conn, ebuf, ebuf_len, &reqerr);
  15226. #if defined(MG_LEGACY_INTERFACE)
  15227. /* TODO: 1) uri is deprecated;
  15228. * 2) here, ri.uri is the http response code */
  15229. conn->request_info.uri = conn->request_info.request_uri;
  15230. #endif
  15231. conn->request_info.local_uri = conn->request_info.request_uri;
  15232. }
  15233. }
  15234. /* if an error occurred, close the connection */
  15235. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15236. mg_close_connection(conn);
  15237. conn = NULL;
  15238. }
  15239. va_end(ap);
  15240. return conn;
  15241. }
  15242. struct websocket_client_thread_data {
  15243. struct mg_connection *conn;
  15244. mg_websocket_data_handler data_handler;
  15245. mg_websocket_close_handler close_handler;
  15246. void *callback_data;
  15247. };
  15248. #if defined(USE_WEBSOCKET)
  15249. #if defined(_WIN32)
  15250. static unsigned __stdcall websocket_client_thread(void *data)
  15251. #else
  15252. static void *
  15253. websocket_client_thread(void *data)
  15254. #endif
  15255. {
  15256. struct websocket_client_thread_data *cdata =
  15257. (struct websocket_client_thread_data *)data;
  15258. void *user_thread_ptr = NULL;
  15259. #if !defined(_WIN32)
  15260. struct sigaction sa;
  15261. /* Ignore SIGPIPE */
  15262. memset(&sa, 0, sizeof(sa));
  15263. sa.sa_handler = SIG_IGN;
  15264. sigaction(SIGPIPE, &sa, NULL);
  15265. #endif
  15266. mg_set_thread_name("ws-clnt");
  15267. if (cdata->conn->phys_ctx) {
  15268. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15269. /* 3 indicates a websocket client thread */
  15270. /* TODO: check if conn->phys_ctx can be set */
  15271. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15272. cdata->conn->phys_ctx, 3);
  15273. }
  15274. }
  15275. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15276. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15277. if (cdata->close_handler != NULL) {
  15278. cdata->close_handler(cdata->conn, cdata->callback_data);
  15279. }
  15280. /* The websocket_client context has only this thread. If it runs out,
  15281. set the stop_flag to 2 (= "stopped"). */
  15282. cdata->conn->phys_ctx->stop_flag = 2;
  15283. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15284. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15285. 3,
  15286. user_thread_ptr);
  15287. }
  15288. mg_free((void *)cdata);
  15289. #if defined(_WIN32)
  15290. return 0;
  15291. #else
  15292. return NULL;
  15293. #endif
  15294. }
  15295. #endif
  15296. struct mg_connection *
  15297. mg_connect_websocket_client(const char *host,
  15298. int port,
  15299. int use_ssl,
  15300. char *error_buffer,
  15301. size_t error_buffer_size,
  15302. const char *path,
  15303. const char *origin,
  15304. mg_websocket_data_handler data_func,
  15305. mg_websocket_close_handler close_func,
  15306. void *user_data)
  15307. {
  15308. struct mg_connection *conn = NULL;
  15309. #if defined(USE_WEBSOCKET)
  15310. struct websocket_client_thread_data *thread_data;
  15311. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15312. static const char *handshake_req;
  15313. if (origin != NULL) {
  15314. handshake_req = "GET %s HTTP/1.1\r\n"
  15315. "Host: %s\r\n"
  15316. "Upgrade: websocket\r\n"
  15317. "Connection: Upgrade\r\n"
  15318. "Sec-WebSocket-Key: %s\r\n"
  15319. "Sec-WebSocket-Version: 13\r\n"
  15320. "Origin: %s\r\n"
  15321. "\r\n";
  15322. } else {
  15323. handshake_req = "GET %s HTTP/1.1\r\n"
  15324. "Host: %s\r\n"
  15325. "Upgrade: websocket\r\n"
  15326. "Connection: Upgrade\r\n"
  15327. "Sec-WebSocket-Key: %s\r\n"
  15328. "Sec-WebSocket-Version: 13\r\n"
  15329. "\r\n";
  15330. }
  15331. #if defined(__clang__)
  15332. #pragma clang diagnostic push
  15333. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15334. #endif
  15335. /* Establish the client connection and request upgrade */
  15336. conn = mg_download(host,
  15337. port,
  15338. use_ssl,
  15339. error_buffer,
  15340. error_buffer_size,
  15341. handshake_req,
  15342. path,
  15343. host,
  15344. magic,
  15345. origin);
  15346. #if defined(__clang__)
  15347. #pragma clang diagnostic pop
  15348. #endif
  15349. /* Connection object will be null if something goes wrong */
  15350. if (conn == NULL) {
  15351. if (!*error_buffer) {
  15352. /* There should be already an error message */
  15353. mg_snprintf(conn,
  15354. NULL, /* No truncation check for ebuf */
  15355. error_buffer,
  15356. error_buffer_size,
  15357. "Unexpected error");
  15358. }
  15359. return NULL;
  15360. }
  15361. if (conn->response_info.status_code != 101) {
  15362. /* We sent an "upgrade" request. For a correct websocket
  15363. * protocol handshake, we expect a "101 Continue" response.
  15364. * Otherwise it is a protocol violation. Maybe the HTTP
  15365. * Server does not know websockets. */
  15366. if (!*error_buffer) {
  15367. /* set an error, if not yet set */
  15368. mg_snprintf(conn,
  15369. NULL, /* No truncation check for ebuf */
  15370. error_buffer,
  15371. error_buffer_size,
  15372. "Unexpected server reply");
  15373. }
  15374. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15375. mg_close_connection(conn);
  15376. return NULL;
  15377. }
  15378. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15379. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15380. if (!thread_data) {
  15381. DEBUG_TRACE("%s\r\n", "Out of memory");
  15382. mg_close_connection(conn);
  15383. return NULL;
  15384. }
  15385. thread_data->conn = conn;
  15386. thread_data->data_handler = data_func;
  15387. thread_data->close_handler = close_func;
  15388. thread_data->callback_data = user_data;
  15389. conn->phys_ctx->worker_threadids =
  15390. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15391. if (!conn->phys_ctx->worker_threadids) {
  15392. DEBUG_TRACE("%s\r\n", "Out of memory");
  15393. mg_free(thread_data);
  15394. mg_close_connection(conn);
  15395. return NULL;
  15396. }
  15397. /* Now upgrade to ws/wss client context */
  15398. conn->phys_ctx->user_data = user_data;
  15399. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15400. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15401. /* Start a thread to read the websocket client connection
  15402. * This thread will automatically stop when mg_disconnect is
  15403. * called on the client connection */
  15404. if (mg_start_thread_with_id(websocket_client_thread,
  15405. thread_data,
  15406. conn->phys_ctx->worker_threadids)
  15407. != 0) {
  15408. conn->phys_ctx->cfg_worker_threads = 0;
  15409. mg_free(thread_data);
  15410. mg_close_connection(conn);
  15411. conn = NULL;
  15412. DEBUG_TRACE("%s",
  15413. "Websocket client connect thread could not be started\r\n");
  15414. }
  15415. #else
  15416. /* Appease "unused parameter" warnings */
  15417. (void)host;
  15418. (void)port;
  15419. (void)use_ssl;
  15420. (void)error_buffer;
  15421. (void)error_buffer_size;
  15422. (void)path;
  15423. (void)origin;
  15424. (void)user_data;
  15425. (void)data_func;
  15426. (void)close_func;
  15427. #endif
  15428. return conn;
  15429. }
  15430. /* Prepare connection data structure */
  15431. static void
  15432. init_connection(struct mg_connection *conn)
  15433. {
  15434. /* Is keep alive allowed by the server */
  15435. int keep_alive_enabled =
  15436. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15437. if (!keep_alive_enabled) {
  15438. conn->must_close = 1;
  15439. }
  15440. /* Important: on new connection, reset the receiving buffer. Credit
  15441. * goes to crule42. */
  15442. conn->data_len = 0;
  15443. conn->handled_requests = 0;
  15444. mg_set_user_connection_data(conn, NULL);
  15445. #if defined(USE_SERVER_STATS)
  15446. conn->conn_state = 2; /* init */
  15447. #endif
  15448. /* call the init_connection callback if assigned */
  15449. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15450. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15451. void *conn_data = NULL;
  15452. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15453. mg_set_user_connection_data(conn, conn_data);
  15454. }
  15455. }
  15456. }
  15457. /* Process a connection - may handle multiple requests
  15458. * using the same connection.
  15459. * Must be called with a valid connection (conn and
  15460. * conn->phys_ctx must be valid).
  15461. */
  15462. static void
  15463. process_new_connection(struct mg_connection *conn)
  15464. {
  15465. struct mg_request_info *ri = &conn->request_info;
  15466. int keep_alive, discard_len;
  15467. char ebuf[100];
  15468. const char *hostend;
  15469. int reqerr, uri_type;
  15470. #if defined(USE_SERVER_STATS)
  15471. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15472. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15473. if (mcon > (conn->phys_ctx->max_active_connections)) {
  15474. /* could use atomic compare exchange, but this
  15475. * seems overkill for statistics data */
  15476. conn->phys_ctx->max_active_connections = mcon;
  15477. }
  15478. #endif
  15479. init_connection(conn);
  15480. DEBUG_TRACE("Start processing connection from %s",
  15481. conn->request_info.remote_addr);
  15482. /* Loop over multiple requests sent using the same connection
  15483. * (while "keep alive"). */
  15484. do {
  15485. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15486. conn->handled_requests + 1);
  15487. #if defined(USE_SERVER_STATS)
  15488. conn->conn_state = 3; /* ready */
  15489. #endif
  15490. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15491. /* The request sent by the client could not be understood by
  15492. * the server, or it was incomplete or a timeout. Send an
  15493. * error message and close the connection. */
  15494. if (reqerr > 0) {
  15495. DEBUG_ASSERT(ebuf[0] != '\0');
  15496. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15497. }
  15498. } else if (strcmp(ri->http_version, "1.0")
  15499. && strcmp(ri->http_version, "1.1")) {
  15500. mg_snprintf(conn,
  15501. NULL, /* No truncation check for ebuf */
  15502. ebuf,
  15503. sizeof(ebuf),
  15504. "Bad HTTP version: [%s]",
  15505. ri->http_version);
  15506. mg_send_http_error(conn, 505, "%s", ebuf);
  15507. }
  15508. if (ebuf[0] == '\0') {
  15509. uri_type = get_uri_type(conn->request_info.request_uri);
  15510. switch (uri_type) {
  15511. case 1:
  15512. /* Asterisk */
  15513. conn->request_info.local_uri = NULL;
  15514. break;
  15515. case 2:
  15516. /* relative uri */
  15517. conn->request_info.local_uri = conn->request_info.request_uri;
  15518. break;
  15519. case 3:
  15520. case 4:
  15521. /* absolute uri (with/without port) */
  15522. hostend = get_rel_url_at_current_server(
  15523. conn->request_info.request_uri, conn);
  15524. if (hostend) {
  15525. conn->request_info.local_uri = hostend;
  15526. } else {
  15527. conn->request_info.local_uri = NULL;
  15528. }
  15529. break;
  15530. default:
  15531. mg_snprintf(conn,
  15532. NULL, /* No truncation check for ebuf */
  15533. ebuf,
  15534. sizeof(ebuf),
  15535. "Invalid URI");
  15536. mg_send_http_error(conn, 400, "%s", ebuf);
  15537. conn->request_info.local_uri = NULL;
  15538. break;
  15539. }
  15540. #if defined(MG_LEGACY_INTERFACE)
  15541. /* Legacy before split into local_uri and request_uri */
  15542. conn->request_info.uri = conn->request_info.local_uri;
  15543. #endif
  15544. }
  15545. DEBUG_TRACE("http: %s, error: %s",
  15546. (ri->http_version ? ri->http_version : "none"),
  15547. (ebuf[0] ? ebuf : "none"));
  15548. if (ebuf[0] == '\0') {
  15549. if (conn->request_info.local_uri) {
  15550. /* handle request to local server */
  15551. #if defined(USE_SERVER_STATS)
  15552. conn->conn_state = 4; /* processing */
  15553. #endif
  15554. handle_request(conn);
  15555. #if defined(USE_SERVER_STATS)
  15556. conn->conn_state = 5; /* processed */
  15557. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15558. conn->consumed_content);
  15559. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15560. conn->num_bytes_sent);
  15561. #endif
  15562. DEBUG_TRACE("%s", "handle_request done");
  15563. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15564. conn->phys_ctx->callbacks.end_request(conn,
  15565. conn->status_code);
  15566. DEBUG_TRACE("%s", "end_request callback done");
  15567. }
  15568. log_access(conn);
  15569. } else {
  15570. /* TODO: handle non-local request (PROXY) */
  15571. conn->must_close = 1;
  15572. }
  15573. } else {
  15574. conn->must_close = 1;
  15575. }
  15576. if (ri->remote_user != NULL) {
  15577. mg_free((void *)ri->remote_user);
  15578. /* Important! When having connections with and without auth
  15579. * would cause double free and then crash */
  15580. ri->remote_user = NULL;
  15581. }
  15582. /* NOTE(lsm): order is important here. should_keep_alive() call
  15583. * is using parsed request, which will be invalid after
  15584. * memmove's below.
  15585. * Therefore, memorize should_keep_alive() result now for later
  15586. * use in loop exit condition. */
  15587. /* Enable it only if this request is completely discardable. */
  15588. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15589. && (conn->content_len >= 0) && (conn->request_len > 0)
  15590. && ((conn->is_chunked == 4)
  15591. || (!conn->is_chunked
  15592. && ((conn->consumed_content == conn->content_len)
  15593. || ((conn->request_len + conn->content_len)
  15594. <= conn->data_len))));
  15595. if (keep_alive) {
  15596. /* Discard all buffered data for this request */
  15597. discard_len =
  15598. ((conn->request_len + conn->content_len) < conn->data_len)
  15599. ? (int)(conn->request_len + conn->content_len)
  15600. : conn->data_len;
  15601. conn->data_len -= discard_len;
  15602. if (conn->data_len > 0) {
  15603. DEBUG_TRACE("discard_len = %d", discard_len);
  15604. memmove(conn->buf,
  15605. conn->buf + discard_len,
  15606. (size_t)conn->data_len);
  15607. }
  15608. }
  15609. DEBUG_ASSERT(conn->data_len >= 0);
  15610. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15611. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15612. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15613. (long int)conn->data_len,
  15614. (long int)conn->buf_size);
  15615. break;
  15616. }
  15617. conn->handled_requests++;
  15618. } while (keep_alive);
  15619. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15620. conn->request_info.remote_addr,
  15621. difftime(time(NULL), conn->conn_birth_time));
  15622. close_connection(conn);
  15623. #if defined(USE_SERVER_STATS)
  15624. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15625. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15626. #endif
  15627. }
  15628. #if defined(ALTERNATIVE_QUEUE)
  15629. static void
  15630. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15631. {
  15632. unsigned int i;
  15633. while (!ctx->stop_flag) {
  15634. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15635. /* find a free worker slot and signal it */
  15636. if (ctx->client_socks[i].in_use == 2) {
  15637. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15638. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15639. ctx->client_socks[i] = *sp;
  15640. ctx->client_socks[i].in_use = 1;
  15641. /* socket has been moved to the consumer */
  15642. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15643. (void)event_signal(ctx->client_wait_events[i]);
  15644. return;
  15645. }
  15646. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15647. }
  15648. }
  15649. /* queue is full */
  15650. mg_sleep(1);
  15651. }
  15652. /* must consume */
  15653. set_blocking_mode(sp->sock);
  15654. closesocket(sp->sock);
  15655. }
  15656. static int
  15657. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15658. {
  15659. DEBUG_TRACE("%s", "going idle");
  15660. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15661. ctx->client_socks[thread_index].in_use = 2;
  15662. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15663. event_wait(ctx->client_wait_events[thread_index]);
  15664. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15665. *sp = ctx->client_socks[thread_index];
  15666. if (ctx->stop_flag) {
  15667. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15668. if (sp->in_use == 1) {
  15669. /* must consume */
  15670. set_blocking_mode(sp->sock);
  15671. closesocket(sp->sock);
  15672. }
  15673. return 0;
  15674. }
  15675. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15676. if (sp->in_use == 1) {
  15677. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15678. return 1;
  15679. }
  15680. /* must not reach here */
  15681. DEBUG_ASSERT(0);
  15682. return 0;
  15683. }
  15684. #else /* ALTERNATIVE_QUEUE */
  15685. /* Worker threads take accepted socket from the queue */
  15686. static int
  15687. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15688. {
  15689. (void)thread_index;
  15690. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15691. DEBUG_TRACE("%s", "going idle");
  15692. /* If the queue is empty, wait. We're idle at this point. */
  15693. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15694. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15695. }
  15696. /* If we're stopping, sq_head may be equal to sq_tail. */
  15697. if (ctx->sq_head > ctx->sq_tail) {
  15698. /* Copy socket from the queue and increment tail */
  15699. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  15700. ctx->sq_tail++;
  15701. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15702. /* Wrap pointers if needed */
  15703. while (ctx->sq_tail > ctx->sq_size) {
  15704. ctx->sq_tail -= ctx->sq_size;
  15705. ctx->sq_head -= ctx->sq_size;
  15706. }
  15707. }
  15708. (void)pthread_cond_signal(&ctx->sq_empty);
  15709. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15710. return !ctx->stop_flag;
  15711. }
  15712. /* Master thread adds accepted socket to a queue */
  15713. static void
  15714. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15715. {
  15716. int queue_filled;
  15717. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15718. queue_filled = ctx->sq_head - ctx->sq_tail;
  15719. /* If the queue is full, wait */
  15720. while ((ctx->stop_flag == 0) && (queue_filled >= ctx->sq_size)) {
  15721. ctx->sq_blocked = 1; /* Status information: All threads bussy */
  15722. #if defined(USE_SERVER_STATS)
  15723. if (queue_filled > ctx->sq_max_fill) {
  15724. ctx->sq_max_fill = queue_filled;
  15725. }
  15726. #endif
  15727. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15728. ctx->sq_blocked = 0; /* Not blocked now */
  15729. queue_filled = ctx->sq_head - ctx->sq_tail;
  15730. }
  15731. if (queue_filled < ctx->sq_size) {
  15732. /* Copy socket to the queue and increment head */
  15733. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  15734. ctx->sq_head++;
  15735. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15736. }
  15737. queue_filled = ctx->sq_head - ctx->sq_tail;
  15738. #if defined(USE_SERVER_STATS)
  15739. if (queue_filled > ctx->sq_max_fill) {
  15740. ctx->sq_max_fill = queue_filled;
  15741. }
  15742. #endif
  15743. (void)pthread_cond_signal(&ctx->sq_full);
  15744. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15745. }
  15746. #endif /* ALTERNATIVE_QUEUE */
  15747. static void
  15748. worker_thread_run(struct mg_connection *conn)
  15749. {
  15750. struct mg_context *ctx = conn->phys_ctx;
  15751. int thread_index;
  15752. struct mg_workerTLS tls;
  15753. #if defined(MG_LEGACY_INTERFACE)
  15754. uint32_t addr;
  15755. #endif
  15756. mg_set_thread_name("worker");
  15757. tls.is_master = 0;
  15758. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15759. #if defined(_WIN32)
  15760. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15761. #endif
  15762. /* Initialize thread local storage before calling any callback */
  15763. pthread_setspecific(sTlsKey, &tls);
  15764. /* Check if there is a user callback */
  15765. if (ctx->callbacks.init_thread) {
  15766. /* call init_thread for a worker thread (type 1), and store the return
  15767. * value */
  15768. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15769. } else {
  15770. /* No callback: set user pointer to NULL */
  15771. tls.user_ptr = NULL;
  15772. }
  15773. /* Connection structure has been pre-allocated */
  15774. thread_index = (int)(conn - ctx->worker_connections);
  15775. if ((thread_index < 0)
  15776. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15777. mg_cry_ctx_internal(ctx,
  15778. "Internal error: Invalid worker index %i",
  15779. thread_index);
  15780. return;
  15781. }
  15782. /* Request buffers are not pre-allocated. They are private to the
  15783. * request and do not contain any state information that might be
  15784. * of interest to anyone observing a server status. */
  15785. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15786. if (conn->buf == NULL) {
  15787. mg_cry_ctx_internal(
  15788. ctx,
  15789. "Out of memory: Cannot allocate buffer for worker %i",
  15790. thread_index);
  15791. return;
  15792. }
  15793. conn->buf_size = (int)ctx->max_request_size;
  15794. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15795. conn->host = NULL; /* until we have more information. */
  15796. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15797. conn->request_info.user_data = ctx->user_data;
  15798. /* Allocate a mutex for this connection to allow communication both
  15799. * within the request handler and from elsewhere in the application
  15800. */
  15801. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15802. mg_free(conn->buf);
  15803. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15804. return;
  15805. }
  15806. #if defined(USE_SERVER_STATS)
  15807. conn->conn_state = 1; /* not consumed */
  15808. #endif
  15809. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15810. * signal sq_empty condvar to wake up the master waiting in
  15811. * produce_socket() */
  15812. while (consume_socket(ctx, &conn->client, thread_index)) {
  15813. #if defined(USE_SERVER_STATS)
  15814. conn->conn_close_time = 0;
  15815. #endif
  15816. conn->conn_birth_time = time(NULL);
  15817. /* Fill in IP, port info early so even if SSL setup below fails,
  15818. * error handler would have the corresponding info.
  15819. * Thanks to Johannes Winkelmann for the patch.
  15820. */
  15821. #if defined(USE_IPV6)
  15822. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15823. conn->request_info.remote_port =
  15824. ntohs(conn->client.rsa.sin6.sin6_port);
  15825. } else
  15826. #endif
  15827. {
  15828. conn->request_info.remote_port =
  15829. ntohs(conn->client.rsa.sin.sin_port);
  15830. }
  15831. sockaddr_to_string(conn->request_info.remote_addr,
  15832. sizeof(conn->request_info.remote_addr),
  15833. &conn->client.rsa);
  15834. DEBUG_TRACE("Start processing connection from %s",
  15835. conn->request_info.remote_addr);
  15836. conn->request_info.is_ssl = conn->client.is_ssl;
  15837. if (conn->client.is_ssl) {
  15838. #if !defined(NO_SSL)
  15839. /* HTTPS connection */
  15840. if (sslize(conn,
  15841. conn->dom_ctx->ssl_ctx,
  15842. SSL_accept,
  15843. &(conn->phys_ctx->stop_flag),
  15844. NULL)) {
  15845. /* conn->dom_ctx is set in get_request */
  15846. /* Get SSL client certificate information (if set) */
  15847. ssl_get_client_cert_info(conn);
  15848. /* process HTTPS connection */
  15849. process_new_connection(conn);
  15850. /* Free client certificate info */
  15851. if (conn->request_info.client_cert) {
  15852. mg_free((void *)(conn->request_info.client_cert->subject));
  15853. mg_free((void *)(conn->request_info.client_cert->issuer));
  15854. mg_free((void *)(conn->request_info.client_cert->serial));
  15855. mg_free((void *)(conn->request_info.client_cert->finger));
  15856. /* Free certificate memory */
  15857. X509_free(
  15858. (X509 *)conn->request_info.client_cert->peer_cert);
  15859. conn->request_info.client_cert->peer_cert = 0;
  15860. conn->request_info.client_cert->subject = 0;
  15861. conn->request_info.client_cert->issuer = 0;
  15862. conn->request_info.client_cert->serial = 0;
  15863. conn->request_info.client_cert->finger = 0;
  15864. mg_free(conn->request_info.client_cert);
  15865. conn->request_info.client_cert = 0;
  15866. }
  15867. } else {
  15868. /* make sure the connection is cleaned up on SSL failure */
  15869. close_connection(conn);
  15870. }
  15871. #endif
  15872. } else {
  15873. /* process HTTP connection */
  15874. process_new_connection(conn);
  15875. }
  15876. DEBUG_TRACE("%s", "Connection closed");
  15877. #if defined(USE_SERVER_STATS)
  15878. conn->conn_close_time = time(NULL);
  15879. #endif
  15880. }
  15881. /* Call exit thread user callback */
  15882. if (ctx->callbacks.exit_thread) {
  15883. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15884. }
  15885. /* delete thread local storage objects */
  15886. pthread_setspecific(sTlsKey, NULL);
  15887. #if defined(_WIN32)
  15888. CloseHandle(tls.pthread_cond_helper_mutex);
  15889. #endif
  15890. pthread_mutex_destroy(&conn->mutex);
  15891. /* Free the request buffer. */
  15892. conn->buf_size = 0;
  15893. mg_free(conn->buf);
  15894. conn->buf = NULL;
  15895. #if defined(USE_SERVER_STATS)
  15896. conn->conn_state = 9; /* done */
  15897. #endif
  15898. DEBUG_TRACE("%s", "exiting");
  15899. }
  15900. /* Threads have different return types on Windows and Unix. */
  15901. #if defined(_WIN32)
  15902. static unsigned __stdcall worker_thread(void *thread_func_param)
  15903. {
  15904. worker_thread_run((struct mg_connection *)thread_func_param);
  15905. return 0;
  15906. }
  15907. #else
  15908. static void *
  15909. worker_thread(void *thread_func_param)
  15910. {
  15911. #if !defined(__ZEPHYR__)
  15912. struct sigaction sa;
  15913. /* Ignore SIGPIPE */
  15914. memset(&sa, 0, sizeof(sa));
  15915. sa.sa_handler = SIG_IGN;
  15916. sigaction(SIGPIPE, &sa, NULL);
  15917. #endif
  15918. worker_thread_run((struct mg_connection *)thread_func_param);
  15919. return NULL;
  15920. }
  15921. #endif /* _WIN32 */
  15922. /* This is an internal function, thus all arguments are expected to be
  15923. * valid - a NULL check is not required. */
  15924. static void
  15925. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15926. {
  15927. struct socket so;
  15928. char src_addr[IP_ADDR_STR_LEN];
  15929. socklen_t len = sizeof(so.rsa);
  15930. #if !defined(__ZEPHYR__)
  15931. int on = 1;
  15932. #endif
  15933. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15934. == INVALID_SOCKET) {
  15935. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15936. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15937. mg_cry_ctx_internal(ctx,
  15938. "%s: %s is not allowed to connect",
  15939. __func__,
  15940. src_addr);
  15941. closesocket(so.sock);
  15942. } else {
  15943. /* Put so socket structure into the queue */
  15944. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15945. set_close_on_exec(so.sock, NULL, ctx);
  15946. so.is_ssl = listener->is_ssl;
  15947. so.ssl_redir = listener->ssl_redir;
  15948. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15949. mg_cry_ctx_internal(ctx,
  15950. "%s: getsockname() failed: %s",
  15951. __func__,
  15952. strerror(ERRNO));
  15953. }
  15954. #if !defined(__ZEPHYR__)
  15955. /* Set TCP keep-alive. This is needed because if HTTP-level
  15956. * keep-alive
  15957. * is enabled, and client resets the connection, server won't get
  15958. * TCP FIN or RST and will keep the connection open forever. With
  15959. * TCP keep-alive, next keep-alive handshake will figure out that
  15960. * the client is down and will close the server end.
  15961. * Thanks to Igor Klopov who suggested the patch. */
  15962. if (setsockopt(so.sock,
  15963. SOL_SOCKET,
  15964. SO_KEEPALIVE,
  15965. (SOCK_OPT_TYPE)&on,
  15966. sizeof(on))
  15967. != 0) {
  15968. mg_cry_ctx_internal(
  15969. ctx,
  15970. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15971. __func__,
  15972. strerror(ERRNO));
  15973. }
  15974. #endif
  15975. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15976. * to effectively fill up the underlying IP packet payload and
  15977. * reduce the overhead of sending lots of small buffers. However
  15978. * this hurts the server's throughput (ie. operations per second)
  15979. * when HTTP 1.1 persistent connections are used and the responses
  15980. * are relatively small (eg. less than 1400 bytes).
  15981. */
  15982. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15983. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15984. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15985. mg_cry_ctx_internal(
  15986. ctx,
  15987. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15988. __func__,
  15989. strerror(ERRNO));
  15990. }
  15991. }
  15992. /* The "non blocking" property should already be
  15993. * inherited from the parent socket. Set it for
  15994. * non-compliant socket implementations. */
  15995. set_non_blocking_mode(so.sock);
  15996. so.in_use = 0;
  15997. produce_socket(ctx, &so);
  15998. }
  15999. }
  16000. static void
  16001. master_thread_run(struct mg_context *ctx)
  16002. {
  16003. struct mg_workerTLS tls;
  16004. struct mg_pollfd *pfd;
  16005. unsigned int i;
  16006. unsigned int workerthreadcount;
  16007. if (!ctx) {
  16008. return;
  16009. }
  16010. mg_set_thread_name("master");
  16011. /* Increase priority of the master thread */
  16012. #if defined(_WIN32)
  16013. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16014. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16015. int min_prio = sched_get_priority_min(SCHED_RR);
  16016. int max_prio = sched_get_priority_max(SCHED_RR);
  16017. if ((min_prio >= 0) && (max_prio >= 0)
  16018. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16019. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16020. struct sched_param sched_param = {0};
  16021. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16022. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16023. }
  16024. #endif
  16025. /* Initialize thread local storage */
  16026. #if defined(_WIN32)
  16027. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16028. #endif
  16029. tls.is_master = 1;
  16030. pthread_setspecific(sTlsKey, &tls);
  16031. if (ctx->callbacks.init_thread) {
  16032. /* Callback for the master thread (type 0) */
  16033. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16034. } else {
  16035. tls.user_ptr = NULL;
  16036. }
  16037. /* Server starts *now* */
  16038. ctx->start_time = time(NULL);
  16039. /* Start the server */
  16040. pfd = ctx->listening_socket_fds;
  16041. while (ctx->stop_flag == 0) {
  16042. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16043. pfd[i].fd = ctx->listening_sockets[i].sock;
  16044. pfd[i].events = POLLIN;
  16045. }
  16046. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16047. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16048. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16049. * successful poll, and POLLIN is defined as
  16050. * (POLLRDNORM | POLLRDBAND)
  16051. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16052. * pfd[i].revents == POLLIN. */
  16053. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  16054. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16055. }
  16056. }
  16057. }
  16058. }
  16059. /* Here stop_flag is 1 - Initiate shutdown. */
  16060. DEBUG_TRACE("%s", "stopping workers");
  16061. /* Stop signal received: somebody called mg_stop. Quit. */
  16062. close_all_listening_sockets(ctx);
  16063. /* Wakeup workers that are waiting for connections to handle. */
  16064. #if defined(ALTERNATIVE_QUEUE)
  16065. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16066. event_signal(ctx->client_wait_events[i]);
  16067. }
  16068. #else
  16069. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16070. pthread_cond_broadcast(&ctx->sq_full);
  16071. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16072. #endif
  16073. /* Join all worker threads to avoid leaking threads. */
  16074. workerthreadcount = ctx->cfg_worker_threads;
  16075. for (i = 0; i < workerthreadcount; i++) {
  16076. if (ctx->worker_threadids[i] != 0) {
  16077. mg_join_thread(ctx->worker_threadids[i]);
  16078. }
  16079. }
  16080. #if defined(USE_LUA)
  16081. /* Free Lua state of lua background task */
  16082. if (ctx->lua_background_state) {
  16083. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16084. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16085. if (lua_istable(lstate, -1)) {
  16086. reg_boolean(lstate, "shutdown", 1);
  16087. lua_pop(lstate, 1);
  16088. mg_sleep(2);
  16089. }
  16090. lua_close(lstate);
  16091. ctx->lua_background_state = 0;
  16092. }
  16093. #endif
  16094. DEBUG_TRACE("%s", "exiting");
  16095. /* call exit thread callback */
  16096. if (ctx->callbacks.exit_thread) {
  16097. /* Callback for the master thread (type 0) */
  16098. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16099. }
  16100. #if defined(_WIN32)
  16101. CloseHandle(tls.pthread_cond_helper_mutex);
  16102. #endif
  16103. pthread_setspecific(sTlsKey, NULL);
  16104. /* Signal mg_stop() that we're done.
  16105. * WARNING: This must be the very last thing this
  16106. * thread does, as ctx becomes invalid after this line. */
  16107. ctx->stop_flag = 2;
  16108. }
  16109. /* Threads have different return types on Windows and Unix. */
  16110. #if defined(_WIN32)
  16111. static unsigned __stdcall master_thread(void *thread_func_param)
  16112. {
  16113. master_thread_run((struct mg_context *)thread_func_param);
  16114. return 0;
  16115. }
  16116. #else
  16117. static void *
  16118. master_thread(void *thread_func_param)
  16119. {
  16120. #if !defined(__ZEPHYR__)
  16121. struct sigaction sa;
  16122. /* Ignore SIGPIPE */
  16123. memset(&sa, 0, sizeof(sa));
  16124. sa.sa_handler = SIG_IGN;
  16125. sigaction(SIGPIPE, &sa, NULL);
  16126. #endif
  16127. master_thread_run((struct mg_context *)thread_func_param);
  16128. return NULL;
  16129. }
  16130. #endif /* _WIN32 */
  16131. static void
  16132. free_context(struct mg_context *ctx)
  16133. {
  16134. int i;
  16135. struct mg_handler_info *tmp_rh;
  16136. if (ctx == NULL) {
  16137. return;
  16138. }
  16139. if (ctx->callbacks.exit_context) {
  16140. ctx->callbacks.exit_context(ctx);
  16141. }
  16142. /* All threads exited, no sync is needed. Destroy thread mutex and
  16143. * condvars
  16144. */
  16145. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16146. #if defined(ALTERNATIVE_QUEUE)
  16147. mg_free(ctx->client_socks);
  16148. if (ctx->client_wait_events != NULL) {
  16149. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16150. event_destroy(ctx->client_wait_events[i]);
  16151. }
  16152. mg_free(ctx->client_wait_events);
  16153. }
  16154. #else
  16155. (void)pthread_cond_destroy(&ctx->sq_empty);
  16156. (void)pthread_cond_destroy(&ctx->sq_full);
  16157. mg_free(ctx->squeue);
  16158. #endif
  16159. /* Destroy other context global data structures mutex */
  16160. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16161. #if defined(USE_TIMERS)
  16162. timers_exit(ctx);
  16163. #endif
  16164. /* Deallocate config parameters */
  16165. for (i = 0; i < NUM_OPTIONS; i++) {
  16166. if (ctx->dd.config[i] != NULL) {
  16167. #if defined(_MSC_VER)
  16168. #pragma warning(suppress : 6001)
  16169. #endif
  16170. mg_free(ctx->dd.config[i]);
  16171. }
  16172. }
  16173. /* Deallocate request handlers */
  16174. while (ctx->dd.handlers) {
  16175. tmp_rh = ctx->dd.handlers;
  16176. ctx->dd.handlers = tmp_rh->next;
  16177. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  16178. pthread_cond_destroy(&tmp_rh->refcount_cond);
  16179. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  16180. }
  16181. mg_free(tmp_rh->uri);
  16182. mg_free(tmp_rh);
  16183. }
  16184. #if !defined(NO_SSL)
  16185. /* Deallocate SSL context */
  16186. if (ctx->dd.ssl_ctx != NULL) {
  16187. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16188. int callback_ret =
  16189. (ctx->callbacks.external_ssl_ctx == NULL)
  16190. ? 0
  16191. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16192. if (callback_ret == 0) {
  16193. SSL_CTX_free(ctx->dd.ssl_ctx);
  16194. }
  16195. /* else: ignore error and ommit SSL_CTX_free in case
  16196. * callback_ret is 1 */
  16197. }
  16198. #endif /* !NO_SSL */
  16199. /* Deallocate worker thread ID array */
  16200. mg_free(ctx->worker_threadids);
  16201. /* Deallocate worker thread ID array */
  16202. mg_free(ctx->worker_connections);
  16203. /* deallocate system name string */
  16204. mg_free(ctx->systemName);
  16205. /* Deallocate context itself */
  16206. mg_free(ctx);
  16207. }
  16208. void
  16209. mg_stop(struct mg_context *ctx)
  16210. {
  16211. pthread_t mt;
  16212. if (!ctx) {
  16213. return;
  16214. }
  16215. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16216. * two threads is not allowed. */
  16217. mt = ctx->masterthreadid;
  16218. if (mt == 0) {
  16219. return;
  16220. }
  16221. ctx->masterthreadid = 0;
  16222. /* Set stop flag, so all threads know they have to exit. */
  16223. ctx->stop_flag = 1;
  16224. /* Wait until everything has stopped. */
  16225. while (ctx->stop_flag != 2) {
  16226. (void)mg_sleep(10);
  16227. }
  16228. mg_join_thread(mt);
  16229. free_context(ctx);
  16230. #if defined(_WIN32)
  16231. (void)WSACleanup();
  16232. #endif /* _WIN32 */
  16233. }
  16234. static void
  16235. get_system_name(char **sysName)
  16236. {
  16237. #if defined(_WIN32)
  16238. #if defined(_WIN32_WCE)
  16239. *sysName = mg_strdup("WinCE");
  16240. #else
  16241. char name[128];
  16242. DWORD dwVersion = 0;
  16243. DWORD dwMajorVersion = 0;
  16244. DWORD dwMinorVersion = 0;
  16245. DWORD dwBuild = 0;
  16246. BOOL wowRet, isWoW = FALSE;
  16247. #if defined(_MSC_VER)
  16248. #pragma warning(push)
  16249. /* GetVersion was declared deprecated */
  16250. #pragma warning(disable : 4996)
  16251. #endif
  16252. dwVersion = GetVersion();
  16253. #if defined(_MSC_VER)
  16254. #pragma warning(pop)
  16255. #endif
  16256. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16257. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16258. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16259. (void)dwBuild;
  16260. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16261. sprintf(name,
  16262. "Windows %u.%u%s",
  16263. (unsigned)dwMajorVersion,
  16264. (unsigned)dwMinorVersion,
  16265. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16266. *sysName = mg_strdup(name);
  16267. #endif
  16268. #elif defined(__ZEPHYR__)
  16269. *sysName = mg_strdup("Zephyr OS");
  16270. #else
  16271. struct utsname name;
  16272. memset(&name, 0, sizeof(name));
  16273. uname(&name);
  16274. *sysName = mg_strdup(name.sysname);
  16275. #endif
  16276. }
  16277. static void
  16278. legacy_init(const char **options)
  16279. {
  16280. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16281. if (options) {
  16282. const char **run_options = options;
  16283. const char *optname = config_options[LISTENING_PORTS].name;
  16284. /* Try to find the "listening_ports" option */
  16285. while (*run_options) {
  16286. if (!strcmp(*run_options, optname)) {
  16287. ports_option = run_options[1];
  16288. }
  16289. run_options += 2;
  16290. }
  16291. }
  16292. if (is_ssl_port_used(ports_option)) {
  16293. /* Initialize with SSL support */
  16294. mg_init_library(MG_FEATURES_TLS);
  16295. } else {
  16296. /* Initialize without SSL support */
  16297. mg_init_library(MG_FEATURES_DEFAULT);
  16298. }
  16299. }
  16300. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16301. static
  16302. #endif
  16303. struct mg_context *
  16304. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16305. {
  16306. struct mg_context *ctx;
  16307. const char *name, *value, *default_value;
  16308. int idx, ok, workerthreadcount;
  16309. unsigned int i;
  16310. int itmp;
  16311. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16312. const char **options =
  16313. ((init != NULL) ? (init->configuration_options) : (NULL));
  16314. struct mg_workerTLS tls;
  16315. #if defined(_WIN32)
  16316. WSADATA data;
  16317. WSAStartup(MAKEWORD(2, 2), &data);
  16318. #endif /* _WIN32 */
  16319. if (error != NULL) {
  16320. error->code = 0;
  16321. if (error->text_buffer_size > 0) {
  16322. *error->text = 0;
  16323. }
  16324. }
  16325. if (mg_init_library_called == 0) {
  16326. /* Legacy INIT, if mg_start is called without mg_init_library.
  16327. * Note: This will cause a memory leak when unloading the library. */
  16328. legacy_init(options);
  16329. }
  16330. /* Allocate context and initialize reasonable general case defaults. */
  16331. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16332. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16333. mg_snprintf(NULL,
  16334. NULL, /* No truncation check for error buffers */
  16335. error->text,
  16336. error->text_buffer_size,
  16337. "%s",
  16338. "Out of memory");
  16339. }
  16340. return NULL;
  16341. }
  16342. /* Random number generator will initialize at the first call */
  16343. ctx->dd.auth_nonce_mask =
  16344. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16345. tls.is_master = -1; /* Thread calling mg_start */
  16346. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16347. #if defined(_WIN32)
  16348. tls.pthread_cond_helper_mutex = NULL;
  16349. #endif
  16350. pthread_setspecific(sTlsKey, &tls);
  16351. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16352. #if !defined(ALTERNATIVE_QUEUE)
  16353. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16354. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16355. ctx->sq_blocked = 0;
  16356. #endif
  16357. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16358. if (!ok) {
  16359. const char *err_msg =
  16360. "Cannot initialize thread synchronization objects";
  16361. /* Fatal error - abort start. However, this situation should never
  16362. * occur in practice. */
  16363. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16364. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16365. mg_snprintf(NULL,
  16366. NULL, /* No truncation check for error buffers */
  16367. error->text,
  16368. error->text_buffer_size,
  16369. "%s",
  16370. err_msg);
  16371. }
  16372. mg_free(ctx);
  16373. pthread_setspecific(sTlsKey, NULL);
  16374. return NULL;
  16375. }
  16376. if ((init != NULL) && (init->callbacks != NULL)) {
  16377. /* Set all callbacks except exit_context. */
  16378. ctx->callbacks = *init->callbacks;
  16379. exit_callback = init->callbacks->exit_context;
  16380. /* The exit callback is activated once the context is successfully
  16381. * created. It should not be called, if an incomplete context object is
  16382. * deleted during a failed initialization. */
  16383. ctx->callbacks.exit_context = 0;
  16384. }
  16385. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16386. ctx->dd.handlers = NULL;
  16387. ctx->dd.next = NULL;
  16388. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16389. ctx->dd.shared_lua_websockets = NULL;
  16390. #endif
  16391. /* Store options */
  16392. while (options && (name = *options++) != NULL) {
  16393. if ((idx = get_option_index(name)) == -1) {
  16394. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16395. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16396. mg_snprintf(NULL,
  16397. NULL, /* No truncation check for error buffers */
  16398. error->text,
  16399. error->text_buffer_size,
  16400. "Invalid configuration option: %s",
  16401. name);
  16402. }
  16403. free_context(ctx);
  16404. pthread_setspecific(sTlsKey, NULL);
  16405. return NULL;
  16406. } else if ((value = *options++) == NULL) {
  16407. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16408. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16409. mg_snprintf(NULL,
  16410. NULL, /* No truncation check for error buffers */
  16411. error->text,
  16412. error->text_buffer_size,
  16413. "Invalid configuration option value: %s",
  16414. name);
  16415. }
  16416. free_context(ctx);
  16417. pthread_setspecific(sTlsKey, NULL);
  16418. return NULL;
  16419. }
  16420. if (ctx->dd.config[idx] != NULL) {
  16421. /* A duplicate configuration option is not an error - the last
  16422. * option value will be used. */
  16423. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16424. mg_free(ctx->dd.config[idx]);
  16425. }
  16426. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16427. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16428. }
  16429. /* Set default value if needed */
  16430. for (i = 0; config_options[i].name != NULL; i++) {
  16431. default_value = config_options[i].default_value;
  16432. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16433. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16434. }
  16435. }
  16436. /* Request size option */
  16437. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16438. if (itmp < 1024) {
  16439. mg_cry_ctx_internal(ctx,
  16440. "%s too small",
  16441. config_options[MAX_REQUEST_SIZE].name);
  16442. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16443. mg_snprintf(NULL,
  16444. NULL, /* No truncation check for error buffers */
  16445. error->text,
  16446. error->text_buffer_size,
  16447. "Invalid configuration option value: %s",
  16448. config_options[MAX_REQUEST_SIZE].name);
  16449. }
  16450. free_context(ctx);
  16451. pthread_setspecific(sTlsKey, NULL);
  16452. return NULL;
  16453. }
  16454. ctx->max_request_size = (unsigned)itmp;
  16455. /* Queue length */
  16456. #if !defined(ALTERNATIVE_QUEUE)
  16457. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16458. if (itmp < 1) {
  16459. mg_cry_ctx_internal(ctx,
  16460. "%s too small",
  16461. config_options[CONNECTION_QUEUE_SIZE].name);
  16462. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16463. mg_snprintf(NULL,
  16464. NULL, /* No truncation check for error buffers */
  16465. error->text,
  16466. error->text_buffer_size,
  16467. "Invalid configuration option value: %s",
  16468. config_options[CONNECTION_QUEUE_SIZE].name);
  16469. }
  16470. free_context(ctx);
  16471. pthread_setspecific(sTlsKey, NULL);
  16472. return NULL;
  16473. }
  16474. ctx->squeue = (struct socket *)mg_calloc(itmp, sizeof(struct socket));
  16475. if (ctx->squeue == NULL) {
  16476. mg_cry_ctx_internal(ctx,
  16477. "Out of memory: Cannot allocate %s",
  16478. config_options[CONNECTION_QUEUE_SIZE].name);
  16479. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16480. mg_snprintf(NULL,
  16481. NULL, /* No truncation check for error buffers */
  16482. error->text,
  16483. error->text_buffer_size,
  16484. "Out of memory: Cannot allocate %s",
  16485. config_options[CONNECTION_QUEUE_SIZE].name);
  16486. }
  16487. free_context(ctx);
  16488. pthread_setspecific(sTlsKey, NULL);
  16489. return NULL;
  16490. }
  16491. ctx->sq_size = itmp;
  16492. #endif
  16493. /* Worker thread count option */
  16494. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16495. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16496. if (workerthreadcount <= 0) {
  16497. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16498. } else {
  16499. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16500. }
  16501. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16502. mg_snprintf(NULL,
  16503. NULL, /* No truncation check for error buffers */
  16504. error->text,
  16505. error->text_buffer_size,
  16506. "Invalid configuration option value: %s",
  16507. config_options[NUM_THREADS].name);
  16508. }
  16509. free_context(ctx);
  16510. pthread_setspecific(sTlsKey, NULL);
  16511. return NULL;
  16512. }
  16513. /* Document root */
  16514. #if defined(NO_FILES)
  16515. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16516. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16517. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16518. mg_snprintf(NULL,
  16519. NULL, /* No truncation check for error buffers */
  16520. error->text,
  16521. error->text_buffer_size,
  16522. "Invalid configuration option value: %s",
  16523. config_options[DOCUMENT_ROOT].name);
  16524. }
  16525. free_context(ctx);
  16526. pthread_setspecific(sTlsKey, NULL);
  16527. return NULL;
  16528. }
  16529. #endif
  16530. get_system_name(&ctx->systemName);
  16531. #if defined(USE_LUA)
  16532. /* If a Lua background script has been configured, start it. */
  16533. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16534. char ebuf[256];
  16535. struct vec opt_vec;
  16536. struct vec eq_vec;
  16537. const char *sparams;
  16538. lua_State *state = mg_prepare_lua_context_script(
  16539. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16540. if (!state) {
  16541. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16542. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16543. mg_snprintf(NULL,
  16544. NULL, /* No truncation check for error buffers */
  16545. error->text,
  16546. error->text_buffer_size,
  16547. "Error in script %s: %s",
  16548. config_options[DOCUMENT_ROOT].name,
  16549. ebuf);
  16550. }
  16551. free_context(ctx);
  16552. pthread_setspecific(sTlsKey, NULL);
  16553. return NULL;
  16554. }
  16555. ctx->lua_background_state = (void *)state;
  16556. lua_newtable(state);
  16557. reg_boolean(state, "shutdown", 0);
  16558. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16559. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16560. reg_llstring(
  16561. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16562. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16563. break;
  16564. }
  16565. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16566. } else {
  16567. ctx->lua_background_state = 0;
  16568. }
  16569. #endif
  16570. /* Step by step initialization of ctx - depending on build options */
  16571. #if !defined(NO_FILESYSTEMS)
  16572. if (!set_gpass_option(ctx, NULL)) {
  16573. const char *err_msg = "Invalid global password file";
  16574. /* Fatal error - abort start. */
  16575. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16576. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16577. mg_snprintf(NULL,
  16578. NULL, /* No truncation check for error buffers */
  16579. error->text,
  16580. error->text_buffer_size,
  16581. "%s",
  16582. err_msg);
  16583. }
  16584. free_context(ctx);
  16585. pthread_setspecific(sTlsKey, NULL);
  16586. return NULL;
  16587. }
  16588. #endif
  16589. #if !defined(NO_SSL)
  16590. if (!init_ssl_ctx(ctx, NULL)) {
  16591. const char *err_msg = "Error initializing SSL context";
  16592. /* Fatal error - abort start. */
  16593. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16594. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16595. mg_snprintf(NULL,
  16596. NULL, /* No truncation check for error buffers */
  16597. error->text,
  16598. error->text_buffer_size,
  16599. "%s",
  16600. err_msg);
  16601. }
  16602. free_context(ctx);
  16603. pthread_setspecific(sTlsKey, NULL);
  16604. return NULL;
  16605. }
  16606. #endif
  16607. if (!set_ports_option(ctx)) {
  16608. const char *err_msg = "Failed to setup server ports";
  16609. /* Fatal error - abort start. */
  16610. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16611. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16612. mg_snprintf(NULL,
  16613. NULL, /* No truncation check for error buffers */
  16614. error->text,
  16615. error->text_buffer_size,
  16616. "%s",
  16617. err_msg);
  16618. }
  16619. free_context(ctx);
  16620. pthread_setspecific(sTlsKey, NULL);
  16621. return NULL;
  16622. }
  16623. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16624. if (!set_uid_option(ctx)) {
  16625. const char *err_msg = "Failed to run as configured user";
  16626. /* Fatal error - abort start. */
  16627. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16628. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16629. mg_snprintf(NULL,
  16630. NULL, /* No truncation check for error buffers */
  16631. error->text,
  16632. error->text_buffer_size,
  16633. "%s",
  16634. err_msg);
  16635. }
  16636. free_context(ctx);
  16637. pthread_setspecific(sTlsKey, NULL);
  16638. return NULL;
  16639. }
  16640. #endif
  16641. if (!set_acl_option(ctx)) {
  16642. const char *err_msg = "Failed to setup access control list";
  16643. /* Fatal error - abort start. */
  16644. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16645. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16646. mg_snprintf(NULL,
  16647. NULL, /* No truncation check for error buffers */
  16648. error->text,
  16649. error->text_buffer_size,
  16650. "%s",
  16651. err_msg);
  16652. }
  16653. free_context(ctx);
  16654. pthread_setspecific(sTlsKey, NULL);
  16655. return NULL;
  16656. }
  16657. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16658. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16659. sizeof(pthread_t),
  16660. ctx);
  16661. if (ctx->worker_threadids == NULL) {
  16662. const char *err_msg = "Not enough memory for worker thread ID array";
  16663. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16664. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16665. mg_snprintf(NULL,
  16666. NULL, /* No truncation check for error buffers */
  16667. error->text,
  16668. error->text_buffer_size,
  16669. "%s",
  16670. err_msg);
  16671. }
  16672. free_context(ctx);
  16673. pthread_setspecific(sTlsKey, NULL);
  16674. return NULL;
  16675. }
  16676. ctx->worker_connections =
  16677. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16678. sizeof(struct mg_connection),
  16679. ctx);
  16680. if (ctx->worker_connections == NULL) {
  16681. const char *err_msg =
  16682. "Not enough memory for worker thread connection array";
  16683. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16684. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16685. mg_snprintf(NULL,
  16686. NULL, /* No truncation check for error buffers */
  16687. error->text,
  16688. error->text_buffer_size,
  16689. "%s",
  16690. err_msg);
  16691. }
  16692. free_context(ctx);
  16693. pthread_setspecific(sTlsKey, NULL);
  16694. return NULL;
  16695. }
  16696. #if defined(ALTERNATIVE_QUEUE)
  16697. ctx->client_wait_events =
  16698. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16699. sizeof(ctx->client_wait_events[0]),
  16700. ctx);
  16701. if (ctx->client_wait_events == NULL) {
  16702. const char *err_msg = "Not enough memory for worker event array";
  16703. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16704. mg_free(ctx->worker_threadids);
  16705. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16706. mg_snprintf(NULL,
  16707. NULL, /* No truncation check for error buffers */
  16708. error->text,
  16709. error->text_buffer_size,
  16710. "%s",
  16711. err_msg);
  16712. }
  16713. free_context(ctx);
  16714. pthread_setspecific(sTlsKey, NULL);
  16715. return NULL;
  16716. }
  16717. ctx->client_socks =
  16718. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16719. sizeof(ctx->client_socks[0]),
  16720. ctx);
  16721. if (ctx->client_socks == NULL) {
  16722. const char *err_msg = "Not enough memory for worker socket array";
  16723. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16724. mg_free(ctx->client_wait_events);
  16725. mg_free(ctx->worker_threadids);
  16726. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16727. mg_snprintf(NULL,
  16728. NULL, /* No truncation check for error buffers */
  16729. error->text,
  16730. error->text_buffer_size,
  16731. "%s",
  16732. err_msg);
  16733. }
  16734. free_context(ctx);
  16735. pthread_setspecific(sTlsKey, NULL);
  16736. return NULL;
  16737. }
  16738. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16739. ctx->client_wait_events[i] = event_create();
  16740. if (ctx->client_wait_events[i] == 0) {
  16741. const char *err_msg = "Error creating worker event %i";
  16742. mg_cry_ctx_internal(ctx, err_msg, i);
  16743. while (i > 0) {
  16744. i--;
  16745. event_destroy(ctx->client_wait_events[i]);
  16746. }
  16747. mg_free(ctx->client_socks);
  16748. mg_free(ctx->client_wait_events);
  16749. mg_free(ctx->worker_threadids);
  16750. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16751. mg_snprintf(NULL,
  16752. NULL, /* No truncation check for error buffers */
  16753. error->text,
  16754. error->text_buffer_size,
  16755. err_msg,
  16756. i);
  16757. }
  16758. free_context(ctx);
  16759. pthread_setspecific(sTlsKey, NULL);
  16760. return NULL;
  16761. }
  16762. }
  16763. #endif
  16764. #if defined(USE_TIMERS)
  16765. if (timers_init(ctx) != 0) {
  16766. const char *err_msg = "Error creating timers";
  16767. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16768. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16769. mg_snprintf(NULL,
  16770. NULL, /* No truncation check for error buffers */
  16771. error->text,
  16772. error->text_buffer_size,
  16773. "%s",
  16774. err_msg);
  16775. }
  16776. free_context(ctx);
  16777. pthread_setspecific(sTlsKey, NULL);
  16778. return NULL;
  16779. }
  16780. #endif
  16781. /* Context has been created - init user libraries */
  16782. if (ctx->callbacks.init_context) {
  16783. ctx->callbacks.init_context(ctx);
  16784. }
  16785. /* From now, the context is successfully created.
  16786. * When it is destroyed, the exit callback should be called. */
  16787. ctx->callbacks.exit_context = exit_callback;
  16788. ctx->context_type = CONTEXT_SERVER; /* server context */
  16789. /* Start master (listening) thread */
  16790. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16791. /* Start worker threads */
  16792. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16793. /* worker_thread sets up the other fields */
  16794. ctx->worker_connections[i].phys_ctx = ctx;
  16795. if (mg_start_thread_with_id(worker_thread,
  16796. &ctx->worker_connections[i],
  16797. &ctx->worker_threadids[i])
  16798. != 0) {
  16799. long error_no = (long)ERRNO;
  16800. /* thread was not created */
  16801. if (i > 0) {
  16802. /* If the second, third, ... thread cannot be created, set a
  16803. * warning, but keep running. */
  16804. mg_cry_ctx_internal(ctx,
  16805. "Cannot start worker thread %i: error %ld",
  16806. i + 1,
  16807. error_no);
  16808. /* If the server initialization should stop here, all threads
  16809. * that have already been created must be stopped first, before
  16810. * any free_context(ctx) call.
  16811. */
  16812. } else {
  16813. /* If the first worker thread cannot be created, stop
  16814. * initialization and free the entire server context. */
  16815. mg_cry_ctx_internal(ctx,
  16816. "Cannot create threads: error %ld",
  16817. error_no);
  16818. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16819. mg_snprintf(
  16820. NULL,
  16821. NULL, /* No truncation check for error buffers */
  16822. error->text,
  16823. error->text_buffer_size,
  16824. "Cannot create first worker thread: error %ld",
  16825. error_no);
  16826. }
  16827. free_context(ctx);
  16828. pthread_setspecific(sTlsKey, NULL);
  16829. return NULL;
  16830. }
  16831. break;
  16832. }
  16833. }
  16834. pthread_setspecific(sTlsKey, NULL);
  16835. return ctx;
  16836. }
  16837. struct mg_context *
  16838. mg_start(const struct mg_callbacks *callbacks,
  16839. void *user_data,
  16840. const char **options)
  16841. {
  16842. struct mg_init_data init = {0};
  16843. init.callbacks = callbacks;
  16844. init.user_data = user_data;
  16845. init.configuration_options = options;
  16846. return mg_start2(&init, NULL);
  16847. }
  16848. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16849. /* Add an additional domain to an already running web server. */
  16850. int
  16851. mg_start_domain2(struct mg_context *ctx,
  16852. const char **options,
  16853. struct mg_error_data *error)
  16854. {
  16855. const char *name;
  16856. const char *value;
  16857. const char *default_value;
  16858. struct mg_domain_context *new_dom;
  16859. struct mg_domain_context *dom;
  16860. int idx, i;
  16861. if (error != NULL) {
  16862. error->code = 0;
  16863. if (error->text_buffer_size > 0) {
  16864. *error->text = 0;
  16865. }
  16866. }
  16867. if ((ctx == NULL) || (options == NULL)) {
  16868. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16869. mg_snprintf(NULL,
  16870. NULL, /* No truncation check for error buffers */
  16871. error->text,
  16872. error->text_buffer_size,
  16873. "%s",
  16874. "Invalid parameters");
  16875. }
  16876. return -1;
  16877. }
  16878. if (ctx->stop_flag != 0) {
  16879. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16880. mg_snprintf(NULL,
  16881. NULL, /* No truncation check for error buffers */
  16882. error->text,
  16883. error->text_buffer_size,
  16884. "%s",
  16885. "Server already stopped");
  16886. }
  16887. return -1;
  16888. }
  16889. new_dom = (struct mg_domain_context *)
  16890. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16891. if (!new_dom) {
  16892. /* Out of memory */
  16893. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16894. mg_snprintf(NULL,
  16895. NULL, /* No truncation check for error buffers */
  16896. error->text,
  16897. error->text_buffer_size,
  16898. "%s",
  16899. "Out or memory");
  16900. }
  16901. return -6;
  16902. }
  16903. /* Store options - TODO: unite duplicate code */
  16904. while (options && (name = *options++) != NULL) {
  16905. if ((idx = get_option_index(name)) == -1) {
  16906. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16907. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16908. mg_snprintf(NULL,
  16909. NULL, /* No truncation check for error buffers */
  16910. error->text,
  16911. error->text_buffer_size,
  16912. "Invalid option: %s",
  16913. name);
  16914. }
  16915. mg_free(new_dom);
  16916. return -2;
  16917. } else if ((value = *options++) == NULL) {
  16918. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16919. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16920. mg_snprintf(NULL,
  16921. NULL, /* No truncation check for error buffers */
  16922. error->text,
  16923. error->text_buffer_size,
  16924. "Invalid option value: %s",
  16925. name);
  16926. }
  16927. mg_free(new_dom);
  16928. return -2;
  16929. }
  16930. if (new_dom->config[idx] != NULL) {
  16931. /* Duplicate option: Later values overwrite earlier ones. */
  16932. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16933. mg_free(new_dom->config[idx]);
  16934. }
  16935. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16936. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16937. }
  16938. /* Authentication domain is mandatory */
  16939. /* TODO: Maybe use a new option hostname? */
  16940. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16941. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16942. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16943. mg_snprintf(NULL,
  16944. NULL, /* No truncation check for error buffers */
  16945. error->text,
  16946. error->text_buffer_size,
  16947. "Mandatory option %s missing",
  16948. config_options[AUTHENTICATION_DOMAIN].name);
  16949. }
  16950. mg_free(new_dom);
  16951. return -4;
  16952. }
  16953. /* Set default value if needed. Take the config value from
  16954. * ctx as a default value. */
  16955. for (i = 0; config_options[i].name != NULL; i++) {
  16956. default_value = ctx->dd.config[i];
  16957. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16958. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16959. }
  16960. }
  16961. new_dom->handlers = NULL;
  16962. new_dom->next = NULL;
  16963. new_dom->nonce_count = 0;
  16964. new_dom->auth_nonce_mask =
  16965. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16966. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16967. new_dom->shared_lua_websockets = NULL;
  16968. #endif
  16969. if (!init_ssl_ctx(ctx, new_dom)) {
  16970. /* Init SSL failed */
  16971. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16972. mg_snprintf(NULL,
  16973. NULL, /* No truncation check for error buffers */
  16974. error->text,
  16975. error->text_buffer_size,
  16976. "%s",
  16977. "Initializing SSL context failed");
  16978. }
  16979. mg_free(new_dom);
  16980. return -3;
  16981. }
  16982. /* Add element to linked list. */
  16983. mg_lock_context(ctx);
  16984. idx = 0;
  16985. dom = &(ctx->dd);
  16986. for (;;) {
  16987. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16988. dom->config[AUTHENTICATION_DOMAIN])) {
  16989. /* Domain collision */
  16990. mg_cry_ctx_internal(ctx,
  16991. "domain %s already in use",
  16992. new_dom->config[AUTHENTICATION_DOMAIN]);
  16993. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16994. mg_snprintf(NULL,
  16995. NULL, /* No truncation check for error buffers */
  16996. error->text,
  16997. error->text_buffer_size,
  16998. "Domain %s specified by %s is already in use",
  16999. new_dom->config[AUTHENTICATION_DOMAIN],
  17000. config_options[AUTHENTICATION_DOMAIN].name);
  17001. }
  17002. mg_free(new_dom);
  17003. return -5;
  17004. }
  17005. /* Count number of domains */
  17006. idx++;
  17007. if (dom->next == NULL) {
  17008. dom->next = new_dom;
  17009. break;
  17010. }
  17011. dom = dom->next;
  17012. }
  17013. mg_unlock_context(ctx);
  17014. /* Return domain number */
  17015. return idx;
  17016. }
  17017. int
  17018. mg_start_domain(struct mg_context *ctx, const char **options)
  17019. {
  17020. return mg_start_domain2(ctx, options, NULL);
  17021. }
  17022. #endif
  17023. /* Feature check API function */
  17024. unsigned
  17025. mg_check_feature(unsigned feature)
  17026. {
  17027. static const unsigned feature_set = 0
  17028. /* Set bits for available features according to API documentation.
  17029. * This bit mask is created at compile time, according to the active
  17030. * preprocessor defines. It is a single const value at runtime. */
  17031. #if !defined(NO_FILES)
  17032. | MG_FEATURES_FILES
  17033. #endif
  17034. #if !defined(NO_SSL)
  17035. | MG_FEATURES_SSL
  17036. #endif
  17037. #if !defined(NO_CGI)
  17038. | MG_FEATURES_CGI
  17039. #endif
  17040. #if defined(USE_IPV6)
  17041. | MG_FEATURES_IPV6
  17042. #endif
  17043. #if defined(USE_WEBSOCKET)
  17044. | MG_FEATURES_WEBSOCKET
  17045. #endif
  17046. #if defined(USE_LUA)
  17047. | MG_FEATURES_LUA
  17048. #endif
  17049. #if defined(USE_DUKTAPE)
  17050. | MG_FEATURES_SSJS
  17051. #endif
  17052. #if !defined(NO_CACHING)
  17053. | MG_FEATURES_CACHE
  17054. #endif
  17055. #if defined(USE_SERVER_STATS)
  17056. | MG_FEATURES_STATS
  17057. #endif
  17058. #if defined(USE_ZLIB)
  17059. | MG_FEATURES_COMPRESSION
  17060. #endif
  17061. /* Set some extra bits not defined in the API documentation.
  17062. * These bits may change without further notice. */
  17063. #if defined(MG_LEGACY_INTERFACE)
  17064. | 0x00008000u
  17065. #endif
  17066. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17067. | 0x00004000u
  17068. #endif
  17069. #if defined(MEMORY_DEBUGGING)
  17070. | 0x00001000u
  17071. #endif
  17072. #if defined(USE_TIMERS)
  17073. | 0x00020000u
  17074. #endif
  17075. #if !defined(NO_NONCE_CHECK)
  17076. | 0x00040000u
  17077. #endif
  17078. #if !defined(NO_POPEN)
  17079. | 0x00080000u
  17080. #endif
  17081. ;
  17082. return (feature & feature_set);
  17083. }
  17084. static size_t
  17085. mg_str_append(char **dst, char *end, const char *src)
  17086. {
  17087. size_t len = strlen(src);
  17088. if (*dst != end) {
  17089. /* Append src if enough space, or close dst. */
  17090. if ((size_t)(end - *dst) > len) {
  17091. strcpy(*dst, src);
  17092. *dst += len;
  17093. } else {
  17094. *dst = end;
  17095. }
  17096. }
  17097. return len;
  17098. }
  17099. /* Get system information. It can be printed or stored by the caller.
  17100. * Return the size of available information. */
  17101. int
  17102. mg_get_system_info(char *buffer, int buflen)
  17103. {
  17104. char *end, *append_eoobj = NULL, block[256];
  17105. size_t system_info_length = 0;
  17106. #if defined(_WIN32)
  17107. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17108. #else
  17109. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17110. #endif
  17111. if ((buffer == NULL) || (buflen < 1)) {
  17112. buflen = 0;
  17113. end = buffer;
  17114. } else {
  17115. *buffer = 0;
  17116. end = buffer + buflen;
  17117. }
  17118. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17119. /* has enough space to append eoobj */
  17120. append_eoobj = buffer;
  17121. end -= sizeof(eoobj) - 1;
  17122. }
  17123. system_info_length += mg_str_append(&buffer, end, "{");
  17124. /* Server version */
  17125. {
  17126. const char *version = mg_version();
  17127. mg_snprintf(NULL,
  17128. NULL,
  17129. block,
  17130. sizeof(block),
  17131. "%s\"version\" : \"%s\"",
  17132. eol,
  17133. version);
  17134. system_info_length += mg_str_append(&buffer, end, block);
  17135. }
  17136. /* System info */
  17137. {
  17138. #if defined(_WIN32)
  17139. DWORD dwVersion = 0;
  17140. DWORD dwMajorVersion = 0;
  17141. DWORD dwMinorVersion = 0;
  17142. SYSTEM_INFO si;
  17143. GetSystemInfo(&si);
  17144. #if defined(_MSC_VER)
  17145. #pragma warning(push)
  17146. /* GetVersion was declared deprecated */
  17147. #pragma warning(disable : 4996)
  17148. #endif
  17149. dwVersion = GetVersion();
  17150. #if defined(_MSC_VER)
  17151. #pragma warning(pop)
  17152. #endif
  17153. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17154. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17155. mg_snprintf(NULL,
  17156. NULL,
  17157. block,
  17158. sizeof(block),
  17159. ",%s\"os\" : \"Windows %u.%u\"",
  17160. eol,
  17161. (unsigned)dwMajorVersion,
  17162. (unsigned)dwMinorVersion);
  17163. system_info_length += mg_str_append(&buffer, end, block);
  17164. mg_snprintf(NULL,
  17165. NULL,
  17166. block,
  17167. sizeof(block),
  17168. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17169. eol,
  17170. (unsigned)si.wProcessorArchitecture,
  17171. (unsigned)si.dwNumberOfProcessors,
  17172. (unsigned)si.dwActiveProcessorMask);
  17173. system_info_length += mg_str_append(&buffer, end, block);
  17174. #elif defined(__ZEPHYR__)
  17175. mg_snprintf(NULL,
  17176. NULL,
  17177. block,
  17178. sizeof(block),
  17179. ",%s\"os\" : \"%s %s\"",
  17180. eol,
  17181. "Zephyr OS",
  17182. ZEPHYR_VERSION);
  17183. system_info_length += mg_str_append(&buffer, end, block);
  17184. #else
  17185. struct utsname name;
  17186. memset(&name, 0, sizeof(name));
  17187. uname(&name);
  17188. mg_snprintf(NULL,
  17189. NULL,
  17190. block,
  17191. sizeof(block),
  17192. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17193. eol,
  17194. name.sysname,
  17195. name.version,
  17196. name.release,
  17197. name.machine);
  17198. system_info_length += mg_str_append(&buffer, end, block);
  17199. #endif
  17200. }
  17201. /* Features */
  17202. {
  17203. mg_snprintf(NULL,
  17204. NULL,
  17205. block,
  17206. sizeof(block),
  17207. ",%s\"features\" : %lu"
  17208. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17209. eol,
  17210. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17211. eol,
  17212. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17213. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17214. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17215. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17216. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17217. : "",
  17218. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17219. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17220. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17221. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17222. system_info_length += mg_str_append(&buffer, end, block);
  17223. #if defined(USE_LUA)
  17224. mg_snprintf(NULL,
  17225. NULL,
  17226. block,
  17227. sizeof(block),
  17228. ",%s\"lua_version\" : \"%u (%s)\"",
  17229. eol,
  17230. (unsigned)LUA_VERSION_NUM,
  17231. LUA_RELEASE);
  17232. system_info_length += mg_str_append(&buffer, end, block);
  17233. #endif
  17234. #if defined(USE_DUKTAPE)
  17235. mg_snprintf(NULL,
  17236. NULL,
  17237. block,
  17238. sizeof(block),
  17239. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17240. eol,
  17241. (unsigned)DUK_VERSION / 10000,
  17242. ((unsigned)DUK_VERSION / 100) % 100,
  17243. (unsigned)DUK_VERSION % 100);
  17244. system_info_length += mg_str_append(&buffer, end, block);
  17245. #endif
  17246. }
  17247. /* Build date */
  17248. {
  17249. #if defined(GCC_DIAGNOSTIC)
  17250. #if GCC_VERSION >= 40900
  17251. #pragma GCC diagnostic push
  17252. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17253. #pragma GCC diagnostic ignored "-Wdate-time"
  17254. #endif
  17255. #endif
  17256. mg_snprintf(NULL,
  17257. NULL,
  17258. block,
  17259. sizeof(block),
  17260. ",%s\"build\" : \"%s\"",
  17261. eol,
  17262. __DATE__);
  17263. #if defined(GCC_DIAGNOSTIC)
  17264. #if GCC_VERSION >= 40900
  17265. #pragma GCC diagnostic pop
  17266. #endif
  17267. #endif
  17268. system_info_length += mg_str_append(&buffer, end, block);
  17269. }
  17270. /* Compiler information */
  17271. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17272. {
  17273. #if defined(_MSC_VER)
  17274. mg_snprintf(NULL,
  17275. NULL,
  17276. block,
  17277. sizeof(block),
  17278. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17279. eol,
  17280. (unsigned)_MSC_VER,
  17281. (unsigned)_MSC_FULL_VER);
  17282. system_info_length += mg_str_append(&buffer, end, block);
  17283. #elif defined(__MINGW64__)
  17284. mg_snprintf(NULL,
  17285. NULL,
  17286. block,
  17287. sizeof(block),
  17288. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17289. eol,
  17290. (unsigned)__MINGW64_VERSION_MAJOR,
  17291. (unsigned)__MINGW64_VERSION_MINOR);
  17292. system_info_length += mg_str_append(&buffer, end, block);
  17293. mg_snprintf(NULL,
  17294. NULL,
  17295. block,
  17296. sizeof(block),
  17297. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17298. eol,
  17299. (unsigned)__MINGW32_MAJOR_VERSION,
  17300. (unsigned)__MINGW32_MINOR_VERSION);
  17301. system_info_length += mg_str_append(&buffer, end, block);
  17302. #elif defined(__MINGW32__)
  17303. mg_snprintf(NULL,
  17304. NULL,
  17305. block,
  17306. sizeof(block),
  17307. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17308. eol,
  17309. (unsigned)__MINGW32_MAJOR_VERSION,
  17310. (unsigned)__MINGW32_MINOR_VERSION);
  17311. system_info_length += mg_str_append(&buffer, end, block);
  17312. #elif defined(__clang__)
  17313. mg_snprintf(NULL,
  17314. NULL,
  17315. block,
  17316. sizeof(block),
  17317. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17318. eol,
  17319. __clang_major__,
  17320. __clang_minor__,
  17321. __clang_patchlevel__,
  17322. __clang_version__);
  17323. system_info_length += mg_str_append(&buffer, end, block);
  17324. #elif defined(__GNUC__)
  17325. mg_snprintf(NULL,
  17326. NULL,
  17327. block,
  17328. sizeof(block),
  17329. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17330. eol,
  17331. (unsigned)__GNUC__,
  17332. (unsigned)__GNUC_MINOR__,
  17333. (unsigned)__GNUC_PATCHLEVEL__);
  17334. system_info_length += mg_str_append(&buffer, end, block);
  17335. #elif defined(__INTEL_COMPILER)
  17336. mg_snprintf(NULL,
  17337. NULL,
  17338. block,
  17339. sizeof(block),
  17340. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17341. eol,
  17342. (unsigned)__INTEL_COMPILER);
  17343. system_info_length += mg_str_append(&buffer, end, block);
  17344. #elif defined(__BORLANDC__)
  17345. mg_snprintf(NULL,
  17346. NULL,
  17347. block,
  17348. sizeof(block),
  17349. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17350. eol,
  17351. (unsigned)__BORLANDC__);
  17352. system_info_length += mg_str_append(&buffer, end, block);
  17353. #elif defined(__SUNPRO_C)
  17354. mg_snprintf(NULL,
  17355. NULL,
  17356. block,
  17357. sizeof(block),
  17358. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17359. eol,
  17360. (unsigned)__SUNPRO_C);
  17361. system_info_length += mg_str_append(&buffer, end, block);
  17362. #else
  17363. mg_snprintf(NULL,
  17364. NULL,
  17365. block,
  17366. sizeof(block),
  17367. ",%s\"compiler\" : \"other\"",
  17368. eol);
  17369. system_info_length += mg_str_append(&buffer, end, block);
  17370. #endif
  17371. }
  17372. /* Determine 32/64 bit data mode.
  17373. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17374. {
  17375. mg_snprintf(NULL,
  17376. NULL,
  17377. block,
  17378. sizeof(block),
  17379. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17380. "char:%u/%u, "
  17381. "ptr:%u, size:%u, time:%u\"",
  17382. eol,
  17383. (unsigned)sizeof(short),
  17384. (unsigned)sizeof(int),
  17385. (unsigned)sizeof(long),
  17386. (unsigned)sizeof(long long),
  17387. (unsigned)sizeof(float),
  17388. (unsigned)sizeof(double),
  17389. (unsigned)sizeof(long double),
  17390. (unsigned)sizeof(char),
  17391. (unsigned)sizeof(wchar_t),
  17392. (unsigned)sizeof(void *),
  17393. (unsigned)sizeof(size_t),
  17394. (unsigned)sizeof(time_t));
  17395. system_info_length += mg_str_append(&buffer, end, block);
  17396. }
  17397. /* Terminate string */
  17398. if (append_eoobj) {
  17399. strcat(append_eoobj, eoobj);
  17400. }
  17401. system_info_length += sizeof(eoobj) - 1;
  17402. return (int)system_info_length;
  17403. }
  17404. /* Get context information. It can be printed or stored by the caller.
  17405. * Return the size of available information. */
  17406. int
  17407. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17408. {
  17409. #if defined(USE_SERVER_STATS)
  17410. char *end, *append_eoobj = NULL, block[256];
  17411. size_t context_info_length = 0;
  17412. #if defined(_WIN32)
  17413. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17414. #else
  17415. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17416. #endif
  17417. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17418. if ((buffer == NULL) || (buflen < 1)) {
  17419. buflen = 0;
  17420. end = buffer;
  17421. } else {
  17422. *buffer = 0;
  17423. end = buffer + buflen;
  17424. }
  17425. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17426. /* has enough space to append eoobj */
  17427. append_eoobj = buffer;
  17428. end -= sizeof(eoobj) - 1;
  17429. }
  17430. context_info_length += mg_str_append(&buffer, end, "{");
  17431. if (ms) { /* <-- should be always true */
  17432. /* Memory information */
  17433. mg_snprintf(NULL,
  17434. NULL,
  17435. block,
  17436. sizeof(block),
  17437. "%s\"memory\" : {%s"
  17438. "\"blocks\" : %i,%s"
  17439. "\"used\" : %" INT64_FMT ",%s"
  17440. "\"maxUsed\" : %" INT64_FMT "%s"
  17441. "}",
  17442. eol,
  17443. eol,
  17444. ms->blockCount,
  17445. eol,
  17446. ms->totalMemUsed,
  17447. eol,
  17448. ms->maxMemUsed,
  17449. eol);
  17450. context_info_length += mg_str_append(&buffer, end, block);
  17451. }
  17452. if (ctx) {
  17453. /* Declare all variables at begin of the block, to comply
  17454. * with old C standards. */
  17455. char start_time_str[64] = {0};
  17456. char now_str[64] = {0};
  17457. time_t start_time = ctx->start_time;
  17458. time_t now = time(NULL);
  17459. /* Connections information */
  17460. mg_snprintf(NULL,
  17461. NULL,
  17462. block,
  17463. sizeof(block),
  17464. ",%s\"connections\" : {%s"
  17465. "\"active\" : %i,%s"
  17466. "\"maxActive\" : %i,%s"
  17467. "\"total\" : %" INT64_FMT "%s"
  17468. "}",
  17469. eol,
  17470. eol,
  17471. ctx->active_connections,
  17472. eol,
  17473. ctx->max_active_connections,
  17474. eol,
  17475. ctx->total_connections,
  17476. eol);
  17477. context_info_length += mg_str_append(&buffer, end, block);
  17478. /* Queue information */
  17479. #if !defined(ALTERNATIVE_QUEUE)
  17480. mg_snprintf(NULL,
  17481. NULL,
  17482. block,
  17483. sizeof(block),
  17484. ",%s\"queue\" : {%s"
  17485. "\"length\" : %i,%s"
  17486. "\"filled\" : %i,%s"
  17487. "\"maxFilled\" : %i,%s"
  17488. "\"full\" : %s%s"
  17489. "}",
  17490. eol,
  17491. eol,
  17492. ctx->sq_size,
  17493. eol,
  17494. ctx->sq_head - ctx->sq_tail,
  17495. eol,
  17496. ctx->sq_max_fill,
  17497. eol,
  17498. (ctx->sq_blocked ? "true" : "false"),
  17499. eol);
  17500. context_info_length += mg_str_append(&buffer, end, block);
  17501. #endif
  17502. /* Requests information */
  17503. mg_snprintf(NULL,
  17504. NULL,
  17505. block,
  17506. sizeof(block),
  17507. ",%s\"requests\" : {%s"
  17508. "\"total\" : %" INT64_FMT "%s"
  17509. "}",
  17510. eol,
  17511. eol,
  17512. ctx->total_requests,
  17513. eol);
  17514. context_info_length += mg_str_append(&buffer, end, block);
  17515. /* Data information */
  17516. mg_snprintf(NULL,
  17517. NULL,
  17518. block,
  17519. sizeof(block),
  17520. ",%s\"data\" : {%s"
  17521. "\"read\" : %" INT64_FMT ",%s"
  17522. "\"written\" : %" INT64_FMT "%s"
  17523. "}",
  17524. eol,
  17525. eol,
  17526. ctx->total_data_read,
  17527. eol,
  17528. ctx->total_data_written,
  17529. eol);
  17530. context_info_length += mg_str_append(&buffer, end, block);
  17531. /* Execution time information */
  17532. gmt_time_string(start_time_str,
  17533. sizeof(start_time_str) - 1,
  17534. &start_time);
  17535. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17536. mg_snprintf(NULL,
  17537. NULL,
  17538. block,
  17539. sizeof(block),
  17540. ",%s\"time\" : {%s"
  17541. "\"uptime\" : %.0f,%s"
  17542. "\"start\" : \"%s\",%s"
  17543. "\"now\" : \"%s\"%s"
  17544. "}",
  17545. eol,
  17546. eol,
  17547. difftime(now, start_time),
  17548. eol,
  17549. start_time_str,
  17550. eol,
  17551. now_str,
  17552. eol);
  17553. context_info_length += mg_str_append(&buffer, end, block);
  17554. }
  17555. /* Terminate string */
  17556. if (append_eoobj) {
  17557. strcat(append_eoobj, eoobj);
  17558. }
  17559. context_info_length += sizeof(eoobj) - 1;
  17560. return (int)context_info_length;
  17561. #else
  17562. (void)ctx;
  17563. if ((buffer != NULL) && (buflen > 0)) {
  17564. *buffer = 0;
  17565. }
  17566. return 0;
  17567. #endif
  17568. }
  17569. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17570. /* Get connection information. It can be printed or stored by the caller.
  17571. * Return the size of available information. */
  17572. int
  17573. mg_get_connection_info(const struct mg_context *ctx,
  17574. int idx,
  17575. char *buffer,
  17576. int buflen)
  17577. {
  17578. const struct mg_connection *conn;
  17579. const struct mg_request_info *ri;
  17580. char *end, *append_eoobj = NULL, block[256];
  17581. size_t connection_info_length = 0;
  17582. int state = 0;
  17583. const char *state_str = "unknown";
  17584. #if defined(_WIN32)
  17585. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17586. #else
  17587. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17588. #endif
  17589. if ((buffer == NULL) || (buflen < 1)) {
  17590. buflen = 0;
  17591. end = buffer;
  17592. } else {
  17593. *buffer = 0;
  17594. end = buffer + buflen;
  17595. }
  17596. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17597. /* has enough space to append eoobj */
  17598. append_eoobj = buffer;
  17599. end -= sizeof(eoobj) - 1;
  17600. }
  17601. if ((ctx == NULL) || (idx < 0)) {
  17602. /* Parameter error */
  17603. return 0;
  17604. }
  17605. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  17606. /* Out of range */
  17607. return 0;
  17608. }
  17609. /* Take connection [idx]. This connection is not locked in
  17610. * any way, so some other thread might use it. */
  17611. conn = (ctx->worker_connections) + idx;
  17612. /* Initialize output string */
  17613. connection_info_length += mg_str_append(&buffer, end, "{");
  17614. /* Init variables */
  17615. ri = &(conn->request_info);
  17616. #if defined(USE_SERVER_STATS)
  17617. state = conn->conn_state;
  17618. /* State as string */
  17619. switch (state) {
  17620. case 0:
  17621. state_str = "undefined";
  17622. break;
  17623. case 1:
  17624. state_str = "not used";
  17625. break;
  17626. case 2:
  17627. state_str = "init";
  17628. break;
  17629. case 3:
  17630. state_str = "ready";
  17631. break;
  17632. case 4:
  17633. state_str = "processing";
  17634. break;
  17635. case 5:
  17636. state_str = "processed";
  17637. break;
  17638. case 6:
  17639. state_str = "to close";
  17640. break;
  17641. case 7:
  17642. state_str = "closing";
  17643. break;
  17644. case 8:
  17645. state_str = "closed";
  17646. break;
  17647. case 9:
  17648. state_str = "done";
  17649. break;
  17650. }
  17651. #endif
  17652. /* Connection info */
  17653. if ((state >= 3) && (state < 9)) {
  17654. mg_snprintf(NULL,
  17655. NULL,
  17656. block,
  17657. sizeof(block),
  17658. "%s\"connection\" : {%s"
  17659. "\"remote\" : {%s"
  17660. "\"protocol\" : \"%s\",%s"
  17661. "\"addr\" : \"%s\",%s"
  17662. "\"port\" : %u%s"
  17663. "},%s"
  17664. "\"handled_requests\" : %u%s"
  17665. "}",
  17666. eol,
  17667. eol,
  17668. eol,
  17669. get_proto_name(conn),
  17670. eol,
  17671. ri->remote_addr,
  17672. eol,
  17673. ri->remote_port,
  17674. eol,
  17675. eol,
  17676. conn->handled_requests,
  17677. eol);
  17678. connection_info_length += mg_str_append(&buffer, end, block);
  17679. }
  17680. /* Request info */
  17681. if ((state >= 4) && (state < 6)) {
  17682. mg_snprintf(NULL,
  17683. NULL,
  17684. block,
  17685. sizeof(block),
  17686. "%s%s\"request_info\" : {%s"
  17687. "\"method\" : \"%s\",%s"
  17688. "\"uri\" : \"%s\",%s"
  17689. "\"query\" : %s%s%s%s"
  17690. "}",
  17691. (connection_info_length > 1 ? "," : ""),
  17692. eol,
  17693. eol,
  17694. ri->request_method,
  17695. eol,
  17696. ri->request_uri,
  17697. eol,
  17698. ri->query_string ? "\"" : "",
  17699. ri->query_string ? ri->query_string : "null",
  17700. ri->query_string ? "\"" : "",
  17701. eol);
  17702. connection_info_length += mg_str_append(&buffer, end, block);
  17703. }
  17704. /* Execution time information */
  17705. if ((state >= 2) && (state < 9)) {
  17706. char start_time_str[64] = {0};
  17707. char close_time_str[64] = {0};
  17708. time_t start_time = conn->conn_birth_time;
  17709. time_t close_time = conn->conn_close_time;
  17710. double time_diff;
  17711. gmt_time_string(start_time_str,
  17712. sizeof(start_time_str) - 1,
  17713. &start_time);
  17714. if (close_time != 0) {
  17715. time_diff = difftime(close_time, start_time);
  17716. gmt_time_string(close_time_str,
  17717. sizeof(close_time_str) - 1,
  17718. &close_time);
  17719. } else {
  17720. time_t now = time(NULL);
  17721. time_diff = difftime(now, start_time);
  17722. close_time_str[0] = 0; /* or use "now" ? */
  17723. }
  17724. mg_snprintf(NULL,
  17725. NULL,
  17726. block,
  17727. sizeof(block),
  17728. "%s%s\"time\" : {%s"
  17729. "\"uptime\" : %.0f,%s"
  17730. "\"start\" : \"%s\",%s"
  17731. "\"closed\" : \"%s\"%s"
  17732. "}",
  17733. (connection_info_length > 1 ? "," : ""),
  17734. eol,
  17735. eol,
  17736. time_diff,
  17737. eol,
  17738. start_time_str,
  17739. eol,
  17740. close_time_str,
  17741. eol);
  17742. connection_info_length += mg_str_append(&buffer, end, block);
  17743. }
  17744. /* Remote user name */
  17745. if ((ri->remote_user) && (state < 9)) {
  17746. mg_snprintf(NULL,
  17747. NULL,
  17748. block,
  17749. sizeof(block),
  17750. "%s%s\"user\" : {%s"
  17751. "\"name\" : \"%s\",%s"
  17752. "}",
  17753. (connection_info_length > 1 ? "," : ""),
  17754. eol,
  17755. eol,
  17756. ri->remote_user,
  17757. eol);
  17758. connection_info_length += mg_str_append(&buffer, end, block);
  17759. }
  17760. /* Data block */
  17761. if (state >= 3) {
  17762. mg_snprintf(NULL,
  17763. NULL,
  17764. block,
  17765. sizeof(block),
  17766. "%s%s\"data\" : {%s"
  17767. "\"read\" : %" INT64_FMT ",%s"
  17768. "\"written\" : %" INT64_FMT "%s"
  17769. "}",
  17770. (connection_info_length > 1 ? "," : ""),
  17771. eol,
  17772. eol,
  17773. conn->consumed_content,
  17774. eol,
  17775. conn->num_bytes_sent,
  17776. eol);
  17777. connection_info_length += mg_str_append(&buffer, end, block);
  17778. }
  17779. /* State */
  17780. mg_snprintf(NULL,
  17781. NULL,
  17782. block,
  17783. sizeof(block),
  17784. "%s%s\"state\" : \"%s\"",
  17785. (connection_info_length > 1 ? "," : ""),
  17786. eol,
  17787. state_str);
  17788. connection_info_length += mg_str_append(&buffer, end, block);
  17789. /* Terminate string */
  17790. if (append_eoobj) {
  17791. strcat(append_eoobj, eoobj);
  17792. }
  17793. connection_info_length += sizeof(eoobj) - 1;
  17794. return (int)connection_info_length;
  17795. }
  17796. #endif
  17797. /* Initialize this library. This function does not need to be thread safe.
  17798. */
  17799. unsigned
  17800. mg_init_library(unsigned features)
  17801. {
  17802. #if !defined(NO_SSL)
  17803. char ebuf[128];
  17804. #endif
  17805. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17806. unsigned features_inited = features_to_init;
  17807. if (mg_init_library_called <= 0) {
  17808. /* Not initialized yet */
  17809. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17810. return 0;
  17811. }
  17812. }
  17813. mg_global_lock();
  17814. if (mg_init_library_called <= 0) {
  17815. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17816. /* Fatal error - abort start. However, this situation should
  17817. * never occur in practice. */
  17818. mg_global_unlock();
  17819. return 0;
  17820. }
  17821. #if defined(_WIN32)
  17822. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17823. #else
  17824. pthread_mutexattr_init(&pthread_mutex_attr);
  17825. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17826. #endif
  17827. #if defined(USE_LUA)
  17828. lua_init_optional_libraries();
  17829. #endif
  17830. }
  17831. mg_global_unlock();
  17832. #if !defined(NO_SSL)
  17833. if (features_to_init & MG_FEATURES_SSL) {
  17834. if (!mg_ssl_initialized) {
  17835. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17836. mg_ssl_initialized = 1;
  17837. } else {
  17838. (void)ebuf;
  17839. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17840. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17841. }
  17842. } else {
  17843. /* ssl already initialized */
  17844. }
  17845. }
  17846. #endif
  17847. /* Start WinSock for Windows */
  17848. mg_global_lock();
  17849. if (mg_init_library_called <= 0) {
  17850. #if defined(_WIN32)
  17851. WSADATA data;
  17852. WSAStartup(MAKEWORD(2, 2), &data);
  17853. #endif /* _WIN32 */
  17854. mg_init_library_called = 1;
  17855. } else {
  17856. mg_init_library_called++;
  17857. }
  17858. mg_global_unlock();
  17859. return features_inited;
  17860. }
  17861. /* Un-initialize this library. */
  17862. unsigned
  17863. mg_exit_library(void)
  17864. {
  17865. if (mg_init_library_called <= 0) {
  17866. return 0;
  17867. }
  17868. mg_global_lock();
  17869. mg_init_library_called--;
  17870. if (mg_init_library_called == 0) {
  17871. #if defined(_WIN32)
  17872. (void)WSACleanup();
  17873. #endif /* _WIN32 */
  17874. #if !defined(NO_SSL)
  17875. if (mg_ssl_initialized) {
  17876. uninitialize_ssl();
  17877. mg_ssl_initialized = 0;
  17878. }
  17879. #endif
  17880. #if defined(_WIN32)
  17881. (void)pthread_mutex_destroy(&global_log_file_lock);
  17882. #else
  17883. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17884. #endif
  17885. (void)pthread_key_delete(sTlsKey);
  17886. #if defined(USE_LUA)
  17887. lua_exit_optional_libraries();
  17888. #endif
  17889. mg_global_unlock();
  17890. (void)pthread_mutex_destroy(&global_lock_mutex);
  17891. return 1;
  17892. }
  17893. mg_global_unlock();
  17894. return 1;
  17895. }
  17896. /* End of civetweb.c */