civetweb.c 529 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911
  1. /* Copyright (c) 2013-2018 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(_LARGEFILE_SOURCE)
  59. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  60. #endif
  61. #if !defined(_FILE_OFFSET_BITS)
  62. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  63. #endif
  64. #if !defined(__STDC_FORMAT_MACROS)
  65. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  66. #endif
  67. #if !defined(__STDC_LIMIT_MACROS)
  68. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  69. #endif
  70. #if !defined(_DARWIN_UNLIMITED_SELECT)
  71. #define _DARWIN_UNLIMITED_SELECT
  72. #endif
  73. #if defined(__sun)
  74. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  75. #define __inline inline /* not recognized on older compiler versions */
  76. #endif
  77. #endif
  78. #if defined(__clang__)
  79. /* Enable reserved-id-macro warning again. */
  80. #pragma GCC diagnostic pop
  81. #endif
  82. #if defined(USE_LUA)
  83. #define USE_TIMERS
  84. #endif
  85. #if defined(_MSC_VER)
  86. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  87. #pragma warning(disable : 4306)
  88. /* conditional expression is constant: introduced by FD_SET(..) */
  89. #pragma warning(disable : 4127)
  90. /* non-constant aggregate initializer: issued due to missing C99 support */
  91. #pragma warning(disable : 4204)
  92. /* padding added after data member */
  93. #pragma warning(disable : 4820)
  94. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  95. #pragma warning(disable : 4668)
  96. /* no function prototype given: converting '()' to '(void)' */
  97. #pragma warning(disable : 4255)
  98. /* function has been selected for automatic inline expansion */
  99. #pragma warning(disable : 4711)
  100. #endif
  101. /* This code uses static_assert to check some conditions.
  102. * Unfortunately some compilers still do not support it, so we have a
  103. * replacement function here. */
  104. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  105. #define mg_static_assert _Static_assert
  106. #elif defined(__cplusplus) && __cplusplus >= 201103L
  107. #define mg_static_assert static_assert
  108. #else
  109. char static_assert_replacement[1];
  110. #define mg_static_assert(cond, txt) \
  111. extern char static_assert_replacement[(cond) ? 1 : -1]
  112. #endif
  113. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  114. "int data type size check");
  115. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  116. "pointer data type size check");
  117. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  118. /* Alternative queue is well tested and should be the new default */
  119. #if defined(NO_ALTERNATIVE_QUEUE)
  120. #if defined(ALTERNATIVE_QUEUE)
  121. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  122. #endif
  123. #else
  124. #define ALTERNATIVE_QUEUE
  125. #endif
  126. /* DTL -- including winsock2.h works better if lean and mean */
  127. #if !defined(WIN32_LEAN_AND_MEAN)
  128. #define WIN32_LEAN_AND_MEAN
  129. #endif
  130. #if defined(__SYMBIAN32__)
  131. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  132. * Symbian is no longer maintained since 2014-01-01.
  133. * Recent versions of CivetWeb are no longer tested for Symbian.
  134. * It makes no sense, to support an abandoned operating system.
  135. */
  136. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  137. #define NO_SSL /* SSL is not supported */
  138. #define NO_CGI /* CGI is not supported */
  139. #define PATH_MAX FILENAME_MAX
  140. #endif /* __SYMBIAN32__ */
  141. #if !defined(CIVETWEB_HEADER_INCLUDED)
  142. /* Include the header file here, so the CivetWeb interface is defined for the
  143. * entire implementation, including the following forward definitions. */
  144. #include "civetweb.h"
  145. #endif
  146. #if !defined(DEBUG_TRACE)
  147. #if defined(DEBUG)
  148. static void DEBUG_TRACE_FUNC(const char *func,
  149. unsigned line,
  150. PRINTF_FORMAT_STRING(const char *fmt),
  151. ...) PRINTF_ARGS(3, 4);
  152. #define DEBUG_TRACE(fmt, ...) \
  153. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  154. #define NEED_DEBUG_TRACE_FUNC
  155. #else
  156. #define DEBUG_TRACE(fmt, ...) \
  157. do { \
  158. } while (0)
  159. #endif /* DEBUG */
  160. #endif /* DEBUG_TRACE */
  161. #if !defined(DEBUG_ASSERT)
  162. #if defined(DEBUG)
  163. #define DEBUG_ASSERT(cond) \
  164. do { \
  165. if (!(cond)) { \
  166. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  167. exit(2); /* Exit with error */ \
  168. } \
  169. } while (0)
  170. #else
  171. #define DEBUG_ASSERT(cond)
  172. #endif /* DEBUG */
  173. #endif
  174. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  175. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  176. __attribute__((no_instrument_function));
  177. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  178. __attribute__((no_instrument_function));
  179. void
  180. __cyg_profile_func_enter(void *this_fn, void *call_site)
  181. {
  182. if ((void *)this_fn != (void *)printf) {
  183. printf("E %p %p\n", this_fn, call_site);
  184. }
  185. }
  186. void
  187. __cyg_profile_func_exit(void *this_fn, void *call_site)
  188. {
  189. if ((void *)this_fn != (void *)printf) {
  190. printf("X %p %p\n", this_fn, call_site);
  191. }
  192. }
  193. #endif
  194. #if !defined(IGNORE_UNUSED_RESULT)
  195. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  196. #endif
  197. #if defined(__GNUC__) || defined(__MINGW32__)
  198. /* GCC unused function attribute seems fundamentally broken.
  199. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  200. * OR UNUSED" for individual functions failed.
  201. * Either the compiler creates an "unused-function" warning if a
  202. * function is not marked with __attribute__((unused)).
  203. * On the other hand, if the function is marked with this attribute,
  204. * but is used, the compiler raises a completely idiotic
  205. * "used-but-marked-unused" warning - and
  206. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  207. * raises error: unknown option after "#pragma GCC diagnostic".
  208. * Disable this warning completely, until the GCC guys sober up
  209. * again.
  210. */
  211. #pragma GCC diagnostic ignored "-Wunused-function"
  212. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  213. #else
  214. #define FUNCTION_MAY_BE_UNUSED
  215. #endif
  216. /* Some ANSI #includes are not available on Windows CE */
  217. #if !defined(_WIN32_WCE)
  218. #include <errno.h>
  219. #include <fcntl.h>
  220. #include <signal.h>
  221. #include <sys/stat.h>
  222. #include <sys/types.h>
  223. #endif /* !_WIN32_WCE */
  224. #if defined(__clang__)
  225. /* When using -Weverything, clang does not accept it's own headers
  226. * in a release build configuration. Disable what is too much in
  227. * -Weverything. */
  228. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  229. #endif
  230. #if defined(__GNUC__) || defined(__MINGW32__)
  231. /* Who on earth came to the conclusion, using __DATE__ should rise
  232. * an "expansion of date or time macro is not reproducible"
  233. * warning. That's exactly what was intended by using this macro.
  234. * Just disable this nonsense warning. */
  235. /* And disabling them does not work either:
  236. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  237. * #pragma clang diagnostic ignored "-Wdate-time"
  238. * So we just have to disable ALL warnings for some lines
  239. * of code.
  240. * This seems to be a known GCC bug, not resolved since 2012:
  241. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  242. */
  243. #endif
  244. #if defined(__MACH__) /* Apple OSX section */
  245. #if defined(__clang__)
  246. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  247. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  248. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  249. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  250. #endif
  251. #endif
  252. #define CLOCK_MONOTONIC (1)
  253. #define CLOCK_REALTIME (2)
  254. #include <mach/clock.h>
  255. #include <mach/mach.h>
  256. #include <mach/mach_time.h>
  257. #include <sys/errno.h>
  258. #include <sys/time.h>
  259. /* clock_gettime is not implemented on OSX prior to 10.12 */
  260. static int
  261. _civet_clock_gettime(int clk_id, struct timespec *t)
  262. {
  263. memset(t, 0, sizeof(*t));
  264. if (clk_id == CLOCK_REALTIME) {
  265. struct timeval now;
  266. int rv = gettimeofday(&now, NULL);
  267. if (rv) {
  268. return rv;
  269. }
  270. t->tv_sec = now.tv_sec;
  271. t->tv_nsec = now.tv_usec * 1000;
  272. return 0;
  273. } else if (clk_id == CLOCK_MONOTONIC) {
  274. static uint64_t clock_start_time = 0;
  275. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  276. uint64_t now = mach_absolute_time();
  277. if (clock_start_time == 0) {
  278. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  279. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  280. /* appease "unused variable" warning for release builds */
  281. (void)mach_status;
  282. clock_start_time = now;
  283. }
  284. now = (uint64_t)((double)(now - clock_start_time)
  285. * (double)timebase_ifo.numer
  286. / (double)timebase_ifo.denom);
  287. t->tv_sec = now / 1000000000;
  288. t->tv_nsec = now % 1000000000;
  289. return 0;
  290. }
  291. return -1; /* EINVAL - Clock ID is unknown */
  292. }
  293. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  294. #if defined(__CLOCK_AVAILABILITY)
  295. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  296. * declared but it may be NULL at runtime. So we need to check before using
  297. * it. */
  298. static int
  299. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  300. {
  301. if (clock_gettime) {
  302. return clock_gettime(clk_id, t);
  303. }
  304. return _civet_clock_gettime(clk_id, t);
  305. }
  306. #define clock_gettime _civet_safe_clock_gettime
  307. #else
  308. #define clock_gettime _civet_clock_gettime
  309. #endif
  310. #endif
  311. #include <ctype.h>
  312. #include <limits.h>
  313. #include <stdarg.h>
  314. #include <stddef.h>
  315. #include <stdint.h>
  316. #include <stdio.h>
  317. #include <stdlib.h>
  318. #include <string.h>
  319. #include <time.h>
  320. /********************************************************************/
  321. /* CivetWeb configuration defines */
  322. /********************************************************************/
  323. /* Maximum number of threads that can be configured.
  324. * The number of threads actually created depends on the "num_threads"
  325. * configuration parameter, but this is the upper limit. */
  326. #if !defined(MAX_WORKER_THREADS)
  327. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  328. #endif
  329. /* Timeout interval for select/poll calls.
  330. * The timeouts depend on "*_timeout_ms" configuration values, but long
  331. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  332. * This reduces the time required to stop the server. */
  333. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  334. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  335. #endif
  336. /* Do not try to compress files smaller than this limit. */
  337. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  338. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  339. #endif
  340. #if !defined(PASSWORDS_FILE_NAME)
  341. #define PASSWORDS_FILE_NAME ".htpasswd"
  342. #endif
  343. /* Initial buffer size for all CGI environment variables. In case there is
  344. * not enough space, another block is allocated. */
  345. #if !defined(CGI_ENVIRONMENT_SIZE)
  346. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  347. #endif
  348. /* Maximum number of environment variables. */
  349. #if !defined(MAX_CGI_ENVIR_VARS)
  350. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  351. #endif
  352. /* General purpose buffer size. */
  353. #if !defined(MG_BUF_LEN) /* in bytes */
  354. #define MG_BUF_LEN (1024 * 8)
  355. #endif
  356. /* Size of the accepted socket queue (in case the old queue implementation
  357. * is used). */
  358. #if !defined(MGSQLEN)
  359. #define MGSQLEN (20) /* count */
  360. #endif
  361. /********************************************************************/
  362. /* Helper makros */
  363. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  364. /* Standard defines */
  365. #if !defined(INT64_MAX)
  366. #define INT64_MAX (9223372036854775807)
  367. #endif
  368. #define SHUTDOWN_RD (0)
  369. #define SHUTDOWN_WR (1)
  370. #define SHUTDOWN_BOTH (2)
  371. mg_static_assert(MAX_WORKER_THREADS >= 1,
  372. "worker threads must be a positive number");
  373. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  374. "size_t data type size check");
  375. #if defined(_WIN32) /* WINDOWS include block */
  376. #include <windows.h>
  377. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  378. #include <ws2tcpip.h>
  379. typedef const char *SOCK_OPT_TYPE;
  380. #if !defined(PATH_MAX)
  381. #define W_PATH_MAX (MAX_PATH)
  382. /* at most three UTF-8 chars per wchar_t */
  383. #define PATH_MAX (W_PATH_MAX * 3)
  384. #else
  385. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  386. #endif
  387. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  388. #if !defined(_IN_PORT_T)
  389. #if !defined(in_port_t)
  390. #define in_port_t u_short
  391. #endif
  392. #endif
  393. #if !defined(_WIN32_WCE)
  394. #include <direct.h>
  395. #include <io.h>
  396. #include <process.h>
  397. #else /* _WIN32_WCE */
  398. #define NO_CGI /* WinCE has no pipes */
  399. #define NO_POPEN /* WinCE has no popen */
  400. typedef long off_t;
  401. #define errno ((int)(GetLastError()))
  402. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  403. #endif /* _WIN32_WCE */
  404. #define MAKEUQUAD(lo, hi) \
  405. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  406. #define RATE_DIFF (10000000) /* 100 nsecs */
  407. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  408. #define SYS2UNIX_TIME(lo, hi) \
  409. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  410. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  411. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  412. * Also use _strtoui64 on modern M$ compilers */
  413. #if defined(_MSC_VER)
  414. #if (_MSC_VER < 1300)
  415. #define STRX(x) #x
  416. #define STR(x) STRX(x)
  417. #define __func__ __FILE__ ":" STR(__LINE__)
  418. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  419. #define strtoll(x, y, z) (_atoi64(x))
  420. #else
  421. #define __func__ __FUNCTION__
  422. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  423. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  424. #endif
  425. #endif /* _MSC_VER */
  426. #define ERRNO ((int)(GetLastError()))
  427. #define NO_SOCKLEN_T
  428. #if defined(_WIN64) || defined(__MINGW64__)
  429. #if !defined(SSL_LIB)
  430. #define SSL_LIB "ssleay64.dll"
  431. #endif
  432. #if !defined(CRYPTO_LIB)
  433. #define CRYPTO_LIB "libeay64.dll"
  434. #endif
  435. #else
  436. #if !defined(SSL_LIB)
  437. #define SSL_LIB "ssleay32.dll"
  438. #endif
  439. #if !defined(CRYPTO_LIB)
  440. #define CRYPTO_LIB "libeay32.dll"
  441. #endif
  442. #endif
  443. #define O_NONBLOCK (0)
  444. #if !defined(W_OK)
  445. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  446. #endif
  447. #if !defined(EWOULDBLOCK)
  448. #define EWOULDBLOCK WSAEWOULDBLOCK
  449. #endif /* !EWOULDBLOCK */
  450. #define _POSIX_
  451. #define INT64_FMT "I64d"
  452. #define UINT64_FMT "I64u"
  453. #define WINCDECL __cdecl
  454. #define vsnprintf_impl _vsnprintf
  455. #define access _access
  456. #define mg_sleep(x) (Sleep(x))
  457. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  458. #if !defined(popen)
  459. #define popen(x, y) (_popen(x, y))
  460. #endif
  461. #if !defined(pclose)
  462. #define pclose(x) (_pclose(x))
  463. #endif
  464. #define close(x) (_close(x))
  465. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  466. #define RTLD_LAZY (0)
  467. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  468. #define fdopen(x, y) (_fdopen((x), (y)))
  469. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  470. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  471. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  472. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  473. #define sleep(x) (Sleep((x)*1000))
  474. #define rmdir(x) (_rmdir(x))
  475. #if defined(_WIN64) || !defined(__MINGW32__)
  476. /* Only MinGW 32 bit is missing this function */
  477. #define timegm(x) (_mkgmtime(x))
  478. #else
  479. time_t timegm(struct tm *tm);
  480. #define NEED_TIMEGM
  481. #endif
  482. #if !defined(fileno)
  483. #define fileno(x) (_fileno(x))
  484. #endif /* !fileno MINGW #defines fileno */
  485. typedef HANDLE pthread_mutex_t;
  486. typedef DWORD pthread_key_t;
  487. typedef HANDLE pthread_t;
  488. typedef struct {
  489. CRITICAL_SECTION threadIdSec;
  490. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  491. } pthread_cond_t;
  492. #if !defined(__clockid_t_defined)
  493. typedef DWORD clockid_t;
  494. #endif
  495. #if !defined(CLOCK_MONOTONIC)
  496. #define CLOCK_MONOTONIC (1)
  497. #endif
  498. #if !defined(CLOCK_REALTIME)
  499. #define CLOCK_REALTIME (2)
  500. #endif
  501. #if !defined(CLOCK_THREAD)
  502. #define CLOCK_THREAD (3)
  503. #endif
  504. #if !defined(CLOCK_PROCESS)
  505. #define CLOCK_PROCESS (4)
  506. #endif
  507. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  508. #define _TIMESPEC_DEFINED
  509. #endif
  510. #if !defined(_TIMESPEC_DEFINED)
  511. struct timespec {
  512. time_t tv_sec; /* seconds */
  513. long tv_nsec; /* nanoseconds */
  514. };
  515. #endif
  516. #if !defined(WIN_PTHREADS_TIME_H)
  517. #define MUST_IMPLEMENT_CLOCK_GETTIME
  518. #endif
  519. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  520. #define clock_gettime mg_clock_gettime
  521. static int
  522. clock_gettime(clockid_t clk_id, struct timespec *tp)
  523. {
  524. FILETIME ft;
  525. ULARGE_INTEGER li, li2;
  526. BOOL ok = FALSE;
  527. double d;
  528. static double perfcnt_per_sec = 0.0;
  529. static BOOL initialized = FALSE;
  530. if (!initialized) {
  531. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  532. perfcnt_per_sec = 1.0 / li.QuadPart;
  533. initialized = TRUE;
  534. }
  535. if (tp) {
  536. memset(tp, 0, sizeof(*tp));
  537. if (clk_id == CLOCK_REALTIME) {
  538. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  539. GetSystemTimeAsFileTime(&ft);
  540. li.LowPart = ft.dwLowDateTime;
  541. li.HighPart = ft.dwHighDateTime;
  542. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  543. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  544. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  545. ok = TRUE;
  546. /* END: CLOCK_REALTIME */
  547. } else if (clk_id == CLOCK_MONOTONIC) {
  548. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  549. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  550. d = li.QuadPart * perfcnt_per_sec;
  551. tp->tv_sec = (time_t)d;
  552. d -= (double)tp->tv_sec;
  553. tp->tv_nsec = (long)(d * 1.0E9);
  554. ok = TRUE;
  555. /* END: CLOCK_MONOTONIC */
  556. } else if (clk_id == CLOCK_THREAD) {
  557. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  558. FILETIME t_create, t_exit, t_kernel, t_user;
  559. if (GetThreadTimes(GetCurrentThread(),
  560. &t_create,
  561. &t_exit,
  562. &t_kernel,
  563. &t_user)) {
  564. li.LowPart = t_user.dwLowDateTime;
  565. li.HighPart = t_user.dwHighDateTime;
  566. li2.LowPart = t_kernel.dwLowDateTime;
  567. li2.HighPart = t_kernel.dwHighDateTime;
  568. li.QuadPart += li2.QuadPart;
  569. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  570. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  571. ok = TRUE;
  572. }
  573. /* END: CLOCK_THREAD */
  574. } else if (clk_id == CLOCK_PROCESS) {
  575. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  576. FILETIME t_create, t_exit, t_kernel, t_user;
  577. if (GetProcessTimes(GetCurrentProcess(),
  578. &t_create,
  579. &t_exit,
  580. &t_kernel,
  581. &t_user)) {
  582. li.LowPart = t_user.dwLowDateTime;
  583. li.HighPart = t_user.dwHighDateTime;
  584. li2.LowPart = t_kernel.dwLowDateTime;
  585. li2.HighPart = t_kernel.dwHighDateTime;
  586. li.QuadPart += li2.QuadPart;
  587. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  588. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  589. ok = TRUE;
  590. }
  591. /* END: CLOCK_PROCESS */
  592. } else {
  593. /* BEGIN: unknown clock */
  594. /* ok = FALSE; already set by init */
  595. /* END: unknown clock */
  596. }
  597. }
  598. return ok ? 0 : -1;
  599. }
  600. #endif
  601. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  602. static int pthread_mutex_lock(pthread_mutex_t *);
  603. static int pthread_mutex_unlock(pthread_mutex_t *);
  604. static void path_to_unicode(const struct mg_connection *conn,
  605. const char *path,
  606. wchar_t *wbuf,
  607. size_t wbuf_len);
  608. /* All file operations need to be rewritten to solve #246. */
  609. struct mg_file;
  610. static const char *
  611. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  612. /* POSIX dirent interface */
  613. struct dirent {
  614. char d_name[PATH_MAX];
  615. };
  616. typedef struct DIR {
  617. HANDLE handle;
  618. WIN32_FIND_DATAW info;
  619. struct dirent result;
  620. } DIR;
  621. #if defined(HAVE_POLL)
  622. #define mg_pollfd pollfd
  623. #else
  624. struct mg_pollfd {
  625. SOCKET fd;
  626. short events;
  627. short revents;
  628. };
  629. #endif
  630. /* Mark required libraries */
  631. #if defined(_MSC_VER)
  632. #pragma comment(lib, "Ws2_32.lib")
  633. #endif
  634. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  635. #include <arpa/inet.h>
  636. #include <inttypes.h>
  637. #include <netdb.h>
  638. #include <netinet/in.h>
  639. #include <netinet/tcp.h>
  640. #include <stdint.h>
  641. #include <sys/poll.h>
  642. #include <sys/socket.h>
  643. #include <sys/time.h>
  644. #include <sys/utsname.h>
  645. #include <sys/wait.h>
  646. typedef const void *SOCK_OPT_TYPE;
  647. #if defined(ANDROID)
  648. typedef unsigned short int in_port_t;
  649. #endif
  650. #include <dirent.h>
  651. #include <grp.h>
  652. #include <pwd.h>
  653. #include <unistd.h>
  654. #define vsnprintf_impl vsnprintf
  655. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  656. #include <dlfcn.h>
  657. #endif
  658. #include <pthread.h>
  659. #if defined(__MACH__)
  660. #define SSL_LIB "libssl.dylib"
  661. #define CRYPTO_LIB "libcrypto.dylib"
  662. #else
  663. #if !defined(SSL_LIB)
  664. #define SSL_LIB "libssl.so"
  665. #endif
  666. #if !defined(CRYPTO_LIB)
  667. #define CRYPTO_LIB "libcrypto.so"
  668. #endif
  669. #endif
  670. #if !defined(O_BINARY)
  671. #define O_BINARY (0)
  672. #endif /* O_BINARY */
  673. #define closesocket(a) (close(a))
  674. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  675. #define mg_remove(conn, x) (remove(x))
  676. #define mg_sleep(x) (usleep((x)*1000))
  677. #define mg_opendir(conn, x) (opendir(x))
  678. #define mg_closedir(x) (closedir(x))
  679. #define mg_readdir(x) (readdir(x))
  680. #define ERRNO (errno)
  681. #define INVALID_SOCKET (-1)
  682. #define INT64_FMT PRId64
  683. #define UINT64_FMT PRIu64
  684. typedef int SOCKET;
  685. #define WINCDECL
  686. #if defined(__hpux)
  687. /* HPUX 11 does not have monotonic, fall back to realtime */
  688. #if !defined(CLOCK_MONOTONIC)
  689. #define CLOCK_MONOTONIC CLOCK_REALTIME
  690. #endif
  691. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  692. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  693. * the prototypes use int* rather than socklen_t* which matches the
  694. * actual library expectation. When called with the wrong size arg
  695. * accept() returns a zero client inet addr and check_acl() always
  696. * fails. Since socklen_t is widely used below, just force replace
  697. * their typedef with int. - DTL
  698. */
  699. #define socklen_t int
  700. #endif /* hpux */
  701. #define mg_pollfd pollfd
  702. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  703. /* Maximum queue length for pending connections. This value is passed as
  704. * parameter to the "listen" socket call. */
  705. #if !defined(SOMAXCONN)
  706. /* This symbol may be defined in winsock2.h so this must after that include */
  707. #define SOMAXCONN (100) /* in pending connections (count) */
  708. #endif
  709. /* In case our C library is missing "timegm", provide an implementation */
  710. #if defined(NEED_TIMEGM)
  711. static inline int
  712. is_leap(int y)
  713. {
  714. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  715. }
  716. static inline int
  717. count_leap(int y)
  718. {
  719. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  720. }
  721. time_t
  722. timegm(struct tm *tm)
  723. {
  724. static const unsigned short ydays[] = {
  725. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  726. int year = tm->tm_year + 1900;
  727. int mon = tm->tm_mon;
  728. int mday = tm->tm_mday - 1;
  729. int hour = tm->tm_hour;
  730. int min = tm->tm_min;
  731. int sec = tm->tm_sec;
  732. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  733. || (mday >= ydays[mon + 1] - ydays[mon]
  734. + (mon == 1 && is_leap(year) ? 1 : 0))
  735. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  736. return -1;
  737. time_t res = year - 1970;
  738. res *= 365;
  739. res += mday;
  740. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  741. res += count_leap(year);
  742. res *= 24;
  743. res += hour;
  744. res *= 60;
  745. res += min;
  746. res *= 60;
  747. res += sec;
  748. return res;
  749. }
  750. #endif /* NEED_TIMEGM */
  751. /* va_copy should always be a macro, C99 and C++11 - DTL */
  752. #if !defined(va_copy)
  753. #define va_copy(x, y) ((x) = (y))
  754. #endif
  755. #if defined(_WIN32)
  756. /* Create substitutes for POSIX functions in Win32. */
  757. #if defined(GCC_DIAGNOSTIC)
  758. /* Show no warning in case system functions are not used. */
  759. #pragma GCC diagnostic push
  760. #pragma GCC diagnostic ignored "-Wunused-function"
  761. #endif
  762. static CRITICAL_SECTION global_log_file_lock;
  763. FUNCTION_MAY_BE_UNUSED
  764. static DWORD
  765. pthread_self(void)
  766. {
  767. return GetCurrentThreadId();
  768. }
  769. FUNCTION_MAY_BE_UNUSED
  770. static int
  771. pthread_key_create(
  772. pthread_key_t *key,
  773. void (*_ignored)(void *) /* destructor not supported for Windows */
  774. )
  775. {
  776. (void)_ignored;
  777. if ((key != 0)) {
  778. *key = TlsAlloc();
  779. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  780. }
  781. return -2;
  782. }
  783. FUNCTION_MAY_BE_UNUSED
  784. static int
  785. pthread_key_delete(pthread_key_t key)
  786. {
  787. return TlsFree(key) ? 0 : 1;
  788. }
  789. FUNCTION_MAY_BE_UNUSED
  790. static int
  791. pthread_setspecific(pthread_key_t key, void *value)
  792. {
  793. return TlsSetValue(key, value) ? 0 : 1;
  794. }
  795. FUNCTION_MAY_BE_UNUSED
  796. static void *
  797. pthread_getspecific(pthread_key_t key)
  798. {
  799. return TlsGetValue(key);
  800. }
  801. #if defined(GCC_DIAGNOSTIC)
  802. /* Enable unused function warning again */
  803. #pragma GCC diagnostic pop
  804. #endif
  805. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  806. #else
  807. static pthread_mutexattr_t pthread_mutex_attr;
  808. #endif /* _WIN32 */
  809. #if defined(_WIN32_WCE)
  810. /* Create substitutes for POSIX functions in Win32. */
  811. #if defined(GCC_DIAGNOSTIC)
  812. /* Show no warning in case system functions are not used. */
  813. #pragma GCC diagnostic push
  814. #pragma GCC diagnostic ignored "-Wunused-function"
  815. #endif
  816. FUNCTION_MAY_BE_UNUSED
  817. static time_t
  818. time(time_t *ptime)
  819. {
  820. time_t t;
  821. SYSTEMTIME st;
  822. FILETIME ft;
  823. GetSystemTime(&st);
  824. SystemTimeToFileTime(&st, &ft);
  825. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  826. if (ptime != NULL) {
  827. *ptime = t;
  828. }
  829. return t;
  830. }
  831. FUNCTION_MAY_BE_UNUSED
  832. static struct tm *
  833. localtime_s(const time_t *ptime, struct tm *ptm)
  834. {
  835. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  836. FILETIME ft, lft;
  837. SYSTEMTIME st;
  838. TIME_ZONE_INFORMATION tzinfo;
  839. if (ptm == NULL) {
  840. return NULL;
  841. }
  842. *(int64_t *)&ft = t;
  843. FileTimeToLocalFileTime(&ft, &lft);
  844. FileTimeToSystemTime(&lft, &st);
  845. ptm->tm_year = st.wYear - 1900;
  846. ptm->tm_mon = st.wMonth - 1;
  847. ptm->tm_wday = st.wDayOfWeek;
  848. ptm->tm_mday = st.wDay;
  849. ptm->tm_hour = st.wHour;
  850. ptm->tm_min = st.wMinute;
  851. ptm->tm_sec = st.wSecond;
  852. ptm->tm_yday = 0; /* hope nobody uses this */
  853. ptm->tm_isdst =
  854. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  855. return ptm;
  856. }
  857. FUNCTION_MAY_BE_UNUSED
  858. static struct tm *
  859. gmtime_s(const time_t *ptime, struct tm *ptm)
  860. {
  861. /* FIXME(lsm): fix this. */
  862. return localtime_s(ptime, ptm);
  863. }
  864. static int mg_atomic_inc(volatile int *addr);
  865. static struct tm tm_array[MAX_WORKER_THREADS];
  866. static int tm_index = 0;
  867. FUNCTION_MAY_BE_UNUSED
  868. static struct tm *
  869. localtime(const time_t *ptime)
  870. {
  871. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  872. return localtime_s(ptime, tm_array + i);
  873. }
  874. FUNCTION_MAY_BE_UNUSED
  875. static struct tm *
  876. gmtime(const time_t *ptime)
  877. {
  878. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  879. return gmtime_s(ptime, tm_array + i);
  880. }
  881. FUNCTION_MAY_BE_UNUSED
  882. static size_t
  883. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  884. {
  885. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  886. * for WinCE"); */
  887. return 0;
  888. }
  889. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  890. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  891. #define remove(f) mg_remove(NULL, f)
  892. FUNCTION_MAY_BE_UNUSED
  893. static int
  894. rename(const char *a, const char *b)
  895. {
  896. wchar_t wa[W_PATH_MAX];
  897. wchar_t wb[W_PATH_MAX];
  898. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  899. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  900. return MoveFileW(wa, wb) ? 0 : -1;
  901. }
  902. struct stat {
  903. int64_t st_size;
  904. time_t st_mtime;
  905. };
  906. FUNCTION_MAY_BE_UNUSED
  907. static int
  908. stat(const char *name, struct stat *st)
  909. {
  910. wchar_t wbuf[W_PATH_MAX];
  911. WIN32_FILE_ATTRIBUTE_DATA attr;
  912. time_t creation_time, write_time;
  913. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  914. memset(&attr, 0, sizeof(attr));
  915. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  916. st->st_size =
  917. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  918. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  919. attr.ftLastWriteTime.dwHighDateTime);
  920. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  921. attr.ftCreationTime.dwHighDateTime);
  922. if (creation_time > write_time) {
  923. st->st_mtime = creation_time;
  924. } else {
  925. st->st_mtime = write_time;
  926. }
  927. return 0;
  928. }
  929. #define access(x, a) 1 /* not required anyway */
  930. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  931. /* Values from errno.h in Windows SDK (Visual Studio). */
  932. #define EEXIST 17
  933. #define EACCES 13
  934. #define ENOENT 2
  935. #if defined(GCC_DIAGNOSTIC)
  936. /* Enable unused function warning again */
  937. #pragma GCC diagnostic pop
  938. #endif
  939. #endif /* defined(_WIN32_WCE) */
  940. #if defined(GCC_DIAGNOSTIC)
  941. /* Show no warning in case system functions are not used. */
  942. #pragma GCC diagnostic push
  943. #pragma GCC diagnostic ignored "-Wunused-function"
  944. #endif /* defined(GCC_DIAGNOSTIC) */
  945. #if defined(__clang__)
  946. /* Show no warning in case system functions are not used. */
  947. #pragma clang diagnostic push
  948. #pragma clang diagnostic ignored "-Wunused-function"
  949. #endif
  950. static pthread_mutex_t global_lock_mutex;
  951. #if defined(_WIN32)
  952. /* Forward declaration for Windows */
  953. FUNCTION_MAY_BE_UNUSED
  954. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  955. FUNCTION_MAY_BE_UNUSED
  956. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  957. #endif
  958. FUNCTION_MAY_BE_UNUSED
  959. static void
  960. mg_global_lock(void)
  961. {
  962. (void)pthread_mutex_lock(&global_lock_mutex);
  963. }
  964. FUNCTION_MAY_BE_UNUSED
  965. static void
  966. mg_global_unlock(void)
  967. {
  968. (void)pthread_mutex_unlock(&global_lock_mutex);
  969. }
  970. FUNCTION_MAY_BE_UNUSED
  971. static int
  972. mg_atomic_inc(volatile int *addr)
  973. {
  974. int ret;
  975. #if defined(_WIN32) && !defined(NO_ATOMICS)
  976. /* Depending on the SDK, this function uses either
  977. * (volatile unsigned int *) or (volatile LONG *),
  978. * so whatever you use, the other SDK is likely to raise a warning. */
  979. ret = InterlockedIncrement((volatile long *)addr);
  980. #elif defined(__GNUC__) \
  981. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  982. && !defined(NO_ATOMICS)
  983. ret = __sync_add_and_fetch(addr, 1);
  984. #else
  985. mg_global_lock();
  986. ret = (++(*addr));
  987. mg_global_unlock();
  988. #endif
  989. return ret;
  990. }
  991. FUNCTION_MAY_BE_UNUSED
  992. static int
  993. mg_atomic_dec(volatile int *addr)
  994. {
  995. int ret;
  996. #if defined(_WIN32) && !defined(NO_ATOMICS)
  997. /* Depending on the SDK, this function uses either
  998. * (volatile unsigned int *) or (volatile LONG *),
  999. * so whatever you use, the other SDK is likely to raise a warning. */
  1000. ret = InterlockedDecrement((volatile long *)addr);
  1001. #elif defined(__GNUC__) \
  1002. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1003. && !defined(NO_ATOMICS)
  1004. ret = __sync_sub_and_fetch(addr, 1);
  1005. #else
  1006. mg_global_lock();
  1007. ret = (--(*addr));
  1008. mg_global_unlock();
  1009. #endif
  1010. return ret;
  1011. }
  1012. #if defined(USE_SERVER_STATS)
  1013. static int64_t
  1014. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1015. {
  1016. int64_t ret;
  1017. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1018. ret = InterlockedAdd64(addr, value);
  1019. #elif defined(__GNUC__) \
  1020. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1021. && !defined(NO_ATOMICS)
  1022. ret = __sync_add_and_fetch(addr, value);
  1023. #else
  1024. mg_global_lock();
  1025. *addr += value;
  1026. ret = (*addr);
  1027. mg_global_unlock();
  1028. #endif
  1029. return ret;
  1030. }
  1031. #endif
  1032. #if defined(GCC_DIAGNOSTIC)
  1033. /* Show no warning in case system functions are not used. */
  1034. #pragma GCC diagnostic pop
  1035. #endif /* defined(GCC_DIAGNOSTIC) */
  1036. #if defined(__clang__)
  1037. /* Show no warning in case system functions are not used. */
  1038. #pragma clang diagnostic pop
  1039. #endif
  1040. #if defined(USE_SERVER_STATS)
  1041. struct mg_memory_stat {
  1042. volatile int64_t totalMemUsed;
  1043. volatile int64_t maxMemUsed;
  1044. volatile int blockCount;
  1045. };
  1046. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1047. static void *
  1048. mg_malloc_ex(size_t size,
  1049. struct mg_context *ctx,
  1050. const char *file,
  1051. unsigned line)
  1052. {
  1053. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1054. void *memory = 0;
  1055. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1056. #if defined(MEMORY_DEBUGGING)
  1057. char mallocStr[256];
  1058. #else
  1059. (void)file;
  1060. (void)line;
  1061. #endif
  1062. if (data) {
  1063. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1064. if (mmem > mstat->maxMemUsed) {
  1065. /* could use atomic compare exchange, but this
  1066. * seems overkill for statistics data */
  1067. mstat->maxMemUsed = mmem;
  1068. }
  1069. mg_atomic_inc(&mstat->blockCount);
  1070. ((uintptr_t *)data)[0] = size;
  1071. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1072. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1073. }
  1074. #if defined(MEMORY_DEBUGGING)
  1075. sprintf(mallocStr,
  1076. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1077. memory,
  1078. (unsigned long)size,
  1079. (unsigned long)mstat->totalMemUsed,
  1080. (unsigned long)mstat->blockCount,
  1081. file,
  1082. line);
  1083. #if defined(_WIN32)
  1084. OutputDebugStringA(mallocStr);
  1085. #else
  1086. DEBUG_TRACE("%s", mallocStr);
  1087. #endif
  1088. #endif
  1089. return memory;
  1090. }
  1091. static void *
  1092. mg_calloc_ex(size_t count,
  1093. size_t size,
  1094. struct mg_context *ctx,
  1095. const char *file,
  1096. unsigned line)
  1097. {
  1098. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1099. if (data) {
  1100. memset(data, 0, size * count);
  1101. }
  1102. return data;
  1103. }
  1104. static void
  1105. mg_free_ex(void *memory, const char *file, unsigned line)
  1106. {
  1107. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1108. #if defined(MEMORY_DEBUGGING)
  1109. char mallocStr[256];
  1110. #else
  1111. (void)file;
  1112. (void)line;
  1113. #endif
  1114. if (memory) {
  1115. uintptr_t size = ((uintptr_t *)data)[0];
  1116. struct mg_memory_stat *mstat =
  1117. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1118. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1119. mg_atomic_dec(&mstat->blockCount);
  1120. #if defined(MEMORY_DEBUGGING)
  1121. sprintf(mallocStr,
  1122. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1123. memory,
  1124. (unsigned long)size,
  1125. (unsigned long)mstat->totalMemUsed,
  1126. (unsigned long)mstat->blockCount,
  1127. file,
  1128. line);
  1129. #if defined(_WIN32)
  1130. OutputDebugStringA(mallocStr);
  1131. #else
  1132. DEBUG_TRACE("%s", mallocStr);
  1133. #endif
  1134. #endif
  1135. free(data);
  1136. }
  1137. }
  1138. static void *
  1139. mg_realloc_ex(void *memory,
  1140. size_t newsize,
  1141. struct mg_context *ctx,
  1142. const char *file,
  1143. unsigned line)
  1144. {
  1145. void *data;
  1146. void *_realloc;
  1147. uintptr_t oldsize;
  1148. #if defined(MEMORY_DEBUGGING)
  1149. char mallocStr[256];
  1150. #else
  1151. (void)file;
  1152. (void)line;
  1153. #endif
  1154. if (newsize) {
  1155. if (memory) {
  1156. /* Reallocate existing block */
  1157. struct mg_memory_stat *mstat;
  1158. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1159. oldsize = ((uintptr_t *)data)[0];
  1160. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1161. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1162. if (_realloc) {
  1163. data = _realloc;
  1164. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1165. #if defined(MEMORY_DEBUGGING)
  1166. sprintf(mallocStr,
  1167. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1168. memory,
  1169. (unsigned long)oldsize,
  1170. (unsigned long)mstat->totalMemUsed,
  1171. (unsigned long)mstat->blockCount,
  1172. file,
  1173. line);
  1174. #if defined(_WIN32)
  1175. OutputDebugStringA(mallocStr);
  1176. #else
  1177. DEBUG_TRACE("%s", mallocStr);
  1178. #endif
  1179. #endif
  1180. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1181. #if defined(MEMORY_DEBUGGING)
  1182. sprintf(mallocStr,
  1183. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1184. memory,
  1185. (unsigned long)newsize,
  1186. (unsigned long)mstat->totalMemUsed,
  1187. (unsigned long)mstat->blockCount,
  1188. file,
  1189. line);
  1190. #if defined(_WIN32)
  1191. OutputDebugStringA(mallocStr);
  1192. #else
  1193. DEBUG_TRACE("%s", mallocStr);
  1194. #endif
  1195. #endif
  1196. *(uintptr_t *)data = newsize;
  1197. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1198. } else {
  1199. #if defined(MEMORY_DEBUGGING)
  1200. #if defined(_WIN32)
  1201. OutputDebugStringA("MEM: realloc failed\n");
  1202. #else
  1203. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1204. #endif
  1205. #endif
  1206. return _realloc;
  1207. }
  1208. } else {
  1209. /* Allocate new block */
  1210. data = mg_malloc_ex(newsize, ctx, file, line);
  1211. }
  1212. } else {
  1213. /* Free existing block */
  1214. data = 0;
  1215. mg_free_ex(memory, file, line);
  1216. }
  1217. return data;
  1218. }
  1219. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1220. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1221. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1222. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1223. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1224. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1225. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1226. #else /* USE_SERVER_STATS */
  1227. static __inline void *
  1228. mg_malloc(size_t a)
  1229. {
  1230. return malloc(a);
  1231. }
  1232. static __inline void *
  1233. mg_calloc(size_t a, size_t b)
  1234. {
  1235. return calloc(a, b);
  1236. }
  1237. static __inline void *
  1238. mg_realloc(void *a, size_t b)
  1239. {
  1240. return realloc(a, b);
  1241. }
  1242. static __inline void
  1243. mg_free(void *a)
  1244. {
  1245. free(a);
  1246. }
  1247. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1248. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1249. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1250. #define mg_free_ctx(a, c) mg_free(a)
  1251. #endif /* USE_SERVER_STATS */
  1252. static void mg_vsnprintf(const struct mg_connection *conn,
  1253. int *truncated,
  1254. char *buf,
  1255. size_t buflen,
  1256. const char *fmt,
  1257. va_list ap);
  1258. static void mg_snprintf(const struct mg_connection *conn,
  1259. int *truncated,
  1260. char *buf,
  1261. size_t buflen,
  1262. PRINTF_FORMAT_STRING(const char *fmt),
  1263. ...) PRINTF_ARGS(5, 6);
  1264. /* This following lines are just meant as a reminder to use the mg-functions
  1265. * for memory management */
  1266. #if defined(malloc)
  1267. #undef malloc
  1268. #endif
  1269. #if defined(calloc)
  1270. #undef calloc
  1271. #endif
  1272. #if defined(realloc)
  1273. #undef realloc
  1274. #endif
  1275. #if defined(free)
  1276. #undef free
  1277. #endif
  1278. #if defined(snprintf)
  1279. #undef snprintf
  1280. #endif
  1281. #if defined(vsnprintf)
  1282. #undef vsnprintf
  1283. #endif
  1284. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1285. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1286. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1287. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1288. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1289. #if defined(_WIN32)
  1290. /* vsnprintf must not be used in any system,
  1291. * but this define only works well for Windows. */
  1292. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1293. #endif
  1294. /* mg_init_library counter */
  1295. static int mg_init_library_called = 0;
  1296. #if !defined(NO_SSL)
  1297. static int mg_ssl_initialized = 0;
  1298. #endif
  1299. static pthread_key_t sTlsKey; /* Thread local storage index */
  1300. static int thread_idx_max = 0;
  1301. #if defined(MG_LEGACY_INTERFACE)
  1302. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1303. #endif
  1304. struct mg_workerTLS {
  1305. int is_master;
  1306. unsigned long thread_idx;
  1307. #if defined(_WIN32)
  1308. HANDLE pthread_cond_helper_mutex;
  1309. struct mg_workerTLS *next_waiting_thread;
  1310. #endif
  1311. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1312. char txtbuf[4];
  1313. #endif
  1314. };
  1315. #if defined(GCC_DIAGNOSTIC)
  1316. /* Show no warning in case system functions are not used. */
  1317. #pragma GCC diagnostic push
  1318. #pragma GCC diagnostic ignored "-Wunused-function"
  1319. #endif /* defined(GCC_DIAGNOSTIC) */
  1320. #if defined(__clang__)
  1321. /* Show no warning in case system functions are not used. */
  1322. #pragma clang diagnostic push
  1323. #pragma clang diagnostic ignored "-Wunused-function"
  1324. #endif
  1325. /* Get a unique thread ID as unsigned long, independent from the data type
  1326. * of thread IDs defined by the operating system API.
  1327. * If two calls to mg_current_thread_id return the same value, they calls
  1328. * are done from the same thread. If they return different values, they are
  1329. * done from different threads. (Provided this function is used in the same
  1330. * process context and threads are not repeatedly created and deleted, but
  1331. * CivetWeb does not do that).
  1332. * This function must match the signature required for SSL id callbacks:
  1333. * CRYPTO_set_id_callback
  1334. */
  1335. FUNCTION_MAY_BE_UNUSED
  1336. static unsigned long
  1337. mg_current_thread_id(void)
  1338. {
  1339. #if defined(_WIN32)
  1340. return GetCurrentThreadId();
  1341. #else
  1342. #if defined(__clang__)
  1343. #pragma clang diagnostic push
  1344. #pragma clang diagnostic ignored "-Wunreachable-code"
  1345. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1346. * or not, so one of the two conditions will be unreachable by construction.
  1347. * Unfortunately the C standard does not define a way to check this at
  1348. * compile time, since the #if preprocessor conditions can not use the sizeof
  1349. * operator as an argument. */
  1350. #endif
  1351. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1352. /* This is the problematic case for CRYPTO_set_id_callback:
  1353. * The OS pthread_t can not be cast to unsigned long. */
  1354. struct mg_workerTLS *tls =
  1355. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1356. if (tls == NULL) {
  1357. /* SSL called from an unknown thread: Create some thread index.
  1358. */
  1359. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1360. tls->is_master = -2; /* -2 means "3rd party thread" */
  1361. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1362. pthread_setspecific(sTlsKey, tls);
  1363. }
  1364. return tls->thread_idx;
  1365. } else {
  1366. /* pthread_t may be any data type, so a simple cast to unsigned long
  1367. * can rise a warning/error, depending on the platform.
  1368. * Here memcpy is used as an anything-to-anything cast. */
  1369. unsigned long ret = 0;
  1370. pthread_t t = pthread_self();
  1371. memcpy(&ret, &t, sizeof(pthread_t));
  1372. return ret;
  1373. }
  1374. #if defined(__clang__)
  1375. #pragma clang diagnostic pop
  1376. #endif
  1377. #endif
  1378. }
  1379. FUNCTION_MAY_BE_UNUSED
  1380. static uint64_t
  1381. mg_get_current_time_ns(void)
  1382. {
  1383. struct timespec tsnow;
  1384. clock_gettime(CLOCK_REALTIME, &tsnow);
  1385. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1386. }
  1387. #if defined(GCC_DIAGNOSTIC)
  1388. /* Show no warning in case system functions are not used. */
  1389. #pragma GCC diagnostic pop
  1390. #endif /* defined(GCC_DIAGNOSTIC) */
  1391. #if defined(__clang__)
  1392. /* Show no warning in case system functions are not used. */
  1393. #pragma clang diagnostic pop
  1394. #endif
  1395. #if defined(NEED_DEBUG_TRACE_FUNC)
  1396. static void
  1397. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1398. {
  1399. va_list args;
  1400. uint64_t nsnow;
  1401. static uint64_t nslast;
  1402. struct timespec tsnow;
  1403. /* Get some operating system independent thread id */
  1404. unsigned long thread_id = mg_current_thread_id();
  1405. clock_gettime(CLOCK_REALTIME, &tsnow);
  1406. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1407. + ((uint64_t)tsnow.tv_nsec);
  1408. if (!nslast) {
  1409. nslast = nsnow;
  1410. }
  1411. flockfile(stdout);
  1412. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1413. (unsigned long)tsnow.tv_sec,
  1414. (unsigned long)tsnow.tv_nsec,
  1415. nsnow - nslast,
  1416. thread_id,
  1417. func,
  1418. line);
  1419. va_start(args, fmt);
  1420. vprintf(fmt, args);
  1421. va_end(args);
  1422. putchar('\n');
  1423. fflush(stdout);
  1424. funlockfile(stdout);
  1425. nslast = nsnow;
  1426. }
  1427. #endif /* NEED_DEBUG_TRACE_FUNC */
  1428. #define MD5_STATIC static
  1429. #include "md5.inl"
  1430. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1431. #if defined(NO_SOCKLEN_T)
  1432. typedef int socklen_t;
  1433. #endif /* NO_SOCKLEN_T */
  1434. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1435. #if !defined(MSG_NOSIGNAL)
  1436. #define MSG_NOSIGNAL (0)
  1437. #endif
  1438. #if defined(NO_SSL)
  1439. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1440. typedef struct SSL_CTX SSL_CTX;
  1441. #else
  1442. #if defined(NO_SSL_DL)
  1443. #include <openssl/bn.h>
  1444. #include <openssl/conf.h>
  1445. #include <openssl/crypto.h>
  1446. #include <openssl/dh.h>
  1447. #include <openssl/engine.h>
  1448. #include <openssl/err.h>
  1449. #include <openssl/opensslv.h>
  1450. #include <openssl/pem.h>
  1451. #include <openssl/ssl.h>
  1452. #include <openssl/tls1.h>
  1453. #include <openssl/x509.h>
  1454. #if defined(WOLFSSL_VERSION)
  1455. /* Additional defines for WolfSSL, see
  1456. * https://github.com/civetweb/civetweb/issues/583 */
  1457. #include "wolfssl_extras.inl"
  1458. #endif
  1459. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1460. /* If OpenSSL headers are included, automatically select the API version */
  1461. #if !defined(OPENSSL_API_1_1)
  1462. #define OPENSSL_API_1_1
  1463. #endif
  1464. #define OPENSSL_REMOVE_THREAD_STATE()
  1465. #else
  1466. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1467. #endif
  1468. #else
  1469. /* SSL loaded dynamically from DLL.
  1470. * I put the prototypes here to be independent from OpenSSL source
  1471. * installation. */
  1472. typedef struct ssl_st SSL;
  1473. typedef struct ssl_method_st SSL_METHOD;
  1474. typedef struct ssl_ctx_st SSL_CTX;
  1475. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1476. typedef struct x509_name X509_NAME;
  1477. typedef struct asn1_integer ASN1_INTEGER;
  1478. typedef struct bignum BIGNUM;
  1479. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1480. typedef struct evp_md EVP_MD;
  1481. typedef struct x509 X509;
  1482. #define SSL_CTRL_OPTIONS (32)
  1483. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1484. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1485. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1486. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1487. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1488. #define SSL_VERIFY_NONE (0)
  1489. #define SSL_VERIFY_PEER (1)
  1490. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1491. #define SSL_VERIFY_CLIENT_ONCE (4)
  1492. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1493. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1494. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1495. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1496. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1497. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1498. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1499. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1500. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1501. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1502. #define SSL_CB_HANDSHAKE_START (0x10)
  1503. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1504. #define SSL_ERROR_NONE (0)
  1505. #define SSL_ERROR_SSL (1)
  1506. #define SSL_ERROR_WANT_READ (2)
  1507. #define SSL_ERROR_WANT_WRITE (3)
  1508. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1509. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1510. #define SSL_ERROR_ZERO_RETURN (6)
  1511. #define SSL_ERROR_WANT_CONNECT (7)
  1512. #define SSL_ERROR_WANT_ACCEPT (8)
  1513. #define TLSEXT_TYPE_server_name (0)
  1514. #define TLSEXT_NAMETYPE_host_name (0)
  1515. #define SSL_TLSEXT_ERR_OK (0)
  1516. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1517. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1518. #define SSL_TLSEXT_ERR_NOACK (3)
  1519. struct ssl_func {
  1520. const char *name; /* SSL function name */
  1521. void (*ptr)(void); /* Function pointer */
  1522. };
  1523. #if defined(OPENSSL_API_1_1)
  1524. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1525. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1526. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1527. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1528. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1529. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1530. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1531. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1532. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1533. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1534. #define OPENSSL_init_ssl \
  1535. (*(int (*)(uint64_t opts, \
  1536. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1537. .ptr)
  1538. #define SSL_CTX_use_PrivateKey_file \
  1539. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1540. #define SSL_CTX_use_certificate_file \
  1541. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1542. #define SSL_CTX_set_default_passwd_cb \
  1543. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1544. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1545. #define SSL_CTX_use_certificate_chain_file \
  1546. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1547. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1548. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1549. #define SSL_CTX_set_verify \
  1550. (*(void (*)(SSL_CTX *, \
  1551. int, \
  1552. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1553. .ptr)
  1554. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1555. #define SSL_CTX_load_verify_locations \
  1556. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1557. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1558. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1559. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1560. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1561. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1562. #define SSL_CIPHER_get_name \
  1563. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1564. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1565. #define SSL_CTX_set_session_id_context \
  1566. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1567. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1568. #define SSL_CTX_set_cipher_list \
  1569. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1570. #define SSL_CTX_set_options \
  1571. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1572. #define SSL_CTX_set_info_callback \
  1573. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1574. ssl_sw[32] \
  1575. .ptr)
  1576. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1577. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1578. #define SSL_CTX_callback_ctrl \
  1579. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1580. #define SSL_get_servername \
  1581. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1582. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1583. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1584. #define SSL_CTX_clear_options(ctx, op) \
  1585. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1586. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1587. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1588. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1589. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1590. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1591. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1592. SSL_CTX_callback_ctrl(ctx, \
  1593. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1594. (void (*)(void))cb)
  1595. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1596. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1597. #define SSL_set_tlsext_host_name(ctx, arg) \
  1598. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1599. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1600. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1601. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1602. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1603. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1604. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1605. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1606. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1607. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1608. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1609. #define X509_NAME_oneline \
  1610. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1611. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1612. #define EVP_get_digestbyname \
  1613. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1614. #define EVP_Digest \
  1615. (*(int (*)( \
  1616. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1617. crypto_sw[9] \
  1618. .ptr)
  1619. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1620. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1621. #define ASN1_INTEGER_to_BN \
  1622. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1623. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1624. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1625. #define OPENSSL_free(a) CRYPTO_free(a)
  1626. #define OPENSSL_REMOVE_THREAD_STATE()
  1627. /* init_ssl_ctx() function updates this array.
  1628. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1629. * of respective functions. The macros above (like SSL_connect()) are really
  1630. * just calling these functions indirectly via the pointer. */
  1631. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1632. {"SSL_accept", NULL},
  1633. {"SSL_connect", NULL},
  1634. {"SSL_read", NULL},
  1635. {"SSL_write", NULL},
  1636. {"SSL_get_error", NULL},
  1637. {"SSL_set_fd", NULL},
  1638. {"SSL_new", NULL},
  1639. {"SSL_CTX_new", NULL},
  1640. {"TLS_server_method", NULL},
  1641. {"OPENSSL_init_ssl", NULL},
  1642. {"SSL_CTX_use_PrivateKey_file", NULL},
  1643. {"SSL_CTX_use_certificate_file", NULL},
  1644. {"SSL_CTX_set_default_passwd_cb", NULL},
  1645. {"SSL_CTX_free", NULL},
  1646. {"SSL_CTX_use_certificate_chain_file", NULL},
  1647. {"TLS_client_method", NULL},
  1648. {"SSL_pending", NULL},
  1649. {"SSL_CTX_set_verify", NULL},
  1650. {"SSL_shutdown", NULL},
  1651. {"SSL_CTX_load_verify_locations", NULL},
  1652. {"SSL_CTX_set_default_verify_paths", NULL},
  1653. {"SSL_CTX_set_verify_depth", NULL},
  1654. {"SSL_get_peer_certificate", NULL},
  1655. {"SSL_get_version", NULL},
  1656. {"SSL_get_current_cipher", NULL},
  1657. {"SSL_CIPHER_get_name", NULL},
  1658. {"SSL_CTX_check_private_key", NULL},
  1659. {"SSL_CTX_set_session_id_context", NULL},
  1660. {"SSL_CTX_ctrl", NULL},
  1661. {"SSL_CTX_set_cipher_list", NULL},
  1662. {"SSL_CTX_set_options", NULL},
  1663. {"SSL_CTX_set_info_callback", NULL},
  1664. {"SSL_get_ex_data", NULL},
  1665. {"SSL_set_ex_data", NULL},
  1666. {"SSL_CTX_callback_ctrl", NULL},
  1667. {"SSL_get_servername", NULL},
  1668. {"SSL_set_SSL_CTX", NULL},
  1669. {"SSL_ctrl", NULL},
  1670. {NULL, NULL}};
  1671. /* Similar array as ssl_sw. These functions could be located in different
  1672. * lib. */
  1673. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1674. {"ERR_error_string", NULL},
  1675. {"CONF_modules_unload", NULL},
  1676. {"X509_free", NULL},
  1677. {"X509_get_subject_name", NULL},
  1678. {"X509_get_issuer_name", NULL},
  1679. {"X509_NAME_oneline", NULL},
  1680. {"X509_get_serialNumber", NULL},
  1681. {"EVP_get_digestbyname", NULL},
  1682. {"EVP_Digest", NULL},
  1683. {"i2d_X509", NULL},
  1684. {"BN_bn2hex", NULL},
  1685. {"ASN1_INTEGER_to_BN", NULL},
  1686. {"BN_free", NULL},
  1687. {"CRYPTO_free", NULL},
  1688. {NULL, NULL}};
  1689. #else
  1690. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1691. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1692. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1693. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1694. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1695. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1696. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1697. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1698. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1699. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1700. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1701. #define SSL_CTX_use_PrivateKey_file \
  1702. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1703. #define SSL_CTX_use_certificate_file \
  1704. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1705. #define SSL_CTX_set_default_passwd_cb \
  1706. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1707. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1708. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1709. #define SSL_CTX_use_certificate_chain_file \
  1710. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1711. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1712. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1713. #define SSL_CTX_set_verify \
  1714. (*(void (*)(SSL_CTX *, \
  1715. int, \
  1716. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1717. .ptr)
  1718. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1719. #define SSL_CTX_load_verify_locations \
  1720. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1721. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1722. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1723. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1724. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1725. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1726. #define SSL_CIPHER_get_name \
  1727. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1728. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1729. #define SSL_CTX_set_session_id_context \
  1730. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1731. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1732. #define SSL_CTX_set_cipher_list \
  1733. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1734. #define SSL_CTX_set_info_callback \
  1735. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1736. .ptr)
  1737. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1738. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1739. #define SSL_CTX_callback_ctrl \
  1740. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1741. #define SSL_get_servername \
  1742. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1743. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1744. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1745. #define SSL_CTX_set_options(ctx, op) \
  1746. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1747. #define SSL_CTX_clear_options(ctx, op) \
  1748. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1749. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1750. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1751. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1752. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1753. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1754. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1755. SSL_CTX_callback_ctrl(ctx, \
  1756. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1757. (void (*)(void))cb)
  1758. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1759. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1760. #define SSL_set_tlsext_host_name(ctx, arg) \
  1761. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1762. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1763. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1764. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1765. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1766. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1767. #define CRYPTO_set_locking_callback \
  1768. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1769. #define CRYPTO_set_id_callback \
  1770. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1771. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1772. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1773. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1774. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1775. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1776. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1777. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1778. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1779. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1780. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1781. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1782. #define X509_NAME_oneline \
  1783. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1784. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1785. #define i2c_ASN1_INTEGER \
  1786. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1787. #define EVP_get_digestbyname \
  1788. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1789. #define EVP_Digest \
  1790. (*(int (*)( \
  1791. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1792. crypto_sw[18] \
  1793. .ptr)
  1794. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1795. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1796. #define ASN1_INTEGER_to_BN \
  1797. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1798. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1799. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1800. #define OPENSSL_free(a) CRYPTO_free(a)
  1801. /* use here ERR_remove_state,
  1802. * while on some platforms function is not included into library due to
  1803. * deprication */
  1804. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1805. /* init_ssl_ctx() function updates this array.
  1806. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1807. * of respective functions. The macros above (like SSL_connect()) are really
  1808. * just calling these functions indirectly via the pointer. */
  1809. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1810. {"SSL_accept", NULL},
  1811. {"SSL_connect", NULL},
  1812. {"SSL_read", NULL},
  1813. {"SSL_write", NULL},
  1814. {"SSL_get_error", NULL},
  1815. {"SSL_set_fd", NULL},
  1816. {"SSL_new", NULL},
  1817. {"SSL_CTX_new", NULL},
  1818. {"SSLv23_server_method", NULL},
  1819. {"SSL_library_init", NULL},
  1820. {"SSL_CTX_use_PrivateKey_file", NULL},
  1821. {"SSL_CTX_use_certificate_file", NULL},
  1822. {"SSL_CTX_set_default_passwd_cb", NULL},
  1823. {"SSL_CTX_free", NULL},
  1824. {"SSL_load_error_strings", NULL},
  1825. {"SSL_CTX_use_certificate_chain_file", NULL},
  1826. {"SSLv23_client_method", NULL},
  1827. {"SSL_pending", NULL},
  1828. {"SSL_CTX_set_verify", NULL},
  1829. {"SSL_shutdown", NULL},
  1830. {"SSL_CTX_load_verify_locations", NULL},
  1831. {"SSL_CTX_set_default_verify_paths", NULL},
  1832. {"SSL_CTX_set_verify_depth", NULL},
  1833. {"SSL_get_peer_certificate", NULL},
  1834. {"SSL_get_version", NULL},
  1835. {"SSL_get_current_cipher", NULL},
  1836. {"SSL_CIPHER_get_name", NULL},
  1837. {"SSL_CTX_check_private_key", NULL},
  1838. {"SSL_CTX_set_session_id_context", NULL},
  1839. {"SSL_CTX_ctrl", NULL},
  1840. {"SSL_CTX_set_cipher_list", NULL},
  1841. {"SSL_CTX_set_info_callback", NULL},
  1842. {"SSL_get_ex_data", NULL},
  1843. {"SSL_set_ex_data", NULL},
  1844. {"SSL_CTX_callback_ctrl", NULL},
  1845. {"SSL_get_servername", NULL},
  1846. {"SSL_set_SSL_CTX", NULL},
  1847. {"SSL_ctrl", NULL},
  1848. {NULL, NULL}};
  1849. /* Similar array as ssl_sw. These functions could be located in different
  1850. * lib. */
  1851. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1852. {"CRYPTO_set_locking_callback", NULL},
  1853. {"CRYPTO_set_id_callback", NULL},
  1854. {"ERR_get_error", NULL},
  1855. {"ERR_error_string", NULL},
  1856. {"ERR_remove_state", NULL},
  1857. {"ERR_free_strings", NULL},
  1858. {"ENGINE_cleanup", NULL},
  1859. {"CONF_modules_unload", NULL},
  1860. {"CRYPTO_cleanup_all_ex_data", NULL},
  1861. {"EVP_cleanup", NULL},
  1862. {"X509_free", NULL},
  1863. {"X509_get_subject_name", NULL},
  1864. {"X509_get_issuer_name", NULL},
  1865. {"X509_NAME_oneline", NULL},
  1866. {"X509_get_serialNumber", NULL},
  1867. {"i2c_ASN1_INTEGER", NULL},
  1868. {"EVP_get_digestbyname", NULL},
  1869. {"EVP_Digest", NULL},
  1870. {"i2d_X509", NULL},
  1871. {"BN_bn2hex", NULL},
  1872. {"ASN1_INTEGER_to_BN", NULL},
  1873. {"BN_free", NULL},
  1874. {"CRYPTO_free", NULL},
  1875. {NULL, NULL}};
  1876. #endif /* OPENSSL_API_1_1 */
  1877. #endif /* NO_SSL_DL */
  1878. #endif /* NO_SSL */
  1879. #if !defined(NO_CACHING)
  1880. static const char *month_names[] = {"Jan",
  1881. "Feb",
  1882. "Mar",
  1883. "Apr",
  1884. "May",
  1885. "Jun",
  1886. "Jul",
  1887. "Aug",
  1888. "Sep",
  1889. "Oct",
  1890. "Nov",
  1891. "Dec"};
  1892. #endif /* !NO_CACHING */
  1893. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1894. * the
  1895. * union u. */
  1896. union usa {
  1897. struct sockaddr sa;
  1898. struct sockaddr_in sin;
  1899. #if defined(USE_IPV6)
  1900. struct sockaddr_in6 sin6;
  1901. #endif
  1902. };
  1903. /* Describes a string (chunk of memory). */
  1904. struct vec {
  1905. const char *ptr;
  1906. size_t len;
  1907. };
  1908. struct mg_file_stat {
  1909. /* File properties filled by mg_stat: */
  1910. uint64_t size;
  1911. time_t last_modified;
  1912. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1913. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1914. * case we need a "Content-Eencoding: gzip" header */
  1915. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1916. };
  1917. struct mg_file_in_memory {
  1918. char *p;
  1919. uint32_t pos;
  1920. char mode;
  1921. };
  1922. struct mg_file_access {
  1923. /* File properties filled by mg_fopen: */
  1924. FILE *fp;
  1925. #if defined(MG_USE_OPEN_FILE)
  1926. /* TODO (low): Remove obsolete "file in memory" implementation.
  1927. * In an "early 2017" discussion at Google groups
  1928. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1929. * we decided to get rid of this feature (after some fade-out
  1930. * phase). */
  1931. const char *membuf;
  1932. #endif
  1933. };
  1934. struct mg_file {
  1935. struct mg_file_stat stat;
  1936. struct mg_file_access access;
  1937. };
  1938. #if defined(MG_USE_OPEN_FILE)
  1939. #define STRUCT_FILE_INITIALIZER \
  1940. { \
  1941. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1942. { \
  1943. (FILE *)NULL, (const char *)NULL \
  1944. } \
  1945. }
  1946. #else
  1947. #define STRUCT_FILE_INITIALIZER \
  1948. { \
  1949. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1950. { \
  1951. (FILE *)NULL \
  1952. } \
  1953. }
  1954. #endif
  1955. /* Describes listening socket, or socket which was accept()-ed by the master
  1956. * thread and queued for future handling by the worker thread. */
  1957. struct socket {
  1958. SOCKET sock; /* Listening socket */
  1959. union usa lsa; /* Local socket address */
  1960. union usa rsa; /* Remote socket address */
  1961. unsigned char is_ssl; /* Is port SSL-ed */
  1962. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1963. * port */
  1964. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1965. };
  1966. /* Enum const for all options must be in sync with
  1967. * static struct mg_option config_options[]
  1968. * This is tested in the unit test (test/private.c)
  1969. * "Private Config Options"
  1970. */
  1971. enum {
  1972. /* Once for each server */
  1973. LISTENING_PORTS,
  1974. NUM_THREADS,
  1975. RUN_AS_USER,
  1976. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1977. * socket option typedef TCP_NODELAY. */
  1978. MAX_REQUEST_SIZE,
  1979. LINGER_TIMEOUT,
  1980. #if defined(__linux__)
  1981. ALLOW_SENDFILE_CALL,
  1982. #endif
  1983. #if defined(_WIN32)
  1984. CASE_SENSITIVE_FILES,
  1985. #endif
  1986. THROTTLE,
  1987. ACCESS_LOG_FILE,
  1988. ERROR_LOG_FILE,
  1989. ENABLE_KEEP_ALIVE,
  1990. REQUEST_TIMEOUT,
  1991. KEEP_ALIVE_TIMEOUT,
  1992. #if defined(USE_WEBSOCKET)
  1993. WEBSOCKET_TIMEOUT,
  1994. ENABLE_WEBSOCKET_PING_PONG,
  1995. #endif
  1996. DECODE_URL,
  1997. #if defined(USE_LUA)
  1998. LUA_BACKGROUND_SCRIPT,
  1999. LUA_BACKGROUND_SCRIPT_PARAMS,
  2000. #endif
  2001. #if defined(USE_TIMERS)
  2002. CGI_TIMEOUT,
  2003. #endif
  2004. /* Once for each domain */
  2005. DOCUMENT_ROOT,
  2006. CGI_EXTENSIONS,
  2007. CGI_ENVIRONMENT,
  2008. PUT_DELETE_PASSWORDS_FILE,
  2009. CGI_INTERPRETER,
  2010. PROTECT_URI,
  2011. AUTHENTICATION_DOMAIN,
  2012. ENABLE_AUTH_DOMAIN_CHECK,
  2013. SSI_EXTENSIONS,
  2014. ENABLE_DIRECTORY_LISTING,
  2015. GLOBAL_PASSWORDS_FILE,
  2016. INDEX_FILES,
  2017. ACCESS_CONTROL_LIST,
  2018. EXTRA_MIME_TYPES,
  2019. SSL_CERTIFICATE,
  2020. SSL_CERTIFICATE_CHAIN,
  2021. URL_REWRITE_PATTERN,
  2022. HIDE_FILES,
  2023. SSL_DO_VERIFY_PEER,
  2024. SSL_CA_PATH,
  2025. SSL_CA_FILE,
  2026. SSL_VERIFY_DEPTH,
  2027. SSL_DEFAULT_VERIFY_PATHS,
  2028. SSL_CIPHER_LIST,
  2029. SSL_PROTOCOL_VERSION,
  2030. SSL_SHORT_TRUST,
  2031. #if defined(USE_LUA)
  2032. LUA_PRELOAD_FILE,
  2033. LUA_SCRIPT_EXTENSIONS,
  2034. LUA_SERVER_PAGE_EXTENSIONS,
  2035. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2036. LUA_DEBUG_PARAMS,
  2037. #endif
  2038. #endif
  2039. #if defined(USE_DUKTAPE)
  2040. DUKTAPE_SCRIPT_EXTENSIONS,
  2041. #endif
  2042. #if defined(USE_WEBSOCKET)
  2043. WEBSOCKET_ROOT,
  2044. #endif
  2045. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2046. LUA_WEBSOCKET_EXTENSIONS,
  2047. #endif
  2048. ACCESS_CONTROL_ALLOW_ORIGIN,
  2049. ACCESS_CONTROL_ALLOW_METHODS,
  2050. ACCESS_CONTROL_ALLOW_HEADERS,
  2051. ERROR_PAGES,
  2052. #if !defined(NO_CACHING)
  2053. STATIC_FILE_MAX_AGE,
  2054. #endif
  2055. #if !defined(NO_SSL)
  2056. STRICT_HTTPS_MAX_AGE,
  2057. #endif
  2058. ADDITIONAL_HEADER,
  2059. ALLOW_INDEX_SCRIPT_SUB_RES,
  2060. #if defined(DAEMONIZE)
  2061. ENABLE_DAEMONIZE,
  2062. #endif
  2063. NUM_OPTIONS
  2064. };
  2065. /* Config option name, config types, default value.
  2066. * Must be in the same order as the enum const above.
  2067. */
  2068. static const struct mg_option config_options[] = {
  2069. /* Once for each server */
  2070. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2071. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2072. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2073. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2074. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2075. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2076. #if defined(__linux__)
  2077. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2078. #endif
  2079. #if defined(_WIN32)
  2080. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2081. #endif
  2082. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2083. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2084. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2085. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2086. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2087. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2088. #if defined(USE_WEBSOCKET)
  2089. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2090. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2091. #endif
  2092. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2093. #if defined(USE_LUA)
  2094. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2095. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2096. #endif
  2097. #if defined(USE_TIMERS)
  2098. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2099. #endif
  2100. /* Once for each domain */
  2101. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2102. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2103. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2104. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2105. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2106. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2107. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2108. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2109. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2110. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2111. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2112. {"index_files",
  2113. MG_CONFIG_TYPE_STRING_LIST,
  2114. #if defined(USE_LUA)
  2115. "index.xhtml,index.html,index.htm,"
  2116. "index.lp,index.lsp,index.lua,index.cgi,"
  2117. "index.shtml,index.php"},
  2118. #else
  2119. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2120. #endif
  2121. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2122. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2123. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2124. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2125. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2126. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2127. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2128. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2129. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2130. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2131. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2132. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2133. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2134. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2135. #if defined(USE_LUA)
  2136. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2137. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2138. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2139. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2140. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2141. #endif
  2142. #endif
  2143. #if defined(USE_DUKTAPE)
  2144. /* The support for duktape is still in alpha version state.
  2145. * The name of this config option might change. */
  2146. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2147. #endif
  2148. #if defined(USE_WEBSOCKET)
  2149. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2150. #endif
  2151. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2152. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2153. #endif
  2154. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2155. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2156. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2157. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2158. #if !defined(NO_CACHING)
  2159. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2160. #endif
  2161. #if !defined(NO_SSL)
  2162. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2163. #endif
  2164. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2165. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2166. #if defined(DAEMONIZE)
  2167. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2168. #endif
  2169. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2170. /* Check if the config_options and the corresponding enum have compatible
  2171. * sizes. */
  2172. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2173. == (NUM_OPTIONS + 1),
  2174. "config_options and enum not sync");
  2175. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2176. struct mg_handler_info {
  2177. /* Name/Pattern of the URI. */
  2178. char *uri;
  2179. size_t uri_len;
  2180. /* handler type */
  2181. int handler_type;
  2182. /* Handler for http/https or authorization requests. */
  2183. mg_request_handler handler;
  2184. unsigned int refcount;
  2185. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2186. pthread_cond_t
  2187. refcount_cond; /* Signaled when handler refcount is decremented */
  2188. /* Handler for ws/wss (websocket) requests. */
  2189. mg_websocket_connect_handler connect_handler;
  2190. mg_websocket_ready_handler ready_handler;
  2191. mg_websocket_data_handler data_handler;
  2192. mg_websocket_close_handler close_handler;
  2193. /* accepted subprotocols for ws/wss requests. */
  2194. struct mg_websocket_subprotocols *subprotocols;
  2195. /* Handler for authorization requests */
  2196. mg_authorization_handler auth_handler;
  2197. /* User supplied argument for the handler function. */
  2198. void *cbdata;
  2199. /* next handler in a linked list */
  2200. struct mg_handler_info *next;
  2201. };
  2202. enum {
  2203. CONTEXT_INVALID,
  2204. CONTEXT_SERVER,
  2205. CONTEXT_HTTP_CLIENT,
  2206. CONTEXT_WS_CLIENT
  2207. };
  2208. struct mg_domain_context {
  2209. SSL_CTX *ssl_ctx; /* SSL context */
  2210. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2211. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2212. /* Server nonce */
  2213. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2214. unsigned long nonce_count; /* Used nonces, used for authentication */
  2215. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2216. /* linked list of shared lua websockets */
  2217. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2218. #endif
  2219. /* Linked list of domains */
  2220. struct mg_domain_context *next;
  2221. };
  2222. struct mg_context {
  2223. /* Part 1 - Physical context:
  2224. * This holds threads, ports, timeouts, ...
  2225. * set for the entire server, independent from the
  2226. * addressed hostname.
  2227. */
  2228. /* Connection related */
  2229. int context_type; /* See CONTEXT_* above */
  2230. struct socket *listening_sockets;
  2231. struct mg_pollfd *listening_socket_fds;
  2232. unsigned int num_listening_sockets;
  2233. struct mg_connection *worker_connections; /* The connection struct, pre-
  2234. * allocated for each worker */
  2235. #if defined(USE_SERVER_STATS)
  2236. int active_connections;
  2237. int max_connections;
  2238. int64_t total_connections;
  2239. int64_t total_requests;
  2240. int64_t total_data_read;
  2241. int64_t total_data_written;
  2242. #endif
  2243. /* Thread related */
  2244. volatile int stop_flag; /* Should we stop event loop */
  2245. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2246. pthread_t masterthreadid; /* The master thread ID */
  2247. unsigned int
  2248. cfg_worker_threads; /* The number of configured worker threads. */
  2249. pthread_t *worker_threadids; /* The worker thread IDs */
  2250. /* Connection to thread dispatching */
  2251. #if defined(ALTERNATIVE_QUEUE)
  2252. struct socket *client_socks;
  2253. void **client_wait_events;
  2254. #else
  2255. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2256. volatile int sq_head; /* Head of the socket queue */
  2257. volatile int sq_tail; /* Tail of the socket queue */
  2258. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2259. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2260. #endif
  2261. /* Memory related */
  2262. unsigned int max_request_size; /* The max request size */
  2263. #if defined(USE_SERVER_STATS)
  2264. struct mg_memory_stat ctx_memory;
  2265. #endif
  2266. /* Operating system related */
  2267. char *systemName; /* What operating system is running */
  2268. time_t start_time; /* Server start time, used for authentication
  2269. * and for diagnstics. */
  2270. #if defined(USE_TIMERS)
  2271. struct ttimers *timers;
  2272. #endif
  2273. /* Lua specific: Background operations and shared websockets */
  2274. #if defined(USE_LUA)
  2275. void *lua_background_state;
  2276. #endif
  2277. /* Server nonce */
  2278. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2279. /* Server callbacks */
  2280. struct mg_callbacks callbacks; /* User-defined callback function */
  2281. void *user_data; /* User-defined data */
  2282. /* Part 2 - Logical domain:
  2283. * This holds hostname, TLS certificate, document root, ...
  2284. * set for a domain hosted at the server.
  2285. * There may be multiple domains hosted at one physical server.
  2286. * The default domain "dd" is the first element of a list of
  2287. * domains.
  2288. */
  2289. struct mg_domain_context dd; /* default domain */
  2290. };
  2291. #if defined(USE_SERVER_STATS)
  2292. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2293. static struct mg_memory_stat *
  2294. get_memory_stat(struct mg_context *ctx)
  2295. {
  2296. if (ctx) {
  2297. return &(ctx->ctx_memory);
  2298. }
  2299. return &mg_common_memory;
  2300. }
  2301. #endif
  2302. enum {
  2303. CONNECTION_TYPE_INVALID,
  2304. CONNECTION_TYPE_REQUEST,
  2305. CONNECTION_TYPE_RESPONSE
  2306. };
  2307. struct mg_connection {
  2308. int connection_type; /* see CONNECTION_TYPE_* above */
  2309. struct mg_request_info request_info;
  2310. struct mg_response_info response_info;
  2311. struct mg_context *phys_ctx;
  2312. struct mg_domain_context *dom_ctx;
  2313. #if defined(USE_SERVER_STATS)
  2314. int conn_state; /* 0 = undef, numerical value may change in different
  2315. * versions. For the current definition, see
  2316. * mg_get_connection_info_impl */
  2317. #endif
  2318. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2319. SSL *ssl; /* SSL descriptor */
  2320. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2321. struct socket client; /* Connected client */
  2322. time_t conn_birth_time; /* Time (wall clock) when connection was
  2323. * established */
  2324. struct timespec req_time; /* Time (since system start) when the request
  2325. * was received */
  2326. int64_t num_bytes_sent; /* Total bytes sent to client */
  2327. int64_t content_len; /* Content-Length header value */
  2328. int64_t consumed_content; /* How many bytes of content have been read */
  2329. int is_chunked; /* Transfer-Encoding is chunked:
  2330. * 0 = not chunked,
  2331. * 1 = chunked, do data read yet,
  2332. * 2 = chunked, some data read,
  2333. * 3 = chunked, all data read
  2334. */
  2335. size_t chunk_remainder; /* Unread data from the last chunk */
  2336. char *buf; /* Buffer for received data */
  2337. char *path_info; /* PATH_INFO part of the URL */
  2338. int must_close; /* 1 if connection must be closed */
  2339. int accept_gzip; /* 1 if gzip encoding is accepted */
  2340. int in_error_handler; /* 1 if in handler for user defined error
  2341. * pages */
  2342. #if defined(USE_WEBSOCKET)
  2343. int in_websocket_handling; /* 1 if in read_websocket */
  2344. #endif
  2345. int handled_requests; /* Number of requests handled by this connection
  2346. */
  2347. int buf_size; /* Buffer size */
  2348. int request_len; /* Size of the request + headers in a buffer */
  2349. int data_len; /* Total size of data in a buffer */
  2350. int status_code; /* HTTP reply status code, e.g. 200 */
  2351. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2352. * throttle */
  2353. time_t last_throttle_time; /* Last time throttled data was sent */
  2354. int64_t last_throttle_bytes; /* Bytes sent this second */
  2355. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2356. * atomic transmissions for websockets */
  2357. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2358. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2359. #endif
  2360. int thread_index; /* Thread index within ctx */
  2361. };
  2362. /* Directory entry */
  2363. struct de {
  2364. struct mg_connection *conn;
  2365. char *file_name;
  2366. struct mg_file_stat file;
  2367. };
  2368. #if defined(USE_WEBSOCKET)
  2369. static int is_websocket_protocol(const struct mg_connection *conn);
  2370. #else
  2371. #define is_websocket_protocol(conn) (0)
  2372. #endif
  2373. #define mg_cry_internal(conn, fmt, ...) \
  2374. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2375. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2376. const char *func,
  2377. unsigned line,
  2378. const char *fmt,
  2379. ...) PRINTF_ARGS(4, 5);
  2380. #if !defined(NO_THREAD_NAME)
  2381. #if defined(_WIN32) && defined(_MSC_VER)
  2382. /* Set the thread name for debugging purposes in Visual Studio
  2383. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2384. */
  2385. #pragma pack(push, 8)
  2386. typedef struct tagTHREADNAME_INFO {
  2387. DWORD dwType; /* Must be 0x1000. */
  2388. LPCSTR szName; /* Pointer to name (in user addr space). */
  2389. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2390. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2391. } THREADNAME_INFO;
  2392. #pragma pack(pop)
  2393. #elif defined(__linux__)
  2394. #include <sys/prctl.h>
  2395. #include <sys/sendfile.h>
  2396. #if defined(ALTERNATIVE_QUEUE)
  2397. #include <sys/eventfd.h>
  2398. #endif /* ALTERNATIVE_QUEUE */
  2399. #if defined(ALTERNATIVE_QUEUE)
  2400. static void *
  2401. event_create(void)
  2402. {
  2403. int evhdl = eventfd(0, EFD_CLOEXEC);
  2404. int *ret;
  2405. if (evhdl == -1) {
  2406. /* Linux uses -1 on error, Windows NULL. */
  2407. /* However, Linux does not return 0 on success either. */
  2408. return 0;
  2409. }
  2410. ret = (int *)mg_malloc(sizeof(int));
  2411. if (ret) {
  2412. *ret = evhdl;
  2413. } else {
  2414. (void)close(evhdl);
  2415. }
  2416. return (void *)ret;
  2417. }
  2418. static int
  2419. event_wait(void *eventhdl)
  2420. {
  2421. uint64_t u;
  2422. int evhdl, s;
  2423. if (!eventhdl) {
  2424. /* error */
  2425. return 0;
  2426. }
  2427. evhdl = *(int *)eventhdl;
  2428. s = (int)read(evhdl, &u, sizeof(u));
  2429. if (s != sizeof(u)) {
  2430. /* error */
  2431. return 0;
  2432. }
  2433. (void)u; /* the value is not required */
  2434. return 1;
  2435. }
  2436. static int
  2437. event_signal(void *eventhdl)
  2438. {
  2439. uint64_t u = 1;
  2440. int evhdl, s;
  2441. if (!eventhdl) {
  2442. /* error */
  2443. return 0;
  2444. }
  2445. evhdl = *(int *)eventhdl;
  2446. s = (int)write(evhdl, &u, sizeof(u));
  2447. if (s != sizeof(u)) {
  2448. /* error */
  2449. return 0;
  2450. }
  2451. return 1;
  2452. }
  2453. static void
  2454. event_destroy(void *eventhdl)
  2455. {
  2456. int evhdl;
  2457. if (!eventhdl) {
  2458. /* error */
  2459. return;
  2460. }
  2461. evhdl = *(int *)eventhdl;
  2462. close(evhdl);
  2463. mg_free(eventhdl);
  2464. }
  2465. #endif
  2466. #endif
  2467. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2468. struct posix_event {
  2469. pthread_mutex_t mutex;
  2470. pthread_cond_t cond;
  2471. int signaled;
  2472. };
  2473. static void *
  2474. event_create(void)
  2475. {
  2476. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2477. if (ret == 0) {
  2478. /* out of memory */
  2479. return 0;
  2480. }
  2481. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2482. /* pthread mutex not available */
  2483. mg_free(ret);
  2484. return 0;
  2485. }
  2486. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2487. /* pthread cond not available */
  2488. pthread_mutex_destroy(&(ret->mutex));
  2489. mg_free(ret);
  2490. return 0;
  2491. }
  2492. ret->signaled = 0;
  2493. return (void *)ret;
  2494. }
  2495. static int
  2496. event_wait(void *eventhdl)
  2497. {
  2498. struct posix_event *ev = (struct posix_event *)eventhdl;
  2499. pthread_mutex_lock(&(ev->mutex));
  2500. while (!ev->signaled) {
  2501. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2502. }
  2503. ev->signaled = 0;
  2504. pthread_mutex_unlock(&(ev->mutex));
  2505. return 1;
  2506. }
  2507. static int
  2508. event_signal(void *eventhdl)
  2509. {
  2510. struct posix_event *ev = (struct posix_event *)eventhdl;
  2511. pthread_mutex_lock(&(ev->mutex));
  2512. pthread_cond_signal(&(ev->cond));
  2513. ev->signaled = 1;
  2514. pthread_mutex_unlock(&(ev->mutex));
  2515. return 1;
  2516. }
  2517. static void
  2518. event_destroy(void *eventhdl)
  2519. {
  2520. struct posix_event *ev = (struct posix_event *)eventhdl;
  2521. pthread_cond_destroy(&(ev->cond));
  2522. pthread_mutex_destroy(&(ev->mutex));
  2523. mg_free(ev);
  2524. }
  2525. #endif
  2526. static void
  2527. mg_set_thread_name(const char *name)
  2528. {
  2529. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2530. mg_snprintf(
  2531. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2532. #if defined(_WIN32)
  2533. #if defined(_MSC_VER)
  2534. /* Windows and Visual Studio Compiler */
  2535. __try {
  2536. THREADNAME_INFO info;
  2537. info.dwType = 0x1000;
  2538. info.szName = threadName;
  2539. info.dwThreadID = ~0U;
  2540. info.dwFlags = 0;
  2541. RaiseException(0x406D1388,
  2542. 0,
  2543. sizeof(info) / sizeof(ULONG_PTR),
  2544. (ULONG_PTR *)&info);
  2545. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2546. }
  2547. #elif defined(__MINGW32__)
  2548. /* No option known to set thread name for MinGW */
  2549. #endif
  2550. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2551. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2552. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2553. #if defined(__MACH__)
  2554. /* OS X only current thread name can be changed */
  2555. (void)pthread_setname_np(threadName);
  2556. #else
  2557. (void)pthread_setname_np(pthread_self(), threadName);
  2558. #endif
  2559. #elif defined(__linux__)
  2560. /* on linux we can use the old prctl function */
  2561. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2562. #endif
  2563. }
  2564. #else /* !defined(NO_THREAD_NAME) */
  2565. void
  2566. mg_set_thread_name(const char *threadName)
  2567. {
  2568. }
  2569. #endif
  2570. #if defined(MG_LEGACY_INTERFACE)
  2571. const char **
  2572. mg_get_valid_option_names(void)
  2573. {
  2574. /* This function is deprecated. Use mg_get_valid_options instead. */
  2575. static const char
  2576. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2577. int i;
  2578. for (i = 0; config_options[i].name != NULL; i++) {
  2579. data[i * 2] = config_options[i].name;
  2580. data[i * 2 + 1] = config_options[i].default_value;
  2581. }
  2582. return data;
  2583. }
  2584. #endif
  2585. const struct mg_option *
  2586. mg_get_valid_options(void)
  2587. {
  2588. return config_options;
  2589. }
  2590. /* Do not open file (used in is_file_in_memory) */
  2591. #define MG_FOPEN_MODE_NONE (0)
  2592. /* Open file for read only access */
  2593. #define MG_FOPEN_MODE_READ (1)
  2594. /* Open file for writing, create and overwrite */
  2595. #define MG_FOPEN_MODE_WRITE (2)
  2596. /* Open file for writing, create and append */
  2597. #define MG_FOPEN_MODE_APPEND (4)
  2598. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2599. * output filep and return 1, otherwise return 0 and don't modify anything.
  2600. */
  2601. static int
  2602. open_file_in_memory(const struct mg_connection *conn,
  2603. const char *path,
  2604. struct mg_file *filep,
  2605. int mode)
  2606. {
  2607. #if defined(MG_USE_OPEN_FILE)
  2608. size_t size = 0;
  2609. const char *buf = NULL;
  2610. if (!conn) {
  2611. return 0;
  2612. }
  2613. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2614. return 0;
  2615. }
  2616. if (conn->phys_ctx->callbacks.open_file) {
  2617. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2618. if (buf != NULL) {
  2619. if (filep == NULL) {
  2620. /* This is a file in memory, but we cannot store the
  2621. * properties
  2622. * now.
  2623. * Called from "is_file_in_memory" function. */
  2624. return 1;
  2625. }
  2626. /* NOTE: override filep->size only on success. Otherwise, it
  2627. * might
  2628. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2629. filep->access.membuf = buf;
  2630. filep->access.fp = NULL;
  2631. /* Size was set by the callback */
  2632. filep->stat.size = size;
  2633. /* Assume the data may change during runtime by setting
  2634. * last_modified = now */
  2635. filep->stat.last_modified = time(NULL);
  2636. filep->stat.is_directory = 0;
  2637. filep->stat.is_gzipped = 0;
  2638. }
  2639. }
  2640. return (buf != NULL);
  2641. #else
  2642. (void)conn;
  2643. (void)path;
  2644. (void)filep;
  2645. (void)mode;
  2646. return 0;
  2647. #endif
  2648. }
  2649. static int
  2650. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2651. {
  2652. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2653. }
  2654. static int
  2655. is_file_opened(const struct mg_file_access *fileacc)
  2656. {
  2657. if (!fileacc) {
  2658. return 0;
  2659. }
  2660. #if defined(MG_USE_OPEN_FILE)
  2661. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2662. #else
  2663. return (fileacc->fp != NULL);
  2664. #endif
  2665. }
  2666. static int mg_stat(const struct mg_connection *conn,
  2667. const char *path,
  2668. struct mg_file_stat *filep);
  2669. /* mg_fopen will open a file either in memory or on the disk.
  2670. * The input parameter path is a string in UTF-8 encoding.
  2671. * The input parameter mode is MG_FOPEN_MODE_*
  2672. * On success, either fp or membuf will be set in the output
  2673. * struct file. All status members will also be set.
  2674. * The function returns 1 on success, 0 on error. */
  2675. static int
  2676. mg_fopen(const struct mg_connection *conn,
  2677. const char *path,
  2678. int mode,
  2679. struct mg_file *filep)
  2680. {
  2681. int found;
  2682. if (!filep) {
  2683. return 0;
  2684. }
  2685. filep->access.fp = NULL;
  2686. #if defined(MG_USE_OPEN_FILE)
  2687. filep->access.membuf = NULL;
  2688. #endif
  2689. if (!is_file_in_memory(conn, path)) {
  2690. /* filep is initialized in mg_stat: all fields with memset to,
  2691. * some fields like size and modification date with values */
  2692. found = mg_stat(conn, path, &(filep->stat));
  2693. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2694. /* file does not exist and will not be created */
  2695. return 0;
  2696. }
  2697. #if defined(_WIN32)
  2698. {
  2699. wchar_t wbuf[W_PATH_MAX];
  2700. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2701. switch (mode) {
  2702. case MG_FOPEN_MODE_READ:
  2703. filep->access.fp = _wfopen(wbuf, L"rb");
  2704. break;
  2705. case MG_FOPEN_MODE_WRITE:
  2706. filep->access.fp = _wfopen(wbuf, L"wb");
  2707. break;
  2708. case MG_FOPEN_MODE_APPEND:
  2709. filep->access.fp = _wfopen(wbuf, L"ab");
  2710. break;
  2711. }
  2712. }
  2713. #else
  2714. /* Linux et al already use unicode. No need to convert. */
  2715. switch (mode) {
  2716. case MG_FOPEN_MODE_READ:
  2717. filep->access.fp = fopen(path, "r");
  2718. break;
  2719. case MG_FOPEN_MODE_WRITE:
  2720. filep->access.fp = fopen(path, "w");
  2721. break;
  2722. case MG_FOPEN_MODE_APPEND:
  2723. filep->access.fp = fopen(path, "a");
  2724. break;
  2725. }
  2726. #endif
  2727. if (!found) {
  2728. /* File did not exist before fopen was called.
  2729. * Maybe it has been created now. Get stat info
  2730. * like creation time now. */
  2731. found = mg_stat(conn, path, &(filep->stat));
  2732. (void)found;
  2733. }
  2734. /* file is on disk */
  2735. return (filep->access.fp != NULL);
  2736. } else {
  2737. #if defined(MG_USE_OPEN_FILE)
  2738. /* is_file_in_memory returned true */
  2739. if (open_file_in_memory(conn, path, filep, mode)) {
  2740. /* file is in memory */
  2741. return (filep->access.membuf != NULL);
  2742. }
  2743. #endif
  2744. }
  2745. /* Open failed */
  2746. return 0;
  2747. }
  2748. /* return 0 on success, just like fclose */
  2749. static int
  2750. mg_fclose(struct mg_file_access *fileacc)
  2751. {
  2752. int ret = -1;
  2753. if (fileacc != NULL) {
  2754. if (fileacc->fp != NULL) {
  2755. ret = fclose(fileacc->fp);
  2756. #if defined(MG_USE_OPEN_FILE)
  2757. } else if (fileacc->membuf != NULL) {
  2758. ret = 0;
  2759. #endif
  2760. }
  2761. /* reset all members of fileacc */
  2762. memset(fileacc, 0, sizeof(*fileacc));
  2763. }
  2764. return ret;
  2765. }
  2766. static void
  2767. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2768. {
  2769. for (; *src != '\0' && n > 1; n--) {
  2770. *dst++ = *src++;
  2771. }
  2772. *dst = '\0';
  2773. }
  2774. static int
  2775. lowercase(const char *s)
  2776. {
  2777. return tolower(*(const unsigned char *)s);
  2778. }
  2779. int
  2780. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2781. {
  2782. int diff = 0;
  2783. if (len > 0) {
  2784. do {
  2785. diff = lowercase(s1++) - lowercase(s2++);
  2786. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2787. }
  2788. return diff;
  2789. }
  2790. int
  2791. mg_strcasecmp(const char *s1, const char *s2)
  2792. {
  2793. int diff;
  2794. do {
  2795. diff = lowercase(s1++) - lowercase(s2++);
  2796. } while (diff == 0 && s1[-1] != '\0');
  2797. return diff;
  2798. }
  2799. static char *
  2800. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2801. {
  2802. char *p;
  2803. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2804. * defined */
  2805. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2806. mg_strlcpy(p, ptr, len + 1);
  2807. }
  2808. return p;
  2809. }
  2810. static char *
  2811. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2812. {
  2813. return mg_strndup_ctx(str, strlen(str), ctx);
  2814. }
  2815. static char *
  2816. mg_strdup(const char *str)
  2817. {
  2818. return mg_strndup_ctx(str, strlen(str), NULL);
  2819. }
  2820. static const char *
  2821. mg_strcasestr(const char *big_str, const char *small_str)
  2822. {
  2823. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2824. if (big_len >= small_len) {
  2825. for (i = 0; i <= (big_len - small_len); i++) {
  2826. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2827. return big_str + i;
  2828. }
  2829. }
  2830. }
  2831. return NULL;
  2832. }
  2833. /* Return null terminated string of given maximum length.
  2834. * Report errors if length is exceeded. */
  2835. static void
  2836. mg_vsnprintf(const struct mg_connection *conn,
  2837. int *truncated,
  2838. char *buf,
  2839. size_t buflen,
  2840. const char *fmt,
  2841. va_list ap)
  2842. {
  2843. int n, ok;
  2844. if (buflen == 0) {
  2845. if (truncated) {
  2846. *truncated = 1;
  2847. }
  2848. return;
  2849. }
  2850. #if defined(__clang__)
  2851. #pragma clang diagnostic push
  2852. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2853. /* Using fmt as a non-literal is intended here, since it is mostly called
  2854. * indirectly by mg_snprintf */
  2855. #endif
  2856. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2857. ok = (n >= 0) && ((size_t)n < buflen);
  2858. #if defined(__clang__)
  2859. #pragma clang diagnostic pop
  2860. #endif
  2861. if (ok) {
  2862. if (truncated) {
  2863. *truncated = 0;
  2864. }
  2865. } else {
  2866. if (truncated) {
  2867. *truncated = 1;
  2868. }
  2869. mg_cry_internal(conn,
  2870. "truncating vsnprintf buffer: [%.*s]",
  2871. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2872. buf);
  2873. n = (int)buflen - 1;
  2874. }
  2875. buf[n] = '\0';
  2876. }
  2877. static void
  2878. mg_snprintf(const struct mg_connection *conn,
  2879. int *truncated,
  2880. char *buf,
  2881. size_t buflen,
  2882. const char *fmt,
  2883. ...)
  2884. {
  2885. va_list ap;
  2886. va_start(ap, fmt);
  2887. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2888. va_end(ap);
  2889. }
  2890. static int
  2891. get_option_index(const char *name)
  2892. {
  2893. int i;
  2894. for (i = 0; config_options[i].name != NULL; i++) {
  2895. if (strcmp(config_options[i].name, name) == 0) {
  2896. return i;
  2897. }
  2898. }
  2899. return -1;
  2900. }
  2901. const char *
  2902. mg_get_option(const struct mg_context *ctx, const char *name)
  2903. {
  2904. int i;
  2905. if ((i = get_option_index(name)) == -1) {
  2906. return NULL;
  2907. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2908. return "";
  2909. } else {
  2910. return ctx->dd.config[i];
  2911. }
  2912. }
  2913. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2914. struct mg_context *
  2915. mg_get_context(const struct mg_connection *conn)
  2916. {
  2917. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2918. }
  2919. void *
  2920. mg_get_user_data(const struct mg_context *ctx)
  2921. {
  2922. return (ctx == NULL) ? NULL : ctx->user_data;
  2923. }
  2924. void
  2925. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2926. {
  2927. if (conn != NULL) {
  2928. conn->request_info.conn_data = data;
  2929. }
  2930. }
  2931. void *
  2932. mg_get_user_connection_data(const struct mg_connection *conn)
  2933. {
  2934. if (conn != NULL) {
  2935. return conn->request_info.conn_data;
  2936. }
  2937. return NULL;
  2938. }
  2939. #if defined(MG_LEGACY_INTERFACE)
  2940. /* Deprecated: Use mg_get_server_ports instead. */
  2941. size_t
  2942. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2943. {
  2944. size_t i;
  2945. if (!ctx) {
  2946. return 0;
  2947. }
  2948. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2949. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2950. ports[i] =
  2951. #if defined(USE_IPV6)
  2952. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2953. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2954. :
  2955. #endif
  2956. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2957. }
  2958. return i;
  2959. }
  2960. #endif
  2961. int
  2962. mg_get_server_ports(const struct mg_context *ctx,
  2963. int size,
  2964. struct mg_server_ports *ports)
  2965. {
  2966. int i, cnt = 0;
  2967. if (size <= 0) {
  2968. return -1;
  2969. }
  2970. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2971. if (!ctx) {
  2972. return -1;
  2973. }
  2974. if (!ctx->listening_sockets) {
  2975. return -1;
  2976. }
  2977. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2978. ports[cnt].port =
  2979. #if defined(USE_IPV6)
  2980. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2981. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2982. :
  2983. #endif
  2984. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2985. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2986. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2987. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2988. /* IPv4 */
  2989. ports[cnt].protocol = 1;
  2990. cnt++;
  2991. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2992. /* IPv6 */
  2993. ports[cnt].protocol = 3;
  2994. cnt++;
  2995. }
  2996. }
  2997. return cnt;
  2998. }
  2999. static void
  3000. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3001. {
  3002. buf[0] = '\0';
  3003. if (!usa) {
  3004. return;
  3005. }
  3006. if (usa->sa.sa_family == AF_INET) {
  3007. getnameinfo(&usa->sa,
  3008. sizeof(usa->sin),
  3009. buf,
  3010. (unsigned)len,
  3011. NULL,
  3012. 0,
  3013. NI_NUMERICHOST);
  3014. }
  3015. #if defined(USE_IPV6)
  3016. else if (usa->sa.sa_family == AF_INET6) {
  3017. getnameinfo(&usa->sa,
  3018. sizeof(usa->sin6),
  3019. buf,
  3020. (unsigned)len,
  3021. NULL,
  3022. 0,
  3023. NI_NUMERICHOST);
  3024. }
  3025. #endif
  3026. }
  3027. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3028. * included in all responses other than 100, 101, 5xx. */
  3029. static void
  3030. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3031. {
  3032. #if !defined(REENTRANT_TIME)
  3033. struct tm *tm;
  3034. tm = ((t != NULL) ? gmtime(t) : NULL);
  3035. if (tm != NULL) {
  3036. #else
  3037. struct tm _tm;
  3038. struct tm *tm = &_tm;
  3039. if (t != NULL) {
  3040. gmtime_r(t, tm);
  3041. #endif
  3042. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3043. } else {
  3044. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3045. buf[buf_len - 1] = '\0';
  3046. }
  3047. }
  3048. /* difftime for struct timespec. Return value is in seconds. */
  3049. static double
  3050. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3051. {
  3052. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3053. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3054. }
  3055. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3056. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3057. const char *func,
  3058. unsigned line,
  3059. const char *fmt,
  3060. va_list ap);
  3061. #include "external_mg_cry_internal_impl.inl"
  3062. #else
  3063. /* Print error message to the opened error log stream. */
  3064. static void
  3065. mg_cry_internal_impl(const struct mg_connection *conn,
  3066. const char *func,
  3067. unsigned line,
  3068. const char *fmt,
  3069. va_list ap)
  3070. {
  3071. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3072. struct mg_file fi;
  3073. time_t timestamp;
  3074. /* Unused, in the RELEASE build */
  3075. (void)func;
  3076. (void)line;
  3077. #if defined(GCC_DIAGNOSTIC)
  3078. #pragma GCC diagnostic push
  3079. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3080. #endif
  3081. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3082. #if defined(GCC_DIAGNOSTIC)
  3083. #pragma GCC diagnostic pop
  3084. #endif
  3085. buf[sizeof(buf) - 1] = 0;
  3086. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3087. if (!conn) {
  3088. puts(buf);
  3089. return;
  3090. }
  3091. /* Do not lock when getting the callback value, here and below.
  3092. * I suppose this is fine, since function cannot disappear in the
  3093. * same way string option can. */
  3094. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3095. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3096. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3097. if (mg_fopen(conn,
  3098. conn->dom_ctx->config[ERROR_LOG_FILE],
  3099. MG_FOPEN_MODE_APPEND,
  3100. &fi)
  3101. == 0) {
  3102. fi.access.fp = NULL;
  3103. }
  3104. } else {
  3105. fi.access.fp = NULL;
  3106. }
  3107. if (fi.access.fp != NULL) {
  3108. flockfile(fi.access.fp);
  3109. timestamp = time(NULL);
  3110. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3111. fprintf(fi.access.fp,
  3112. "[%010lu] [error] [client %s] ",
  3113. (unsigned long)timestamp,
  3114. src_addr);
  3115. if (conn->request_info.request_method != NULL) {
  3116. fprintf(fi.access.fp,
  3117. "%s %s: ",
  3118. conn->request_info.request_method,
  3119. conn->request_info.request_uri
  3120. ? conn->request_info.request_uri
  3121. : "");
  3122. }
  3123. fprintf(fi.access.fp, "%s", buf);
  3124. fputc('\n', fi.access.fp);
  3125. fflush(fi.access.fp);
  3126. funlockfile(fi.access.fp);
  3127. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3128. * mg_cry here anyway ;-) */
  3129. }
  3130. }
  3131. }
  3132. #endif /* Externally provided function */
  3133. static void
  3134. mg_cry_internal_wrap(const struct mg_connection *conn,
  3135. const char *func,
  3136. unsigned line,
  3137. const char *fmt,
  3138. ...)
  3139. {
  3140. va_list ap;
  3141. va_start(ap, fmt);
  3142. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3143. va_end(ap);
  3144. }
  3145. void
  3146. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3147. {
  3148. va_list ap;
  3149. va_start(ap, fmt);
  3150. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3151. va_end(ap);
  3152. }
  3153. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3154. /* Return fake connection structure. Used for logging, if connection
  3155. * is not applicable at the moment of logging. */
  3156. static struct mg_connection *
  3157. fc(struct mg_context *ctx)
  3158. {
  3159. static struct mg_connection fake_connection;
  3160. fake_connection.phys_ctx = ctx;
  3161. fake_connection.dom_ctx = &(ctx->dd);
  3162. return &fake_connection;
  3163. }
  3164. const char *
  3165. mg_version(void)
  3166. {
  3167. return CIVETWEB_VERSION;
  3168. }
  3169. const struct mg_request_info *
  3170. mg_get_request_info(const struct mg_connection *conn)
  3171. {
  3172. if (!conn) {
  3173. return NULL;
  3174. }
  3175. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3176. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3177. char txt[16];
  3178. struct mg_workerTLS *tls =
  3179. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3180. sprintf(txt, "%03i", conn->response_info.status_code);
  3181. if (strlen(txt) == 3) {
  3182. memcpy(tls->txtbuf, txt, 4);
  3183. } else {
  3184. strcpy(tls->txtbuf, "ERR");
  3185. }
  3186. ((struct mg_connection *)conn)->request_info.local_uri =
  3187. ((struct mg_connection *)conn)->request_info.request_uri =
  3188. tls->txtbuf; /* use thread safe buffer */
  3189. ((struct mg_connection *)conn)->request_info.num_headers =
  3190. conn->response_info.num_headers;
  3191. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3192. conn->response_info.http_headers,
  3193. sizeof(conn->response_info.http_headers));
  3194. } else
  3195. #endif
  3196. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3197. return NULL;
  3198. }
  3199. return &conn->request_info;
  3200. }
  3201. const struct mg_response_info *
  3202. mg_get_response_info(const struct mg_connection *conn)
  3203. {
  3204. if (!conn) {
  3205. return NULL;
  3206. }
  3207. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3208. return NULL;
  3209. }
  3210. return &conn->response_info;
  3211. }
  3212. static const char *
  3213. get_proto_name(const struct mg_connection *conn)
  3214. {
  3215. #if defined(__clang__)
  3216. #pragma clang diagnostic push
  3217. #pragma clang diagnostic ignored "-Wunreachable-code"
  3218. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3219. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3220. * unreachable, but splitting into four different #ifdef clauses here is more
  3221. * complicated.
  3222. */
  3223. #endif
  3224. const struct mg_request_info *ri = &conn->request_info;
  3225. const char *proto =
  3226. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3227. : (ri->is_ssl ? "https" : "http"));
  3228. return proto;
  3229. #if defined(__clang__)
  3230. #pragma clang diagnostic pop
  3231. #endif
  3232. }
  3233. int
  3234. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3235. {
  3236. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3237. return -1;
  3238. } else {
  3239. int truncated = 0;
  3240. const struct mg_request_info *ri = &conn->request_info;
  3241. const char *proto = get_proto_name(conn);
  3242. if (ri->local_uri == NULL) {
  3243. return -1;
  3244. }
  3245. if ((ri->request_uri != NULL)
  3246. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3247. /* The request uri is different from the local uri.
  3248. * This is usually if an absolute URI, including server
  3249. * name has been provided. */
  3250. mg_snprintf(conn,
  3251. &truncated,
  3252. buf,
  3253. buflen,
  3254. "%s://%s",
  3255. proto,
  3256. ri->request_uri);
  3257. if (truncated) {
  3258. return -1;
  3259. }
  3260. return 0;
  3261. } else {
  3262. /* The common case is a relative URI, so we have to
  3263. * construct an absolute URI from server name and port */
  3264. #if defined(USE_IPV6)
  3265. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3266. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3267. : htons(conn->client.lsa.sin.sin_port);
  3268. #else
  3269. int port = htons(conn->client.lsa.sin.sin_port);
  3270. #endif
  3271. int def_port = ri->is_ssl ? 443 : 80;
  3272. int auth_domain_check_enabled =
  3273. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3274. && (!mg_strcasecmp(
  3275. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3276. const char *server_domain =
  3277. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3278. char portstr[16];
  3279. char server_ip[48];
  3280. if (port != def_port) {
  3281. sprintf(portstr, ":%u", (unsigned)port);
  3282. } else {
  3283. portstr[0] = 0;
  3284. }
  3285. if (!auth_domain_check_enabled || !server_domain) {
  3286. sockaddr_to_string(server_ip,
  3287. sizeof(server_ip),
  3288. &conn->client.lsa);
  3289. server_domain = server_ip;
  3290. }
  3291. mg_snprintf(conn,
  3292. &truncated,
  3293. buf,
  3294. buflen,
  3295. "%s://%s%s%s",
  3296. proto,
  3297. server_domain,
  3298. portstr,
  3299. ri->local_uri);
  3300. if (truncated) {
  3301. return -1;
  3302. }
  3303. return 0;
  3304. }
  3305. }
  3306. }
  3307. /* Skip the characters until one of the delimiters characters found.
  3308. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3309. * Advance pointer to buffer to the next word. Return found 0-terminated
  3310. * word.
  3311. * Delimiters can be quoted with quotechar. */
  3312. static char *
  3313. skip_quoted(char **buf,
  3314. const char *delimiters,
  3315. const char *whitespace,
  3316. char quotechar)
  3317. {
  3318. char *p, *begin_word, *end_word, *end_whitespace;
  3319. begin_word = *buf;
  3320. end_word = begin_word + strcspn(begin_word, delimiters);
  3321. /* Check for quotechar */
  3322. if (end_word > begin_word) {
  3323. p = end_word - 1;
  3324. while (*p == quotechar) {
  3325. /* While the delimiter is quoted, look for the next delimiter.
  3326. */
  3327. /* This happens, e.g., in calls from parse_auth_header,
  3328. * if the user name contains a " character. */
  3329. /* If there is anything beyond end_word, copy it. */
  3330. if (*end_word != '\0') {
  3331. size_t end_off = strcspn(end_word + 1, delimiters);
  3332. memmove(p, end_word, end_off + 1);
  3333. p += end_off; /* p must correspond to end_word - 1 */
  3334. end_word += end_off + 1;
  3335. } else {
  3336. *p = '\0';
  3337. break;
  3338. }
  3339. }
  3340. for (p++; p < end_word; p++) {
  3341. *p = '\0';
  3342. }
  3343. }
  3344. if (*end_word == '\0') {
  3345. *buf = end_word;
  3346. } else {
  3347. #if defined(GCC_DIAGNOSTIC)
  3348. /* Disable spurious conversion warning for GCC */
  3349. #pragma GCC diagnostic push
  3350. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3351. #endif /* defined(GCC_DIAGNOSTIC) */
  3352. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3353. #if defined(GCC_DIAGNOSTIC)
  3354. #pragma GCC diagnostic pop
  3355. #endif /* defined(GCC_DIAGNOSTIC) */
  3356. for (p = end_word; p < end_whitespace; p++) {
  3357. *p = '\0';
  3358. }
  3359. *buf = end_whitespace;
  3360. }
  3361. return begin_word;
  3362. }
  3363. /* Return HTTP header value, or NULL if not found. */
  3364. static const char *
  3365. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3366. {
  3367. int i;
  3368. for (i = 0; i < num_hdr; i++) {
  3369. if (!mg_strcasecmp(name, hdr[i].name)) {
  3370. return hdr[i].value;
  3371. }
  3372. }
  3373. return NULL;
  3374. }
  3375. #if defined(USE_WEBSOCKET)
  3376. /* Retrieve requested HTTP header multiple values, and return the number of
  3377. * found occurrences */
  3378. static int
  3379. get_req_headers(const struct mg_request_info *ri,
  3380. const char *name,
  3381. const char **output,
  3382. int output_max_size)
  3383. {
  3384. int i;
  3385. int cnt = 0;
  3386. if (ri) {
  3387. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3388. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3389. output[cnt++] = ri->http_headers[i].value;
  3390. }
  3391. }
  3392. }
  3393. return cnt;
  3394. }
  3395. #endif
  3396. const char *
  3397. mg_get_header(const struct mg_connection *conn, const char *name)
  3398. {
  3399. if (!conn) {
  3400. return NULL;
  3401. }
  3402. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3403. return get_header(conn->request_info.http_headers,
  3404. conn->request_info.num_headers,
  3405. name);
  3406. }
  3407. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3408. return get_header(conn->response_info.http_headers,
  3409. conn->response_info.num_headers,
  3410. name);
  3411. }
  3412. return NULL;
  3413. }
  3414. static const char *
  3415. get_http_version(const struct mg_connection *conn)
  3416. {
  3417. if (!conn) {
  3418. return NULL;
  3419. }
  3420. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3421. return conn->request_info.http_version;
  3422. }
  3423. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3424. return conn->response_info.http_version;
  3425. }
  3426. return NULL;
  3427. }
  3428. /* A helper function for traversing a comma separated list of values.
  3429. * It returns a list pointer shifted to the next value, or NULL if the end
  3430. * of the list found.
  3431. * Value is stored in val vector. If value has form "x=y", then eq_val
  3432. * vector is initialized to point to the "y" part, and val vector length
  3433. * is adjusted to point only to "x". */
  3434. static const char *
  3435. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3436. {
  3437. int end;
  3438. reparse:
  3439. if (val == NULL || list == NULL || *list == '\0') {
  3440. /* End of the list */
  3441. return NULL;
  3442. }
  3443. /* Skip over leading LWS */
  3444. while (*list == ' ' || *list == '\t')
  3445. list++;
  3446. val->ptr = list;
  3447. if ((list = strchr(val->ptr, ',')) != NULL) {
  3448. /* Comma found. Store length and shift the list ptr */
  3449. val->len = ((size_t)(list - val->ptr));
  3450. list++;
  3451. } else {
  3452. /* This value is the last one */
  3453. list = val->ptr + strlen(val->ptr);
  3454. val->len = ((size_t)(list - val->ptr));
  3455. }
  3456. /* Adjust length for trailing LWS */
  3457. end = (int)val->len - 1;
  3458. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3459. end--;
  3460. val->len = (size_t)(end + 1);
  3461. if (val->len == 0) {
  3462. /* Ignore any empty entries. */
  3463. goto reparse;
  3464. }
  3465. if (eq_val != NULL) {
  3466. /* Value has form "x=y", adjust pointers and lengths
  3467. * so that val points to "x", and eq_val points to "y". */
  3468. eq_val->len = 0;
  3469. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3470. if (eq_val->ptr != NULL) {
  3471. eq_val->ptr++; /* Skip over '=' character */
  3472. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3473. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3474. }
  3475. }
  3476. return list;
  3477. }
  3478. /* A helper function for checking if a comma separated list of values
  3479. * contains
  3480. * the given option (case insensitvely).
  3481. * 'header' can be NULL, in which case false is returned. */
  3482. static int
  3483. header_has_option(const char *header, const char *option)
  3484. {
  3485. struct vec opt_vec;
  3486. struct vec eq_vec;
  3487. DEBUG_ASSERT(option != NULL);
  3488. DEBUG_ASSERT(option[0] != '\0');
  3489. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3490. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3491. return 1;
  3492. }
  3493. return 0;
  3494. }
  3495. /* Perform case-insensitive match of string against pattern */
  3496. static ptrdiff_t
  3497. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3498. {
  3499. const char *or_str;
  3500. ptrdiff_t i, j, len, res;
  3501. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3502. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3503. return (res > 0) ? res
  3504. : match_prefix(or_str + 1,
  3505. (size_t)((pattern + pattern_len)
  3506. - (or_str + 1)),
  3507. str);
  3508. }
  3509. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3510. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3511. continue;
  3512. } else if (pattern[i] == '$') {
  3513. return (str[j] == '\0') ? j : -1;
  3514. } else if (pattern[i] == '*') {
  3515. i++;
  3516. if (pattern[i] == '*') {
  3517. i++;
  3518. len = strlen(str + j);
  3519. } else {
  3520. len = strcspn(str + j, "/");
  3521. }
  3522. if (i == (ptrdiff_t)pattern_len) {
  3523. return j + len;
  3524. }
  3525. do {
  3526. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3527. } while (res == -1 && len-- > 0);
  3528. return (res == -1) ? -1 : j + res + len;
  3529. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3530. return -1;
  3531. }
  3532. }
  3533. return (ptrdiff_t)j;
  3534. }
  3535. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3536. * This function must tolerate situations when connection info is not
  3537. * set up, for example if request parsing failed. */
  3538. static int
  3539. should_keep_alive(const struct mg_connection *conn)
  3540. {
  3541. const char *http_version;
  3542. const char *header;
  3543. /* First satisfy needs of the server */
  3544. if ((conn == NULL) || conn->must_close) {
  3545. /* Close, if civetweb framework needs to close */
  3546. return 0;
  3547. }
  3548. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3549. /* Close, if keep alive is not enabled */
  3550. return 0;
  3551. }
  3552. /* Check explicit wish of the client */
  3553. header = mg_get_header(conn, "Connection");
  3554. if (header) {
  3555. /* If there is a connection header from the client, obey */
  3556. if (header_has_option(header, "keep-alive")) {
  3557. return 1;
  3558. }
  3559. return 0;
  3560. }
  3561. /* Use default of the standard */
  3562. http_version = get_http_version(conn);
  3563. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3564. /* HTTP 1.1 default is keep alive */
  3565. return 1;
  3566. }
  3567. /* HTTP 1.0 (and earlier) default is to close the connection */
  3568. return 0;
  3569. }
  3570. static int
  3571. should_decode_url(const struct mg_connection *conn)
  3572. {
  3573. if (!conn || !conn->dom_ctx) {
  3574. return 0;
  3575. }
  3576. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3577. }
  3578. static const char *
  3579. suggest_connection_header(const struct mg_connection *conn)
  3580. {
  3581. return should_keep_alive(conn) ? "keep-alive" : "close";
  3582. }
  3583. static int
  3584. send_no_cache_header(struct mg_connection *conn)
  3585. {
  3586. /* Send all current and obsolete cache opt-out directives. */
  3587. return mg_printf(conn,
  3588. "Cache-Control: no-cache, no-store, "
  3589. "must-revalidate, private, max-age=0\r\n"
  3590. "Pragma: no-cache\r\n"
  3591. "Expires: 0\r\n");
  3592. }
  3593. static int
  3594. send_static_cache_header(struct mg_connection *conn)
  3595. {
  3596. #if !defined(NO_CACHING)
  3597. /* Read the server config to check how long a file may be cached.
  3598. * The configuration is in seconds. */
  3599. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3600. if (max_age <= 0) {
  3601. /* 0 means "do not cache". All values <0 are reserved
  3602. * and may be used differently in the future. */
  3603. /* If a file should not be cached, do not only send
  3604. * max-age=0, but also pragmas and Expires headers. */
  3605. return send_no_cache_header(conn);
  3606. }
  3607. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3608. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3609. /* See also https://www.mnot.net/cache_docs/ */
  3610. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3611. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3612. * leap
  3613. * year to 31622400 seconds. For the moment, we just send whatever has
  3614. * been configured, still the behavior for >1 year should be considered
  3615. * as undefined. */
  3616. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3617. #else /* NO_CACHING */
  3618. return send_no_cache_header(conn);
  3619. #endif /* !NO_CACHING */
  3620. }
  3621. static int
  3622. send_additional_header(struct mg_connection *conn)
  3623. {
  3624. int i = 0;
  3625. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3626. #if !defined(NO_SSL)
  3627. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3628. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3629. if (max_age >= 0) {
  3630. i += mg_printf(conn,
  3631. "Strict-Transport-Security: max-age=%u\r\n",
  3632. (unsigned)max_age);
  3633. }
  3634. }
  3635. #endif
  3636. if (header && header[0]) {
  3637. i += mg_printf(conn, "%s\r\n", header);
  3638. }
  3639. return i;
  3640. }
  3641. static void handle_file_based_request(struct mg_connection *conn,
  3642. const char *path,
  3643. struct mg_file *filep);
  3644. const char *
  3645. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3646. {
  3647. /* See IANA HTTP status code assignment:
  3648. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3649. */
  3650. switch (response_code) {
  3651. /* RFC2616 Section 10.1 - Informational 1xx */
  3652. case 100:
  3653. return "Continue"; /* RFC2616 Section 10.1.1 */
  3654. case 101:
  3655. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3656. case 102:
  3657. return "Processing"; /* RFC2518 Section 10.1 */
  3658. /* RFC2616 Section 10.2 - Successful 2xx */
  3659. case 200:
  3660. return "OK"; /* RFC2616 Section 10.2.1 */
  3661. case 201:
  3662. return "Created"; /* RFC2616 Section 10.2.2 */
  3663. case 202:
  3664. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3665. case 203:
  3666. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3667. case 204:
  3668. return "No Content"; /* RFC2616 Section 10.2.5 */
  3669. case 205:
  3670. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3671. case 206:
  3672. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3673. case 207:
  3674. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3675. */
  3676. case 208:
  3677. return "Already Reported"; /* RFC5842 Section 7.1 */
  3678. case 226:
  3679. return "IM used"; /* RFC3229 Section 10.4.1 */
  3680. /* RFC2616 Section 10.3 - Redirection 3xx */
  3681. case 300:
  3682. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3683. case 301:
  3684. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3685. case 302:
  3686. return "Found"; /* RFC2616 Section 10.3.3 */
  3687. case 303:
  3688. return "See Other"; /* RFC2616 Section 10.3.4 */
  3689. case 304:
  3690. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3691. case 305:
  3692. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3693. case 307:
  3694. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3695. case 308:
  3696. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3697. /* RFC2616 Section 10.4 - Client Error 4xx */
  3698. case 400:
  3699. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3700. case 401:
  3701. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3702. case 402:
  3703. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3704. case 403:
  3705. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3706. case 404:
  3707. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3708. case 405:
  3709. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3710. case 406:
  3711. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3712. case 407:
  3713. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3714. case 408:
  3715. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3716. case 409:
  3717. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3718. case 410:
  3719. return "Gone"; /* RFC2616 Section 10.4.11 */
  3720. case 411:
  3721. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3722. case 412:
  3723. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3724. case 413:
  3725. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3726. case 414:
  3727. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3728. case 415:
  3729. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3730. case 416:
  3731. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3732. */
  3733. case 417:
  3734. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3735. case 421:
  3736. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3737. case 422:
  3738. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3739. * Section 11.2 */
  3740. case 423:
  3741. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3742. case 424:
  3743. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3744. * Section 11.4 */
  3745. case 426:
  3746. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3747. case 428:
  3748. return "Precondition Required"; /* RFC 6585, Section 3 */
  3749. case 429:
  3750. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3751. case 431:
  3752. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3753. case 451:
  3754. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3755. * Section 3 */
  3756. /* RFC2616 Section 10.5 - Server Error 5xx */
  3757. case 500:
  3758. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3759. case 501:
  3760. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3761. case 502:
  3762. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3763. case 503:
  3764. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3765. case 504:
  3766. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3767. case 505:
  3768. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3769. case 506:
  3770. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3771. case 507:
  3772. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3773. * Section 11.5 */
  3774. case 508:
  3775. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3776. case 510:
  3777. return "Not Extended"; /* RFC 2774, Section 7 */
  3778. case 511:
  3779. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3780. /* Other status codes, not shown in the IANA HTTP status code
  3781. * assignment.
  3782. * E.g., "de facto" standards due to common use, ... */
  3783. case 418:
  3784. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3785. case 419:
  3786. return "Authentication Timeout"; /* common use */
  3787. case 420:
  3788. return "Enhance Your Calm"; /* common use */
  3789. case 440:
  3790. return "Login Timeout"; /* common use */
  3791. case 509:
  3792. return "Bandwidth Limit Exceeded"; /* common use */
  3793. default:
  3794. /* This error code is unknown. This should not happen. */
  3795. if (conn) {
  3796. mg_cry_internal(conn,
  3797. "Unknown HTTP response code: %u",
  3798. response_code);
  3799. }
  3800. /* Return at least a category according to RFC 2616 Section 10. */
  3801. if (response_code >= 100 && response_code < 200) {
  3802. /* Unknown informational status code */
  3803. return "Information";
  3804. }
  3805. if (response_code >= 200 && response_code < 300) {
  3806. /* Unknown success code */
  3807. return "Success";
  3808. }
  3809. if (response_code >= 300 && response_code < 400) {
  3810. /* Unknown redirection code */
  3811. return "Redirection";
  3812. }
  3813. if (response_code >= 400 && response_code < 500) {
  3814. /* Unknown request error code */
  3815. return "Client Error";
  3816. }
  3817. if (response_code >= 500 && response_code < 600) {
  3818. /* Unknown server error code */
  3819. return "Server Error";
  3820. }
  3821. /* Response code not even within reasonable range */
  3822. return "";
  3823. }
  3824. }
  3825. static int
  3826. mg_send_http_error_impl(struct mg_connection *conn,
  3827. int status,
  3828. const char *fmt,
  3829. va_list args)
  3830. {
  3831. char errmsg_buf[MG_BUF_LEN];
  3832. char path_buf[PATH_MAX];
  3833. va_list ap;
  3834. int len, i, page_handler_found, scope, truncated, has_body;
  3835. char date[64];
  3836. time_t curtime = time(NULL);
  3837. const char *error_handler = NULL;
  3838. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3839. const char *error_page_file_ext, *tstr;
  3840. int handled_by_callback = 0;
  3841. const char *status_text = mg_get_response_code_text(conn, status);
  3842. if ((conn == NULL) || (fmt == NULL)) {
  3843. return -2;
  3844. }
  3845. /* Set status (for log) */
  3846. conn->status_code = status;
  3847. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3848. has_body = ((status > 199) && (status != 204) && (status != 304));
  3849. /* Prepare message in buf, if required */
  3850. if (has_body
  3851. || (!conn->in_error_handler
  3852. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3853. /* Store error message in errmsg_buf */
  3854. va_copy(ap, args);
  3855. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3856. va_end(ap);
  3857. /* In a debug build, print all html errors */
  3858. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3859. }
  3860. /* If there is a http_error callback, call it.
  3861. * But don't do it recursively, if callback calls mg_send_http_error again.
  3862. */
  3863. if (!conn->in_error_handler
  3864. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3865. /* Mark in_error_handler to avoid recursion and call user callback. */
  3866. conn->in_error_handler = 1;
  3867. handled_by_callback =
  3868. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3869. == 0);
  3870. conn->in_error_handler = 0;
  3871. }
  3872. if (!handled_by_callback) {
  3873. /* Check for recursion */
  3874. if (conn->in_error_handler) {
  3875. DEBUG_TRACE(
  3876. "Recursion when handling error %u - fall back to default",
  3877. status);
  3878. } else {
  3879. /* Send user defined error pages, if defined */
  3880. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3881. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3882. page_handler_found = 0;
  3883. if (error_handler != NULL) {
  3884. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3885. switch (scope) {
  3886. case 1: /* Handler for specific error, e.g. 404 error */
  3887. mg_snprintf(conn,
  3888. &truncated,
  3889. path_buf,
  3890. sizeof(path_buf) - 32,
  3891. "%serror%03u.",
  3892. error_handler,
  3893. status);
  3894. break;
  3895. case 2: /* Handler for error group, e.g., 5xx error
  3896. * handler
  3897. * for all server errors (500-599) */
  3898. mg_snprintf(conn,
  3899. &truncated,
  3900. path_buf,
  3901. sizeof(path_buf) - 32,
  3902. "%serror%01uxx.",
  3903. error_handler,
  3904. status / 100);
  3905. break;
  3906. default: /* Handler for all errors */
  3907. mg_snprintf(conn,
  3908. &truncated,
  3909. path_buf,
  3910. sizeof(path_buf) - 32,
  3911. "%serror.",
  3912. error_handler);
  3913. break;
  3914. }
  3915. /* String truncation in buf may only occur if
  3916. * error_handler is too long. This string is
  3917. * from the config, not from a client. */
  3918. (void)truncated;
  3919. len = (int)strlen(path_buf);
  3920. tstr = strchr(error_page_file_ext, '.');
  3921. while (tstr) {
  3922. for (i = 1;
  3923. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3924. i++) {
  3925. /* buffer overrun is not possible here, since
  3926. * (i < 32) && (len < sizeof(path_buf) - 32)
  3927. * ==> (i + len) < sizeof(path_buf) */
  3928. path_buf[len + i - 1] = tstr[i];
  3929. }
  3930. /* buffer overrun is not possible here, since
  3931. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3932. * ==> (i + len) <= sizeof(path_buf) */
  3933. path_buf[len + i - 1] = 0;
  3934. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3935. DEBUG_TRACE("Check error page %s - found",
  3936. path_buf);
  3937. page_handler_found = 1;
  3938. break;
  3939. }
  3940. DEBUG_TRACE("Check error page %s - not found",
  3941. path_buf);
  3942. tstr = strchr(tstr + i, '.');
  3943. }
  3944. }
  3945. }
  3946. if (page_handler_found) {
  3947. conn->in_error_handler = 1;
  3948. handle_file_based_request(conn, path_buf, &error_page_file);
  3949. conn->in_error_handler = 0;
  3950. return 0;
  3951. }
  3952. }
  3953. /* No custom error page. Send default error page. */
  3954. gmt_time_string(date, sizeof(date), &curtime);
  3955. conn->must_close = 1;
  3956. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3957. send_no_cache_header(conn);
  3958. send_additional_header(conn);
  3959. if (has_body) {
  3960. mg_printf(conn,
  3961. "%s",
  3962. "Content-Type: text/plain; charset=utf-8\r\n");
  3963. }
  3964. mg_printf(conn,
  3965. "Date: %s\r\n"
  3966. "Connection: close\r\n\r\n",
  3967. date);
  3968. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3969. if (has_body) {
  3970. /* For other errors, send a generic error message. */
  3971. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3972. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3973. } else {
  3974. /* No body allowed. Close the connection. */
  3975. DEBUG_TRACE("Error %i", status);
  3976. }
  3977. }
  3978. return 0;
  3979. }
  3980. int
  3981. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3982. {
  3983. va_list ap;
  3984. int ret;
  3985. va_start(ap, fmt);
  3986. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3987. va_end(ap);
  3988. return ret;
  3989. }
  3990. int
  3991. mg_send_http_ok(struct mg_connection *conn,
  3992. const char *mime_type,
  3993. long long content_length)
  3994. {
  3995. char date[64];
  3996. time_t curtime = time(NULL);
  3997. if ((mime_type == NULL) || (*mime_type == 0)) {
  3998. /* Parameter error */
  3999. return -2;
  4000. }
  4001. gmt_time_string(date, sizeof(date), &curtime);
  4002. mg_printf(conn,
  4003. "HTTP/1.1 200 OK\r\n"
  4004. "Content-Type: %s\r\n"
  4005. "Date: %s\r\n"
  4006. "Connection: %s\r\n",
  4007. mime_type,
  4008. date,
  4009. suggest_connection_header(conn));
  4010. send_no_cache_header(conn);
  4011. send_additional_header(conn);
  4012. if (content_length < 0) {
  4013. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4014. } else {
  4015. mg_printf(conn,
  4016. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4017. (uint64_t)content_length);
  4018. }
  4019. return 0;
  4020. }
  4021. int
  4022. mg_send_http_redirect(struct mg_connection *conn,
  4023. const char *target_url,
  4024. int redirect_code)
  4025. {
  4026. /* Send a 30x redirect response.
  4027. *
  4028. * Redirect types (status codes):
  4029. *
  4030. * Status | Perm/Temp | Method | Version
  4031. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4032. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4033. * 303 | temporary | always use GET | HTTP/1.1
  4034. * 307 | temporary | always keep method | HTTP/1.1
  4035. * 308 | permanent | always keep method | HTTP/1.1
  4036. */
  4037. const char *redirect_text;
  4038. int ret;
  4039. size_t content_len = 0;
  4040. char reply[MG_BUF_LEN];
  4041. /* In case redirect_code=0, use 307. */
  4042. if (redirect_code == 0) {
  4043. redirect_code = 307;
  4044. }
  4045. /* In case redirect_code is none of the above, return error. */
  4046. if ((redirect_code != 301) && (redirect_code != 302)
  4047. && (redirect_code != 303) && (redirect_code != 307)
  4048. && (redirect_code != 308)) {
  4049. /* Parameter error */
  4050. return -2;
  4051. }
  4052. /* Get proper text for response code */
  4053. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4054. /* If target_url is not defined, redirect to "/". */
  4055. if ((target_url == NULL) || (*target_url == 0)) {
  4056. target_url = "/";
  4057. }
  4058. #if defined(MG_SEND_REDIRECT_BODY)
  4059. /* TODO: condition name? */
  4060. /* Prepare a response body with a hyperlink.
  4061. *
  4062. * According to RFC2616 (and RFC1945 before):
  4063. * Unless the request method was HEAD, the entity of the
  4064. * response SHOULD contain a short hypertext note with a hyperlink to
  4065. * the new URI(s).
  4066. *
  4067. * However, this response body is not useful in M2M communication.
  4068. * Probably the original reason in the RFC was, clients not supporting
  4069. * a 30x HTTP redirect could still show the HTML page and let the user
  4070. * press the link. Since current browsers support 30x HTTP, the additional
  4071. * HTML body does not seem to make sense anymore.
  4072. *
  4073. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4074. * but it only notes:
  4075. * The server's response payload usually contains a short
  4076. * hypertext note with a hyperlink to the new URI(s).
  4077. *
  4078. * Deactivated by default. If you need the 30x body, set the define.
  4079. */
  4080. mg_snprintf(
  4081. conn,
  4082. NULL /* ignore truncation */,
  4083. reply,
  4084. sizeof(reply),
  4085. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4086. redirect_text,
  4087. target_url,
  4088. target_url);
  4089. content_len = strlen(reply);
  4090. #else
  4091. reply[0] = 0;
  4092. #endif
  4093. /* Do not send any additional header. For all other options,
  4094. * including caching, there are suitable defaults. */
  4095. ret = mg_printf(conn,
  4096. "HTTP/1.1 %i %s\r\n"
  4097. "Location: %s\r\n"
  4098. "Content-Length: %u\r\n"
  4099. "Connection: %s\r\n\r\n",
  4100. redirect_code,
  4101. redirect_text,
  4102. target_url,
  4103. (unsigned int)content_len,
  4104. suggest_connection_header(conn));
  4105. /* Send response body */
  4106. if (ret > 0) {
  4107. /* ... unless it is a HEAD request */
  4108. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4109. ret = mg_write(conn, reply, content_len);
  4110. }
  4111. }
  4112. return (ret > 0) ? ret : -1;
  4113. }
  4114. #if defined(_WIN32)
  4115. /* Create substitutes for POSIX functions in Win32. */
  4116. #if defined(GCC_DIAGNOSTIC)
  4117. /* Show no warning in case system functions are not used. */
  4118. #pragma GCC diagnostic push
  4119. #pragma GCC diagnostic ignored "-Wunused-function"
  4120. #endif
  4121. FUNCTION_MAY_BE_UNUSED
  4122. static int
  4123. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4124. {
  4125. (void)unused;
  4126. *mutex = CreateMutex(NULL, FALSE, NULL);
  4127. return (*mutex == NULL) ? -1 : 0;
  4128. }
  4129. FUNCTION_MAY_BE_UNUSED
  4130. static int
  4131. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4132. {
  4133. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4134. }
  4135. FUNCTION_MAY_BE_UNUSED
  4136. static int
  4137. pthread_mutex_lock(pthread_mutex_t *mutex)
  4138. {
  4139. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4140. : -1;
  4141. }
  4142. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4143. FUNCTION_MAY_BE_UNUSED
  4144. static int
  4145. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4146. {
  4147. switch (WaitForSingleObject(*mutex, 0)) {
  4148. case WAIT_OBJECT_0:
  4149. return 0;
  4150. case WAIT_TIMEOUT:
  4151. return -2; /* EBUSY */
  4152. }
  4153. return -1;
  4154. }
  4155. #endif
  4156. FUNCTION_MAY_BE_UNUSED
  4157. static int
  4158. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4159. {
  4160. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4161. }
  4162. FUNCTION_MAY_BE_UNUSED
  4163. static int
  4164. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4165. {
  4166. (void)unused;
  4167. InitializeCriticalSection(&cv->threadIdSec);
  4168. cv->waiting_thread = NULL;
  4169. return 0;
  4170. }
  4171. FUNCTION_MAY_BE_UNUSED
  4172. static int
  4173. pthread_cond_timedwait(pthread_cond_t *cv,
  4174. pthread_mutex_t *mutex,
  4175. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4176. {
  4177. struct mg_workerTLS **ptls,
  4178. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4179. int ok;
  4180. int64_t nsnow, nswaitabs, nswaitrel;
  4181. DWORD mswaitrel;
  4182. EnterCriticalSection(&cv->threadIdSec);
  4183. /* Add this thread to cv's waiting list */
  4184. ptls = &cv->waiting_thread;
  4185. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4186. ;
  4187. tls->next_waiting_thread = NULL;
  4188. *ptls = tls;
  4189. LeaveCriticalSection(&cv->threadIdSec);
  4190. if (abstime) {
  4191. nsnow = mg_get_current_time_ns();
  4192. nswaitabs =
  4193. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4194. nswaitrel = nswaitabs - nsnow;
  4195. if (nswaitrel < 0) {
  4196. nswaitrel = 0;
  4197. }
  4198. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4199. } else {
  4200. mswaitrel = (DWORD)INFINITE;
  4201. }
  4202. pthread_mutex_unlock(mutex);
  4203. ok = (WAIT_OBJECT_0
  4204. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4205. if (!ok) {
  4206. ok = 1;
  4207. EnterCriticalSection(&cv->threadIdSec);
  4208. ptls = &cv->waiting_thread;
  4209. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4210. if (*ptls == tls) {
  4211. *ptls = tls->next_waiting_thread;
  4212. ok = 0;
  4213. break;
  4214. }
  4215. }
  4216. LeaveCriticalSection(&cv->threadIdSec);
  4217. if (ok) {
  4218. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4219. (DWORD)INFINITE);
  4220. }
  4221. }
  4222. /* This thread has been removed from cv's waiting list */
  4223. pthread_mutex_lock(mutex);
  4224. return ok ? 0 : -1;
  4225. }
  4226. FUNCTION_MAY_BE_UNUSED
  4227. static int
  4228. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4229. {
  4230. return pthread_cond_timedwait(cv, mutex, NULL);
  4231. }
  4232. FUNCTION_MAY_BE_UNUSED
  4233. static int
  4234. pthread_cond_signal(pthread_cond_t *cv)
  4235. {
  4236. HANDLE wkup = NULL;
  4237. BOOL ok = FALSE;
  4238. EnterCriticalSection(&cv->threadIdSec);
  4239. if (cv->waiting_thread) {
  4240. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4241. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4242. ok = SetEvent(wkup);
  4243. DEBUG_ASSERT(ok);
  4244. }
  4245. LeaveCriticalSection(&cv->threadIdSec);
  4246. return ok ? 0 : 1;
  4247. }
  4248. FUNCTION_MAY_BE_UNUSED
  4249. static int
  4250. pthread_cond_broadcast(pthread_cond_t *cv)
  4251. {
  4252. EnterCriticalSection(&cv->threadIdSec);
  4253. while (cv->waiting_thread) {
  4254. pthread_cond_signal(cv);
  4255. }
  4256. LeaveCriticalSection(&cv->threadIdSec);
  4257. return 0;
  4258. }
  4259. FUNCTION_MAY_BE_UNUSED
  4260. static int
  4261. pthread_cond_destroy(pthread_cond_t *cv)
  4262. {
  4263. EnterCriticalSection(&cv->threadIdSec);
  4264. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4265. LeaveCriticalSection(&cv->threadIdSec);
  4266. DeleteCriticalSection(&cv->threadIdSec);
  4267. return 0;
  4268. }
  4269. #if defined(ALTERNATIVE_QUEUE)
  4270. FUNCTION_MAY_BE_UNUSED
  4271. static void *
  4272. event_create(void)
  4273. {
  4274. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4275. }
  4276. FUNCTION_MAY_BE_UNUSED
  4277. static int
  4278. event_wait(void *eventhdl)
  4279. {
  4280. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4281. return (res == WAIT_OBJECT_0);
  4282. }
  4283. FUNCTION_MAY_BE_UNUSED
  4284. static int
  4285. event_signal(void *eventhdl)
  4286. {
  4287. return (int)SetEvent((HANDLE)eventhdl);
  4288. }
  4289. FUNCTION_MAY_BE_UNUSED
  4290. static void
  4291. event_destroy(void *eventhdl)
  4292. {
  4293. CloseHandle((HANDLE)eventhdl);
  4294. }
  4295. #endif
  4296. #if defined(GCC_DIAGNOSTIC)
  4297. /* Enable unused function warning again */
  4298. #pragma GCC diagnostic pop
  4299. #endif
  4300. /* For Windows, change all slashes to backslashes in path names. */
  4301. static void
  4302. change_slashes_to_backslashes(char *path)
  4303. {
  4304. int i;
  4305. for (i = 0; path[i] != '\0'; i++) {
  4306. if (path[i] == '/') {
  4307. path[i] = '\\';
  4308. }
  4309. /* remove double backslash (check i > 0 to preserve UNC paths,
  4310. * like \\server\file.txt) */
  4311. if ((path[i] == '\\') && (i > 0)) {
  4312. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4313. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4314. }
  4315. }
  4316. }
  4317. }
  4318. static int
  4319. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4320. {
  4321. int diff;
  4322. do {
  4323. diff = tolower(*s1) - tolower(*s2);
  4324. s1++;
  4325. s2++;
  4326. } while ((diff == 0) && (s1[-1] != '\0'));
  4327. return diff;
  4328. }
  4329. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4330. * wbuf and wbuf_len is a target buffer and its length. */
  4331. static void
  4332. path_to_unicode(const struct mg_connection *conn,
  4333. const char *path,
  4334. wchar_t *wbuf,
  4335. size_t wbuf_len)
  4336. {
  4337. char buf[PATH_MAX], buf2[PATH_MAX];
  4338. wchar_t wbuf2[W_PATH_MAX + 1];
  4339. DWORD long_len, err;
  4340. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4341. mg_strlcpy(buf, path, sizeof(buf));
  4342. change_slashes_to_backslashes(buf);
  4343. /* Convert to Unicode and back. If doubly-converted string does not
  4344. * match the original, something is fishy, reject. */
  4345. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4346. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4347. WideCharToMultiByte(
  4348. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4349. if (strcmp(buf, buf2) != 0) {
  4350. wbuf[0] = L'\0';
  4351. }
  4352. /* Windows file systems are not case sensitive, but you can still use
  4353. * uppercase and lowercase letters (on all modern file systems).
  4354. * The server can check if the URI uses the same upper/lowercase
  4355. * letters an the file system, effectively making Windows servers
  4356. * case sensitive (like Linux servers are). It is still not possible
  4357. * to use two files with the same name in different cases on Windows
  4358. * (like /a and /A) - this would be possible in Linux.
  4359. * As a default, Windows is not case sensitive, but the case sensitive
  4360. * file name check can be activated by an additional configuration. */
  4361. if (conn) {
  4362. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4363. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4364. "yes")) {
  4365. /* Use case sensitive compare function */
  4366. fcompare = wcscmp;
  4367. }
  4368. }
  4369. (void)conn; /* conn is currently unused */
  4370. #if !defined(_WIN32_WCE)
  4371. /* Only accept a full file path, not a Windows short (8.3) path. */
  4372. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4373. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4374. if (long_len == 0) {
  4375. err = GetLastError();
  4376. if (err == ERROR_FILE_NOT_FOUND) {
  4377. /* File does not exist. This is not always a problem here. */
  4378. return;
  4379. }
  4380. }
  4381. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4382. /* Short name is used. */
  4383. wbuf[0] = L'\0';
  4384. }
  4385. #else
  4386. (void)long_len;
  4387. (void)wbuf2;
  4388. (void)err;
  4389. if (strchr(path, '~')) {
  4390. wbuf[0] = L'\0';
  4391. }
  4392. #endif
  4393. }
  4394. /* Windows happily opens files with some garbage at the end of file name.
  4395. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4396. * "a.cgi", despite one would expect an error back.
  4397. * This function returns non-0 if path ends with some garbage. */
  4398. static int
  4399. path_cannot_disclose_cgi(const char *path)
  4400. {
  4401. static const char *allowed_last_characters = "_-";
  4402. int last = path[strlen(path) - 1];
  4403. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4404. }
  4405. static int
  4406. mg_stat(const struct mg_connection *conn,
  4407. const char *path,
  4408. struct mg_file_stat *filep)
  4409. {
  4410. wchar_t wbuf[W_PATH_MAX];
  4411. WIN32_FILE_ATTRIBUTE_DATA info;
  4412. time_t creation_time;
  4413. if (!filep) {
  4414. return 0;
  4415. }
  4416. memset(filep, 0, sizeof(*filep));
  4417. if (conn && is_file_in_memory(conn, path)) {
  4418. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4419. * memset */
  4420. /* Quick fix (for 1.9.x): */
  4421. /* mg_stat must fill all fields, also for files in memory */
  4422. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4423. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4424. filep->size = tmp_file.stat.size;
  4425. filep->location = 2;
  4426. /* TODO: for 1.10: restructure how files in memory are handled */
  4427. /* The "file in memory" feature is a candidate for deletion.
  4428. * Please join the discussion at
  4429. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4430. */
  4431. filep->last_modified = time(NULL); /* TODO */
  4432. /* last_modified = now ... assumes the file may change during
  4433. * runtime,
  4434. * so every mg_fopen call may return different data */
  4435. /* last_modified = conn->phys_ctx.start_time;
  4436. * May be used it the data does not change during runtime. This
  4437. * allows
  4438. * browser caching. Since we do not know, we have to assume the file
  4439. * in memory may change. */
  4440. return 1;
  4441. }
  4442. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4443. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4444. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4445. filep->last_modified =
  4446. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4447. info.ftLastWriteTime.dwHighDateTime);
  4448. /* On Windows, the file creation time can be higher than the
  4449. * modification time, e.g. when a file is copied.
  4450. * Since the Last-Modified timestamp is used for caching
  4451. * it should be based on the most recent timestamp. */
  4452. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4453. info.ftCreationTime.dwHighDateTime);
  4454. if (creation_time > filep->last_modified) {
  4455. filep->last_modified = creation_time;
  4456. }
  4457. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4458. /* If file name is fishy, reset the file structure and return
  4459. * error.
  4460. * Note it is important to reset, not just return the error, cause
  4461. * functions like is_file_opened() check the struct. */
  4462. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4463. memset(filep, 0, sizeof(*filep));
  4464. return 0;
  4465. }
  4466. return 1;
  4467. }
  4468. return 0;
  4469. }
  4470. static int
  4471. mg_remove(const struct mg_connection *conn, const char *path)
  4472. {
  4473. wchar_t wbuf[W_PATH_MAX];
  4474. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4475. return DeleteFileW(wbuf) ? 0 : -1;
  4476. }
  4477. static int
  4478. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4479. {
  4480. wchar_t wbuf[W_PATH_MAX];
  4481. (void)mode;
  4482. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4483. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4484. }
  4485. /* Create substitutes for POSIX functions in Win32. */
  4486. #if defined(GCC_DIAGNOSTIC)
  4487. /* Show no warning in case system functions are not used. */
  4488. #pragma GCC diagnostic push
  4489. #pragma GCC diagnostic ignored "-Wunused-function"
  4490. #endif
  4491. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4492. FUNCTION_MAY_BE_UNUSED
  4493. static DIR *
  4494. mg_opendir(const struct mg_connection *conn, const char *name)
  4495. {
  4496. DIR *dir = NULL;
  4497. wchar_t wpath[W_PATH_MAX];
  4498. DWORD attrs;
  4499. if (name == NULL) {
  4500. SetLastError(ERROR_BAD_ARGUMENTS);
  4501. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4502. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4503. } else {
  4504. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4505. attrs = GetFileAttributesW(wpath);
  4506. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4507. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4508. (void)wcscat(wpath, L"\\*");
  4509. dir->handle = FindFirstFileW(wpath, &dir->info);
  4510. dir->result.d_name[0] = '\0';
  4511. } else {
  4512. mg_free(dir);
  4513. dir = NULL;
  4514. }
  4515. }
  4516. return dir;
  4517. }
  4518. FUNCTION_MAY_BE_UNUSED
  4519. static int
  4520. mg_closedir(DIR *dir)
  4521. {
  4522. int result = 0;
  4523. if (dir != NULL) {
  4524. if (dir->handle != INVALID_HANDLE_VALUE)
  4525. result = FindClose(dir->handle) ? 0 : -1;
  4526. mg_free(dir);
  4527. } else {
  4528. result = -1;
  4529. SetLastError(ERROR_BAD_ARGUMENTS);
  4530. }
  4531. return result;
  4532. }
  4533. FUNCTION_MAY_BE_UNUSED
  4534. static struct dirent *
  4535. mg_readdir(DIR *dir)
  4536. {
  4537. struct dirent *result = 0;
  4538. if (dir) {
  4539. if (dir->handle != INVALID_HANDLE_VALUE) {
  4540. result = &dir->result;
  4541. (void)WideCharToMultiByte(CP_UTF8,
  4542. 0,
  4543. dir->info.cFileName,
  4544. -1,
  4545. result->d_name,
  4546. sizeof(result->d_name),
  4547. NULL,
  4548. NULL);
  4549. if (!FindNextFileW(dir->handle, &dir->info)) {
  4550. (void)FindClose(dir->handle);
  4551. dir->handle = INVALID_HANDLE_VALUE;
  4552. }
  4553. } else {
  4554. SetLastError(ERROR_FILE_NOT_FOUND);
  4555. }
  4556. } else {
  4557. SetLastError(ERROR_BAD_ARGUMENTS);
  4558. }
  4559. return result;
  4560. }
  4561. #if !defined(HAVE_POLL)
  4562. #undef POLLIN
  4563. #undef POLLPRI
  4564. #undef POLLOUT
  4565. #define POLLIN (1) /* Data ready - read will not block. */
  4566. #define POLLPRI (2) /* Priority data ready. */
  4567. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4568. FUNCTION_MAY_BE_UNUSED
  4569. static int
  4570. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4571. {
  4572. struct timeval tv;
  4573. fd_set rset;
  4574. fd_set wset;
  4575. unsigned int i;
  4576. int result;
  4577. SOCKET maxfd = 0;
  4578. memset(&tv, 0, sizeof(tv));
  4579. tv.tv_sec = milliseconds / 1000;
  4580. tv.tv_usec = (milliseconds % 1000) * 1000;
  4581. FD_ZERO(&rset);
  4582. FD_ZERO(&wset);
  4583. for (i = 0; i < n; i++) {
  4584. if (pfd[i].events & POLLIN) {
  4585. FD_SET((SOCKET)pfd[i].fd, &rset);
  4586. } else if (pfd[i].events & POLLOUT) {
  4587. FD_SET((SOCKET)pfd[i].fd, &wset);
  4588. }
  4589. pfd[i].revents = 0;
  4590. if (pfd[i].fd > maxfd) {
  4591. maxfd = pfd[i].fd;
  4592. }
  4593. }
  4594. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4595. for (i = 0; i < n; i++) {
  4596. if (FD_ISSET(pfd[i].fd, &rset)) {
  4597. pfd[i].revents |= POLLIN;
  4598. }
  4599. if (FD_ISSET(pfd[i].fd, &wset)) {
  4600. pfd[i].revents |= POLLOUT;
  4601. }
  4602. }
  4603. }
  4604. /* We should subtract the time used in select from remaining
  4605. * "milliseconds", in particular if called from mg_poll with a
  4606. * timeout quantum.
  4607. * Unfortunately, the remaining time is not stored in "tv" in all
  4608. * implementations, so the result in "tv" must be considered undefined.
  4609. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4610. return result;
  4611. }
  4612. #endif /* HAVE_POLL */
  4613. #if defined(GCC_DIAGNOSTIC)
  4614. /* Enable unused function warning again */
  4615. #pragma GCC diagnostic pop
  4616. #endif
  4617. static void
  4618. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4619. {
  4620. (void)conn; /* Unused. */
  4621. #if defined(_WIN32_WCE)
  4622. (void)sock;
  4623. #else
  4624. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4625. #endif
  4626. }
  4627. int
  4628. mg_start_thread(mg_thread_func_t f, void *p)
  4629. {
  4630. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4631. /* Compile-time option to control stack size, e.g.
  4632. * -DUSE_STACK_SIZE=16384
  4633. */
  4634. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4635. == ((uintptr_t)(-1L)))
  4636. ? -1
  4637. : 0);
  4638. #else
  4639. return (
  4640. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4641. ? -1
  4642. : 0);
  4643. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4644. }
  4645. /* Start a thread storing the thread context. */
  4646. static int
  4647. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4648. void *p,
  4649. pthread_t *threadidptr)
  4650. {
  4651. uintptr_t uip;
  4652. HANDLE threadhandle;
  4653. int result = -1;
  4654. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4655. threadhandle = (HANDLE)uip;
  4656. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4657. *threadidptr = threadhandle;
  4658. result = 0;
  4659. }
  4660. return result;
  4661. }
  4662. /* Wait for a thread to finish. */
  4663. static int
  4664. mg_join_thread(pthread_t threadid)
  4665. {
  4666. int result;
  4667. DWORD dwevent;
  4668. result = -1;
  4669. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4670. if (dwevent == WAIT_FAILED) {
  4671. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4672. } else {
  4673. if (dwevent == WAIT_OBJECT_0) {
  4674. CloseHandle(threadid);
  4675. result = 0;
  4676. }
  4677. }
  4678. return result;
  4679. }
  4680. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4681. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4682. /* Create substitutes for POSIX functions in Win32. */
  4683. #if defined(GCC_DIAGNOSTIC)
  4684. /* Show no warning in case system functions are not used. */
  4685. #pragma GCC diagnostic push
  4686. #pragma GCC diagnostic ignored "-Wunused-function"
  4687. #endif
  4688. FUNCTION_MAY_BE_UNUSED
  4689. static HANDLE
  4690. dlopen(const char *dll_name, int flags)
  4691. {
  4692. wchar_t wbuf[W_PATH_MAX];
  4693. (void)flags;
  4694. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4695. return LoadLibraryW(wbuf);
  4696. }
  4697. FUNCTION_MAY_BE_UNUSED
  4698. static int
  4699. dlclose(void *handle)
  4700. {
  4701. int result;
  4702. if (FreeLibrary((HMODULE)handle) != 0) {
  4703. result = 0;
  4704. } else {
  4705. result = -1;
  4706. }
  4707. return result;
  4708. }
  4709. #if defined(GCC_DIAGNOSTIC)
  4710. /* Enable unused function warning again */
  4711. #pragma GCC diagnostic pop
  4712. #endif
  4713. #endif
  4714. #if !defined(NO_CGI)
  4715. #define SIGKILL (0)
  4716. static int
  4717. kill(pid_t pid, int sig_num)
  4718. {
  4719. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4720. (void)CloseHandle((HANDLE)pid);
  4721. return 0;
  4722. }
  4723. #if !defined(WNOHANG)
  4724. #define WNOHANG (1)
  4725. #endif
  4726. static pid_t
  4727. waitpid(pid_t pid, int *status, int flags)
  4728. {
  4729. DWORD timeout = INFINITE;
  4730. DWORD waitres;
  4731. (void)status; /* Currently not used by any client here */
  4732. if ((flags | WNOHANG) == WNOHANG) {
  4733. timeout = 0;
  4734. }
  4735. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4736. if (waitres == WAIT_OBJECT_0) {
  4737. return pid;
  4738. }
  4739. if (waitres == WAIT_TIMEOUT) {
  4740. return 0;
  4741. }
  4742. return (pid_t)-1;
  4743. }
  4744. static void
  4745. trim_trailing_whitespaces(char *s)
  4746. {
  4747. char *e = s + strlen(s) - 1;
  4748. while ((e > s) && isspace(*(unsigned char *)e)) {
  4749. *e-- = '\0';
  4750. }
  4751. }
  4752. static pid_t
  4753. spawn_process(struct mg_connection *conn,
  4754. const char *prog,
  4755. char *envblk,
  4756. char *envp[],
  4757. int fdin[2],
  4758. int fdout[2],
  4759. int fderr[2],
  4760. const char *dir)
  4761. {
  4762. HANDLE me;
  4763. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4764. cmdline[PATH_MAX], buf[PATH_MAX];
  4765. int truncated;
  4766. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4767. STARTUPINFOA si;
  4768. PROCESS_INFORMATION pi = {0};
  4769. (void)envp;
  4770. memset(&si, 0, sizeof(si));
  4771. si.cb = sizeof(si);
  4772. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4773. si.wShowWindow = SW_HIDE;
  4774. me = GetCurrentProcess();
  4775. DuplicateHandle(me,
  4776. (HANDLE)_get_osfhandle(fdin[0]),
  4777. me,
  4778. &si.hStdInput,
  4779. 0,
  4780. TRUE,
  4781. DUPLICATE_SAME_ACCESS);
  4782. DuplicateHandle(me,
  4783. (HANDLE)_get_osfhandle(fdout[1]),
  4784. me,
  4785. &si.hStdOutput,
  4786. 0,
  4787. TRUE,
  4788. DUPLICATE_SAME_ACCESS);
  4789. DuplicateHandle(me,
  4790. (HANDLE)_get_osfhandle(fderr[1]),
  4791. me,
  4792. &si.hStdError,
  4793. 0,
  4794. TRUE,
  4795. DUPLICATE_SAME_ACCESS);
  4796. /* Mark handles that should not be inherited. See
  4797. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4798. */
  4799. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4800. HANDLE_FLAG_INHERIT,
  4801. 0);
  4802. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4803. HANDLE_FLAG_INHERIT,
  4804. 0);
  4805. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4806. HANDLE_FLAG_INHERIT,
  4807. 0);
  4808. /* If CGI file is a script, try to read the interpreter line */
  4809. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4810. if (interp == NULL) {
  4811. buf[0] = buf[1] = '\0';
  4812. /* Read the first line of the script into the buffer */
  4813. mg_snprintf(
  4814. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4815. if (truncated) {
  4816. pi.hProcess = (pid_t)-1;
  4817. goto spawn_cleanup;
  4818. }
  4819. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4820. #if defined(MG_USE_OPEN_FILE)
  4821. p = (char *)file.access.membuf;
  4822. #else
  4823. p = (char *)NULL;
  4824. #endif
  4825. mg_fgets(buf, sizeof(buf), &file, &p);
  4826. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4827. buf[sizeof(buf) - 1] = '\0';
  4828. }
  4829. if ((buf[0] == '#') && (buf[1] == '!')) {
  4830. trim_trailing_whitespaces(buf + 2);
  4831. } else {
  4832. buf[2] = '\0';
  4833. }
  4834. interp = buf + 2;
  4835. }
  4836. if (interp[0] != '\0') {
  4837. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4838. interp = full_interp;
  4839. }
  4840. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4841. if (interp[0] != '\0') {
  4842. mg_snprintf(conn,
  4843. &truncated,
  4844. cmdline,
  4845. sizeof(cmdline),
  4846. "\"%s\" \"%s\\%s\"",
  4847. interp,
  4848. full_dir,
  4849. prog);
  4850. } else {
  4851. mg_snprintf(conn,
  4852. &truncated,
  4853. cmdline,
  4854. sizeof(cmdline),
  4855. "\"%s\\%s\"",
  4856. full_dir,
  4857. prog);
  4858. }
  4859. if (truncated) {
  4860. pi.hProcess = (pid_t)-1;
  4861. goto spawn_cleanup;
  4862. }
  4863. DEBUG_TRACE("Running [%s]", cmdline);
  4864. if (CreateProcessA(NULL,
  4865. cmdline,
  4866. NULL,
  4867. NULL,
  4868. TRUE,
  4869. CREATE_NEW_PROCESS_GROUP,
  4870. envblk,
  4871. NULL,
  4872. &si,
  4873. &pi)
  4874. == 0) {
  4875. mg_cry_internal(
  4876. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4877. pi.hProcess = (pid_t)-1;
  4878. /* goto spawn_cleanup; */
  4879. }
  4880. spawn_cleanup:
  4881. (void)CloseHandle(si.hStdOutput);
  4882. (void)CloseHandle(si.hStdError);
  4883. (void)CloseHandle(si.hStdInput);
  4884. if (pi.hThread != NULL) {
  4885. (void)CloseHandle(pi.hThread);
  4886. }
  4887. return (pid_t)pi.hProcess;
  4888. }
  4889. #endif /* !NO_CGI */
  4890. static int
  4891. set_blocking_mode(SOCKET sock)
  4892. {
  4893. unsigned long non_blocking = 0;
  4894. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4895. }
  4896. static int
  4897. set_non_blocking_mode(SOCKET sock)
  4898. {
  4899. unsigned long non_blocking = 1;
  4900. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4901. }
  4902. #else
  4903. static int
  4904. mg_stat(const struct mg_connection *conn,
  4905. const char *path,
  4906. struct mg_file_stat *filep)
  4907. {
  4908. struct stat st;
  4909. if (!filep) {
  4910. return 0;
  4911. }
  4912. memset(filep, 0, sizeof(*filep));
  4913. if (conn && is_file_in_memory(conn, path)) {
  4914. /* Quick fix (for 1.9.x): */
  4915. /* mg_stat must fill all fields, also for files in memory */
  4916. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4917. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4918. filep->size = tmp_file.stat.size;
  4919. filep->last_modified = time(NULL);
  4920. filep->location = 2;
  4921. /* TODO: remove legacy "files in memory" feature */
  4922. return 1;
  4923. }
  4924. if (0 == stat(path, &st)) {
  4925. filep->size = (uint64_t)(st.st_size);
  4926. filep->last_modified = st.st_mtime;
  4927. filep->is_directory = S_ISDIR(st.st_mode);
  4928. return 1;
  4929. }
  4930. return 0;
  4931. }
  4932. static void
  4933. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4934. {
  4935. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4936. if (conn) {
  4937. mg_cry_internal(conn,
  4938. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4939. __func__,
  4940. strerror(ERRNO));
  4941. }
  4942. }
  4943. }
  4944. int
  4945. mg_start_thread(mg_thread_func_t func, void *param)
  4946. {
  4947. pthread_t thread_id;
  4948. pthread_attr_t attr;
  4949. int result;
  4950. (void)pthread_attr_init(&attr);
  4951. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4952. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4953. /* Compile-time option to control stack size,
  4954. * e.g. -DUSE_STACK_SIZE=16384 */
  4955. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4956. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4957. result = pthread_create(&thread_id, &attr, func, param);
  4958. pthread_attr_destroy(&attr);
  4959. return result;
  4960. }
  4961. /* Start a thread storing the thread context. */
  4962. static int
  4963. mg_start_thread_with_id(mg_thread_func_t func,
  4964. void *param,
  4965. pthread_t *threadidptr)
  4966. {
  4967. pthread_t thread_id;
  4968. pthread_attr_t attr;
  4969. int result;
  4970. (void)pthread_attr_init(&attr);
  4971. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4972. /* Compile-time option to control stack size,
  4973. * e.g. -DUSE_STACK_SIZE=16384 */
  4974. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4975. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4976. result = pthread_create(&thread_id, &attr, func, param);
  4977. pthread_attr_destroy(&attr);
  4978. if ((result == 0) && (threadidptr != NULL)) {
  4979. *threadidptr = thread_id;
  4980. }
  4981. return result;
  4982. }
  4983. /* Wait for a thread to finish. */
  4984. static int
  4985. mg_join_thread(pthread_t threadid)
  4986. {
  4987. int result;
  4988. result = pthread_join(threadid, NULL);
  4989. return result;
  4990. }
  4991. #if !defined(NO_CGI)
  4992. static pid_t
  4993. spawn_process(struct mg_connection *conn,
  4994. const char *prog,
  4995. char *envblk,
  4996. char *envp[],
  4997. int fdin[2],
  4998. int fdout[2],
  4999. int fderr[2],
  5000. const char *dir)
  5001. {
  5002. pid_t pid;
  5003. const char *interp;
  5004. (void)envblk;
  5005. if (conn == NULL) {
  5006. return 0;
  5007. }
  5008. if ((pid = fork()) == -1) {
  5009. /* Parent */
  5010. mg_send_http_error(conn,
  5011. 500,
  5012. "Error: Creating CGI process\nfork(): %s",
  5013. strerror(ERRNO));
  5014. } else if (pid == 0) {
  5015. /* Child */
  5016. if (chdir(dir) != 0) {
  5017. mg_cry_internal(
  5018. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5019. } else if (dup2(fdin[0], 0) == -1) {
  5020. mg_cry_internal(conn,
  5021. "%s: dup2(%d, 0): %s",
  5022. __func__,
  5023. fdin[0],
  5024. strerror(ERRNO));
  5025. } else if (dup2(fdout[1], 1) == -1) {
  5026. mg_cry_internal(conn,
  5027. "%s: dup2(%d, 1): %s",
  5028. __func__,
  5029. fdout[1],
  5030. strerror(ERRNO));
  5031. } else if (dup2(fderr[1], 2) == -1) {
  5032. mg_cry_internal(conn,
  5033. "%s: dup2(%d, 2): %s",
  5034. __func__,
  5035. fderr[1],
  5036. strerror(ERRNO));
  5037. } else {
  5038. /* Keep stderr and stdout in two different pipes.
  5039. * Stdout will be sent back to the client,
  5040. * stderr should go into a server error log. */
  5041. (void)close(fdin[0]);
  5042. (void)close(fdout[1]);
  5043. (void)close(fderr[1]);
  5044. /* Close write end fdin and read end fdout and fderr */
  5045. (void)close(fdin[1]);
  5046. (void)close(fdout[0]);
  5047. (void)close(fderr[0]);
  5048. /* After exec, all signal handlers are restored to their default
  5049. * values, with one exception of SIGCHLD. According to
  5050. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5051. * will leave unchanged after exec if it was set to be ignored.
  5052. * Restore it to default action. */
  5053. signal(SIGCHLD, SIG_DFL);
  5054. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5055. if (interp == NULL) {
  5056. (void)execle(prog, prog, NULL, envp);
  5057. mg_cry_internal(conn,
  5058. "%s: execle(%s): %s",
  5059. __func__,
  5060. prog,
  5061. strerror(ERRNO));
  5062. } else {
  5063. (void)execle(interp, interp, prog, NULL, envp);
  5064. mg_cry_internal(conn,
  5065. "%s: execle(%s %s): %s",
  5066. __func__,
  5067. interp,
  5068. prog,
  5069. strerror(ERRNO));
  5070. }
  5071. }
  5072. exit(EXIT_FAILURE);
  5073. }
  5074. return pid;
  5075. }
  5076. #endif /* !NO_CGI */
  5077. static int
  5078. set_non_blocking_mode(SOCKET sock)
  5079. {
  5080. int flags = fcntl(sock, F_GETFL, 0);
  5081. if (flags < 0) {
  5082. return -1;
  5083. }
  5084. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5085. return -1;
  5086. }
  5087. return 0;
  5088. }
  5089. static int
  5090. set_blocking_mode(SOCKET sock)
  5091. {
  5092. int flags = fcntl(sock, F_GETFL, 0);
  5093. if (flags < 0) {
  5094. return -1;
  5095. }
  5096. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5097. return -1;
  5098. }
  5099. return 0;
  5100. }
  5101. #endif /* _WIN32 / else */
  5102. /* End of initial operating system specific define block. */
  5103. /* Get a random number (independent of C rand function) */
  5104. static uint64_t
  5105. get_random(void)
  5106. {
  5107. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5108. static uint64_t lcg = 0; /* Linear congruential generator */
  5109. uint64_t now = mg_get_current_time_ns();
  5110. if (lfsr == 0) {
  5111. /* lfsr will be only 0 if has not been initialized,
  5112. * so this code is called only once. */
  5113. lfsr = mg_get_current_time_ns();
  5114. lcg = mg_get_current_time_ns();
  5115. } else {
  5116. /* Get the next step of both random number generators. */
  5117. lfsr = (lfsr >> 1)
  5118. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5119. << 63);
  5120. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5121. }
  5122. /* Combining two pseudo-random number generators and a high resolution
  5123. * part
  5124. * of the current server time will make it hard (impossible?) to guess
  5125. * the
  5126. * next number. */
  5127. return (lfsr ^ lcg ^ now);
  5128. }
  5129. static int
  5130. mg_poll(struct mg_pollfd *pfd,
  5131. unsigned int n,
  5132. int milliseconds,
  5133. volatile int *stop_server)
  5134. {
  5135. /* Call poll, but only for a maximum time of a few seconds.
  5136. * This will allow to stop the server after some seconds, instead
  5137. * of having to wait for a long socket timeout. */
  5138. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5139. do {
  5140. int result;
  5141. if (*stop_server) {
  5142. /* Shut down signal */
  5143. return -2;
  5144. }
  5145. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5146. ms_now = milliseconds;
  5147. }
  5148. result = poll(pfd, n, ms_now);
  5149. if (result != 0) {
  5150. /* Poll returned either success (1) or error (-1).
  5151. * Forward both to the caller. */
  5152. return result;
  5153. }
  5154. /* Poll returned timeout (0). */
  5155. if (milliseconds > 0) {
  5156. milliseconds -= ms_now;
  5157. }
  5158. } while (milliseconds != 0);
  5159. /* timeout: return 0 */
  5160. return 0;
  5161. }
  5162. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5163. * descriptor.
  5164. * Return value:
  5165. * >=0 .. number of bytes successfully written
  5166. * -1 .. timeout
  5167. * -2 .. error
  5168. */
  5169. static int
  5170. push_inner(struct mg_context *ctx,
  5171. FILE *fp,
  5172. SOCKET sock,
  5173. SSL *ssl,
  5174. const char *buf,
  5175. int len,
  5176. double timeout)
  5177. {
  5178. uint64_t start = 0, now = 0, timeout_ns = 0;
  5179. int n, err;
  5180. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5181. #if defined(_WIN32)
  5182. typedef int len_t;
  5183. #else
  5184. typedef size_t len_t;
  5185. #endif
  5186. if (timeout > 0) {
  5187. now = mg_get_current_time_ns();
  5188. start = now;
  5189. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5190. }
  5191. if (ctx == NULL) {
  5192. return -2;
  5193. }
  5194. #if defined(NO_SSL)
  5195. if (ssl) {
  5196. return -2;
  5197. }
  5198. #endif
  5199. /* Try to read until it succeeds, fails, times out, or the server
  5200. * shuts down. */
  5201. for (;;) {
  5202. #if !defined(NO_SSL)
  5203. if (ssl != NULL) {
  5204. n = SSL_write(ssl, buf, len);
  5205. if (n <= 0) {
  5206. err = SSL_get_error(ssl, n);
  5207. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5208. err = ERRNO;
  5209. } else if ((err == SSL_ERROR_WANT_READ)
  5210. || (err == SSL_ERROR_WANT_WRITE)) {
  5211. n = 0;
  5212. } else {
  5213. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5214. return -2;
  5215. }
  5216. } else {
  5217. err = 0;
  5218. }
  5219. } else
  5220. #endif
  5221. if (fp != NULL) {
  5222. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5223. if (ferror(fp)) {
  5224. n = -1;
  5225. err = ERRNO;
  5226. } else {
  5227. err = 0;
  5228. }
  5229. } else {
  5230. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5231. err = (n < 0) ? ERRNO : 0;
  5232. #if defined(_WIN32)
  5233. if (err == WSAEWOULDBLOCK) {
  5234. err = 0;
  5235. n = 0;
  5236. }
  5237. #else
  5238. if (err == EWOULDBLOCK) {
  5239. err = 0;
  5240. n = 0;
  5241. }
  5242. #endif
  5243. if (n < 0) {
  5244. /* shutdown of the socket at client side */
  5245. return -2;
  5246. }
  5247. }
  5248. if (ctx->stop_flag) {
  5249. return -2;
  5250. }
  5251. if ((n > 0) || ((n == 0) && (len == 0))) {
  5252. /* some data has been read, or no data was requested */
  5253. return n;
  5254. }
  5255. if (n < 0) {
  5256. /* socket error - check errno */
  5257. DEBUG_TRACE("send() failed, error %d", err);
  5258. /* TODO (mid): error handling depending on the error code.
  5259. * These codes are different between Windows and Linux.
  5260. * Currently there is no problem with failing send calls,
  5261. * if there is a reproducible situation, it should be
  5262. * investigated in detail.
  5263. */
  5264. return -2;
  5265. }
  5266. /* Only in case n=0 (timeout), repeat calling the write function */
  5267. /* If send failed, wait before retry */
  5268. if (fp != NULL) {
  5269. /* For files, just wait a fixed time.
  5270. * Maybe it helps, maybe not. */
  5271. mg_sleep(5);
  5272. } else {
  5273. /* For sockets, wait for the socket using poll */
  5274. struct mg_pollfd pfd[1];
  5275. int pollres;
  5276. pfd[0].fd = sock;
  5277. pfd[0].events = POLLOUT;
  5278. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5279. if (ctx->stop_flag) {
  5280. return -2;
  5281. }
  5282. if (pollres > 0) {
  5283. continue;
  5284. }
  5285. }
  5286. if (timeout > 0) {
  5287. now = mg_get_current_time_ns();
  5288. if ((now - start) > timeout_ns) {
  5289. /* Timeout */
  5290. break;
  5291. }
  5292. }
  5293. }
  5294. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5295. used */
  5296. return -1;
  5297. }
  5298. static int64_t
  5299. push_all(struct mg_context *ctx,
  5300. FILE *fp,
  5301. SOCKET sock,
  5302. SSL *ssl,
  5303. const char *buf,
  5304. int64_t len)
  5305. {
  5306. double timeout = -1.0;
  5307. int64_t n, nwritten = 0;
  5308. if (ctx == NULL) {
  5309. return -1;
  5310. }
  5311. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5312. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5313. }
  5314. while ((len > 0) && (ctx->stop_flag == 0)) {
  5315. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5316. if (n < 0) {
  5317. if (nwritten == 0) {
  5318. nwritten = n; /* Propagate the error */
  5319. }
  5320. break;
  5321. } else if (n == 0) {
  5322. break; /* No more data to write */
  5323. } else {
  5324. nwritten += n;
  5325. len -= n;
  5326. }
  5327. }
  5328. return nwritten;
  5329. }
  5330. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5331. * Return value:
  5332. * >=0 .. number of bytes successfully read
  5333. * -1 .. timeout
  5334. * -2 .. error
  5335. */
  5336. static int
  5337. pull_inner(FILE *fp,
  5338. struct mg_connection *conn,
  5339. char *buf,
  5340. int len,
  5341. double timeout)
  5342. {
  5343. int nread, err = 0;
  5344. #if defined(_WIN32)
  5345. typedef int len_t;
  5346. #else
  5347. typedef size_t len_t;
  5348. #endif
  5349. #if !defined(NO_SSL)
  5350. int ssl_pending;
  5351. #endif
  5352. /* We need an additional wait loop around this, because in some cases
  5353. * with TLSwe may get data from the socket but not from SSL_read.
  5354. * In this case we need to repeat at least once.
  5355. */
  5356. if (fp != NULL) {
  5357. #if !defined(_WIN32_WCE)
  5358. /* Use read() instead of fread(), because if we're reading from the
  5359. * CGI pipe, fread() may block until IO buffer is filled up. We
  5360. * cannot afford to block and must pass all read bytes immediately
  5361. * to the client. */
  5362. nread = (int)read(fileno(fp), buf, (size_t)len);
  5363. #else
  5364. /* WinCE does not support CGI pipes */
  5365. nread = (int)fread(buf, 1, (size_t)len, fp);
  5366. #endif
  5367. err = (nread < 0) ? ERRNO : 0;
  5368. if ((nread == 0) && (len > 0)) {
  5369. /* Should get data, but got EOL */
  5370. return -2;
  5371. }
  5372. #if !defined(NO_SSL)
  5373. } else if ((conn->ssl != NULL)
  5374. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5375. /* We already know there is no more data buffered in conn->buf
  5376. * but there is more available in the SSL layer. So don't poll
  5377. * conn->client.sock yet. */
  5378. if (ssl_pending > len) {
  5379. ssl_pending = len;
  5380. }
  5381. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5382. if (nread <= 0) {
  5383. err = SSL_get_error(conn->ssl, nread);
  5384. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5385. err = ERRNO;
  5386. } else if ((err == SSL_ERROR_WANT_READ)
  5387. || (err == SSL_ERROR_WANT_WRITE)) {
  5388. nread = 0;
  5389. } else {
  5390. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5391. return -1;
  5392. }
  5393. } else {
  5394. err = 0;
  5395. }
  5396. } else if (conn->ssl != NULL) {
  5397. struct mg_pollfd pfd[1];
  5398. int pollres;
  5399. pfd[0].fd = conn->client.sock;
  5400. pfd[0].events = POLLIN;
  5401. pollres = mg_poll(pfd,
  5402. 1,
  5403. (int)(timeout * 1000.0),
  5404. &(conn->phys_ctx->stop_flag));
  5405. if (conn->phys_ctx->stop_flag) {
  5406. return -2;
  5407. }
  5408. if (pollres > 0) {
  5409. nread = SSL_read(conn->ssl, buf, len);
  5410. if (nread <= 0) {
  5411. err = SSL_get_error(conn->ssl, nread);
  5412. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5413. err = ERRNO;
  5414. } else if ((err == SSL_ERROR_WANT_READ)
  5415. || (err == SSL_ERROR_WANT_WRITE)) {
  5416. nread = 0;
  5417. } else {
  5418. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5419. return -2;
  5420. }
  5421. } else {
  5422. err = 0;
  5423. }
  5424. } else if (pollres < 0) {
  5425. /* Error */
  5426. return -2;
  5427. } else {
  5428. /* pollres = 0 means timeout */
  5429. nread = 0;
  5430. }
  5431. #endif
  5432. } else {
  5433. struct mg_pollfd pfd[1];
  5434. int pollres;
  5435. pfd[0].fd = conn->client.sock;
  5436. pfd[0].events = POLLIN;
  5437. pollres = mg_poll(pfd,
  5438. 1,
  5439. (int)(timeout * 1000.0),
  5440. &(conn->phys_ctx->stop_flag));
  5441. if (conn->phys_ctx->stop_flag) {
  5442. return -2;
  5443. }
  5444. if (pollres > 0) {
  5445. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5446. err = (nread < 0) ? ERRNO : 0;
  5447. if (nread <= 0) {
  5448. /* shutdown of the socket at client side */
  5449. return -2;
  5450. }
  5451. } else if (pollres < 0) {
  5452. /* error callint poll */
  5453. return -2;
  5454. } else {
  5455. /* pollres = 0 means timeout */
  5456. nread = 0;
  5457. }
  5458. }
  5459. if (conn->phys_ctx->stop_flag) {
  5460. return -2;
  5461. }
  5462. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5463. /* some data has been read, or no data was requested */
  5464. return nread;
  5465. }
  5466. if (nread < 0) {
  5467. /* socket error - check errno */
  5468. #if defined(_WIN32)
  5469. if (err == WSAEWOULDBLOCK) {
  5470. /* TODO (low): check if this is still required */
  5471. /* standard case if called from close_socket_gracefully */
  5472. return -2;
  5473. } else if (err == WSAETIMEDOUT) {
  5474. /* TODO (low): check if this is still required */
  5475. /* timeout is handled by the while loop */
  5476. return 0;
  5477. } else if (err == WSAECONNABORTED) {
  5478. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5479. return -2;
  5480. } else {
  5481. DEBUG_TRACE("recv() failed, error %d", err);
  5482. return -2;
  5483. }
  5484. #else
  5485. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5486. * if the timeout is reached and if the socket was set to non-
  5487. * blocking in close_socket_gracefully, so we can not distinguish
  5488. * here. We have to wait for the timeout in both cases for now.
  5489. */
  5490. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5491. /* TODO (low): check if this is still required */
  5492. /* EAGAIN/EWOULDBLOCK:
  5493. * standard case if called from close_socket_gracefully
  5494. * => should return -1 */
  5495. /* or timeout occurred
  5496. * => the code must stay in the while loop */
  5497. /* EINTR can be generated on a socket with a timeout set even
  5498. * when SA_RESTART is effective for all relevant signals
  5499. * (see signal(7)).
  5500. * => stay in the while loop */
  5501. } else {
  5502. DEBUG_TRACE("recv() failed, error %d", err);
  5503. return -2;
  5504. }
  5505. #endif
  5506. }
  5507. /* Timeout occurred, but no data available. */
  5508. return -1;
  5509. }
  5510. static int
  5511. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5512. {
  5513. int n, nread = 0;
  5514. double timeout = -1.0;
  5515. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5516. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5517. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5518. }
  5519. if (timeout >= 0.0) {
  5520. start_time = mg_get_current_time_ns();
  5521. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5522. }
  5523. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5524. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5525. if (n == -2) {
  5526. if (nread == 0) {
  5527. nread = -1; /* Propagate the error */
  5528. }
  5529. break;
  5530. } else if (n == -1) {
  5531. /* timeout */
  5532. if (timeout >= 0.0) {
  5533. now = mg_get_current_time_ns();
  5534. if ((now - start_time) <= timeout_ns) {
  5535. continue;
  5536. }
  5537. }
  5538. break;
  5539. } else if (n == 0) {
  5540. break; /* No more data to read */
  5541. } else {
  5542. conn->consumed_content += n;
  5543. nread += n;
  5544. len -= n;
  5545. }
  5546. }
  5547. return nread;
  5548. }
  5549. static void
  5550. discard_unread_request_data(struct mg_connection *conn)
  5551. {
  5552. char buf[MG_BUF_LEN];
  5553. size_t to_read;
  5554. int nread;
  5555. if (conn == NULL) {
  5556. return;
  5557. }
  5558. to_read = sizeof(buf);
  5559. if (conn->is_chunked) {
  5560. /* Chunked encoding: 3=chunk read completely
  5561. * completely */
  5562. while (conn->is_chunked != 3) {
  5563. nread = mg_read(conn, buf, to_read);
  5564. if (nread <= 0) {
  5565. break;
  5566. }
  5567. }
  5568. } else {
  5569. /* Not chunked: content length is known */
  5570. while (conn->consumed_content < conn->content_len) {
  5571. if (to_read
  5572. > (size_t)(conn->content_len - conn->consumed_content)) {
  5573. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5574. }
  5575. nread = mg_read(conn, buf, to_read);
  5576. if (nread <= 0) {
  5577. break;
  5578. }
  5579. }
  5580. }
  5581. }
  5582. static int
  5583. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5584. {
  5585. int64_t n, buffered_len, nread;
  5586. int64_t len64 =
  5587. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5588. * int, we may not read more
  5589. * bytes */
  5590. const char *body;
  5591. if (conn == NULL) {
  5592. return 0;
  5593. }
  5594. /* If Content-Length is not set for a request with body data
  5595. * (e.g., a PUT or POST request), we do not know in advance
  5596. * how much data should be read. */
  5597. if (conn->consumed_content == 0) {
  5598. if (conn->is_chunked == 1) {
  5599. conn->content_len = len64;
  5600. conn->is_chunked = 2;
  5601. } else if (conn->content_len == -1) {
  5602. /* The body data is completed when the connection
  5603. * is closed. */
  5604. conn->content_len = INT64_MAX;
  5605. conn->must_close = 1;
  5606. }
  5607. }
  5608. nread = 0;
  5609. if (conn->consumed_content < conn->content_len) {
  5610. /* Adjust number of bytes to read. */
  5611. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5612. if (left_to_read < len64) {
  5613. /* Do not read more than the total content length of the
  5614. * request.
  5615. */
  5616. len64 = left_to_read;
  5617. }
  5618. /* Return buffered data */
  5619. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5620. - conn->consumed_content;
  5621. if (buffered_len > 0) {
  5622. if (len64 < buffered_len) {
  5623. buffered_len = len64;
  5624. }
  5625. body = conn->buf + conn->request_len + conn->consumed_content;
  5626. memcpy(buf, body, (size_t)buffered_len);
  5627. len64 -= buffered_len;
  5628. conn->consumed_content += buffered_len;
  5629. nread += buffered_len;
  5630. buf = (char *)buf + buffered_len;
  5631. }
  5632. /* We have returned all buffered data. Read new data from the remote
  5633. * socket.
  5634. */
  5635. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5636. nread += n;
  5637. } else {
  5638. nread = ((nread > 0) ? nread : n);
  5639. }
  5640. }
  5641. return (int)nread;
  5642. }
  5643. static char
  5644. mg_getc(struct mg_connection *conn)
  5645. {
  5646. char c;
  5647. if (conn == NULL) {
  5648. return 0;
  5649. }
  5650. if (mg_read_inner(conn, &c, 1) <= 0) {
  5651. return (char)0;
  5652. }
  5653. return c;
  5654. }
  5655. int
  5656. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5657. {
  5658. if (len > INT_MAX) {
  5659. len = INT_MAX;
  5660. }
  5661. if (conn == NULL) {
  5662. return 0;
  5663. }
  5664. if (conn->is_chunked) {
  5665. size_t all_read = 0;
  5666. while (len > 0) {
  5667. if (conn->is_chunked == 3) {
  5668. /* No more data left to read */
  5669. return 0;
  5670. }
  5671. if (conn->chunk_remainder) {
  5672. /* copy from the remainder of the last received chunk */
  5673. long read_ret;
  5674. size_t read_now =
  5675. ((conn->chunk_remainder > len) ? (len)
  5676. : (conn->chunk_remainder));
  5677. conn->content_len += (int)read_now;
  5678. read_ret =
  5679. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5680. if (read_ret < 1) {
  5681. /* read error */
  5682. return -1;
  5683. }
  5684. all_read += (size_t)read_ret;
  5685. conn->chunk_remainder -= (size_t)read_ret;
  5686. len -= (size_t)read_ret;
  5687. if (conn->chunk_remainder == 0) {
  5688. /* Add data bytes in the current chunk have been read,
  5689. * so we are expecting \r\n now. */
  5690. char x1, x2;
  5691. conn->content_len += 2;
  5692. x1 = mg_getc(conn);
  5693. x2 = mg_getc(conn);
  5694. if ((x1 != '\r') || (x2 != '\n')) {
  5695. /* Protocol violation */
  5696. return -1;
  5697. }
  5698. }
  5699. } else {
  5700. /* fetch a new chunk */
  5701. int i = 0;
  5702. char lenbuf[64];
  5703. char *end = 0;
  5704. unsigned long chunkSize = 0;
  5705. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5706. conn->content_len++;
  5707. lenbuf[i] = mg_getc(conn);
  5708. if ((i > 0) && (lenbuf[i] == '\r')
  5709. && (lenbuf[i - 1] != '\r')) {
  5710. continue;
  5711. }
  5712. if ((i > 1) && (lenbuf[i] == '\n')
  5713. && (lenbuf[i - 1] == '\r')) {
  5714. lenbuf[i + 1] = 0;
  5715. chunkSize = strtoul(lenbuf, &end, 16);
  5716. if (chunkSize == 0) {
  5717. /* regular end of content */
  5718. conn->is_chunked = 3;
  5719. }
  5720. break;
  5721. }
  5722. if (!isxdigit(lenbuf[i])) {
  5723. /* illegal character for chunk length */
  5724. return -1;
  5725. }
  5726. }
  5727. if ((end == NULL) || (*end != '\r')) {
  5728. /* chunksize not set correctly */
  5729. return -1;
  5730. }
  5731. if (chunkSize == 0) {
  5732. break;
  5733. }
  5734. conn->chunk_remainder = chunkSize;
  5735. }
  5736. }
  5737. return (int)all_read;
  5738. }
  5739. return mg_read_inner(conn, buf, len);
  5740. }
  5741. int
  5742. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5743. {
  5744. time_t now;
  5745. int64_t n, total, allowed;
  5746. if (conn == NULL) {
  5747. return 0;
  5748. }
  5749. if (conn->throttle > 0) {
  5750. if ((now = time(NULL)) != conn->last_throttle_time) {
  5751. conn->last_throttle_time = now;
  5752. conn->last_throttle_bytes = 0;
  5753. }
  5754. allowed = conn->throttle - conn->last_throttle_bytes;
  5755. if (allowed > (int64_t)len) {
  5756. allowed = (int64_t)len;
  5757. }
  5758. if ((total = push_all(conn->phys_ctx,
  5759. NULL,
  5760. conn->client.sock,
  5761. conn->ssl,
  5762. (const char *)buf,
  5763. (int64_t)allowed))
  5764. == allowed) {
  5765. buf = (const char *)buf + total;
  5766. conn->last_throttle_bytes += total;
  5767. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5768. allowed = (conn->throttle > ((int64_t)len - total))
  5769. ? (int64_t)len - total
  5770. : conn->throttle;
  5771. if ((n = push_all(conn->phys_ctx,
  5772. NULL,
  5773. conn->client.sock,
  5774. conn->ssl,
  5775. (const char *)buf,
  5776. (int64_t)allowed))
  5777. != allowed) {
  5778. break;
  5779. }
  5780. sleep(1);
  5781. conn->last_throttle_bytes = allowed;
  5782. conn->last_throttle_time = time(NULL);
  5783. buf = (const char *)buf + n;
  5784. total += n;
  5785. }
  5786. }
  5787. } else {
  5788. total = push_all(conn->phys_ctx,
  5789. NULL,
  5790. conn->client.sock,
  5791. conn->ssl,
  5792. (const char *)buf,
  5793. (int64_t)len);
  5794. }
  5795. if (total > 0) {
  5796. conn->num_bytes_sent += total;
  5797. }
  5798. return (int)total;
  5799. }
  5800. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5801. int
  5802. mg_send_chunk(struct mg_connection *conn,
  5803. const char *chunk,
  5804. unsigned int chunk_len)
  5805. {
  5806. char lenbuf[16];
  5807. size_t lenbuf_len;
  5808. int ret;
  5809. int t;
  5810. /* First store the length information in a text buffer. */
  5811. sprintf(lenbuf, "%x\r\n", chunk_len);
  5812. lenbuf_len = strlen(lenbuf);
  5813. /* Then send length information, chunk and terminating \r\n. */
  5814. ret = mg_write(conn, lenbuf, lenbuf_len);
  5815. if (ret != (int)lenbuf_len) {
  5816. return -1;
  5817. }
  5818. t = ret;
  5819. ret = mg_write(conn, chunk, chunk_len);
  5820. if (ret != (int)chunk_len) {
  5821. return -1;
  5822. }
  5823. t += ret;
  5824. ret = mg_write(conn, "\r\n", 2);
  5825. if (ret != 2) {
  5826. return -1;
  5827. }
  5828. t += ret;
  5829. return t;
  5830. }
  5831. #if defined(GCC_DIAGNOSTIC)
  5832. /* This block forwards format strings to printf implementations,
  5833. * so we need to disable the format-nonliteral warning. */
  5834. #pragma GCC diagnostic push
  5835. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5836. #endif
  5837. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5838. static int
  5839. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5840. {
  5841. va_list ap_copy;
  5842. size_t size = MG_BUF_LEN / 4;
  5843. int len = -1;
  5844. *buf = NULL;
  5845. while (len < 0) {
  5846. if (*buf) {
  5847. mg_free(*buf);
  5848. }
  5849. size *= 4;
  5850. *buf = (char *)mg_malloc(size);
  5851. if (!*buf) {
  5852. break;
  5853. }
  5854. va_copy(ap_copy, ap);
  5855. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5856. va_end(ap_copy);
  5857. (*buf)[size - 1] = 0;
  5858. }
  5859. return len;
  5860. }
  5861. /* Print message to buffer. If buffer is large enough to hold the message,
  5862. * return buffer. If buffer is to small, allocate large enough buffer on
  5863. * heap,
  5864. * and return allocated buffer. */
  5865. static int
  5866. alloc_vprintf(char **out_buf,
  5867. char *prealloc_buf,
  5868. size_t prealloc_size,
  5869. const char *fmt,
  5870. va_list ap)
  5871. {
  5872. va_list ap_copy;
  5873. int len;
  5874. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5875. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5876. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5877. * Therefore, we make two passes: on first pass, get required message
  5878. * length.
  5879. * On second pass, actually print the message. */
  5880. va_copy(ap_copy, ap);
  5881. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5882. va_end(ap_copy);
  5883. if (len < 0) {
  5884. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5885. * Switch to alternative code path that uses incremental
  5886. * allocations.
  5887. */
  5888. va_copy(ap_copy, ap);
  5889. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5890. va_end(ap_copy);
  5891. } else if ((size_t)(len) >= prealloc_size) {
  5892. /* The pre-allocated buffer not large enough. */
  5893. /* Allocate a new buffer. */
  5894. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5895. if (!*out_buf) {
  5896. /* Allocation failed. Return -1 as "out of memory" error. */
  5897. return -1;
  5898. }
  5899. /* Buffer allocation successful. Store the string there. */
  5900. va_copy(ap_copy, ap);
  5901. IGNORE_UNUSED_RESULT(
  5902. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5903. va_end(ap_copy);
  5904. } else {
  5905. /* The pre-allocated buffer is large enough.
  5906. * Use it to store the string and return the address. */
  5907. va_copy(ap_copy, ap);
  5908. IGNORE_UNUSED_RESULT(
  5909. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5910. va_end(ap_copy);
  5911. *out_buf = prealloc_buf;
  5912. }
  5913. return len;
  5914. }
  5915. #if defined(GCC_DIAGNOSTIC)
  5916. /* Enable format-nonliteral warning again. */
  5917. #pragma GCC diagnostic pop
  5918. #endif
  5919. static int
  5920. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5921. {
  5922. char mem[MG_BUF_LEN];
  5923. char *buf = NULL;
  5924. int len;
  5925. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5926. len = mg_write(conn, buf, (size_t)len);
  5927. }
  5928. if ((buf != mem) && (buf != NULL)) {
  5929. mg_free(buf);
  5930. }
  5931. return len;
  5932. }
  5933. int
  5934. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5935. {
  5936. va_list ap;
  5937. int result;
  5938. va_start(ap, fmt);
  5939. result = mg_vprintf(conn, fmt, ap);
  5940. va_end(ap);
  5941. return result;
  5942. }
  5943. int
  5944. mg_url_decode(const char *src,
  5945. int src_len,
  5946. char *dst,
  5947. int dst_len,
  5948. int is_form_url_encoded)
  5949. {
  5950. int i, j, a, b;
  5951. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5952. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5953. if ((i < src_len - 2) && (src[i] == '%')
  5954. && isxdigit(*(const unsigned char *)(src + i + 1))
  5955. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5956. a = tolower(*(const unsigned char *)(src + i + 1));
  5957. b = tolower(*(const unsigned char *)(src + i + 2));
  5958. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5959. i += 2;
  5960. } else if (is_form_url_encoded && (src[i] == '+')) {
  5961. dst[j] = ' ';
  5962. } else {
  5963. dst[j] = src[i];
  5964. }
  5965. }
  5966. dst[j] = '\0'; /* Null-terminate the destination */
  5967. return (i >= src_len) ? j : -1;
  5968. }
  5969. int
  5970. mg_get_var(const char *data,
  5971. size_t data_len,
  5972. const char *name,
  5973. char *dst,
  5974. size_t dst_len)
  5975. {
  5976. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5977. }
  5978. int
  5979. mg_get_var2(const char *data,
  5980. size_t data_len,
  5981. const char *name,
  5982. char *dst,
  5983. size_t dst_len,
  5984. size_t occurrence)
  5985. {
  5986. const char *p, *e, *s;
  5987. size_t name_len;
  5988. int len;
  5989. if ((dst == NULL) || (dst_len == 0)) {
  5990. len = -2;
  5991. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5992. len = -1;
  5993. dst[0] = '\0';
  5994. } else {
  5995. name_len = strlen(name);
  5996. e = data + data_len;
  5997. len = -1;
  5998. dst[0] = '\0';
  5999. /* data is "var1=val1&var2=val2...". Find variable first */
  6000. for (p = data; p + name_len < e; p++) {
  6001. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6002. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6003. /* Point p to variable value */
  6004. p += name_len + 1;
  6005. /* Point s to the end of the value */
  6006. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6007. if (s == NULL) {
  6008. s = e;
  6009. }
  6010. DEBUG_ASSERT(s >= p);
  6011. if (s < p) {
  6012. return -3;
  6013. }
  6014. /* Decode variable into destination buffer */
  6015. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6016. /* Redirect error code from -1 to -2 (destination buffer too
  6017. * small). */
  6018. if (len == -1) {
  6019. len = -2;
  6020. }
  6021. break;
  6022. }
  6023. }
  6024. }
  6025. return len;
  6026. }
  6027. /* HCP24: some changes to compare hole var_name */
  6028. int
  6029. mg_get_cookie(const char *cookie_header,
  6030. const char *var_name,
  6031. char *dst,
  6032. size_t dst_size)
  6033. {
  6034. const char *s, *p, *end;
  6035. int name_len, len = -1;
  6036. if ((dst == NULL) || (dst_size == 0)) {
  6037. return -2;
  6038. }
  6039. dst[0] = '\0';
  6040. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6041. return -1;
  6042. }
  6043. name_len = (int)strlen(var_name);
  6044. end = s + strlen(s);
  6045. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6046. if (s[name_len] == '=') {
  6047. /* HCP24: now check is it a substring or a full cookie name */
  6048. if ((s == cookie_header) || (s[-1] == ' ')) {
  6049. s += name_len + 1;
  6050. if ((p = strchr(s, ' ')) == NULL) {
  6051. p = end;
  6052. }
  6053. if (p[-1] == ';') {
  6054. p--;
  6055. }
  6056. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6057. s++;
  6058. p--;
  6059. }
  6060. if ((size_t)(p - s) < dst_size) {
  6061. len = (int)(p - s);
  6062. mg_strlcpy(dst, s, (size_t)len + 1);
  6063. } else {
  6064. len = -3;
  6065. }
  6066. break;
  6067. }
  6068. }
  6069. }
  6070. return len;
  6071. }
  6072. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6073. static void
  6074. base64_encode(const unsigned char *src, int src_len, char *dst)
  6075. {
  6076. static const char *b64 =
  6077. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6078. int i, j, a, b, c;
  6079. for (i = j = 0; i < src_len; i += 3) {
  6080. a = src[i];
  6081. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6082. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6083. dst[j++] = b64[a >> 2];
  6084. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6085. if (i + 1 < src_len) {
  6086. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6087. }
  6088. if (i + 2 < src_len) {
  6089. dst[j++] = b64[c & 63];
  6090. }
  6091. }
  6092. while (j % 4 != 0) {
  6093. dst[j++] = '=';
  6094. }
  6095. dst[j++] = '\0';
  6096. }
  6097. #endif
  6098. #if defined(USE_LUA)
  6099. static unsigned char
  6100. b64reverse(char letter)
  6101. {
  6102. if ((letter >= 'A') && (letter <= 'Z')) {
  6103. return letter - 'A';
  6104. }
  6105. if ((letter >= 'a') && (letter <= 'z')) {
  6106. return letter - 'a' + 26;
  6107. }
  6108. if ((letter >= '0') && (letter <= '9')) {
  6109. return letter - '0' + 52;
  6110. }
  6111. if (letter == '+') {
  6112. return 62;
  6113. }
  6114. if (letter == '/') {
  6115. return 63;
  6116. }
  6117. if (letter == '=') {
  6118. return 255; /* normal end */
  6119. }
  6120. return 254; /* error */
  6121. }
  6122. static int
  6123. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6124. {
  6125. int i;
  6126. unsigned char a, b, c, d;
  6127. *dst_len = 0;
  6128. for (i = 0; i < src_len; i += 4) {
  6129. a = b64reverse(src[i]);
  6130. if (a >= 254) {
  6131. return i;
  6132. }
  6133. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6134. if (b >= 254) {
  6135. return i + 1;
  6136. }
  6137. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6138. if (c == 254) {
  6139. return i + 2;
  6140. }
  6141. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6142. if (d == 254) {
  6143. return i + 3;
  6144. }
  6145. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6146. if (c != 255) {
  6147. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6148. if (d != 255) {
  6149. dst[(*dst_len)++] = (c << 6) + d;
  6150. }
  6151. }
  6152. }
  6153. return -1;
  6154. }
  6155. #endif
  6156. static int
  6157. is_put_or_delete_method(const struct mg_connection *conn)
  6158. {
  6159. if (conn) {
  6160. const char *s = conn->request_info.request_method;
  6161. return (s != NULL)
  6162. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6163. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6164. }
  6165. return 0;
  6166. }
  6167. #if !defined(NO_FILES)
  6168. static int
  6169. extention_matches_script(
  6170. struct mg_connection *conn, /* in: request (must be valid) */
  6171. const char *filename /* in: filename (must be valid) */
  6172. )
  6173. {
  6174. #if !defined(NO_CGI)
  6175. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6176. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6177. filename)
  6178. > 0) {
  6179. return 1;
  6180. }
  6181. #endif
  6182. #if defined(USE_LUA)
  6183. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6184. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6185. filename)
  6186. > 0) {
  6187. return 1;
  6188. }
  6189. #endif
  6190. #if defined(USE_DUKTAPE)
  6191. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6192. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6193. filename)
  6194. > 0) {
  6195. return 1;
  6196. }
  6197. #endif
  6198. /* filename and conn could be unused, if all preocessor conditions
  6199. * are false (no script language supported). */
  6200. (void)filename;
  6201. (void)conn;
  6202. return 0;
  6203. }
  6204. /* For given directory path, substitute it to valid index file.
  6205. * Return 1 if index file has been found, 0 if not found.
  6206. * If the file is found, it's stats is returned in stp. */
  6207. static int
  6208. substitute_index_file(struct mg_connection *conn,
  6209. char *path,
  6210. size_t path_len,
  6211. struct mg_file_stat *filestat)
  6212. {
  6213. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6214. struct vec filename_vec;
  6215. size_t n = strlen(path);
  6216. int found = 0;
  6217. /* The 'path' given to us points to the directory. Remove all trailing
  6218. * directory separator characters from the end of the path, and
  6219. * then append single directory separator character. */
  6220. while ((n > 0) && (path[n - 1] == '/')) {
  6221. n--;
  6222. }
  6223. path[n] = '/';
  6224. /* Traverse index files list. For each entry, append it to the given
  6225. * path and see if the file exists. If it exists, break the loop */
  6226. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6227. /* Ignore too long entries that may overflow path buffer */
  6228. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6229. continue;
  6230. }
  6231. /* Prepare full path to the index file */
  6232. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6233. /* Does it exist? */
  6234. if (mg_stat(conn, path, filestat)) {
  6235. /* Yes it does, break the loop */
  6236. found = 1;
  6237. break;
  6238. }
  6239. }
  6240. /* If no index file exists, restore directory path */
  6241. if (!found) {
  6242. path[n] = '\0';
  6243. }
  6244. return found;
  6245. }
  6246. #endif
  6247. static void
  6248. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6249. char *filename, /* out: filename */
  6250. size_t filename_buf_len, /* in: size of filename buffer */
  6251. struct mg_file_stat *filestat, /* out: file status structure */
  6252. int *is_found, /* out: file found (directly) */
  6253. int *is_script_resource, /* out: handled by a script? */
  6254. int *is_websocket_request, /* out: websocket connetion? */
  6255. int *is_put_or_delete_request /* out: put/delete a file? */
  6256. )
  6257. {
  6258. char const *accept_encoding;
  6259. #if !defined(NO_FILES)
  6260. const char *uri = conn->request_info.local_uri;
  6261. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6262. const char *rewrite;
  6263. struct vec a, b;
  6264. ptrdiff_t match_len;
  6265. char gz_path[PATH_MAX];
  6266. int truncated;
  6267. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6268. char *tmp_str;
  6269. size_t tmp_str_len, sep_pos;
  6270. int allow_substitute_script_subresources;
  6271. #endif
  6272. #else
  6273. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6274. #endif
  6275. /* Step 1: Set all initially unknown outputs to zero */
  6276. memset(filestat, 0, sizeof(*filestat));
  6277. *filename = 0;
  6278. *is_found = 0;
  6279. *is_script_resource = 0;
  6280. /* Step 2: Check if the request attempts to modify the file system */
  6281. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6282. /* Step 3: Check if it is a websocket request, and modify the document
  6283. * root if required */
  6284. #if defined(USE_WEBSOCKET)
  6285. *is_websocket_request = is_websocket_protocol(conn);
  6286. #if !defined(NO_FILES)
  6287. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6288. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6289. }
  6290. #endif /* !NO_FILES */
  6291. #else /* USE_WEBSOCKET */
  6292. *is_websocket_request = 0;
  6293. #endif /* USE_WEBSOCKET */
  6294. /* Step 4: Check if gzip encoded response is allowed */
  6295. conn->accept_gzip = 0;
  6296. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6297. if (strstr(accept_encoding, "gzip") != NULL) {
  6298. conn->accept_gzip = 1;
  6299. }
  6300. }
  6301. #if !defined(NO_FILES)
  6302. /* Step 5: If there is no root directory, don't look for files. */
  6303. /* Note that root == NULL is a regular use case here. This occurs,
  6304. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6305. * config is not required. */
  6306. if (root == NULL) {
  6307. /* all file related outputs have already been set to 0, just return
  6308. */
  6309. return;
  6310. }
  6311. /* Step 6: Determine the local file path from the root path and the
  6312. * request uri. */
  6313. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6314. * part of the path one byte on the right. */
  6315. mg_snprintf(
  6316. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6317. if (truncated) {
  6318. goto interpret_cleanup;
  6319. }
  6320. /* Step 7: URI rewriting */
  6321. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6322. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6323. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6324. mg_snprintf(conn,
  6325. &truncated,
  6326. filename,
  6327. filename_buf_len - 1,
  6328. "%.*s%s",
  6329. (int)b.len,
  6330. b.ptr,
  6331. uri + match_len);
  6332. break;
  6333. }
  6334. }
  6335. if (truncated) {
  6336. goto interpret_cleanup;
  6337. }
  6338. /* Step 8: Check if the file exists at the server */
  6339. /* Local file path and name, corresponding to requested URI
  6340. * is now stored in "filename" variable. */
  6341. if (mg_stat(conn, filename, filestat)) {
  6342. int uri_len = (int)strlen(uri);
  6343. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6344. /* 8.1: File exists. */
  6345. *is_found = 1;
  6346. /* 8.2: Check if it is a script type. */
  6347. if (extention_matches_script(conn, filename)) {
  6348. /* The request addresses a CGI resource, Lua script or
  6349. * server-side javascript.
  6350. * The URI corresponds to the script itself (like
  6351. * /path/script.cgi), and there is no additional resource
  6352. * path (like /path/script.cgi/something).
  6353. * Requests that modify (replace or delete) a resource, like
  6354. * PUT and DELETE requests, should replace/delete the script
  6355. * file.
  6356. * Requests that read or write from/to a resource, like GET and
  6357. * POST requests, should call the script and return the
  6358. * generated response. */
  6359. *is_script_resource = (!*is_put_or_delete_request);
  6360. }
  6361. /* 8.3: If the request target is a directory, there could be
  6362. * a substitute file (index.html, index.cgi, ...). */
  6363. if (filestat->is_directory && is_uri_end_slash) {
  6364. /* Use a local copy here, since substitute_index_file will
  6365. * change the content of the file status */
  6366. struct mg_file_stat tmp_filestat;
  6367. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6368. if (substitute_index_file(
  6369. conn, filename, filename_buf_len, &tmp_filestat)) {
  6370. /* Substitute file found. Copy stat to the output, then
  6371. * check if the file is a script file */
  6372. *filestat = tmp_filestat;
  6373. if (extention_matches_script(conn, filename)) {
  6374. /* Substitute file is a script file */
  6375. *is_script_resource = 1;
  6376. } else {
  6377. /* Substitute file is a regular file */
  6378. *is_script_resource = 0;
  6379. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6380. }
  6381. }
  6382. /* If there is no substitute file, the server could return
  6383. * a directory listing in a later step */
  6384. }
  6385. return;
  6386. }
  6387. /* Step 9: Check for zipped files: */
  6388. /* If we can't find the actual file, look for the file
  6389. * with the same name but a .gz extension. If we find it,
  6390. * use that and set the gzipped flag in the file struct
  6391. * to indicate that the response need to have the content-
  6392. * encoding: gzip header.
  6393. * We can only do this if the browser declares support. */
  6394. if (conn->accept_gzip) {
  6395. mg_snprintf(
  6396. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6397. if (truncated) {
  6398. goto interpret_cleanup;
  6399. }
  6400. if (mg_stat(conn, gz_path, filestat)) {
  6401. if (filestat) {
  6402. filestat->is_gzipped = 1;
  6403. *is_found = 1;
  6404. }
  6405. /* Currently gz files can not be scripts. */
  6406. return;
  6407. }
  6408. }
  6409. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6410. /* Step 10: Script resources may handle sub-resources */
  6411. /* Support PATH_INFO for CGI scripts. */
  6412. tmp_str_len = strlen(filename);
  6413. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6414. if (!tmp_str) {
  6415. /* Out of memory */
  6416. goto interpret_cleanup;
  6417. }
  6418. memcpy(tmp_str, filename, tmp_str_len + 1);
  6419. /* Check config, if index scripts may have sub-resources */
  6420. allow_substitute_script_subresources =
  6421. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6422. "yes");
  6423. sep_pos = tmp_str_len;
  6424. while (sep_pos > 0) {
  6425. sep_pos--;
  6426. if (tmp_str[sep_pos] == '/') {
  6427. int is_script = 0, does_exist = 0;
  6428. tmp_str[sep_pos] = 0;
  6429. if (tmp_str[0]) {
  6430. is_script = extention_matches_script(conn, tmp_str);
  6431. does_exist = mg_stat(conn, tmp_str, filestat);
  6432. }
  6433. if (does_exist && is_script) {
  6434. filename[sep_pos] = 0;
  6435. memmove(filename + sep_pos + 2,
  6436. filename + sep_pos + 1,
  6437. strlen(filename + sep_pos + 1) + 1);
  6438. conn->path_info = filename + sep_pos + 1;
  6439. filename[sep_pos + 1] = '/';
  6440. *is_script_resource = 1;
  6441. *is_found = 1;
  6442. break;
  6443. }
  6444. if (allow_substitute_script_subresources) {
  6445. if (substitute_index_file(
  6446. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6447. /* some intermediate directory has an index file */
  6448. if (extention_matches_script(conn, tmp_str)) {
  6449. char *tmp_str2;
  6450. DEBUG_TRACE("Substitute script %s serving path %s",
  6451. tmp_str,
  6452. filename);
  6453. /* this index file is a script */
  6454. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6455. conn->phys_ctx);
  6456. mg_snprintf(conn,
  6457. &truncated,
  6458. filename,
  6459. filename_buf_len,
  6460. "%s//%s",
  6461. tmp_str,
  6462. tmp_str2);
  6463. mg_free(tmp_str2);
  6464. if (truncated) {
  6465. mg_free(tmp_str);
  6466. goto interpret_cleanup;
  6467. }
  6468. sep_pos = strlen(tmp_str);
  6469. filename[sep_pos] = 0;
  6470. conn->path_info = filename + sep_pos + 1;
  6471. *is_script_resource = 1;
  6472. *is_found = 1;
  6473. break;
  6474. } else {
  6475. DEBUG_TRACE("Substitute file %s serving path %s",
  6476. tmp_str,
  6477. filename);
  6478. /* non-script files will not have sub-resources */
  6479. filename[sep_pos] = 0;
  6480. conn->path_info = 0;
  6481. *is_script_resource = 0;
  6482. *is_found = 0;
  6483. break;
  6484. }
  6485. }
  6486. }
  6487. tmp_str[sep_pos] = '/';
  6488. }
  6489. }
  6490. mg_free(tmp_str);
  6491. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6492. #endif /* !defined(NO_FILES) */
  6493. return;
  6494. #if !defined(NO_FILES)
  6495. /* Reset all outputs */
  6496. interpret_cleanup:
  6497. memset(filestat, 0, sizeof(*filestat));
  6498. *filename = 0;
  6499. *is_found = 0;
  6500. *is_script_resource = 0;
  6501. *is_websocket_request = 0;
  6502. *is_put_or_delete_request = 0;
  6503. #endif /* !defined(NO_FILES) */
  6504. }
  6505. /* Check whether full request is buffered. Return:
  6506. * -1 if request or response is malformed
  6507. * 0 if request or response is not yet fully buffered
  6508. * >0 actual request length, including last \r\n\r\n */
  6509. static int
  6510. get_http_header_len(const char *buf, int buflen)
  6511. {
  6512. int i;
  6513. for (i = 0; i < buflen; i++) {
  6514. /* Do an unsigned comparison in some conditions below */
  6515. const unsigned char c = ((const unsigned char *)buf)[i];
  6516. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6517. && !isprint(c)) {
  6518. /* abort scan as soon as one malformed character is found */
  6519. return -1;
  6520. }
  6521. if (i < buflen - 1) {
  6522. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6523. /* Two newline, no carriage return - not standard compliant,
  6524. * but
  6525. * it
  6526. * should be accepted */
  6527. return i + 2;
  6528. }
  6529. }
  6530. if (i < buflen - 3) {
  6531. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6532. && (buf[i + 3] == '\n')) {
  6533. /* Two \r\n - standard compliant */
  6534. return i + 4;
  6535. }
  6536. }
  6537. }
  6538. return 0;
  6539. }
  6540. #if !defined(NO_CACHING)
  6541. /* Convert month to the month number. Return -1 on error, or month number */
  6542. static int
  6543. get_month_index(const char *s)
  6544. {
  6545. size_t i;
  6546. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6547. if (!strcmp(s, month_names[i])) {
  6548. return (int)i;
  6549. }
  6550. }
  6551. return -1;
  6552. }
  6553. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6554. static time_t
  6555. parse_date_string(const char *datetime)
  6556. {
  6557. char month_str[32] = {0};
  6558. int second, minute, hour, day, month, year;
  6559. time_t result = (time_t)0;
  6560. struct tm tm;
  6561. if ((sscanf(datetime,
  6562. "%d/%3s/%d %d:%d:%d",
  6563. &day,
  6564. month_str,
  6565. &year,
  6566. &hour,
  6567. &minute,
  6568. &second)
  6569. == 6)
  6570. || (sscanf(datetime,
  6571. "%d %3s %d %d:%d:%d",
  6572. &day,
  6573. month_str,
  6574. &year,
  6575. &hour,
  6576. &minute,
  6577. &second)
  6578. == 6)
  6579. || (sscanf(datetime,
  6580. "%*3s, %d %3s %d %d:%d:%d",
  6581. &day,
  6582. month_str,
  6583. &year,
  6584. &hour,
  6585. &minute,
  6586. &second)
  6587. == 6)
  6588. || (sscanf(datetime,
  6589. "%d-%3s-%d %d:%d:%d",
  6590. &day,
  6591. month_str,
  6592. &year,
  6593. &hour,
  6594. &minute,
  6595. &second)
  6596. == 6)) {
  6597. month = get_month_index(month_str);
  6598. if ((month >= 0) && (year >= 1970)) {
  6599. memset(&tm, 0, sizeof(tm));
  6600. tm.tm_year = year - 1900;
  6601. tm.tm_mon = month;
  6602. tm.tm_mday = day;
  6603. tm.tm_hour = hour;
  6604. tm.tm_min = minute;
  6605. tm.tm_sec = second;
  6606. result = timegm(&tm);
  6607. }
  6608. }
  6609. return result;
  6610. }
  6611. #endif /* !NO_CACHING */
  6612. /* Protect against directory disclosure attack by removing '..',
  6613. * excessive '/' and '\' characters */
  6614. static void
  6615. remove_double_dots_and_double_slashes(char *s)
  6616. {
  6617. char *p = s;
  6618. while ((s[0] == '.') && (s[1] == '.')) {
  6619. s++;
  6620. }
  6621. while (*s != '\0') {
  6622. *p++ = *s++;
  6623. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6624. /* Skip all following slashes, backslashes and double-dots */
  6625. while (s[0] != '\0') {
  6626. if ((s[0] == '/') || (s[0] == '\\')) {
  6627. s++;
  6628. } else if ((s[0] == '.') && (s[1] == '.')) {
  6629. s += 2;
  6630. } else {
  6631. break;
  6632. }
  6633. }
  6634. }
  6635. }
  6636. *p = '\0';
  6637. }
  6638. static const struct {
  6639. const char *extension;
  6640. size_t ext_len;
  6641. const char *mime_type;
  6642. } builtin_mime_types[] = {
  6643. /* IANA registered MIME types
  6644. * (http://www.iana.org/assignments/media-types)
  6645. * application types */
  6646. {".doc", 4, "application/msword"},
  6647. {".eps", 4, "application/postscript"},
  6648. {".exe", 4, "application/octet-stream"},
  6649. {".js", 3, "application/javascript"},
  6650. {".json", 5, "application/json"},
  6651. {".pdf", 4, "application/pdf"},
  6652. {".ps", 3, "application/postscript"},
  6653. {".rtf", 4, "application/rtf"},
  6654. {".xhtml", 6, "application/xhtml+xml"},
  6655. {".xsl", 4, "application/xml"},
  6656. {".xslt", 5, "application/xml"},
  6657. /* fonts */
  6658. {".ttf", 4, "application/font-sfnt"},
  6659. {".cff", 4, "application/font-sfnt"},
  6660. {".otf", 4, "application/font-sfnt"},
  6661. {".aat", 4, "application/font-sfnt"},
  6662. {".sil", 4, "application/font-sfnt"},
  6663. {".pfr", 4, "application/font-tdpfr"},
  6664. {".woff", 5, "application/font-woff"},
  6665. /* audio */
  6666. {".mp3", 4, "audio/mpeg"},
  6667. {".oga", 4, "audio/ogg"},
  6668. {".ogg", 4, "audio/ogg"},
  6669. /* image */
  6670. {".gif", 4, "image/gif"},
  6671. {".ief", 4, "image/ief"},
  6672. {".jpeg", 5, "image/jpeg"},
  6673. {".jpg", 4, "image/jpeg"},
  6674. {".jpm", 4, "image/jpm"},
  6675. {".jpx", 4, "image/jpx"},
  6676. {".png", 4, "image/png"},
  6677. {".svg", 4, "image/svg+xml"},
  6678. {".tif", 4, "image/tiff"},
  6679. {".tiff", 5, "image/tiff"},
  6680. /* model */
  6681. {".wrl", 4, "model/vrml"},
  6682. /* text */
  6683. {".css", 4, "text/css"},
  6684. {".csv", 4, "text/csv"},
  6685. {".htm", 4, "text/html"},
  6686. {".html", 5, "text/html"},
  6687. {".sgm", 4, "text/sgml"},
  6688. {".shtm", 5, "text/html"},
  6689. {".shtml", 6, "text/html"},
  6690. {".txt", 4, "text/plain"},
  6691. {".xml", 4, "text/xml"},
  6692. /* video */
  6693. {".mov", 4, "video/quicktime"},
  6694. {".mp4", 4, "video/mp4"},
  6695. {".mpeg", 5, "video/mpeg"},
  6696. {".mpg", 4, "video/mpeg"},
  6697. {".ogv", 4, "video/ogg"},
  6698. {".qt", 3, "video/quicktime"},
  6699. /* not registered types
  6700. * (http://reference.sitepoint.com/html/mime-types-full,
  6701. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6702. {".arj", 4, "application/x-arj-compressed"},
  6703. {".gz", 3, "application/x-gunzip"},
  6704. {".rar", 4, "application/x-arj-compressed"},
  6705. {".swf", 4, "application/x-shockwave-flash"},
  6706. {".tar", 4, "application/x-tar"},
  6707. {".tgz", 4, "application/x-tar-gz"},
  6708. {".torrent", 8, "application/x-bittorrent"},
  6709. {".ppt", 4, "application/x-mspowerpoint"},
  6710. {".xls", 4, "application/x-msexcel"},
  6711. {".zip", 4, "application/x-zip-compressed"},
  6712. {".aac",
  6713. 4,
  6714. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6715. {".aif", 4, "audio/x-aif"},
  6716. {".m3u", 4, "audio/x-mpegurl"},
  6717. {".mid", 4, "audio/x-midi"},
  6718. {".ra", 3, "audio/x-pn-realaudio"},
  6719. {".ram", 4, "audio/x-pn-realaudio"},
  6720. {".wav", 4, "audio/x-wav"},
  6721. {".bmp", 4, "image/bmp"},
  6722. {".ico", 4, "image/x-icon"},
  6723. {".pct", 4, "image/x-pct"},
  6724. {".pict", 5, "image/pict"},
  6725. {".rgb", 4, "image/x-rgb"},
  6726. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6727. {".asf", 4, "video/x-ms-asf"},
  6728. {".avi", 4, "video/x-msvideo"},
  6729. {".m4v", 4, "video/x-m4v"},
  6730. {NULL, 0, NULL}};
  6731. const char *
  6732. mg_get_builtin_mime_type(const char *path)
  6733. {
  6734. const char *ext;
  6735. size_t i, path_len;
  6736. path_len = strlen(path);
  6737. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6738. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6739. if ((path_len > builtin_mime_types[i].ext_len)
  6740. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6741. return builtin_mime_types[i].mime_type;
  6742. }
  6743. }
  6744. return "text/plain";
  6745. }
  6746. /* Look at the "path" extension and figure what mime type it has.
  6747. * Store mime type in the vector. */
  6748. static void
  6749. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6750. {
  6751. struct vec ext_vec, mime_vec;
  6752. const char *list, *ext;
  6753. size_t path_len;
  6754. path_len = strlen(path);
  6755. if ((conn == NULL) || (vec == NULL)) {
  6756. if (vec != NULL) {
  6757. memset(vec, '\0', sizeof(struct vec));
  6758. }
  6759. return;
  6760. }
  6761. /* Scan user-defined mime types first, in case user wants to
  6762. * override default mime types. */
  6763. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6764. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6765. /* ext now points to the path suffix */
  6766. ext = path + path_len - ext_vec.len;
  6767. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6768. *vec = mime_vec;
  6769. return;
  6770. }
  6771. }
  6772. vec->ptr = mg_get_builtin_mime_type(path);
  6773. vec->len = strlen(vec->ptr);
  6774. }
  6775. /* Stringify binary data. Output buffer must be twice as big as input,
  6776. * because each byte takes 2 bytes in string representation */
  6777. static void
  6778. bin2str(char *to, const unsigned char *p, size_t len)
  6779. {
  6780. static const char *hex = "0123456789abcdef";
  6781. for (; len--; p++) {
  6782. *to++ = hex[p[0] >> 4];
  6783. *to++ = hex[p[0] & 0x0f];
  6784. }
  6785. *to = '\0';
  6786. }
  6787. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6788. */
  6789. char *
  6790. mg_md5(char buf[33], ...)
  6791. {
  6792. md5_byte_t hash[16];
  6793. const char *p;
  6794. va_list ap;
  6795. md5_state_t ctx;
  6796. md5_init(&ctx);
  6797. va_start(ap, buf);
  6798. while ((p = va_arg(ap, const char *)) != NULL) {
  6799. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6800. }
  6801. va_end(ap);
  6802. md5_finish(&ctx, hash);
  6803. bin2str(buf, hash, sizeof(hash));
  6804. return buf;
  6805. }
  6806. /* Check the user's password, return 1 if OK */
  6807. static int
  6808. check_password(const char *method,
  6809. const char *ha1,
  6810. const char *uri,
  6811. const char *nonce,
  6812. const char *nc,
  6813. const char *cnonce,
  6814. const char *qop,
  6815. const char *response)
  6816. {
  6817. char ha2[32 + 1], expected_response[32 + 1];
  6818. /* Some of the parameters may be NULL */
  6819. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6820. || (qop == NULL) || (response == NULL)) {
  6821. return 0;
  6822. }
  6823. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6824. if (strlen(response) != 32) {
  6825. return 0;
  6826. }
  6827. mg_md5(ha2, method, ":", uri, NULL);
  6828. mg_md5(expected_response,
  6829. ha1,
  6830. ":",
  6831. nonce,
  6832. ":",
  6833. nc,
  6834. ":",
  6835. cnonce,
  6836. ":",
  6837. qop,
  6838. ":",
  6839. ha2,
  6840. NULL);
  6841. return mg_strcasecmp(response, expected_response) == 0;
  6842. }
  6843. /* Use the global passwords file, if specified by auth_gpass option,
  6844. * or search for .htpasswd in the requested directory. */
  6845. static void
  6846. open_auth_file(struct mg_connection *conn,
  6847. const char *path,
  6848. struct mg_file *filep)
  6849. {
  6850. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6851. char name[PATH_MAX];
  6852. const char *p, *e,
  6853. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6854. int truncated;
  6855. if (gpass != NULL) {
  6856. /* Use global passwords file */
  6857. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6858. #if defined(DEBUG)
  6859. /* Use mg_cry_internal here, since gpass has been configured. */
  6860. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6861. #endif
  6862. }
  6863. /* Important: using local struct mg_file to test path for
  6864. * is_directory flag. If filep is used, mg_stat() makes it
  6865. * appear as if auth file was opened.
  6866. * TODO(mid): Check if this is still required after rewriting
  6867. * mg_stat */
  6868. } else if (mg_stat(conn, path, &filep->stat)
  6869. && filep->stat.is_directory) {
  6870. mg_snprintf(conn,
  6871. &truncated,
  6872. name,
  6873. sizeof(name),
  6874. "%s/%s",
  6875. path,
  6876. PASSWORDS_FILE_NAME);
  6877. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6878. #if defined(DEBUG)
  6879. /* Don't use mg_cry_internal here, but only a trace, since this
  6880. * is
  6881. * a typical case. It will occur for every directory
  6882. * without a password file. */
  6883. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6884. #endif
  6885. }
  6886. } else {
  6887. /* Try to find .htpasswd in requested directory. */
  6888. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6889. if (e[0] == '/') {
  6890. break;
  6891. }
  6892. }
  6893. mg_snprintf(conn,
  6894. &truncated,
  6895. name,
  6896. sizeof(name),
  6897. "%.*s/%s",
  6898. (int)(e - p),
  6899. p,
  6900. PASSWORDS_FILE_NAME);
  6901. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6902. #if defined(DEBUG)
  6903. /* Don't use mg_cry_internal here, but only a trace, since this
  6904. * is
  6905. * a typical case. It will occur for every directory
  6906. * without a password file. */
  6907. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6908. #endif
  6909. }
  6910. }
  6911. }
  6912. }
  6913. /* Parsed Authorization header */
  6914. struct ah {
  6915. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6916. };
  6917. /* Return 1 on success. Always initializes the ah structure. */
  6918. static int
  6919. parse_auth_header(struct mg_connection *conn,
  6920. char *buf,
  6921. size_t buf_size,
  6922. struct ah *ah)
  6923. {
  6924. char *name, *value, *s;
  6925. const char *auth_header;
  6926. uint64_t nonce;
  6927. if (!ah || !conn) {
  6928. return 0;
  6929. }
  6930. (void)memset(ah, 0, sizeof(*ah));
  6931. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6932. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6933. return 0;
  6934. }
  6935. /* Make modifiable copy of the auth header */
  6936. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6937. s = buf;
  6938. /* Parse authorization header */
  6939. for (;;) {
  6940. /* Gobble initial spaces */
  6941. while (isspace(*(unsigned char *)s)) {
  6942. s++;
  6943. }
  6944. name = skip_quoted(&s, "=", " ", 0);
  6945. /* Value is either quote-delimited, or ends at first comma or space.
  6946. */
  6947. if (s[0] == '\"') {
  6948. s++;
  6949. value = skip_quoted(&s, "\"", " ", '\\');
  6950. if (s[0] == ',') {
  6951. s++;
  6952. }
  6953. } else {
  6954. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6955. * spaces */
  6956. }
  6957. if (*name == '\0') {
  6958. break;
  6959. }
  6960. if (!strcmp(name, "username")) {
  6961. ah->user = value;
  6962. } else if (!strcmp(name, "cnonce")) {
  6963. ah->cnonce = value;
  6964. } else if (!strcmp(name, "response")) {
  6965. ah->response = value;
  6966. } else if (!strcmp(name, "uri")) {
  6967. ah->uri = value;
  6968. } else if (!strcmp(name, "qop")) {
  6969. ah->qop = value;
  6970. } else if (!strcmp(name, "nc")) {
  6971. ah->nc = value;
  6972. } else if (!strcmp(name, "nonce")) {
  6973. ah->nonce = value;
  6974. }
  6975. }
  6976. #if !defined(NO_NONCE_CHECK)
  6977. /* Read the nonce from the response. */
  6978. if (ah->nonce == NULL) {
  6979. return 0;
  6980. }
  6981. s = NULL;
  6982. nonce = strtoull(ah->nonce, &s, 10);
  6983. if ((s == NULL) || (*s != 0)) {
  6984. return 0;
  6985. }
  6986. /* Convert the nonce from the client to a number. */
  6987. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6988. /* The converted number corresponds to the time the nounce has been
  6989. * created. This should not be earlier than the server start. */
  6990. /* Server side nonce check is valuable in all situations but one:
  6991. * if the server restarts frequently, but the client should not see
  6992. * that, so the server should accept nonces from previous starts. */
  6993. /* However, the reasonable default is to not accept a nonce from a
  6994. * previous start, so if anyone changed the access rights between
  6995. * two restarts, a new login is required. */
  6996. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6997. /* nonce is from a previous start of the server and no longer valid
  6998. * (replay attack?) */
  6999. return 0;
  7000. }
  7001. /* Check if the nonce is too high, so it has not (yet) been used by the
  7002. * server. */
  7003. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7004. + conn->dom_ctx->nonce_count)) {
  7005. return 0;
  7006. }
  7007. #else
  7008. (void)nonce;
  7009. #endif
  7010. /* CGI needs it as REMOTE_USER */
  7011. if (ah->user != NULL) {
  7012. conn->request_info.remote_user =
  7013. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7014. } else {
  7015. return 0;
  7016. }
  7017. return 1;
  7018. }
  7019. static const char *
  7020. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7021. {
  7022. #if defined(MG_USE_OPEN_FILE)
  7023. const char *eof;
  7024. size_t len;
  7025. const char *memend;
  7026. #else
  7027. (void)p; /* parameter is unused */
  7028. #endif
  7029. if (!filep) {
  7030. return NULL;
  7031. }
  7032. #if defined(MG_USE_OPEN_FILE)
  7033. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7034. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7035. /* Search for \n from p till the end of stream */
  7036. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7037. if (eof != NULL) {
  7038. eof += 1; /* Include \n */
  7039. } else {
  7040. eof = memend; /* Copy remaining data */
  7041. }
  7042. len =
  7043. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7044. memcpy(buf, *p, len);
  7045. buf[len] = '\0';
  7046. *p += len;
  7047. return len ? eof : NULL;
  7048. } else /* filep->access.fp block below */
  7049. #endif
  7050. if (filep->access.fp != NULL) {
  7051. return fgets(buf, (int)size, filep->access.fp);
  7052. } else {
  7053. return NULL;
  7054. }
  7055. }
  7056. /* Define the initial recursion depth for procesesing htpasswd files that
  7057. * include other htpasswd
  7058. * (or even the same) files. It is not difficult to provide a file or files
  7059. * s.t. they force civetweb
  7060. * to infinitely recurse and then crash.
  7061. */
  7062. #define INITIAL_DEPTH 9
  7063. #if INITIAL_DEPTH <= 0
  7064. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7065. #endif
  7066. struct read_auth_file_struct {
  7067. struct mg_connection *conn;
  7068. struct ah ah;
  7069. const char *domain;
  7070. char buf[256 + 256 + 40];
  7071. const char *f_user;
  7072. const char *f_domain;
  7073. const char *f_ha1;
  7074. };
  7075. static int
  7076. read_auth_file(struct mg_file *filep,
  7077. struct read_auth_file_struct *workdata,
  7078. int depth)
  7079. {
  7080. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7081. int is_authorized = 0;
  7082. struct mg_file fp;
  7083. size_t l;
  7084. if (!filep || !workdata || (0 == depth)) {
  7085. return 0;
  7086. }
  7087. /* Loop over passwords file */
  7088. #if defined(MG_USE_OPEN_FILE)
  7089. p = (char *)filep->access.membuf;
  7090. #endif
  7091. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7092. l = strlen(workdata->buf);
  7093. while (l > 0) {
  7094. if (isspace(workdata->buf[l - 1])
  7095. || iscntrl(workdata->buf[l - 1])) {
  7096. l--;
  7097. workdata->buf[l] = 0;
  7098. } else
  7099. break;
  7100. }
  7101. if (l < 1) {
  7102. continue;
  7103. }
  7104. workdata->f_user = workdata->buf;
  7105. if (workdata->f_user[0] == ':') {
  7106. /* user names may not contain a ':' and may not be empty,
  7107. * so lines starting with ':' may be used for a special purpose
  7108. */
  7109. if (workdata->f_user[1] == '#') {
  7110. /* :# is a comment */
  7111. continue;
  7112. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7113. if (mg_fopen(workdata->conn,
  7114. workdata->f_user + 9,
  7115. MG_FOPEN_MODE_READ,
  7116. &fp)) {
  7117. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7118. (void)mg_fclose(
  7119. &fp.access); /* ignore error on read only file */
  7120. /* No need to continue processing files once we have a
  7121. * match, since nothing will reset it back
  7122. * to 0.
  7123. */
  7124. if (is_authorized) {
  7125. return is_authorized;
  7126. }
  7127. } else {
  7128. mg_cry_internal(workdata->conn,
  7129. "%s: cannot open authorization file: %s",
  7130. __func__,
  7131. workdata->buf);
  7132. }
  7133. continue;
  7134. }
  7135. /* everything is invalid for the moment (might change in the
  7136. * future) */
  7137. mg_cry_internal(workdata->conn,
  7138. "%s: syntax error in authorization file: %s",
  7139. __func__,
  7140. workdata->buf);
  7141. continue;
  7142. }
  7143. workdata->f_domain = strchr(workdata->f_user, ':');
  7144. if (workdata->f_domain == NULL) {
  7145. mg_cry_internal(workdata->conn,
  7146. "%s: syntax error in authorization file: %s",
  7147. __func__,
  7148. workdata->buf);
  7149. continue;
  7150. }
  7151. *(char *)(workdata->f_domain) = 0;
  7152. (workdata->f_domain)++;
  7153. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7154. if (workdata->f_ha1 == NULL) {
  7155. mg_cry_internal(workdata->conn,
  7156. "%s: syntax error in authorization file: %s",
  7157. __func__,
  7158. workdata->buf);
  7159. continue;
  7160. }
  7161. *(char *)(workdata->f_ha1) = 0;
  7162. (workdata->f_ha1)++;
  7163. if (!strcmp(workdata->ah.user, workdata->f_user)
  7164. && !strcmp(workdata->domain, workdata->f_domain)) {
  7165. return check_password(workdata->conn->request_info.request_method,
  7166. workdata->f_ha1,
  7167. workdata->ah.uri,
  7168. workdata->ah.nonce,
  7169. workdata->ah.nc,
  7170. workdata->ah.cnonce,
  7171. workdata->ah.qop,
  7172. workdata->ah.response);
  7173. }
  7174. }
  7175. return is_authorized;
  7176. }
  7177. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7178. static int
  7179. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7180. {
  7181. struct read_auth_file_struct workdata;
  7182. char buf[MG_BUF_LEN];
  7183. if (!conn || !conn->dom_ctx) {
  7184. return 0;
  7185. }
  7186. memset(&workdata, 0, sizeof(workdata));
  7187. workdata.conn = conn;
  7188. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7189. return 0;
  7190. }
  7191. if (realm) {
  7192. workdata.domain = realm;
  7193. } else {
  7194. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7195. }
  7196. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7197. }
  7198. /* Public function to check http digest authentication header */
  7199. int
  7200. mg_check_digest_access_authentication(struct mg_connection *conn,
  7201. const char *realm,
  7202. const char *filename)
  7203. {
  7204. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7205. int auth;
  7206. if (!conn || !filename) {
  7207. return -1;
  7208. }
  7209. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7210. return -2;
  7211. }
  7212. auth = authorize(conn, &file, realm);
  7213. mg_fclose(&file.access);
  7214. return auth;
  7215. }
  7216. /* Return 1 if request is authorised, 0 otherwise. */
  7217. static int
  7218. check_authorization(struct mg_connection *conn, const char *path)
  7219. {
  7220. char fname[PATH_MAX];
  7221. struct vec uri_vec, filename_vec;
  7222. const char *list;
  7223. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7224. int authorized = 1, truncated;
  7225. if (!conn || !conn->dom_ctx) {
  7226. return 0;
  7227. }
  7228. list = conn->dom_ctx->config[PROTECT_URI];
  7229. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7230. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7231. mg_snprintf(conn,
  7232. &truncated,
  7233. fname,
  7234. sizeof(fname),
  7235. "%.*s",
  7236. (int)filename_vec.len,
  7237. filename_vec.ptr);
  7238. if (truncated
  7239. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7240. mg_cry_internal(conn,
  7241. "%s: cannot open %s: %s",
  7242. __func__,
  7243. fname,
  7244. strerror(errno));
  7245. }
  7246. break;
  7247. }
  7248. }
  7249. if (!is_file_opened(&file.access)) {
  7250. open_auth_file(conn, path, &file);
  7251. }
  7252. if (is_file_opened(&file.access)) {
  7253. authorized = authorize(conn, &file, NULL);
  7254. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7255. }
  7256. return authorized;
  7257. }
  7258. /* Internal function. Assumes conn is valid */
  7259. static void
  7260. send_authorization_request(struct mg_connection *conn, const char *realm)
  7261. {
  7262. char date[64];
  7263. time_t curtime = time(NULL);
  7264. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7265. if (!realm) {
  7266. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7267. }
  7268. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7269. nonce += conn->dom_ctx->nonce_count;
  7270. ++conn->dom_ctx->nonce_count;
  7271. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7272. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7273. conn->status_code = 401;
  7274. conn->must_close = 1;
  7275. gmt_time_string(date, sizeof(date), &curtime);
  7276. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7277. send_no_cache_header(conn);
  7278. send_additional_header(conn);
  7279. mg_printf(conn,
  7280. "Date: %s\r\n"
  7281. "Connection: %s\r\n"
  7282. "Content-Length: 0\r\n"
  7283. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7284. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7285. date,
  7286. suggest_connection_header(conn),
  7287. realm,
  7288. nonce);
  7289. }
  7290. /* Interface function. Parameters are provided by the user, so do
  7291. * at least some basic checks.
  7292. */
  7293. int
  7294. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7295. const char *realm)
  7296. {
  7297. if (conn && conn->dom_ctx) {
  7298. send_authorization_request(conn, realm);
  7299. return 0;
  7300. }
  7301. return -1;
  7302. }
  7303. #if !defined(NO_FILES)
  7304. static int
  7305. is_authorized_for_put(struct mg_connection *conn)
  7306. {
  7307. if (conn) {
  7308. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7309. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7310. int ret = 0;
  7311. if (passfile != NULL
  7312. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7313. ret = authorize(conn, &file, NULL);
  7314. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7315. }
  7316. return ret;
  7317. }
  7318. return 0;
  7319. }
  7320. #endif
  7321. int
  7322. mg_modify_passwords_file(const char *fname,
  7323. const char *domain,
  7324. const char *user,
  7325. const char *pass)
  7326. {
  7327. int found, i;
  7328. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7329. FILE *fp, *fp2;
  7330. found = 0;
  7331. fp = fp2 = NULL;
  7332. /* Regard empty password as no password - remove user record. */
  7333. if ((pass != NULL) && (pass[0] == '\0')) {
  7334. pass = NULL;
  7335. }
  7336. /* Other arguments must not be empty */
  7337. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7338. return 0;
  7339. }
  7340. /* Using the given file format, user name and domain must not contain
  7341. * ':'
  7342. */
  7343. if (strchr(user, ':') != NULL) {
  7344. return 0;
  7345. }
  7346. if (strchr(domain, ':') != NULL) {
  7347. return 0;
  7348. }
  7349. /* Do not allow control characters like newline in user name and domain.
  7350. * Do not allow excessively long names either. */
  7351. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7352. if (iscntrl(user[i])) {
  7353. return 0;
  7354. }
  7355. }
  7356. if (user[i]) {
  7357. return 0;
  7358. }
  7359. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7360. if (iscntrl(domain[i])) {
  7361. return 0;
  7362. }
  7363. }
  7364. if (domain[i]) {
  7365. return 0;
  7366. }
  7367. /* The maximum length of the path to the password file is limited */
  7368. if ((strlen(fname) + 4) >= PATH_MAX) {
  7369. return 0;
  7370. }
  7371. /* Create a temporary file name. Length has been checked before. */
  7372. strcpy(tmp, fname);
  7373. strcat(tmp, ".tmp");
  7374. /* Create the file if does not exist */
  7375. /* Use of fopen here is OK, since fname is only ASCII */
  7376. if ((fp = fopen(fname, "a+")) != NULL) {
  7377. (void)fclose(fp);
  7378. }
  7379. /* Open the given file and temporary file */
  7380. if ((fp = fopen(fname, "r")) == NULL) {
  7381. return 0;
  7382. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7383. fclose(fp);
  7384. return 0;
  7385. }
  7386. /* Copy the stuff to temporary file */
  7387. while (fgets(line, sizeof(line), fp) != NULL) {
  7388. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7389. continue;
  7390. }
  7391. u[255] = 0;
  7392. d[255] = 0;
  7393. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7394. found++;
  7395. if (pass != NULL) {
  7396. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7397. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7398. }
  7399. } else {
  7400. fprintf(fp2, "%s", line);
  7401. }
  7402. }
  7403. /* If new user, just add it */
  7404. if (!found && (pass != NULL)) {
  7405. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7406. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7407. }
  7408. /* Close files */
  7409. fclose(fp);
  7410. fclose(fp2);
  7411. /* Put the temp file in place of real file */
  7412. IGNORE_UNUSED_RESULT(remove(fname));
  7413. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7414. return 1;
  7415. }
  7416. static int
  7417. is_valid_port(unsigned long port)
  7418. {
  7419. return (port <= 0xffff);
  7420. }
  7421. static int
  7422. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7423. {
  7424. struct addrinfo hints, *res, *ressave;
  7425. int func_ret = 0;
  7426. int gai_ret;
  7427. memset(&hints, 0, sizeof(struct addrinfo));
  7428. hints.ai_family = af;
  7429. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7430. if (gai_ret != 0) {
  7431. /* gai_strerror could be used to convert gai_ret to a string */
  7432. /* POSIX return values: see
  7433. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7434. */
  7435. /* Windows return values: see
  7436. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7437. */
  7438. return 0;
  7439. }
  7440. ressave = res;
  7441. while (res) {
  7442. if (dstlen >= (size_t)res->ai_addrlen) {
  7443. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7444. func_ret = 1;
  7445. }
  7446. res = res->ai_next;
  7447. }
  7448. freeaddrinfo(ressave);
  7449. return func_ret;
  7450. }
  7451. static int
  7452. connect_socket(struct mg_context *ctx /* may be NULL */,
  7453. const char *host,
  7454. int port,
  7455. int use_ssl,
  7456. char *ebuf,
  7457. size_t ebuf_len,
  7458. SOCKET *sock /* output: socket, must not be NULL */,
  7459. union usa *sa /* output: socket address, must not be NULL */
  7460. )
  7461. {
  7462. int ip_ver = 0;
  7463. int conn_ret = -1;
  7464. int ret;
  7465. *sock = INVALID_SOCKET;
  7466. memset(sa, 0, sizeof(*sa));
  7467. if (ebuf_len > 0) {
  7468. *ebuf = 0;
  7469. }
  7470. if (host == NULL) {
  7471. mg_snprintf(NULL,
  7472. NULL, /* No truncation check for ebuf */
  7473. ebuf,
  7474. ebuf_len,
  7475. "%s",
  7476. "NULL host");
  7477. return 0;
  7478. }
  7479. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7480. mg_snprintf(NULL,
  7481. NULL, /* No truncation check for ebuf */
  7482. ebuf,
  7483. ebuf_len,
  7484. "%s",
  7485. "invalid port");
  7486. return 0;
  7487. }
  7488. #if !defined(NO_SSL)
  7489. #if !defined(NO_SSL_DL)
  7490. #if defined(OPENSSL_API_1_1)
  7491. if (use_ssl && (TLS_client_method == NULL)) {
  7492. mg_snprintf(NULL,
  7493. NULL, /* No truncation check for ebuf */
  7494. ebuf,
  7495. ebuf_len,
  7496. "%s",
  7497. "SSL is not initialized");
  7498. return 0;
  7499. }
  7500. #else
  7501. if (use_ssl && (SSLv23_client_method == NULL)) {
  7502. mg_snprintf(NULL,
  7503. NULL, /* No truncation check for ebuf */
  7504. ebuf,
  7505. ebuf_len,
  7506. "%s",
  7507. "SSL is not initialized");
  7508. return 0;
  7509. }
  7510. #endif /* OPENSSL_API_1_1 */
  7511. #else
  7512. (void)use_ssl;
  7513. #endif /* NO_SSL_DL */
  7514. #else
  7515. (void)use_ssl;
  7516. #endif /* !defined(NO_SSL) */
  7517. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7518. sa->sin.sin_family = AF_INET;
  7519. sa->sin.sin_port = htons((uint16_t)port);
  7520. ip_ver = 4;
  7521. #if defined(USE_IPV6)
  7522. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7523. sa->sin6.sin6_family = AF_INET6;
  7524. sa->sin6.sin6_port = htons((uint16_t)port);
  7525. ip_ver = 6;
  7526. } else if (host[0] == '[') {
  7527. /* While getaddrinfo on Windows will work with [::1],
  7528. * getaddrinfo on Linux only works with ::1 (without []). */
  7529. size_t l = strlen(host + 1);
  7530. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7531. if (h) {
  7532. h[l - 1] = 0;
  7533. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7534. sa->sin6.sin6_family = AF_INET6;
  7535. sa->sin6.sin6_port = htons((uint16_t)port);
  7536. ip_ver = 6;
  7537. }
  7538. mg_free(h);
  7539. }
  7540. #endif
  7541. }
  7542. if (ip_ver == 0) {
  7543. mg_snprintf(NULL,
  7544. NULL, /* No truncation check for ebuf */
  7545. ebuf,
  7546. ebuf_len,
  7547. "%s",
  7548. "host not found");
  7549. return 0;
  7550. }
  7551. if (ip_ver == 4) {
  7552. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7553. }
  7554. #if defined(USE_IPV6)
  7555. else if (ip_ver == 6) {
  7556. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7557. }
  7558. #endif
  7559. if (*sock == INVALID_SOCKET) {
  7560. mg_snprintf(NULL,
  7561. NULL, /* No truncation check for ebuf */
  7562. ebuf,
  7563. ebuf_len,
  7564. "socket(): %s",
  7565. strerror(ERRNO));
  7566. return 0;
  7567. }
  7568. if (0 != set_non_blocking_mode(*sock)) {
  7569. mg_snprintf(NULL,
  7570. NULL, /* No truncation check for ebuf */
  7571. ebuf,
  7572. ebuf_len,
  7573. "Cannot set socket to non-blocking: %s",
  7574. strerror(ERRNO));
  7575. closesocket(*sock);
  7576. *sock = INVALID_SOCKET;
  7577. return 0;
  7578. }
  7579. set_close_on_exec(*sock, fc(ctx));
  7580. if (ip_ver == 4) {
  7581. /* connected with IPv4 */
  7582. conn_ret = connect(*sock,
  7583. (struct sockaddr *)((void *)&sa->sin),
  7584. sizeof(sa->sin));
  7585. }
  7586. #if defined(USE_IPV6)
  7587. else if (ip_ver == 6) {
  7588. /* connected with IPv6 */
  7589. conn_ret = connect(*sock,
  7590. (struct sockaddr *)((void *)&sa->sin6),
  7591. sizeof(sa->sin6));
  7592. }
  7593. #endif
  7594. #if defined(_WIN32)
  7595. if (conn_ret != 0) {
  7596. DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */
  7597. conn_ret = (int)err;
  7598. #if !defined(EINPROGRESS)
  7599. #define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */
  7600. #endif /* if !defined(EINPROGRESS) */
  7601. }
  7602. #endif
  7603. if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) {
  7604. /* Data for getsockopt */
  7605. int sockerr = -1;
  7606. void *psockerr = &sockerr;
  7607. #if defined(_WIN32)
  7608. int len = (int)sizeof(sockerr);
  7609. #else
  7610. socklen_t len = (socklen_t)sizeof(sockerr);
  7611. #endif
  7612. /* Data for poll */
  7613. struct mg_pollfd pfd[1];
  7614. int pollres;
  7615. int ms_wait = 10000; /* 10 second timeout */
  7616. /* For a non-blocking socket, the connect sequence is:
  7617. * 1) call connect (will not block)
  7618. * 2) wait until the socket is ready for writing (select or poll)
  7619. * 3) check connection state with getsockopt
  7620. */
  7621. pfd[0].fd = *sock;
  7622. pfd[0].events = POLLOUT;
  7623. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  7624. if (pollres != 1) {
  7625. /* Not connected */
  7626. mg_snprintf(NULL,
  7627. NULL, /* No truncation check for ebuf */
  7628. ebuf,
  7629. ebuf_len,
  7630. "connect(%s:%d): timeout",
  7631. host,
  7632. port);
  7633. closesocket(*sock);
  7634. *sock = INVALID_SOCKET;
  7635. return 0;
  7636. }
  7637. #if defined(_WIN32)
  7638. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7639. #else
  7640. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7641. #endif
  7642. if ((ret != 0) || (sockerr != 0)) {
  7643. /* Not connected */
  7644. mg_snprintf(NULL,
  7645. NULL, /* No truncation check for ebuf */
  7646. ebuf,
  7647. ebuf_len,
  7648. "connect(%s:%d): error %s",
  7649. host,
  7650. port,
  7651. strerror(sockerr));
  7652. closesocket(*sock);
  7653. *sock = INVALID_SOCKET;
  7654. return 0;
  7655. }
  7656. }
  7657. return 1;
  7658. }
  7659. int
  7660. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7661. {
  7662. static const char *dont_escape = "._-$,;~()";
  7663. static const char *hex = "0123456789abcdef";
  7664. char *pos = dst;
  7665. const char *end = dst + dst_len - 1;
  7666. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7667. if (isalnum(*(const unsigned char *)src)
  7668. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7669. *pos = *src;
  7670. } else if (pos + 2 < end) {
  7671. pos[0] = '%';
  7672. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7673. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7674. pos += 2;
  7675. } else {
  7676. break;
  7677. }
  7678. }
  7679. *pos = '\0';
  7680. return (*src == '\0') ? (int)(pos - dst) : -1;
  7681. }
  7682. /* Return 0 on success, non-zero if an error occurs. */
  7683. static int
  7684. print_dir_entry(struct de *de)
  7685. {
  7686. size_t hrefsize;
  7687. char *href;
  7688. char size[64], mod[64];
  7689. #if defined(REENTRANT_TIME)
  7690. struct tm _tm;
  7691. struct tm *tm = &_tm;
  7692. #else
  7693. struct tm *tm;
  7694. #endif
  7695. hrefsize = PATH_MAX * 3; /* worst case */
  7696. href = (char *)mg_malloc(hrefsize);
  7697. if (href == NULL) {
  7698. return -1;
  7699. }
  7700. if (de->file.is_directory) {
  7701. mg_snprintf(de->conn,
  7702. NULL, /* Buffer is big enough */
  7703. size,
  7704. sizeof(size),
  7705. "%s",
  7706. "[DIRECTORY]");
  7707. } else {
  7708. /* We use (signed) cast below because MSVC 6 compiler cannot
  7709. * convert unsigned __int64 to double. Sigh. */
  7710. if (de->file.size < 1024) {
  7711. mg_snprintf(de->conn,
  7712. NULL, /* Buffer is big enough */
  7713. size,
  7714. sizeof(size),
  7715. "%d",
  7716. (int)de->file.size);
  7717. } else if (de->file.size < 0x100000) {
  7718. mg_snprintf(de->conn,
  7719. NULL, /* Buffer is big enough */
  7720. size,
  7721. sizeof(size),
  7722. "%.1fk",
  7723. (double)de->file.size / 1024.0);
  7724. } else if (de->file.size < 0x40000000) {
  7725. mg_snprintf(de->conn,
  7726. NULL, /* Buffer is big enough */
  7727. size,
  7728. sizeof(size),
  7729. "%.1fM",
  7730. (double)de->file.size / 1048576);
  7731. } else {
  7732. mg_snprintf(de->conn,
  7733. NULL, /* Buffer is big enough */
  7734. size,
  7735. sizeof(size),
  7736. "%.1fG",
  7737. (double)de->file.size / 1073741824);
  7738. }
  7739. }
  7740. /* Note: mg_snprintf will not cause a buffer overflow above.
  7741. * So, string truncation checks are not required here. */
  7742. #if defined(REENTRANT_TIME)
  7743. localtime_r(&de->file.last_modified, tm);
  7744. #else
  7745. tm = localtime(&de->file.last_modified);
  7746. #endif
  7747. if (tm != NULL) {
  7748. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7749. } else {
  7750. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7751. mod[sizeof(mod) - 1] = '\0';
  7752. }
  7753. mg_url_encode(de->file_name, href, hrefsize);
  7754. mg_printf(de->conn,
  7755. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7756. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7757. de->conn->request_info.local_uri,
  7758. href,
  7759. de->file.is_directory ? "/" : "",
  7760. de->file_name,
  7761. de->file.is_directory ? "/" : "",
  7762. mod,
  7763. size);
  7764. mg_free(href);
  7765. return 0;
  7766. }
  7767. /* This function is called from send_directory() and used for
  7768. * sorting directory entries by size, or name, or modification time.
  7769. * On windows, __cdecl specification is needed in case if project is built
  7770. * with __stdcall convention. qsort always requires __cdels callback. */
  7771. static int WINCDECL
  7772. compare_dir_entries(const void *p1, const void *p2)
  7773. {
  7774. if (p1 && p2) {
  7775. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7776. const char *query_string = a->conn->request_info.query_string;
  7777. int cmp_result = 0;
  7778. if (query_string == NULL) {
  7779. query_string = "na";
  7780. }
  7781. if (a->file.is_directory && !b->file.is_directory) {
  7782. return -1; /* Always put directories on top */
  7783. } else if (!a->file.is_directory && b->file.is_directory) {
  7784. return 1; /* Always put directories on top */
  7785. } else if (*query_string == 'n') {
  7786. cmp_result = strcmp(a->file_name, b->file_name);
  7787. } else if (*query_string == 's') {
  7788. cmp_result = (a->file.size == b->file.size)
  7789. ? 0
  7790. : ((a->file.size > b->file.size) ? 1 : -1);
  7791. } else if (*query_string == 'd') {
  7792. cmp_result =
  7793. (a->file.last_modified == b->file.last_modified)
  7794. ? 0
  7795. : ((a->file.last_modified > b->file.last_modified) ? 1
  7796. : -1);
  7797. }
  7798. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7799. }
  7800. return 0;
  7801. }
  7802. static int
  7803. must_hide_file(struct mg_connection *conn, const char *path)
  7804. {
  7805. if (conn && conn->dom_ctx) {
  7806. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7807. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7808. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7809. || ((pattern != NULL)
  7810. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7811. }
  7812. return 0;
  7813. }
  7814. static int
  7815. scan_directory(struct mg_connection *conn,
  7816. const char *dir,
  7817. void *data,
  7818. int (*cb)(struct de *, void *))
  7819. {
  7820. char path[PATH_MAX];
  7821. struct dirent *dp;
  7822. DIR *dirp;
  7823. struct de de;
  7824. int truncated;
  7825. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7826. return 0;
  7827. } else {
  7828. de.conn = conn;
  7829. while ((dp = mg_readdir(dirp)) != NULL) {
  7830. /* Do not show current dir and hidden files */
  7831. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7832. || must_hide_file(conn, dp->d_name)) {
  7833. continue;
  7834. }
  7835. mg_snprintf(
  7836. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7837. /* If we don't memset stat structure to zero, mtime will have
  7838. * garbage and strftime() will segfault later on in
  7839. * print_dir_entry(). memset is required only if mg_stat()
  7840. * fails. For more details, see
  7841. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7842. memset(&de.file, 0, sizeof(de.file));
  7843. if (truncated) {
  7844. /* If the path is not complete, skip processing. */
  7845. continue;
  7846. }
  7847. if (!mg_stat(conn, path, &de.file)) {
  7848. mg_cry_internal(conn,
  7849. "%s: mg_stat(%s) failed: %s",
  7850. __func__,
  7851. path,
  7852. strerror(ERRNO));
  7853. }
  7854. de.file_name = dp->d_name;
  7855. cb(&de, data);
  7856. }
  7857. (void)mg_closedir(dirp);
  7858. }
  7859. return 1;
  7860. }
  7861. #if !defined(NO_FILES)
  7862. static int
  7863. remove_directory(struct mg_connection *conn, const char *dir)
  7864. {
  7865. char path[PATH_MAX];
  7866. struct dirent *dp;
  7867. DIR *dirp;
  7868. struct de de;
  7869. int truncated;
  7870. int ok = 1;
  7871. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7872. return 0;
  7873. } else {
  7874. de.conn = conn;
  7875. while ((dp = mg_readdir(dirp)) != NULL) {
  7876. /* Do not show current dir (but show hidden files as they will
  7877. * also be removed) */
  7878. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7879. continue;
  7880. }
  7881. mg_snprintf(
  7882. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7883. /* If we don't memset stat structure to zero, mtime will have
  7884. * garbage and strftime() will segfault later on in
  7885. * print_dir_entry(). memset is required only if mg_stat()
  7886. * fails. For more details, see
  7887. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7888. memset(&de.file, 0, sizeof(de.file));
  7889. if (truncated) {
  7890. /* Do not delete anything shorter */
  7891. ok = 0;
  7892. continue;
  7893. }
  7894. if (!mg_stat(conn, path, &de.file)) {
  7895. mg_cry_internal(conn,
  7896. "%s: mg_stat(%s) failed: %s",
  7897. __func__,
  7898. path,
  7899. strerror(ERRNO));
  7900. ok = 0;
  7901. }
  7902. if (de.file.is_directory) {
  7903. if (remove_directory(conn, path) == 0) {
  7904. ok = 0;
  7905. }
  7906. } else {
  7907. /* This will fail file is the file is in memory */
  7908. if (mg_remove(conn, path) == 0) {
  7909. ok = 0;
  7910. }
  7911. }
  7912. }
  7913. (void)mg_closedir(dirp);
  7914. IGNORE_UNUSED_RESULT(rmdir(dir));
  7915. }
  7916. return ok;
  7917. }
  7918. #endif
  7919. struct dir_scan_data {
  7920. struct de *entries;
  7921. unsigned int num_entries;
  7922. unsigned int arr_size;
  7923. };
  7924. /* Behaves like realloc(), but frees original pointer on failure */
  7925. static void *
  7926. realloc2(void *ptr, size_t size)
  7927. {
  7928. void *new_ptr = mg_realloc(ptr, size);
  7929. if (new_ptr == NULL) {
  7930. mg_free(ptr);
  7931. }
  7932. return new_ptr;
  7933. }
  7934. static int
  7935. dir_scan_callback(struct de *de, void *data)
  7936. {
  7937. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7938. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7939. dsd->arr_size *= 2;
  7940. dsd->entries =
  7941. (struct de *)realloc2(dsd->entries,
  7942. dsd->arr_size * sizeof(dsd->entries[0]));
  7943. }
  7944. if (dsd->entries == NULL) {
  7945. /* TODO(lsm, low): propagate an error to the caller */
  7946. dsd->num_entries = 0;
  7947. } else {
  7948. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7949. dsd->entries[dsd->num_entries].file = de->file;
  7950. dsd->entries[dsd->num_entries].conn = de->conn;
  7951. dsd->num_entries++;
  7952. }
  7953. return 0;
  7954. }
  7955. static void
  7956. handle_directory_request(struct mg_connection *conn, const char *dir)
  7957. {
  7958. unsigned int i;
  7959. int sort_direction;
  7960. struct dir_scan_data data = {NULL, 0, 128};
  7961. char date[64];
  7962. time_t curtime = time(NULL);
  7963. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7964. mg_send_http_error(conn,
  7965. 500,
  7966. "Error: Cannot open directory\nopendir(%s): %s",
  7967. dir,
  7968. strerror(ERRNO));
  7969. return;
  7970. }
  7971. gmt_time_string(date, sizeof(date), &curtime);
  7972. if (!conn) {
  7973. return;
  7974. }
  7975. sort_direction = ((conn->request_info.query_string != NULL)
  7976. && (conn->request_info.query_string[1] == 'd'))
  7977. ? 'a'
  7978. : 'd';
  7979. conn->must_close = 1;
  7980. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7981. send_static_cache_header(conn);
  7982. send_additional_header(conn);
  7983. mg_printf(conn,
  7984. "Date: %s\r\n"
  7985. "Connection: close\r\n"
  7986. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7987. date);
  7988. mg_printf(conn,
  7989. "<html><head><title>Index of %s</title>"
  7990. "<style>th {text-align: left;}</style></head>"
  7991. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7992. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7993. "<th><a href=\"?d%c\">Modified</a></th>"
  7994. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7995. "<tr><td colspan=\"3\"><hr></td></tr>",
  7996. conn->request_info.local_uri,
  7997. conn->request_info.local_uri,
  7998. sort_direction,
  7999. sort_direction,
  8000. sort_direction);
  8001. /* Print first entry - link to a parent directory */
  8002. mg_printf(conn,
  8003. "<tr><td><a href=\"%s%s\">%s</a></td>"
  8004. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8005. conn->request_info.local_uri,
  8006. "..",
  8007. "Parent directory",
  8008. "-",
  8009. "-");
  8010. /* Sort and print directory entries */
  8011. if (data.entries != NULL) {
  8012. qsort(data.entries,
  8013. (size_t)data.num_entries,
  8014. sizeof(data.entries[0]),
  8015. compare_dir_entries);
  8016. for (i = 0; i < data.num_entries; i++) {
  8017. print_dir_entry(&data.entries[i]);
  8018. mg_free(data.entries[i].file_name);
  8019. }
  8020. mg_free(data.entries);
  8021. }
  8022. mg_printf(conn, "%s", "</table></body></html>");
  8023. conn->status_code = 200;
  8024. }
  8025. /* Send len bytes from the opened file to the client. */
  8026. static void
  8027. send_file_data(struct mg_connection *conn,
  8028. struct mg_file *filep,
  8029. int64_t offset,
  8030. int64_t len)
  8031. {
  8032. char buf[MG_BUF_LEN];
  8033. int to_read, num_read, num_written;
  8034. int64_t size;
  8035. if (!filep || !conn) {
  8036. return;
  8037. }
  8038. /* Sanity check the offset */
  8039. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8040. : (int64_t)(filep->stat.size);
  8041. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8042. #if defined(MG_USE_OPEN_FILE)
  8043. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8044. /* file stored in memory */
  8045. if (len > size - offset) {
  8046. len = size - offset;
  8047. }
  8048. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8049. } else /* else block below */
  8050. #endif
  8051. if (len > 0 && filep->access.fp != NULL) {
  8052. /* file stored on disk */
  8053. #if defined(__linux__)
  8054. /* sendfile is only available for Linux */
  8055. if ((conn->ssl == 0) && (conn->throttle == 0)
  8056. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8057. "yes"))) {
  8058. off_t sf_offs = (off_t)offset;
  8059. ssize_t sf_sent;
  8060. int sf_file = fileno(filep->access.fp);
  8061. int loop_cnt = 0;
  8062. do {
  8063. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8064. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8065. size_t sf_tosend =
  8066. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8067. sf_sent =
  8068. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8069. if (sf_sent > 0) {
  8070. len -= sf_sent;
  8071. offset += sf_sent;
  8072. } else if (loop_cnt == 0) {
  8073. /* This file can not be sent using sendfile.
  8074. * This might be the case for pseudo-files in the
  8075. * /sys/ and /proc/ file system.
  8076. * Use the regular user mode copy code instead. */
  8077. break;
  8078. } else if (sf_sent == 0) {
  8079. /* No error, but 0 bytes sent. May be EOF? */
  8080. return;
  8081. }
  8082. loop_cnt++;
  8083. } while ((len > 0) && (sf_sent >= 0));
  8084. if (sf_sent > 0) {
  8085. return; /* OK */
  8086. }
  8087. /* sf_sent<0 means error, thus fall back to the classic way */
  8088. /* This is always the case, if sf_file is not a "normal" file,
  8089. * e.g., for sending data from the output of a CGI process. */
  8090. offset = (int64_t)sf_offs;
  8091. }
  8092. #endif
  8093. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8094. mg_cry_internal(conn,
  8095. "%s: fseeko() failed: %s",
  8096. __func__,
  8097. strerror(ERRNO));
  8098. mg_send_http_error(
  8099. conn,
  8100. 500,
  8101. "%s",
  8102. "Error: Unable to access file at requested position.");
  8103. } else {
  8104. while (len > 0) {
  8105. /* Calculate how much to read from the file in the buffer */
  8106. to_read = sizeof(buf);
  8107. if ((int64_t)to_read > len) {
  8108. to_read = (int)len;
  8109. }
  8110. /* Read from file, exit the loop on error */
  8111. if ((num_read =
  8112. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8113. <= 0) {
  8114. break;
  8115. }
  8116. /* Send read bytes to the client, exit the loop on error */
  8117. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8118. != num_read) {
  8119. break;
  8120. }
  8121. /* Both read and were successful, adjust counters */
  8122. len -= num_written;
  8123. }
  8124. }
  8125. }
  8126. }
  8127. static int
  8128. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8129. {
  8130. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8131. }
  8132. static void
  8133. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8134. {
  8135. if ((filestat != NULL) && (buf != NULL)) {
  8136. mg_snprintf(NULL,
  8137. NULL, /* All calls to construct_etag use 64 byte buffer */
  8138. buf,
  8139. buf_len,
  8140. "\"%lx.%" INT64_FMT "\"",
  8141. (unsigned long)filestat->last_modified,
  8142. filestat->size);
  8143. }
  8144. }
  8145. static void
  8146. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8147. {
  8148. if (filep != NULL && filep->fp != NULL) {
  8149. #if defined(_WIN32)
  8150. (void)conn; /* Unused. */
  8151. #else
  8152. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8153. mg_cry_internal(conn,
  8154. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8155. __func__,
  8156. strerror(ERRNO));
  8157. }
  8158. #endif
  8159. }
  8160. }
  8161. #if defined(USE_ZLIB)
  8162. #include "mod_zlib.inl"
  8163. #endif
  8164. static void
  8165. handle_static_file_request(struct mg_connection *conn,
  8166. const char *path,
  8167. struct mg_file *filep,
  8168. const char *mime_type,
  8169. const char *additional_headers)
  8170. {
  8171. char date[64], lm[64], etag[64];
  8172. char range[128]; /* large enough, so there will be no overflow */
  8173. const char *msg = "OK", *hdr;
  8174. time_t curtime = time(NULL);
  8175. int64_t cl, r1, r2;
  8176. struct vec mime_vec;
  8177. int n, truncated;
  8178. char gz_path[PATH_MAX];
  8179. const char *encoding = "";
  8180. const char *cors_orig_cfg;
  8181. const char *cors1, *cors2, *cors3;
  8182. int is_head_request;
  8183. #if defined(USE_ZLIB)
  8184. /* Compression is allowed, unless there is a reason not to use compression.
  8185. * If the file is already compressed, too small or a "range" request was
  8186. * made, on the fly compression is not possible. */
  8187. int allow_on_the_fly_compression = 1;
  8188. #endif
  8189. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8190. return;
  8191. }
  8192. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8193. if (mime_type == NULL) {
  8194. get_mime_type(conn, path, &mime_vec);
  8195. } else {
  8196. mime_vec.ptr = mime_type;
  8197. mime_vec.len = strlen(mime_type);
  8198. }
  8199. if (filep->stat.size > INT64_MAX) {
  8200. mg_send_http_error(conn,
  8201. 500,
  8202. "Error: File size is too large to send\n%" INT64_FMT,
  8203. filep->stat.size);
  8204. return;
  8205. }
  8206. cl = (int64_t)filep->stat.size;
  8207. conn->status_code = 200;
  8208. range[0] = '\0';
  8209. #if defined(USE_ZLIB)
  8210. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8211. * it's important to rewrite the filename after resolving
  8212. * the mime type from it, to preserve the actual file's type */
  8213. if (!conn->accept_gzip) {
  8214. allow_on_the_fly_compression = 0;
  8215. }
  8216. #endif
  8217. if (filep->stat.is_gzipped) {
  8218. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8219. if (truncated) {
  8220. mg_send_http_error(conn,
  8221. 500,
  8222. "Error: Path of zipped file too long (%s)",
  8223. path);
  8224. return;
  8225. }
  8226. path = gz_path;
  8227. encoding = "Content-Encoding: gzip\r\n";
  8228. #if defined(USE_ZLIB)
  8229. /* File is already compressed. No "on the fly" compression. */
  8230. allow_on_the_fly_compression = 0;
  8231. #endif
  8232. }
  8233. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8234. mg_send_http_error(conn,
  8235. 500,
  8236. "Error: Cannot open file\nfopen(%s): %s",
  8237. path,
  8238. strerror(ERRNO));
  8239. return;
  8240. }
  8241. fclose_on_exec(&filep->access, conn);
  8242. /* If "Range" request was made: parse header, send only selected part
  8243. * of the file. */
  8244. r1 = r2 = 0;
  8245. hdr = mg_get_header(conn, "Range");
  8246. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  8247. && (r1 >= 0) && (r2 >= 0)) {
  8248. /* actually, range requests don't play well with a pre-gzipped
  8249. * file (since the range is specified in the uncompressed space) */
  8250. if (filep->stat.is_gzipped) {
  8251. mg_send_http_error(
  8252. conn,
  8253. 416, /* 416 = Range Not Satisfiable */
  8254. "%s",
  8255. "Error: Range requests in gzipped files are not supported");
  8256. (void)mg_fclose(
  8257. &filep->access); /* ignore error on read only file */
  8258. return;
  8259. }
  8260. conn->status_code = 206;
  8261. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8262. mg_snprintf(conn,
  8263. NULL, /* range buffer is big enough */
  8264. range,
  8265. sizeof(range),
  8266. "Content-Range: bytes "
  8267. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8268. r1,
  8269. r1 + cl - 1,
  8270. filep->stat.size);
  8271. msg = "Partial Content";
  8272. #if defined(USE_ZLIB)
  8273. /* Do not compress ranges. */
  8274. allow_on_the_fly_compression = 0;
  8275. #endif
  8276. }
  8277. /* Do not compress small files. Small files do not benefit from file
  8278. * compression, but there is still some overhead. */
  8279. #if defined(USE_ZLIB)
  8280. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8281. /* File is below the size limit. */
  8282. allow_on_the_fly_compression = 0;
  8283. }
  8284. #endif
  8285. /* Standard CORS header */
  8286. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8287. hdr = mg_get_header(conn, "Origin");
  8288. if (cors_orig_cfg && *cors_orig_cfg && hdr) {
  8289. /* Cross-origin resource sharing (CORS), see
  8290. * http://www.html5rocks.com/en/tutorials/cors/,
  8291. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8292. * -
  8293. * preflight is not supported for files. */
  8294. cors1 = "Access-Control-Allow-Origin: ";
  8295. cors2 = cors_orig_cfg;
  8296. cors3 = "\r\n";
  8297. } else {
  8298. cors1 = cors2 = cors3 = "";
  8299. }
  8300. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8301. * according to
  8302. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8303. gmt_time_string(date, sizeof(date), &curtime);
  8304. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8305. construct_etag(etag, sizeof(etag), &filep->stat);
  8306. /* Send header */
  8307. (void)mg_printf(conn,
  8308. "HTTP/1.1 %d %s\r\n"
  8309. "%s%s%s" /* CORS */
  8310. "Date: %s\r\n"
  8311. "Last-Modified: %s\r\n"
  8312. "Etag: %s\r\n"
  8313. "Content-Type: %.*s\r\n"
  8314. "Connection: %s\r\n",
  8315. conn->status_code,
  8316. msg,
  8317. cors1,
  8318. cors2,
  8319. cors3,
  8320. date,
  8321. lm,
  8322. etag,
  8323. (int)mime_vec.len,
  8324. mime_vec.ptr,
  8325. suggest_connection_header(conn));
  8326. send_static_cache_header(conn);
  8327. send_additional_header(conn);
  8328. #if defined(USE_ZLIB)
  8329. /* On the fly compression allowed */
  8330. if (allow_on_the_fly_compression) {
  8331. /* For on the fly compression, we don't know the content size in
  8332. * advance, so we have to use chunked encoding */
  8333. (void)mg_printf(conn,
  8334. "Content-Encoding: gzip\r\n"
  8335. "Transfer-Encoding: chunked\r\n");
  8336. } else
  8337. #endif
  8338. {
  8339. /* Without on-the-fly compression, we know the content-length
  8340. * and we can use ranges (with on-the-fly compression we cannot).
  8341. * So we send these response headers only in this case. */
  8342. (void)mg_printf(conn,
  8343. "Content-Length: %" INT64_FMT "\r\n"
  8344. "Accept-Ranges: bytes\r\n"
  8345. "%s" /* range */
  8346. "%s" /* encoding */,
  8347. cl,
  8348. range,
  8349. encoding);
  8350. }
  8351. /* The previous code must not add any header starting with X- to make
  8352. * sure no one of the additional_headers is included twice */
  8353. if (additional_headers != NULL) {
  8354. (void)mg_printf(conn,
  8355. "%.*s\r\n\r\n",
  8356. (int)strlen(additional_headers),
  8357. additional_headers);
  8358. } else {
  8359. (void)mg_printf(conn, "\r\n");
  8360. }
  8361. if (!is_head_request) {
  8362. #if defined(USE_ZLIB)
  8363. if (allow_on_the_fly_compression) {
  8364. /* Compress and send */
  8365. send_compressed_data(conn, filep);
  8366. } else
  8367. #endif
  8368. {
  8369. /* Send file directly */
  8370. send_file_data(conn, filep, r1, cl);
  8371. }
  8372. }
  8373. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8374. }
  8375. int
  8376. mg_send_file_body(struct mg_connection *conn, const char *path)
  8377. {
  8378. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8379. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8380. return -1;
  8381. }
  8382. fclose_on_exec(&file.access, conn);
  8383. send_file_data(conn, &file, 0, INT64_MAX);
  8384. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8385. return 0; /* >= 0 for OK */
  8386. }
  8387. #if !defined(NO_CACHING)
  8388. /* Return True if we should reply 304 Not Modified. */
  8389. static int
  8390. is_not_modified(const struct mg_connection *conn,
  8391. const struct mg_file_stat *filestat)
  8392. {
  8393. char etag[64];
  8394. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8395. const char *inm = mg_get_header(conn, "If-None-Match");
  8396. construct_etag(etag, sizeof(etag), filestat);
  8397. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8398. || ((ims != NULL)
  8399. && (filestat->last_modified <= parse_date_string(ims)));
  8400. }
  8401. static void
  8402. handle_not_modified_static_file_request(struct mg_connection *conn,
  8403. struct mg_file *filep)
  8404. {
  8405. char date[64], lm[64], etag[64];
  8406. time_t curtime = time(NULL);
  8407. if ((conn == NULL) || (filep == NULL)) {
  8408. return;
  8409. }
  8410. conn->status_code = 304;
  8411. gmt_time_string(date, sizeof(date), &curtime);
  8412. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8413. construct_etag(etag, sizeof(etag), &filep->stat);
  8414. (void)mg_printf(conn,
  8415. "HTTP/1.1 %d %s\r\n"
  8416. "Date: %s\r\n",
  8417. conn->status_code,
  8418. mg_get_response_code_text(conn, conn->status_code),
  8419. date);
  8420. send_static_cache_header(conn);
  8421. send_additional_header(conn);
  8422. (void)mg_printf(conn,
  8423. "Last-Modified: %s\r\n"
  8424. "Etag: %s\r\n"
  8425. "Connection: %s\r\n"
  8426. "\r\n",
  8427. lm,
  8428. etag,
  8429. suggest_connection_header(conn));
  8430. }
  8431. #endif
  8432. void
  8433. mg_send_file(struct mg_connection *conn, const char *path)
  8434. {
  8435. mg_send_mime_file2(conn, path, NULL, NULL);
  8436. }
  8437. void
  8438. mg_send_mime_file(struct mg_connection *conn,
  8439. const char *path,
  8440. const char *mime_type)
  8441. {
  8442. mg_send_mime_file2(conn, path, mime_type, NULL);
  8443. }
  8444. void
  8445. mg_send_mime_file2(struct mg_connection *conn,
  8446. const char *path,
  8447. const char *mime_type,
  8448. const char *additional_headers)
  8449. {
  8450. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8451. if (!conn) {
  8452. /* No conn */
  8453. return;
  8454. }
  8455. if (mg_stat(conn, path, &file.stat)) {
  8456. #if !defined(NO_CACHING)
  8457. if (is_not_modified(conn, &file.stat)) {
  8458. /* Send 304 "Not Modified" - this must not send any body data */
  8459. handle_not_modified_static_file_request(conn, &file);
  8460. } else
  8461. #endif /* NO_CACHING */
  8462. if (file.stat.is_directory) {
  8463. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8464. "yes")) {
  8465. handle_directory_request(conn, path);
  8466. } else {
  8467. mg_send_http_error(conn,
  8468. 403,
  8469. "%s",
  8470. "Error: Directory listing denied");
  8471. }
  8472. } else {
  8473. handle_static_file_request(
  8474. conn, path, &file, mime_type, additional_headers);
  8475. }
  8476. } else {
  8477. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8478. }
  8479. }
  8480. /* For a given PUT path, create all intermediate subdirectories.
  8481. * Return 0 if the path itself is a directory.
  8482. * Return 1 if the path leads to a file.
  8483. * Return -1 for if the path is too long.
  8484. * Return -2 if path can not be created.
  8485. */
  8486. static int
  8487. put_dir(struct mg_connection *conn, const char *path)
  8488. {
  8489. char buf[PATH_MAX];
  8490. const char *s, *p;
  8491. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8492. size_t len;
  8493. int res = 1;
  8494. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8495. len = (size_t)(p - path);
  8496. if (len >= sizeof(buf)) {
  8497. /* path too long */
  8498. res = -1;
  8499. break;
  8500. }
  8501. memcpy(buf, path, len);
  8502. buf[len] = '\0';
  8503. /* Try to create intermediate directory */
  8504. DEBUG_TRACE("mkdir(%s)", buf);
  8505. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8506. /* path does not exixt and can not be created */
  8507. res = -2;
  8508. break;
  8509. }
  8510. /* Is path itself a directory? */
  8511. if (p[1] == '\0') {
  8512. res = 0;
  8513. }
  8514. }
  8515. return res;
  8516. }
  8517. static void
  8518. remove_bad_file(const struct mg_connection *conn, const char *path)
  8519. {
  8520. int r = mg_remove(conn, path);
  8521. if (r != 0) {
  8522. mg_cry_internal(conn,
  8523. "%s: Cannot remove invalid file %s",
  8524. __func__,
  8525. path);
  8526. }
  8527. }
  8528. long long
  8529. mg_store_body(struct mg_connection *conn, const char *path)
  8530. {
  8531. char buf[MG_BUF_LEN];
  8532. long long len = 0;
  8533. int ret, n;
  8534. struct mg_file fi;
  8535. if (conn->consumed_content != 0) {
  8536. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8537. return -11;
  8538. }
  8539. ret = put_dir(conn, path);
  8540. if (ret < 0) {
  8541. /* -1 for path too long,
  8542. * -2 for path can not be created. */
  8543. return ret;
  8544. }
  8545. if (ret != 1) {
  8546. /* Return 0 means, path itself is a directory. */
  8547. return 0;
  8548. }
  8549. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8550. return -12;
  8551. }
  8552. ret = mg_read(conn, buf, sizeof(buf));
  8553. while (ret > 0) {
  8554. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8555. if (n != ret) {
  8556. (void)mg_fclose(
  8557. &fi.access); /* File is bad and will be removed anyway. */
  8558. remove_bad_file(conn, path);
  8559. return -13;
  8560. }
  8561. len += ret;
  8562. ret = mg_read(conn, buf, sizeof(buf));
  8563. }
  8564. /* File is open for writing. If fclose fails, there was probably an
  8565. * error flushing the buffer to disk, so the file on disk might be
  8566. * broken. Delete it and return an error to the caller. */
  8567. if (mg_fclose(&fi.access) != 0) {
  8568. remove_bad_file(conn, path);
  8569. return -14;
  8570. }
  8571. return len;
  8572. }
  8573. /* Parse a buffer:
  8574. * Forward the string pointer till the end of a word, then
  8575. * terminate it and forward till the begin of the next word.
  8576. */
  8577. static int
  8578. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8579. {
  8580. /* Forward until a space is found - use isgraph here */
  8581. /* See http://www.cplusplus.com/reference/cctype/ */
  8582. while (isgraph(**ppw)) {
  8583. (*ppw)++;
  8584. }
  8585. /* Check end of word */
  8586. if (eol) {
  8587. /* must be a end of line */
  8588. if ((**ppw != '\r') && (**ppw != '\n')) {
  8589. return -1;
  8590. }
  8591. } else {
  8592. /* must be a end of a word, but not a line */
  8593. if (**ppw != ' ') {
  8594. return -1;
  8595. }
  8596. }
  8597. /* Terminate and forward to the next word */
  8598. do {
  8599. **ppw = 0;
  8600. (*ppw)++;
  8601. } while ((**ppw) && isspace(**ppw));
  8602. /* Check after term */
  8603. if (!eol) {
  8604. /* if it's not the end of line, there must be a next word */
  8605. if (!isgraph(**ppw)) {
  8606. return -1;
  8607. }
  8608. }
  8609. /* ok */
  8610. return 1;
  8611. }
  8612. /* Parse HTTP headers from the given buffer, advance buf pointer
  8613. * to the point where parsing stopped.
  8614. * All parameters must be valid pointers (not NULL).
  8615. * Return <0 on error. */
  8616. static int
  8617. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8618. {
  8619. int i;
  8620. int num_headers = 0;
  8621. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8622. char *dp = *buf;
  8623. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8624. dp++;
  8625. }
  8626. if (dp == *buf) {
  8627. /* End of headers reached. */
  8628. break;
  8629. }
  8630. if (*dp != ':') {
  8631. /* This is not a valid field. */
  8632. return -1;
  8633. }
  8634. /* End of header key (*dp == ':') */
  8635. /* Truncate here and set the key name */
  8636. *dp = 0;
  8637. hdr[i].name = *buf;
  8638. do {
  8639. dp++;
  8640. } while (*dp == ' ');
  8641. /* The rest of the line is the value */
  8642. hdr[i].value = dp;
  8643. *buf = dp + strcspn(dp, "\r\n");
  8644. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8645. *buf = NULL;
  8646. }
  8647. num_headers = i + 1;
  8648. if (*buf) {
  8649. (*buf)[0] = 0;
  8650. (*buf)[1] = 0;
  8651. *buf += 2;
  8652. } else {
  8653. *buf = dp;
  8654. break;
  8655. }
  8656. if ((*buf)[0] == '\r') {
  8657. /* This is the end of the header */
  8658. break;
  8659. }
  8660. }
  8661. return num_headers;
  8662. }
  8663. struct mg_http_method_info {
  8664. const char *name;
  8665. int request_has_body;
  8666. int response_has_body;
  8667. int is_safe;
  8668. int is_idempotent;
  8669. int is_cacheable;
  8670. };
  8671. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8672. static struct mg_http_method_info http_methods[] = {
  8673. /* HTTP (RFC 2616) */
  8674. {"GET", 0, 1, 1, 1, 1},
  8675. {"POST", 1, 1, 0, 0, 0},
  8676. {"PUT", 1, 0, 0, 1, 0},
  8677. {"DELETE", 0, 0, 0, 1, 0},
  8678. {"HEAD", 0, 0, 1, 1, 1},
  8679. {"OPTIONS", 0, 0, 1, 1, 0},
  8680. {"CONNECT", 1, 1, 0, 0, 0},
  8681. /* TRACE method (RFC 2616) is not supported for security reasons */
  8682. /* PATCH method (RFC 5789) */
  8683. {"PATCH", 1, 0, 0, 0, 0},
  8684. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8685. /* WEBDAV (RFC 2518) */
  8686. {"PROPFIND", 0, 1, 1, 1, 0},
  8687. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8688. * Some PROPFIND results MAY be cached, with care,
  8689. * as there is no cache validation mechanism for
  8690. * most properties. This method is both safe and
  8691. * idempotent (see Section 9.1 of [RFC2616]). */
  8692. {"MKCOL", 0, 0, 0, 1, 0},
  8693. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8694. * When MKCOL is invoked without a request body,
  8695. * the newly created collection SHOULD have no
  8696. * members. A MKCOL request message may contain
  8697. * a message body. The precise behavior of a MKCOL
  8698. * request when the body is present is undefined,
  8699. * ... ==> We do not support MKCOL with body data.
  8700. * This method is idempotent, but not safe (see
  8701. * Section 9.1 of [RFC2616]). Responses to this
  8702. * method MUST NOT be cached. */
  8703. /* Unsupported WEBDAV Methods: */
  8704. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8705. /* + 11 methods from RFC 3253 */
  8706. /* ORDERPATCH (RFC 3648) */
  8707. /* ACL (RFC 3744) */
  8708. /* SEARCH (RFC 5323) */
  8709. /* + MicroSoft extensions
  8710. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8711. /* REPORT method (RFC 3253) */
  8712. {"REPORT", 1, 1, 1, 1, 1},
  8713. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8714. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8715. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8716. * to be useful for REST in case a "GET request with body" is
  8717. * required. */
  8718. {NULL, 0, 0, 0, 0, 0}
  8719. /* end of list */
  8720. };
  8721. static const struct mg_http_method_info *
  8722. get_http_method_info(const char *method)
  8723. {
  8724. /* Check if the method is known to the server. The list of all known
  8725. * HTTP methods can be found here at
  8726. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8727. */
  8728. const struct mg_http_method_info *m = http_methods;
  8729. while (m->name) {
  8730. if (!strcmp(m->name, method)) {
  8731. return m;
  8732. }
  8733. m++;
  8734. }
  8735. return NULL;
  8736. }
  8737. static int
  8738. is_valid_http_method(const char *method)
  8739. {
  8740. return (get_http_method_info(method) != NULL);
  8741. }
  8742. /* Parse HTTP request, fill in mg_request_info structure.
  8743. * This function modifies the buffer by NUL-terminating
  8744. * HTTP request components, header names and header values.
  8745. * Parameters:
  8746. * buf (in/out): pointer to the HTTP header to parse and split
  8747. * len (in): length of HTTP header buffer
  8748. * re (out): parsed header as mg_request_info
  8749. * buf and ri must be valid pointers (not NULL), len>0.
  8750. * Returns <0 on error. */
  8751. static int
  8752. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8753. {
  8754. int request_length;
  8755. int init_skip = 0;
  8756. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8757. * remote_port */
  8758. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8759. NULL;
  8760. ri->num_headers = 0;
  8761. /* RFC says that all initial whitespaces should be ingored */
  8762. /* This included all leading \r and \n (isspace) */
  8763. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8764. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8765. buf++;
  8766. len--;
  8767. init_skip++;
  8768. }
  8769. if (len == 0) {
  8770. /* Incomplete request */
  8771. return 0;
  8772. }
  8773. /* Control characters are not allowed, including zero */
  8774. if (iscntrl(*(unsigned char *)buf)) {
  8775. return -1;
  8776. }
  8777. /* Find end of HTTP header */
  8778. request_length = get_http_header_len(buf, len);
  8779. if (request_length <= 0) {
  8780. return request_length;
  8781. }
  8782. buf[request_length - 1] = '\0';
  8783. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8784. return -1;
  8785. }
  8786. /* The first word has to be the HTTP method */
  8787. ri->request_method = buf;
  8788. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8789. return -1;
  8790. }
  8791. /* Check for a valid http method */
  8792. if (!is_valid_http_method(ri->request_method)) {
  8793. return -1;
  8794. }
  8795. /* The second word is the URI */
  8796. ri->request_uri = buf;
  8797. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8798. return -1;
  8799. }
  8800. /* Next would be the HTTP version */
  8801. ri->http_version = buf;
  8802. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8803. return -1;
  8804. }
  8805. /* Check for a valid HTTP version key */
  8806. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8807. /* Invalid request */
  8808. return -1;
  8809. }
  8810. ri->http_version += 5;
  8811. /* Parse all HTTP headers */
  8812. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8813. if (ri->num_headers < 0) {
  8814. /* Error while parsing headers */
  8815. return -1;
  8816. }
  8817. return request_length + init_skip;
  8818. }
  8819. static int
  8820. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8821. {
  8822. int response_length;
  8823. int init_skip = 0;
  8824. char *tmp, *tmp2;
  8825. long l;
  8826. /* Initialize elements. */
  8827. ri->http_version = ri->status_text = NULL;
  8828. ri->num_headers = ri->status_code = 0;
  8829. /* RFC says that all initial whitespaces should be ingored */
  8830. /* This included all leading \r and \n (isspace) */
  8831. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8832. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8833. buf++;
  8834. len--;
  8835. init_skip++;
  8836. }
  8837. if (len == 0) {
  8838. /* Incomplete request */
  8839. return 0;
  8840. }
  8841. /* Control characters are not allowed, including zero */
  8842. if (iscntrl(*(unsigned char *)buf)) {
  8843. return -1;
  8844. }
  8845. /* Find end of HTTP header */
  8846. response_length = get_http_header_len(buf, len);
  8847. if (response_length <= 0) {
  8848. return response_length;
  8849. }
  8850. buf[response_length - 1] = '\0';
  8851. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8852. return -1;
  8853. }
  8854. /* The first word is the HTTP version */
  8855. /* Check for a valid HTTP version key */
  8856. if (strncmp(buf, "HTTP/", 5) != 0) {
  8857. /* Invalid request */
  8858. return -1;
  8859. }
  8860. buf += 5;
  8861. if (!isgraph(buf[0])) {
  8862. /* Invalid request */
  8863. return -1;
  8864. }
  8865. ri->http_version = buf;
  8866. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8867. return -1;
  8868. }
  8869. /* The second word is the status as a number */
  8870. tmp = buf;
  8871. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8872. return -1;
  8873. }
  8874. l = strtol(tmp, &tmp2, 10);
  8875. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8876. /* Everything else but a 3 digit code is invalid */
  8877. return -1;
  8878. }
  8879. ri->status_code = (int)l;
  8880. /* The rest of the line is the status text */
  8881. ri->status_text = buf;
  8882. /* Find end of status text */
  8883. /* isgraph or isspace = isprint */
  8884. while (isprint(*buf)) {
  8885. buf++;
  8886. }
  8887. if ((*buf != '\r') && (*buf != '\n')) {
  8888. return -1;
  8889. }
  8890. /* Terminate string and forward buf to next line */
  8891. do {
  8892. *buf = 0;
  8893. buf++;
  8894. } while ((*buf) && isspace(*buf));
  8895. /* Parse all HTTP headers */
  8896. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8897. if (ri->num_headers < 0) {
  8898. /* Error while parsing headers */
  8899. return -1;
  8900. }
  8901. return response_length + init_skip;
  8902. }
  8903. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8904. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8905. * buffer (which marks the end of HTTP request). Buffer buf may already
  8906. * have some data. The length of the data is stored in nread.
  8907. * Upon every read operation, increase nread by the number of bytes read. */
  8908. static int
  8909. read_message(FILE *fp,
  8910. struct mg_connection *conn,
  8911. char *buf,
  8912. int bufsiz,
  8913. int *nread)
  8914. {
  8915. int request_len, n = 0;
  8916. struct timespec last_action_time;
  8917. double request_timeout;
  8918. if (!conn) {
  8919. return 0;
  8920. }
  8921. memset(&last_action_time, 0, sizeof(last_action_time));
  8922. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8923. /* value of request_timeout is in seconds, config in milliseconds */
  8924. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8925. } else {
  8926. request_timeout = -1.0;
  8927. }
  8928. if (conn->handled_requests > 0) {
  8929. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8930. request_timeout =
  8931. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8932. }
  8933. }
  8934. request_len = get_http_header_len(buf, *nread);
  8935. /* first time reading from this connection */
  8936. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8937. while (request_len == 0) {
  8938. /* Full request not yet received */
  8939. if (conn->phys_ctx->stop_flag != 0) {
  8940. /* Server is to be stopped. */
  8941. return -1;
  8942. }
  8943. if (*nread >= bufsiz) {
  8944. /* Request too long */
  8945. return -2;
  8946. }
  8947. n = pull_inner(
  8948. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8949. if (n == -2) {
  8950. /* Receive error */
  8951. return -1;
  8952. }
  8953. if (n > 0) {
  8954. *nread += n;
  8955. request_len = get_http_header_len(buf, *nread);
  8956. } else {
  8957. request_len = 0;
  8958. }
  8959. if ((request_len == 0) && (request_timeout >= 0)) {
  8960. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8961. > request_timeout) {
  8962. /* Timeout */
  8963. return -1;
  8964. }
  8965. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8966. }
  8967. }
  8968. return request_len;
  8969. }
  8970. #if !defined(NO_CGI) || !defined(NO_FILES)
  8971. static int
  8972. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8973. {
  8974. const char *expect, *body;
  8975. char buf[MG_BUF_LEN];
  8976. int to_read, nread, success = 0;
  8977. int64_t buffered_len;
  8978. double timeout = -1.0;
  8979. if (!conn) {
  8980. return 0;
  8981. }
  8982. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8983. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8984. }
  8985. expect = mg_get_header(conn, "Expect");
  8986. DEBUG_ASSERT(fp != NULL);
  8987. if (!fp) {
  8988. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8989. return 0;
  8990. }
  8991. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8992. /* Content length is not specified by the client. */
  8993. mg_send_http_error(conn,
  8994. 411,
  8995. "%s",
  8996. "Error: Client did not specify content length");
  8997. } else if ((expect != NULL)
  8998. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8999. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9000. */
  9001. mg_send_http_error(conn,
  9002. 417,
  9003. "Error: Can not fulfill expectation %s",
  9004. expect);
  9005. } else {
  9006. if (expect != NULL) {
  9007. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9008. conn->status_code = 100;
  9009. } else {
  9010. conn->status_code = 200;
  9011. }
  9012. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  9013. - conn->consumed_content;
  9014. DEBUG_ASSERT(buffered_len >= 0);
  9015. DEBUG_ASSERT(conn->consumed_content == 0);
  9016. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  9017. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9018. return 0;
  9019. }
  9020. if (buffered_len > 0) {
  9021. if ((int64_t)buffered_len > conn->content_len) {
  9022. buffered_len = (int)conn->content_len;
  9023. }
  9024. body = conn->buf + conn->request_len + conn->consumed_content;
  9025. push_all(
  9026. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  9027. conn->consumed_content += buffered_len;
  9028. }
  9029. nread = 0;
  9030. while (conn->consumed_content < conn->content_len) {
  9031. to_read = sizeof(buf);
  9032. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  9033. to_read = (int)(conn->content_len - conn->consumed_content);
  9034. }
  9035. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  9036. if (nread == -2) {
  9037. /* error */
  9038. break;
  9039. }
  9040. if (nread > 0) {
  9041. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  9042. != nread) {
  9043. break;
  9044. }
  9045. }
  9046. conn->consumed_content += nread;
  9047. }
  9048. if (conn->consumed_content == conn->content_len) {
  9049. success = (nread >= 0);
  9050. }
  9051. /* Each error code path in this function must send an error */
  9052. if (!success) {
  9053. /* NOTE: Maybe some data has already been sent. */
  9054. /* TODO (low): If some data has been sent, a correct error
  9055. * reply can no longer be sent, so just close the connection */
  9056. mg_send_http_error(conn, 500, "%s", "");
  9057. }
  9058. }
  9059. return success;
  9060. }
  9061. #endif
  9062. #if defined(USE_TIMERS)
  9063. #define TIMER_API static
  9064. #include "timer.inl"
  9065. #endif /* USE_TIMERS */
  9066. #if !defined(NO_CGI)
  9067. /* This structure helps to create an environment for the spawned CGI
  9068. * program.
  9069. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9070. * last element must be NULL.
  9071. * However, on Windows there is a requirement that all these
  9072. * VARIABLE=VALUE\0
  9073. * strings must reside in a contiguous buffer. The end of the buffer is
  9074. * marked by two '\0' characters.
  9075. * We satisfy both worlds: we create an envp array (which is vars), all
  9076. * entries are actually pointers inside buf. */
  9077. struct cgi_environment {
  9078. struct mg_connection *conn;
  9079. /* Data block */
  9080. char *buf; /* Environment buffer */
  9081. size_t buflen; /* Space available in buf */
  9082. size_t bufused; /* Space taken in buf */
  9083. /* Index block */
  9084. char **var; /* char **envp */
  9085. size_t varlen; /* Number of variables available in var */
  9086. size_t varused; /* Number of variables stored in var */
  9087. };
  9088. static void addenv(struct cgi_environment *env,
  9089. PRINTF_FORMAT_STRING(const char *fmt),
  9090. ...) PRINTF_ARGS(2, 3);
  9091. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9092. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9093. static void
  9094. addenv(struct cgi_environment *env, const char *fmt, ...)
  9095. {
  9096. size_t n, space;
  9097. int truncated = 0;
  9098. char *added;
  9099. va_list ap;
  9100. /* Calculate how much space is left in the buffer */
  9101. space = (env->buflen - env->bufused);
  9102. /* Calculate an estimate for the required space */
  9103. n = strlen(fmt) + 2 + 128;
  9104. do {
  9105. if (space <= n) {
  9106. /* Allocate new buffer */
  9107. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9108. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9109. if (!added) {
  9110. /* Out of memory */
  9111. mg_cry_internal(
  9112. env->conn,
  9113. "%s: Cannot allocate memory for CGI variable [%s]",
  9114. __func__,
  9115. fmt);
  9116. return;
  9117. }
  9118. env->buf = added;
  9119. env->buflen = n;
  9120. space = (env->buflen - env->bufused);
  9121. }
  9122. /* Make a pointer to the free space int the buffer */
  9123. added = env->buf + env->bufused;
  9124. /* Copy VARIABLE=VALUE\0 string into the free space */
  9125. va_start(ap, fmt);
  9126. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  9127. va_end(ap);
  9128. /* Do not add truncated strings to the environment */
  9129. if (truncated) {
  9130. /* Reallocate the buffer */
  9131. space = 0;
  9132. n = 1;
  9133. }
  9134. } while (truncated);
  9135. /* Calculate number of bytes added to the environment */
  9136. n = strlen(added) + 1;
  9137. env->bufused += n;
  9138. /* Now update the variable index */
  9139. space = (env->varlen - env->varused);
  9140. if (space < 2) {
  9141. mg_cry_internal(env->conn,
  9142. "%s: Cannot register CGI variable [%s]",
  9143. __func__,
  9144. fmt);
  9145. return;
  9146. }
  9147. /* Append a pointer to the added string into the envp array */
  9148. env->var[env->varused] = added;
  9149. env->varused++;
  9150. }
  9151. /* Return 0 on success, non-zero if an error occurs. */
  9152. static int
  9153. prepare_cgi_environment(struct mg_connection *conn,
  9154. const char *prog,
  9155. struct cgi_environment *env)
  9156. {
  9157. const char *s;
  9158. struct vec var_vec;
  9159. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9160. int i, truncated, uri_len;
  9161. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9162. return -1;
  9163. }
  9164. env->conn = conn;
  9165. env->buflen = CGI_ENVIRONMENT_SIZE;
  9166. env->bufused = 0;
  9167. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9168. if (env->buf == NULL) {
  9169. mg_cry_internal(conn,
  9170. "%s: Not enough memory for environmental buffer",
  9171. __func__);
  9172. return -1;
  9173. }
  9174. env->varlen = MAX_CGI_ENVIR_VARS;
  9175. env->varused = 0;
  9176. env->var =
  9177. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  9178. if (env->var == NULL) {
  9179. mg_cry_internal(conn,
  9180. "%s: Not enough memory for environmental variables",
  9181. __func__);
  9182. mg_free(env->buf);
  9183. return -1;
  9184. }
  9185. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9186. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9187. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9188. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9189. /* Prepare the environment block */
  9190. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9191. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9192. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9193. #if defined(USE_IPV6)
  9194. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9195. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9196. } else
  9197. #endif
  9198. {
  9199. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9200. }
  9201. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9202. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9203. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9204. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9205. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9206. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9207. /* SCRIPT_NAME */
  9208. uri_len = (int)strlen(conn->request_info.local_uri);
  9209. if (conn->path_info == NULL) {
  9210. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9211. /* URI: /path_to_script/script.cgi */
  9212. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9213. } else {
  9214. /* URI: /path_to_script/ ... using index.cgi */
  9215. const char *index_file = strrchr(prog, '/');
  9216. if (index_file) {
  9217. addenv(env,
  9218. "SCRIPT_NAME=%s%s",
  9219. conn->request_info.local_uri,
  9220. index_file + 1);
  9221. }
  9222. }
  9223. } else {
  9224. /* URI: /path_to_script/script.cgi/path_info */
  9225. addenv(env,
  9226. "SCRIPT_NAME=%.*s",
  9227. uri_len - (int)strlen(conn->path_info),
  9228. conn->request_info.local_uri);
  9229. }
  9230. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9231. if (conn->path_info == NULL) {
  9232. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9233. } else {
  9234. addenv(env,
  9235. "PATH_TRANSLATED=%s%s",
  9236. conn->dom_ctx->config[DOCUMENT_ROOT],
  9237. conn->path_info);
  9238. }
  9239. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9240. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9241. addenv(env, "CONTENT_TYPE=%s", s);
  9242. }
  9243. if (conn->request_info.query_string != NULL) {
  9244. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9245. }
  9246. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9247. addenv(env, "CONTENT_LENGTH=%s", s);
  9248. }
  9249. if ((s = getenv("PATH")) != NULL) {
  9250. addenv(env, "PATH=%s", s);
  9251. }
  9252. if (conn->path_info != NULL) {
  9253. addenv(env, "PATH_INFO=%s", conn->path_info);
  9254. }
  9255. if (conn->status_code > 0) {
  9256. /* CGI error handler should show the status code */
  9257. addenv(env, "STATUS=%d", conn->status_code);
  9258. }
  9259. #if defined(_WIN32)
  9260. if ((s = getenv("COMSPEC")) != NULL) {
  9261. addenv(env, "COMSPEC=%s", s);
  9262. }
  9263. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9264. addenv(env, "SYSTEMROOT=%s", s);
  9265. }
  9266. if ((s = getenv("SystemDrive")) != NULL) {
  9267. addenv(env, "SystemDrive=%s", s);
  9268. }
  9269. if ((s = getenv("ProgramFiles")) != NULL) {
  9270. addenv(env, "ProgramFiles=%s", s);
  9271. }
  9272. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9273. addenv(env, "ProgramFiles(x86)=%s", s);
  9274. }
  9275. #else
  9276. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9277. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9278. }
  9279. #endif /* _WIN32 */
  9280. if ((s = getenv("PERLLIB")) != NULL) {
  9281. addenv(env, "PERLLIB=%s", s);
  9282. }
  9283. if (conn->request_info.remote_user != NULL) {
  9284. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9285. addenv(env, "%s", "AUTH_TYPE=Digest");
  9286. }
  9287. /* Add all headers as HTTP_* variables */
  9288. for (i = 0; i < conn->request_info.num_headers; i++) {
  9289. (void)mg_snprintf(conn,
  9290. &truncated,
  9291. http_var_name,
  9292. sizeof(http_var_name),
  9293. "HTTP_%s",
  9294. conn->request_info.http_headers[i].name);
  9295. if (truncated) {
  9296. mg_cry_internal(conn,
  9297. "%s: HTTP header variable too long [%s]",
  9298. __func__,
  9299. conn->request_info.http_headers[i].name);
  9300. continue;
  9301. }
  9302. /* Convert variable name into uppercase, and change - to _ */
  9303. for (p = http_var_name; *p != '\0'; p++) {
  9304. if (*p == '-') {
  9305. *p = '_';
  9306. }
  9307. *p = (char)toupper(*(unsigned char *)p);
  9308. }
  9309. addenv(env,
  9310. "%s=%s",
  9311. http_var_name,
  9312. conn->request_info.http_headers[i].value);
  9313. }
  9314. /* Add user-specified variables */
  9315. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9316. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9317. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9318. }
  9319. env->var[env->varused] = NULL;
  9320. env->buf[env->bufused] = '\0';
  9321. return 0;
  9322. }
  9323. /* Data for CGI process control: PID and number of references */
  9324. struct process_control_data {
  9325. pid_t pid;
  9326. int references;
  9327. };
  9328. static int
  9329. abort_process(void *data)
  9330. {
  9331. /* Waitpid checks for child status and won't work for a pid that does not
  9332. * identify a child of the current process. Thus, if the pid is reused,
  9333. * we will not affect a different process. */
  9334. struct process_control_data *proc = (struct process_control_data *)data;
  9335. int status = 0;
  9336. int refs;
  9337. pid_t ret_pid;
  9338. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9339. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9340. /* Stop child process */
  9341. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9342. kill(proc->pid, SIGABRT);
  9343. /* Wait until process is terminated (don't leave zombies) */
  9344. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9345. ;
  9346. } else {
  9347. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9348. }
  9349. /* Dec reference counter */
  9350. refs = mg_atomic_dec(&proc->references);
  9351. if (refs == 0) {
  9352. /* no more references - free data */
  9353. mg_free(data);
  9354. }
  9355. return 0;
  9356. }
  9357. static void
  9358. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9359. {
  9360. char *buf;
  9361. size_t buflen;
  9362. int headers_len, data_len, i, truncated;
  9363. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9364. const char *status, *status_text, *connection_state;
  9365. char *pbuf, dir[PATH_MAX], *p;
  9366. struct mg_request_info ri;
  9367. struct cgi_environment blk;
  9368. FILE *in = NULL, *out = NULL, *err = NULL;
  9369. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9370. pid_t pid = (pid_t)-1;
  9371. struct process_control_data *proc = NULL;
  9372. #if defined(USE_TIMERS)
  9373. double cgi_timeout = -1.0;
  9374. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9375. /* Get timeout in seconds */
  9376. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9377. }
  9378. #endif
  9379. if (conn == NULL) {
  9380. return;
  9381. }
  9382. buf = NULL;
  9383. buflen = conn->phys_ctx->max_request_size;
  9384. i = prepare_cgi_environment(conn, prog, &blk);
  9385. if (i != 0) {
  9386. blk.buf = NULL;
  9387. blk.var = NULL;
  9388. goto done;
  9389. }
  9390. /* CGI must be executed in its own directory. 'dir' must point to the
  9391. * directory containing executable program, 'p' must point to the
  9392. * executable program name relative to 'dir'. */
  9393. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9394. if (truncated) {
  9395. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9396. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9397. goto done;
  9398. }
  9399. if ((p = strrchr(dir, '/')) != NULL) {
  9400. *p++ = '\0';
  9401. } else {
  9402. dir[0] = '.';
  9403. dir[1] = '\0';
  9404. p = (char *)prog;
  9405. }
  9406. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9407. status = strerror(ERRNO);
  9408. mg_cry_internal(
  9409. conn,
  9410. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9411. prog,
  9412. status);
  9413. mg_send_http_error(conn,
  9414. 500,
  9415. "Error: Cannot create CGI pipe: %s",
  9416. status);
  9417. goto done;
  9418. }
  9419. proc = (struct process_control_data *)
  9420. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9421. if (proc == NULL) {
  9422. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9423. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9424. goto done;
  9425. }
  9426. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9427. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9428. if (pid == (pid_t)-1) {
  9429. status = strerror(ERRNO);
  9430. mg_cry_internal(
  9431. conn,
  9432. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9433. prog,
  9434. status);
  9435. mg_send_http_error(conn,
  9436. 500,
  9437. "Error: Cannot spawn CGI process [%s]: %s",
  9438. prog,
  9439. status);
  9440. mg_free(proc);
  9441. proc = NULL;
  9442. goto done;
  9443. }
  9444. /* Store data in shared process_control_data */
  9445. proc->pid = pid;
  9446. proc->references = 1;
  9447. #if defined(USE_TIMERS)
  9448. if (cgi_timeout > 0.0) {
  9449. proc->references = 2;
  9450. // Start a timer for CGI
  9451. timer_add(conn->phys_ctx,
  9452. cgi_timeout /* in seconds */,
  9453. 0.0,
  9454. 1,
  9455. abort_process,
  9456. (void *)proc);
  9457. }
  9458. #endif
  9459. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  9460. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9461. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9462. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9463. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9464. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9465. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9466. /* Parent closes only one side of the pipes.
  9467. * If we don't mark them as closed, close() attempt before
  9468. * return from this function throws an exception on Windows.
  9469. * Windows does not like when closed descriptor is closed again. */
  9470. (void)close(fdin[0]);
  9471. (void)close(fdout[1]);
  9472. (void)close(fderr[1]);
  9473. fdin[0] = fdout[1] = fderr[1] = -1;
  9474. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9475. status = strerror(ERRNO);
  9476. mg_cry_internal(conn,
  9477. "Error: CGI program \"%s\": Can not open stdin: %s",
  9478. prog,
  9479. status);
  9480. mg_send_http_error(conn,
  9481. 500,
  9482. "Error: CGI can not open fdin\nfopen: %s",
  9483. status);
  9484. goto done;
  9485. }
  9486. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9487. status = strerror(ERRNO);
  9488. mg_cry_internal(conn,
  9489. "Error: CGI program \"%s\": Can not open stdout: %s",
  9490. prog,
  9491. status);
  9492. mg_send_http_error(conn,
  9493. 500,
  9494. "Error: CGI can not open fdout\nfopen: %s",
  9495. status);
  9496. goto done;
  9497. }
  9498. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9499. status = strerror(ERRNO);
  9500. mg_cry_internal(conn,
  9501. "Error: CGI program \"%s\": Can not open stderr: %s",
  9502. prog,
  9503. status);
  9504. mg_send_http_error(conn,
  9505. 500,
  9506. "Error: CGI can not open fderr\nfopen: %s",
  9507. status);
  9508. goto done;
  9509. }
  9510. setbuf(in, NULL);
  9511. setbuf(out, NULL);
  9512. setbuf(err, NULL);
  9513. fout.access.fp = out;
  9514. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9515. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9516. (signed long long)conn->request_info.content_length);
  9517. /* This is a POST/PUT request, or another request with body data. */
  9518. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9519. /* Error sending the body data */
  9520. mg_cry_internal(
  9521. conn,
  9522. "Error: CGI program \"%s\": Forward body data failed",
  9523. prog);
  9524. goto done;
  9525. }
  9526. }
  9527. /* Close so child gets an EOF. */
  9528. fclose(in);
  9529. in = NULL;
  9530. fdin[1] = -1;
  9531. /* Now read CGI reply into a buffer. We need to set correct
  9532. * status code, thus we need to see all HTTP headers first.
  9533. * Do not send anything back to client, until we buffer in all
  9534. * HTTP headers. */
  9535. data_len = 0;
  9536. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9537. if (buf == NULL) {
  9538. mg_send_http_error(conn,
  9539. 500,
  9540. "Error: Not enough memory for CGI buffer (%u bytes)",
  9541. (unsigned int)buflen);
  9542. mg_cry_internal(
  9543. conn,
  9544. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9545. "bytes)",
  9546. prog,
  9547. (unsigned int)buflen);
  9548. goto done;
  9549. }
  9550. DEBUG_TRACE("CGI: %s", "wait for response");
  9551. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9552. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9553. if (headers_len <= 0) {
  9554. /* Could not parse the CGI response. Check if some error message on
  9555. * stderr. */
  9556. i = pull_all(err, conn, buf, (int)buflen);
  9557. if (i > 0) {
  9558. /* CGI program explicitly sent an error */
  9559. /* Write the error message to the internal log */
  9560. mg_cry_internal(conn,
  9561. "Error: CGI program \"%s\" sent error "
  9562. "message: [%.*s]",
  9563. prog,
  9564. i,
  9565. buf);
  9566. /* Don't send the error message back to the client */
  9567. mg_send_http_error(conn,
  9568. 500,
  9569. "Error: CGI program \"%s\" failed.",
  9570. prog);
  9571. } else {
  9572. /* CGI program did not explicitly send an error, but a broken
  9573. * respon header */
  9574. mg_cry_internal(conn,
  9575. "Error: CGI program sent malformed or too big "
  9576. "(>%u bytes) HTTP headers: [%.*s]",
  9577. (unsigned)buflen,
  9578. data_len,
  9579. buf);
  9580. mg_send_http_error(conn,
  9581. 500,
  9582. "Error: CGI program sent malformed or too big "
  9583. "(>%u bytes) HTTP headers: [%.*s]",
  9584. (unsigned)buflen,
  9585. data_len,
  9586. buf);
  9587. }
  9588. /* in both cases, abort processing CGI */
  9589. goto done;
  9590. }
  9591. pbuf = buf;
  9592. buf[headers_len - 1] = '\0';
  9593. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9594. /* Make up and send the status line */
  9595. status_text = "OK";
  9596. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9597. != NULL) {
  9598. conn->status_code = atoi(status);
  9599. status_text = status;
  9600. while (isdigit(*(const unsigned char *)status_text)
  9601. || *status_text == ' ') {
  9602. status_text++;
  9603. }
  9604. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9605. != NULL) {
  9606. conn->status_code = 307;
  9607. } else {
  9608. conn->status_code = 200;
  9609. }
  9610. connection_state =
  9611. get_header(ri.http_headers, ri.num_headers, "Connection");
  9612. if (!header_has_option(connection_state, "keep-alive")) {
  9613. conn->must_close = 1;
  9614. }
  9615. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9616. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9617. /* Send headers */
  9618. for (i = 0; i < ri.num_headers; i++) {
  9619. mg_printf(conn,
  9620. "%s: %s\r\n",
  9621. ri.http_headers[i].name,
  9622. ri.http_headers[i].value);
  9623. }
  9624. mg_write(conn, "\r\n", 2);
  9625. /* Send chunk of data that may have been read after the headers */
  9626. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9627. /* Read the rest of CGI output and send to the client */
  9628. DEBUG_TRACE("CGI: %s", "forward all data");
  9629. send_file_data(conn, &fout, 0, INT64_MAX);
  9630. DEBUG_TRACE("CGI: %s", "all data sent");
  9631. done:
  9632. mg_free(blk.var);
  9633. mg_free(blk.buf);
  9634. if (pid != (pid_t)-1) {
  9635. abort_process((void *)proc);
  9636. }
  9637. if (fdin[0] != -1) {
  9638. close(fdin[0]);
  9639. }
  9640. if (fdout[1] != -1) {
  9641. close(fdout[1]);
  9642. }
  9643. if (in != NULL) {
  9644. fclose(in);
  9645. } else if (fdin[1] != -1) {
  9646. close(fdin[1]);
  9647. }
  9648. if (out != NULL) {
  9649. fclose(out);
  9650. } else if (fdout[0] != -1) {
  9651. close(fdout[0]);
  9652. }
  9653. if (err != NULL) {
  9654. fclose(err);
  9655. } else if (fderr[0] != -1) {
  9656. close(fderr[0]);
  9657. }
  9658. if (buf != NULL) {
  9659. mg_free(buf);
  9660. }
  9661. }
  9662. #endif /* !NO_CGI */
  9663. #if !defined(NO_FILES)
  9664. static void
  9665. mkcol(struct mg_connection *conn, const char *path)
  9666. {
  9667. int rc, body_len;
  9668. struct de de;
  9669. char date[64];
  9670. time_t curtime = time(NULL);
  9671. if (conn == NULL) {
  9672. return;
  9673. }
  9674. /* TODO (mid): Check the mg_send_http_error situations in this function
  9675. */
  9676. memset(&de.file, 0, sizeof(de.file));
  9677. if (!mg_stat(conn, path, &de.file)) {
  9678. mg_cry_internal(conn,
  9679. "%s: mg_stat(%s) failed: %s",
  9680. __func__,
  9681. path,
  9682. strerror(ERRNO));
  9683. }
  9684. if (de.file.last_modified) {
  9685. /* TODO (mid): This check does not seem to make any sense ! */
  9686. /* TODO (mid): Add a webdav unit test first, before changing
  9687. * anything here. */
  9688. mg_send_http_error(
  9689. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9690. return;
  9691. }
  9692. body_len = conn->data_len - conn->request_len;
  9693. if (body_len > 0) {
  9694. mg_send_http_error(
  9695. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9696. return;
  9697. }
  9698. rc = mg_mkdir(conn, path, 0755);
  9699. if (rc == 0) {
  9700. conn->status_code = 201;
  9701. gmt_time_string(date, sizeof(date), &curtime);
  9702. mg_printf(conn,
  9703. "HTTP/1.1 %d Created\r\n"
  9704. "Date: %s\r\n",
  9705. conn->status_code,
  9706. date);
  9707. send_static_cache_header(conn);
  9708. send_additional_header(conn);
  9709. mg_printf(conn,
  9710. "Content-Length: 0\r\n"
  9711. "Connection: %s\r\n\r\n",
  9712. suggest_connection_header(conn));
  9713. } else {
  9714. if (errno == EEXIST) {
  9715. mg_send_http_error(
  9716. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9717. } else if (errno == EACCES) {
  9718. mg_send_http_error(
  9719. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9720. } else if (errno == ENOENT) {
  9721. mg_send_http_error(
  9722. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9723. } else {
  9724. mg_send_http_error(
  9725. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9726. }
  9727. }
  9728. }
  9729. static void
  9730. put_file(struct mg_connection *conn, const char *path)
  9731. {
  9732. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9733. const char *range;
  9734. int64_t r1, r2;
  9735. int rc;
  9736. char date[64];
  9737. time_t curtime = time(NULL);
  9738. if (conn == NULL) {
  9739. return;
  9740. }
  9741. if (mg_stat(conn, path, &file.stat)) {
  9742. /* File already exists */
  9743. conn->status_code = 200;
  9744. if (file.stat.is_directory) {
  9745. /* This is an already existing directory,
  9746. * so there is nothing to do for the server. */
  9747. rc = 0;
  9748. } else {
  9749. /* File exists and is not a directory. */
  9750. /* Can it be replaced? */
  9751. #if defined(MG_USE_OPEN_FILE)
  9752. if (file.access.membuf != NULL) {
  9753. /* This is an "in-memory" file, that can not be replaced */
  9754. mg_send_http_error(conn,
  9755. 405,
  9756. "Error: Put not possible\nReplacing %s "
  9757. "is not supported",
  9758. path);
  9759. return;
  9760. }
  9761. #endif
  9762. /* Check if the server may write this file */
  9763. if (access(path, W_OK) == 0) {
  9764. /* Access granted */
  9765. conn->status_code = 200;
  9766. rc = 1;
  9767. } else {
  9768. mg_send_http_error(
  9769. conn,
  9770. 403,
  9771. "Error: Put not possible\nReplacing %s is not allowed",
  9772. path);
  9773. return;
  9774. }
  9775. }
  9776. } else {
  9777. /* File should be created */
  9778. conn->status_code = 201;
  9779. rc = put_dir(conn, path);
  9780. }
  9781. if (rc == 0) {
  9782. /* put_dir returns 0 if path is a directory */
  9783. gmt_time_string(date, sizeof(date), &curtime);
  9784. mg_printf(conn,
  9785. "HTTP/1.1 %d %s\r\n",
  9786. conn->status_code,
  9787. mg_get_response_code_text(NULL, conn->status_code));
  9788. send_no_cache_header(conn);
  9789. send_additional_header(conn);
  9790. mg_printf(conn,
  9791. "Date: %s\r\n"
  9792. "Content-Length: 0\r\n"
  9793. "Connection: %s\r\n\r\n",
  9794. date,
  9795. suggest_connection_header(conn));
  9796. /* Request to create a directory has been fulfilled successfully.
  9797. * No need to put a file. */
  9798. return;
  9799. }
  9800. if (rc == -1) {
  9801. /* put_dir returns -1 if the path is too long */
  9802. mg_send_http_error(conn,
  9803. 414,
  9804. "Error: Path too long\nput_dir(%s): %s",
  9805. path,
  9806. strerror(ERRNO));
  9807. return;
  9808. }
  9809. if (rc == -2) {
  9810. /* put_dir returns -2 if the directory can not be created */
  9811. mg_send_http_error(conn,
  9812. 500,
  9813. "Error: Can not create directory\nput_dir(%s): %s",
  9814. path,
  9815. strerror(ERRNO));
  9816. return;
  9817. }
  9818. /* A file should be created or overwritten. */
  9819. /* Currently CivetWeb does not nead read+write access. */
  9820. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9821. || file.access.fp == NULL) {
  9822. (void)mg_fclose(&file.access);
  9823. mg_send_http_error(conn,
  9824. 500,
  9825. "Error: Can not create file\nfopen(%s): %s",
  9826. path,
  9827. strerror(ERRNO));
  9828. return;
  9829. }
  9830. fclose_on_exec(&file.access, conn);
  9831. range = mg_get_header(conn, "Content-Range");
  9832. r1 = r2 = 0;
  9833. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9834. conn->status_code = 206; /* Partial content */
  9835. fseeko(file.access.fp, r1, SEEK_SET);
  9836. }
  9837. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9838. /* forward_body_data failed.
  9839. * The error code has already been sent to the client,
  9840. * and conn->status_code is already set. */
  9841. (void)mg_fclose(&file.access);
  9842. return;
  9843. }
  9844. if (mg_fclose(&file.access) != 0) {
  9845. /* fclose failed. This might have different reasons, but a likely
  9846. * one is "no space on disk", http 507. */
  9847. conn->status_code = 507;
  9848. }
  9849. gmt_time_string(date, sizeof(date), &curtime);
  9850. mg_printf(conn,
  9851. "HTTP/1.1 %d %s\r\n",
  9852. conn->status_code,
  9853. mg_get_response_code_text(NULL, conn->status_code));
  9854. send_no_cache_header(conn);
  9855. send_additional_header(conn);
  9856. mg_printf(conn,
  9857. "Date: %s\r\n"
  9858. "Content-Length: 0\r\n"
  9859. "Connection: %s\r\n\r\n",
  9860. date,
  9861. suggest_connection_header(conn));
  9862. }
  9863. static void
  9864. delete_file(struct mg_connection *conn, const char *path)
  9865. {
  9866. struct de de;
  9867. memset(&de.file, 0, sizeof(de.file));
  9868. if (!mg_stat(conn, path, &de.file)) {
  9869. /* mg_stat returns 0 if the file does not exist */
  9870. mg_send_http_error(conn,
  9871. 404,
  9872. "Error: Cannot delete file\nFile %s not found",
  9873. path);
  9874. return;
  9875. }
  9876. #if 0 /* Ignore if a file in memory is inside a folder */
  9877. if (de.access.membuf != NULL) {
  9878. /* the file is cached in memory */
  9879. mg_send_http_error(
  9880. conn,
  9881. 405,
  9882. "Error: Delete not possible\nDeleting %s is not supported",
  9883. path);
  9884. return;
  9885. }
  9886. #endif
  9887. if (de.file.is_directory) {
  9888. if (remove_directory(conn, path)) {
  9889. /* Delete is successful: Return 204 without content. */
  9890. mg_send_http_error(conn, 204, "%s", "");
  9891. } else {
  9892. /* Delete is not successful: Return 500 (Server error). */
  9893. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9894. }
  9895. return;
  9896. }
  9897. /* This is an existing file (not a directory).
  9898. * Check if write permission is granted. */
  9899. if (access(path, W_OK) != 0) {
  9900. /* File is read only */
  9901. mg_send_http_error(
  9902. conn,
  9903. 403,
  9904. "Error: Delete not possible\nDeleting %s is not allowed",
  9905. path);
  9906. return;
  9907. }
  9908. /* Try to delete it. */
  9909. if (mg_remove(conn, path) == 0) {
  9910. /* Delete was successful: Return 204 without content. */
  9911. mg_send_http_error(conn, 204, "%s", "");
  9912. } else {
  9913. /* Delete not successful (file locked). */
  9914. mg_send_http_error(conn,
  9915. 423,
  9916. "Error: Cannot delete file\nremove(%s): %s",
  9917. path,
  9918. strerror(ERRNO));
  9919. }
  9920. }
  9921. #endif /* !NO_FILES */
  9922. static void
  9923. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9924. static void
  9925. do_ssi_include(struct mg_connection *conn,
  9926. const char *ssi,
  9927. char *tag,
  9928. int include_level)
  9929. {
  9930. char file_name[MG_BUF_LEN], path[512], *p;
  9931. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9932. size_t len;
  9933. int truncated = 0;
  9934. if (conn == NULL) {
  9935. return;
  9936. }
  9937. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9938. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9939. * always < MG_BUF_LEN. */
  9940. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9941. /* File name is relative to the webserver root */
  9942. file_name[511] = 0;
  9943. (void)mg_snprintf(conn,
  9944. &truncated,
  9945. path,
  9946. sizeof(path),
  9947. "%s/%s",
  9948. conn->dom_ctx->config[DOCUMENT_ROOT],
  9949. file_name);
  9950. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9951. /* File name is relative to the webserver working directory
  9952. * or it is absolute system path */
  9953. file_name[511] = 0;
  9954. (void)
  9955. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9956. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9957. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9958. /* File name is relative to the currect document */
  9959. file_name[511] = 0;
  9960. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9961. if (!truncated) {
  9962. if ((p = strrchr(path, '/')) != NULL) {
  9963. p[1] = '\0';
  9964. }
  9965. len = strlen(path);
  9966. (void)mg_snprintf(conn,
  9967. &truncated,
  9968. path + len,
  9969. sizeof(path) - len,
  9970. "%s",
  9971. file_name);
  9972. }
  9973. } else {
  9974. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9975. return;
  9976. }
  9977. if (truncated) {
  9978. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9979. return;
  9980. }
  9981. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9982. mg_cry_internal(conn,
  9983. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9984. tag,
  9985. path,
  9986. strerror(ERRNO));
  9987. } else {
  9988. fclose_on_exec(&file.access, conn);
  9989. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9990. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9991. path)
  9992. > 0) {
  9993. send_ssi_file(conn, path, &file, include_level + 1);
  9994. } else {
  9995. send_file_data(conn, &file, 0, INT64_MAX);
  9996. }
  9997. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9998. }
  9999. }
  10000. #if !defined(NO_POPEN)
  10001. static void
  10002. do_ssi_exec(struct mg_connection *conn, char *tag)
  10003. {
  10004. char cmd[1024] = "";
  10005. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10006. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10007. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10008. } else {
  10009. cmd[1023] = 0;
  10010. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10011. mg_cry_internal(conn,
  10012. "Cannot SSI #exec: [%s]: %s",
  10013. cmd,
  10014. strerror(ERRNO));
  10015. } else {
  10016. send_file_data(conn, &file, 0, INT64_MAX);
  10017. pclose(file.access.fp);
  10018. }
  10019. }
  10020. }
  10021. #endif /* !NO_POPEN */
  10022. static int
  10023. mg_fgetc(struct mg_file *filep, int offset)
  10024. {
  10025. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10026. if (filep == NULL) {
  10027. return EOF;
  10028. }
  10029. #if defined(MG_USE_OPEN_FILE)
  10030. if ((filep->access.membuf != NULL) && (offset >= 0)
  10031. && (((unsigned int)(offset)) < filep->stat.size)) {
  10032. return ((const unsigned char *)filep->access.membuf)[offset];
  10033. } else /* else block below */
  10034. #endif
  10035. if (filep->access.fp != NULL) {
  10036. return fgetc(filep->access.fp);
  10037. } else {
  10038. return EOF;
  10039. }
  10040. }
  10041. static void
  10042. send_ssi_file(struct mg_connection *conn,
  10043. const char *path,
  10044. struct mg_file *filep,
  10045. int include_level)
  10046. {
  10047. char buf[MG_BUF_LEN];
  10048. int ch, offset, len, in_tag, in_ssi_tag;
  10049. if (include_level > 10) {
  10050. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10051. return;
  10052. }
  10053. in_tag = in_ssi_tag = len = offset = 0;
  10054. /* Read file, byte by byte, and look for SSI include tags */
  10055. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10056. if (in_tag) {
  10057. /* We are in a tag, either SSI tag or html tag */
  10058. if (ch == '>') {
  10059. /* Tag is closing */
  10060. buf[len++] = '>';
  10061. if (in_ssi_tag) {
  10062. /* Handle SSI tag */
  10063. buf[len] = 0;
  10064. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10065. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10066. #if !defined(NO_POPEN)
  10067. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10068. do_ssi_exec(conn, buf + 9);
  10069. #endif /* !NO_POPEN */
  10070. } else {
  10071. mg_cry_internal(conn,
  10072. "%s: unknown SSI "
  10073. "command: \"%s\"",
  10074. path,
  10075. buf);
  10076. }
  10077. len = 0;
  10078. in_ssi_tag = in_tag = 0;
  10079. } else {
  10080. /* Not an SSI tag */
  10081. /* Flush buffer */
  10082. (void)mg_write(conn, buf, (size_t)len);
  10083. len = 0;
  10084. in_tag = 0;
  10085. }
  10086. } else {
  10087. /* Tag is still open */
  10088. buf[len++] = (char)(ch & 0xff);
  10089. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10090. /* All SSI tags start with <!--# */
  10091. in_ssi_tag = 1;
  10092. }
  10093. if ((len + 2) > (int)sizeof(buf)) {
  10094. /* Tag to long for buffer */
  10095. mg_cry_internal(conn, "%s: tag is too large", path);
  10096. return;
  10097. }
  10098. }
  10099. } else {
  10100. /* We are not in a tag yet. */
  10101. if (ch == '<') {
  10102. /* Tag is opening */
  10103. in_tag = 1;
  10104. if (len > 0) {
  10105. /* Flush current buffer.
  10106. * Buffer is filled with "len" bytes. */
  10107. (void)mg_write(conn, buf, (size_t)len);
  10108. }
  10109. /* Store the < */
  10110. len = 1;
  10111. buf[0] = '<';
  10112. } else {
  10113. /* No Tag */
  10114. /* Add data to buffer */
  10115. buf[len++] = (char)(ch & 0xff);
  10116. /* Flush if buffer is full */
  10117. if (len == (int)sizeof(buf)) {
  10118. mg_write(conn, buf, (size_t)len);
  10119. len = 0;
  10120. }
  10121. }
  10122. }
  10123. }
  10124. /* Send the rest of buffered data */
  10125. if (len > 0) {
  10126. mg_write(conn, buf, (size_t)len);
  10127. }
  10128. }
  10129. static void
  10130. handle_ssi_file_request(struct mg_connection *conn,
  10131. const char *path,
  10132. struct mg_file *filep)
  10133. {
  10134. char date[64];
  10135. time_t curtime = time(NULL);
  10136. const char *cors_orig_cfg;
  10137. const char *cors1, *cors2, *cors3;
  10138. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10139. return;
  10140. }
  10141. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10142. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10143. /* Cross-origin resource sharing (CORS). */
  10144. cors1 = "Access-Control-Allow-Origin: ";
  10145. cors2 = cors_orig_cfg;
  10146. cors3 = "\r\n";
  10147. } else {
  10148. cors1 = cors2 = cors3 = "";
  10149. }
  10150. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10151. /* File exists (precondition for calling this function),
  10152. * but can not be opened by the server. */
  10153. mg_send_http_error(conn,
  10154. 500,
  10155. "Error: Cannot read file\nfopen(%s): %s",
  10156. path,
  10157. strerror(ERRNO));
  10158. } else {
  10159. conn->must_close = 1;
  10160. gmt_time_string(date, sizeof(date), &curtime);
  10161. fclose_on_exec(&filep->access, conn);
  10162. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10163. send_no_cache_header(conn);
  10164. send_additional_header(conn);
  10165. mg_printf(conn,
  10166. "%s%s%s"
  10167. "Date: %s\r\n"
  10168. "Content-Type: text/html\r\n"
  10169. "Connection: %s\r\n\r\n",
  10170. cors1,
  10171. cors2,
  10172. cors3,
  10173. date,
  10174. suggest_connection_header(conn));
  10175. send_ssi_file(conn, path, filep, 0);
  10176. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10177. }
  10178. }
  10179. #if !defined(NO_FILES)
  10180. static void
  10181. send_options(struct mg_connection *conn)
  10182. {
  10183. char date[64];
  10184. time_t curtime = time(NULL);
  10185. if (!conn) {
  10186. return;
  10187. }
  10188. conn->status_code = 200;
  10189. conn->must_close = 1;
  10190. gmt_time_string(date, sizeof(date), &curtime);
  10191. /* We do not set a "Cache-Control" header here, but leave the default.
  10192. * Since browsers do not send an OPTIONS request, we can not test the
  10193. * effect anyway. */
  10194. mg_printf(conn,
  10195. "HTTP/1.1 200 OK\r\n"
  10196. "Date: %s\r\n"
  10197. "Connection: %s\r\n"
  10198. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10199. "PROPFIND, MKCOL\r\n"
  10200. "DAV: 1\r\n",
  10201. date,
  10202. suggest_connection_header(conn));
  10203. send_additional_header(conn);
  10204. mg_printf(conn, "\r\n");
  10205. }
  10206. /* Writes PROPFIND properties for a collection element */
  10207. static void
  10208. print_props(struct mg_connection *conn,
  10209. const char *uri,
  10210. struct mg_file_stat *filep)
  10211. {
  10212. char mtime[64];
  10213. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  10214. return;
  10215. }
  10216. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10217. mg_printf(conn,
  10218. "<d:response>"
  10219. "<d:href>%s</d:href>"
  10220. "<d:propstat>"
  10221. "<d:prop>"
  10222. "<d:resourcetype>%s</d:resourcetype>"
  10223. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10224. "<d:getlastmodified>%s</d:getlastmodified>"
  10225. "</d:prop>"
  10226. "<d:status>HTTP/1.1 200 OK</d:status>"
  10227. "</d:propstat>"
  10228. "</d:response>\n",
  10229. uri,
  10230. filep->is_directory ? "<d:collection/>" : "",
  10231. filep->size,
  10232. mtime);
  10233. }
  10234. static int
  10235. print_dav_dir_entry(struct de *de, void *data)
  10236. {
  10237. char href[PATH_MAX];
  10238. int truncated;
  10239. struct mg_connection *conn = (struct mg_connection *)data;
  10240. if (!de || !conn) {
  10241. return -1;
  10242. }
  10243. mg_snprintf(conn,
  10244. &truncated,
  10245. href,
  10246. sizeof(href),
  10247. "%s%s",
  10248. conn->request_info.local_uri,
  10249. de->file_name);
  10250. if (!truncated) {
  10251. size_t href_encoded_size;
  10252. char *href_encoded;
  10253. href_encoded_size = PATH_MAX * 3; /* worst case */
  10254. href_encoded = (char *)mg_malloc(href_encoded_size);
  10255. if (href_encoded == NULL) {
  10256. return -1;
  10257. }
  10258. mg_url_encode(href, href_encoded, href_encoded_size);
  10259. print_props(conn, href_encoded, &de->file);
  10260. mg_free(href_encoded);
  10261. }
  10262. return 0;
  10263. }
  10264. static void
  10265. handle_propfind(struct mg_connection *conn,
  10266. const char *path,
  10267. struct mg_file_stat *filep)
  10268. {
  10269. const char *depth = mg_get_header(conn, "Depth");
  10270. char date[64];
  10271. time_t curtime = time(NULL);
  10272. gmt_time_string(date, sizeof(date), &curtime);
  10273. if (!conn || !path || !filep || !conn->dom_ctx) {
  10274. return;
  10275. }
  10276. conn->must_close = 1;
  10277. conn->status_code = 207;
  10278. mg_printf(conn,
  10279. "HTTP/1.1 207 Multi-Status\r\n"
  10280. "Date: %s\r\n",
  10281. date);
  10282. send_static_cache_header(conn);
  10283. send_additional_header(conn);
  10284. mg_printf(conn,
  10285. "Connection: %s\r\n"
  10286. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10287. suggest_connection_header(conn));
  10288. mg_printf(conn,
  10289. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10290. "<d:multistatus xmlns:d='DAV:'>\n");
  10291. /* Print properties for the requested resource itself */
  10292. print_props(conn, conn->request_info.local_uri, filep);
  10293. /* If it is a directory, print directory entries too if Depth is not 0
  10294. */
  10295. if (filep->is_directory
  10296. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10297. "yes")
  10298. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10299. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10300. }
  10301. mg_printf(conn, "%s\n", "</d:multistatus>");
  10302. }
  10303. #endif
  10304. void
  10305. mg_lock_connection(struct mg_connection *conn)
  10306. {
  10307. if (conn) {
  10308. (void)pthread_mutex_lock(&conn->mutex);
  10309. }
  10310. }
  10311. void
  10312. mg_unlock_connection(struct mg_connection *conn)
  10313. {
  10314. if (conn) {
  10315. (void)pthread_mutex_unlock(&conn->mutex);
  10316. }
  10317. }
  10318. void
  10319. mg_lock_context(struct mg_context *ctx)
  10320. {
  10321. if (ctx) {
  10322. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10323. }
  10324. }
  10325. void
  10326. mg_unlock_context(struct mg_context *ctx)
  10327. {
  10328. if (ctx) {
  10329. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10330. }
  10331. }
  10332. #if defined(USE_LUA)
  10333. #include "mod_lua.inl"
  10334. #endif /* USE_LUA */
  10335. #if defined(USE_DUKTAPE)
  10336. #include "mod_duktape.inl"
  10337. #endif /* USE_DUKTAPE */
  10338. #if defined(USE_WEBSOCKET)
  10339. #if !defined(NO_SSL_DL)
  10340. #define SHA_API static
  10341. #include "sha1.inl"
  10342. #endif
  10343. static int
  10344. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10345. {
  10346. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10347. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10348. SHA_CTX sha_ctx;
  10349. int truncated;
  10350. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10351. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10352. if (truncated) {
  10353. conn->must_close = 1;
  10354. return 0;
  10355. }
  10356. DEBUG_TRACE("%s", "Send websocket handshake");
  10357. SHA1_Init(&sha_ctx);
  10358. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10359. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10360. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10361. mg_printf(conn,
  10362. "HTTP/1.1 101 Switching Protocols\r\n"
  10363. "Upgrade: websocket\r\n"
  10364. "Connection: Upgrade\r\n"
  10365. "Sec-WebSocket-Accept: %s\r\n",
  10366. b64_sha);
  10367. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10368. mg_printf(conn,
  10369. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10370. conn->request_info.acceptedWebSocketSubprotocol);
  10371. } else {
  10372. mg_printf(conn, "%s", "\r\n");
  10373. }
  10374. return 1;
  10375. }
  10376. #if !defined(MG_MAX_UNANSWERED_PING)
  10377. /* Configuration of the maximum number of websocket PINGs that might
  10378. * stay unanswered before the connection is considered broken.
  10379. * Note: The name of this define may still change (until it is
  10380. * defined as a compile parameter in a documentation).
  10381. */
  10382. #define MG_MAX_UNANSWERED_PING (5)
  10383. #endif
  10384. static void
  10385. read_websocket(struct mg_connection *conn,
  10386. mg_websocket_data_handler ws_data_handler,
  10387. void *callback_data)
  10388. {
  10389. /* Pointer to the beginning of the portion of the incoming websocket
  10390. * message queue.
  10391. * The original websocket upgrade request is never removed, so the queue
  10392. * begins after it. */
  10393. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10394. int n, error, exit_by_callback;
  10395. int ret;
  10396. /* body_len is the length of the entire queue in bytes
  10397. * len is the length of the current message
  10398. * data_len is the length of the current message's data payload
  10399. * header_len is the length of the current message's header */
  10400. size_t i, len, mask_len = 0, header_len, body_len;
  10401. uint64_t data_len = 0;
  10402. /* "The masking key is a 32-bit value chosen at random by the client."
  10403. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10404. */
  10405. unsigned char mask[4];
  10406. /* data points to the place where the message is stored when passed to
  10407. * the websocket_data callback. This is either mem on the stack, or a
  10408. * dynamically allocated buffer if it is too large. */
  10409. unsigned char mem[4096];
  10410. unsigned char mop; /* mask flag and opcode */
  10411. /* Variables used for connection monitoring */
  10412. double timeout = -1.0;
  10413. int enable_ping_pong = 0;
  10414. int ping_count = 0;
  10415. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10416. enable_ping_pong =
  10417. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10418. "yes");
  10419. }
  10420. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10421. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10422. }
  10423. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10424. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10425. }
  10426. /* Enter data processing loop */
  10427. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10428. conn->request_info.remote_addr,
  10429. conn->request_info.remote_port);
  10430. conn->in_websocket_handling = 1;
  10431. mg_set_thread_name("wsock");
  10432. /* Loop continuously, reading messages from the socket, invoking the
  10433. * callback, and waiting repeatedly until an error occurs. */
  10434. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10435. header_len = 0;
  10436. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10437. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10438. len = buf[1] & 127;
  10439. mask_len = (buf[1] & 128) ? 4 : 0;
  10440. if ((len < 126) && (body_len >= mask_len)) {
  10441. /* inline 7-bit length field */
  10442. data_len = len;
  10443. header_len = 2 + mask_len;
  10444. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10445. /* 16-bit length field */
  10446. header_len = 4 + mask_len;
  10447. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10448. } else if (body_len >= (10 + mask_len)) {
  10449. /* 64-bit length field */
  10450. uint32_t l1, l2;
  10451. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10452. memcpy(&l2, &buf[6], 4);
  10453. header_len = 10 + mask_len;
  10454. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10455. if (data_len > (uint64_t)0x7FFF0000ul) {
  10456. /* no can do */
  10457. mg_cry_internal(
  10458. conn,
  10459. "%s",
  10460. "websocket out of memory; closing connection");
  10461. break;
  10462. }
  10463. }
  10464. }
  10465. if ((header_len > 0) && (body_len >= header_len)) {
  10466. /* Allocate space to hold websocket payload */
  10467. unsigned char *data = mem;
  10468. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10469. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10470. conn->phys_ctx);
  10471. if (data == NULL) {
  10472. /* Allocation failed, exit the loop and then close the
  10473. * connection */
  10474. mg_cry_internal(
  10475. conn,
  10476. "%s",
  10477. "websocket out of memory; closing connection");
  10478. break;
  10479. }
  10480. }
  10481. /* Copy the mask before we shift the queue and destroy it */
  10482. if (mask_len > 0) {
  10483. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10484. } else {
  10485. memset(mask, 0, sizeof(mask));
  10486. }
  10487. /* Read frame payload from the first message in the queue into
  10488. * data and advance the queue by moving the memory in place. */
  10489. DEBUG_ASSERT(body_len >= header_len);
  10490. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10491. mop = buf[0]; /* current mask and opcode */
  10492. /* Overflow case */
  10493. len = body_len - header_len;
  10494. memcpy(data, buf + header_len, len);
  10495. error = 0;
  10496. while ((uint64_t)len < data_len) {
  10497. n = pull_inner(NULL,
  10498. conn,
  10499. (char *)(data + len),
  10500. (int)(data_len - len),
  10501. timeout);
  10502. if (n <= -2) {
  10503. error = 1;
  10504. break;
  10505. } else if (n > 0) {
  10506. len += (size_t)n;
  10507. } else {
  10508. /* Timeout: should retry */
  10509. /* TODO: retry condition */
  10510. }
  10511. }
  10512. if (error) {
  10513. mg_cry_internal(
  10514. conn,
  10515. "%s",
  10516. "Websocket pull failed; closing connection");
  10517. if (data != mem) {
  10518. mg_free(data);
  10519. }
  10520. break;
  10521. }
  10522. conn->data_len = conn->request_len;
  10523. } else {
  10524. mop = buf[0]; /* current mask and opcode, overwritten by
  10525. * memmove() */
  10526. /* Length of the message being read at the front of the
  10527. * queue. Cast to 31 bit is OK, since we limited
  10528. * data_len before. */
  10529. len = (size_t)data_len + header_len;
  10530. /* Copy the data payload into the data pointer for the
  10531. * callback. Cast to 31 bit is OK, since we
  10532. * limited data_len */
  10533. memcpy(data, buf + header_len, (size_t)data_len);
  10534. /* Move the queue forward len bytes */
  10535. memmove(buf, buf + len, body_len - len);
  10536. /* Mark the queue as advanced */
  10537. conn->data_len -= (int)len;
  10538. }
  10539. /* Apply mask if necessary */
  10540. if (mask_len > 0) {
  10541. for (i = 0; i < (size_t)data_len; i++) {
  10542. data[i] ^= mask[i & 3];
  10543. }
  10544. }
  10545. exit_by_callback = 0;
  10546. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10547. /* filter PONG messages */
  10548. DEBUG_TRACE("PONG from %s:%u",
  10549. conn->request_info.remote_addr,
  10550. conn->request_info.remote_port);
  10551. /* No unanwered PINGs left */
  10552. ping_count = 0;
  10553. } else if (enable_ping_pong
  10554. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10555. /* reply PING messages */
  10556. DEBUG_TRACE("Reply PING from %s:%u",
  10557. conn->request_info.remote_addr,
  10558. conn->request_info.remote_port);
  10559. ret = mg_websocket_write(conn,
  10560. MG_WEBSOCKET_OPCODE_PONG,
  10561. (char *)data,
  10562. (size_t)data_len);
  10563. if (ret <= 0) {
  10564. /* Error: send failed */
  10565. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10566. break;
  10567. }
  10568. } else {
  10569. /* Exit the loop if callback signals to exit (server side),
  10570. * or "connection close" opcode received (client side). */
  10571. if ((ws_data_handler != NULL)
  10572. && !ws_data_handler(conn,
  10573. mop,
  10574. (char *)data,
  10575. (size_t)data_len,
  10576. callback_data)) {
  10577. exit_by_callback = 1;
  10578. }
  10579. }
  10580. /* It a buffer has been allocated, free it again */
  10581. if (data != mem) {
  10582. mg_free(data);
  10583. }
  10584. if (exit_by_callback) {
  10585. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10586. conn->request_info.remote_addr,
  10587. conn->request_info.remote_port);
  10588. break;
  10589. }
  10590. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10591. /* Opcode == 8, connection close */
  10592. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10593. conn->request_info.remote_addr,
  10594. conn->request_info.remote_port);
  10595. break;
  10596. }
  10597. /* Not breaking the loop, process next websocket frame. */
  10598. } else {
  10599. /* Read from the socket into the next available location in the
  10600. * message queue. */
  10601. n = pull_inner(NULL,
  10602. conn,
  10603. conn->buf + conn->data_len,
  10604. conn->buf_size - conn->data_len,
  10605. timeout);
  10606. if (n <= -2) {
  10607. /* Error, no bytes read */
  10608. DEBUG_TRACE("PULL from %s:%u failed",
  10609. conn->request_info.remote_addr,
  10610. conn->request_info.remote_port);
  10611. break;
  10612. }
  10613. if (n > 0) {
  10614. conn->data_len += n;
  10615. /* Reset open PING count */
  10616. ping_count = 0;
  10617. } else {
  10618. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10619. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10620. /* Stop sending PING */
  10621. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10622. "- closing connection",
  10623. ping_count,
  10624. conn->request_info.remote_addr,
  10625. conn->request_info.remote_port);
  10626. break;
  10627. }
  10628. if (enable_ping_pong) {
  10629. /* Send Websocket PING message */
  10630. DEBUG_TRACE("PING to %s:%u",
  10631. conn->request_info.remote_addr,
  10632. conn->request_info.remote_port);
  10633. ret = mg_websocket_write(conn,
  10634. MG_WEBSOCKET_OPCODE_PING,
  10635. NULL,
  10636. 0);
  10637. if (ret <= 0) {
  10638. /* Error: send failed */
  10639. DEBUG_TRACE("Send PING failed (%i)", ret);
  10640. break;
  10641. }
  10642. ping_count++;
  10643. }
  10644. }
  10645. /* Timeout: should retry */
  10646. /* TODO: get timeout def */
  10647. }
  10648. }
  10649. }
  10650. /* Leave data processing loop */
  10651. mg_set_thread_name("worker");
  10652. conn->in_websocket_handling = 0;
  10653. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10654. conn->request_info.remote_addr,
  10655. conn->request_info.remote_port);
  10656. }
  10657. static int
  10658. mg_websocket_write_exec(struct mg_connection *conn,
  10659. int opcode,
  10660. const char *data,
  10661. size_t dataLen,
  10662. uint32_t masking_key)
  10663. {
  10664. unsigned char header[14];
  10665. size_t headerLen;
  10666. int retval;
  10667. #if defined(GCC_DIAGNOSTIC)
  10668. /* Disable spurious conversion warning for GCC */
  10669. #pragma GCC diagnostic push
  10670. #pragma GCC diagnostic ignored "-Wconversion"
  10671. #endif
  10672. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10673. #if defined(GCC_DIAGNOSTIC)
  10674. #pragma GCC diagnostic pop
  10675. #endif
  10676. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10677. if (dataLen < 126) {
  10678. /* inline 7-bit length field */
  10679. header[1] = (unsigned char)dataLen;
  10680. headerLen = 2;
  10681. } else if (dataLen <= 0xFFFF) {
  10682. /* 16-bit length field */
  10683. uint16_t len = htons((uint16_t)dataLen);
  10684. header[1] = 126;
  10685. memcpy(header + 2, &len, 2);
  10686. headerLen = 4;
  10687. } else {
  10688. /* 64-bit length field */
  10689. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10690. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10691. header[1] = 127;
  10692. memcpy(header + 2, &len1, 4);
  10693. memcpy(header + 6, &len2, 4);
  10694. headerLen = 10;
  10695. }
  10696. if (masking_key) {
  10697. /* add mask */
  10698. header[1] |= 0x80;
  10699. memcpy(header + headerLen, &masking_key, 4);
  10700. headerLen += 4;
  10701. }
  10702. /* Note that POSIX/Winsock's send() is threadsafe
  10703. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10704. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10705. * push(), although that is only a problem if the packet is large or
  10706. * outgoing buffer is full). */
  10707. /* TODO: Check if this lock should be moved to user land.
  10708. * Currently the server sets this lock for websockets, but
  10709. * not for any other connection. It must be set for every
  10710. * conn read/written by more than one thread, no matter if
  10711. * it is a websocket or regular connection. */
  10712. (void)mg_lock_connection(conn);
  10713. retval = mg_write(conn, header, headerLen);
  10714. if (retval != (int)headerLen) {
  10715. /* Did not send complete header */
  10716. retval = -1;
  10717. } else {
  10718. if (dataLen > 0) {
  10719. retval = mg_write(conn, data, dataLen);
  10720. }
  10721. /* if dataLen == 0, the header length (2) is returned */
  10722. }
  10723. /* TODO: Remove this unlock as well, when lock is removed. */
  10724. mg_unlock_connection(conn);
  10725. return retval;
  10726. }
  10727. int
  10728. mg_websocket_write(struct mg_connection *conn,
  10729. int opcode,
  10730. const char *data,
  10731. size_t dataLen)
  10732. {
  10733. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10734. }
  10735. static void
  10736. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10737. {
  10738. size_t i = 0;
  10739. i = 0;
  10740. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10741. /* Convert in 32 bit words, if data is 4 byte aligned */
  10742. while (i < (in_len - 3)) {
  10743. *(uint32_t *)(void *)(out + i) =
  10744. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10745. i += 4;
  10746. }
  10747. }
  10748. if (i != in_len) {
  10749. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10750. while (i < in_len) {
  10751. *(uint8_t *)(void *)(out + i) =
  10752. *(uint8_t *)(void *)(in + i)
  10753. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10754. i++;
  10755. }
  10756. }
  10757. }
  10758. int
  10759. mg_websocket_client_write(struct mg_connection *conn,
  10760. int opcode,
  10761. const char *data,
  10762. size_t dataLen)
  10763. {
  10764. int retval = -1;
  10765. char *masked_data =
  10766. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10767. uint32_t masking_key = 0;
  10768. if (masked_data == NULL) {
  10769. /* Return -1 in an error case */
  10770. mg_cry_internal(conn,
  10771. "%s",
  10772. "Cannot allocate buffer for masked websocket response: "
  10773. "Out of memory");
  10774. return -1;
  10775. }
  10776. do {
  10777. /* Get a masking key - but not 0 */
  10778. masking_key = (uint32_t)get_random();
  10779. } while (masking_key == 0);
  10780. mask_data(data, dataLen, masking_key, masked_data);
  10781. retval = mg_websocket_write_exec(
  10782. conn, opcode, masked_data, dataLen, masking_key);
  10783. mg_free(masked_data);
  10784. return retval;
  10785. }
  10786. static void
  10787. handle_websocket_request(struct mg_connection *conn,
  10788. const char *path,
  10789. int is_callback_resource,
  10790. struct mg_websocket_subprotocols *subprotocols,
  10791. mg_websocket_connect_handler ws_connect_handler,
  10792. mg_websocket_ready_handler ws_ready_handler,
  10793. mg_websocket_data_handler ws_data_handler,
  10794. mg_websocket_close_handler ws_close_handler,
  10795. void *cbData)
  10796. {
  10797. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10798. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10799. ptrdiff_t lua_websock = 0;
  10800. #if !defined(USE_LUA)
  10801. (void)path;
  10802. #endif
  10803. /* Step 1: Check websocket protocol version. */
  10804. /* Step 1.1: Check Sec-WebSocket-Key. */
  10805. if (!websock_key) {
  10806. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10807. * requires a Sec-WebSocket-Key header.
  10808. */
  10809. /* It could be the hixie draft version
  10810. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10811. */
  10812. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10813. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10814. char key3[8];
  10815. if ((key1 != NULL) && (key2 != NULL)) {
  10816. /* This version uses 8 byte body data in a GET request */
  10817. conn->content_len = 8;
  10818. if (8 == mg_read(conn, key3, 8)) {
  10819. /* This is the hixie version */
  10820. mg_send_http_error(conn,
  10821. 426,
  10822. "%s",
  10823. "Protocol upgrade to RFC 6455 required");
  10824. return;
  10825. }
  10826. }
  10827. /* This is an unknown version */
  10828. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10829. return;
  10830. }
  10831. /* Step 1.2: Check websocket protocol version. */
  10832. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10833. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10834. /* Reject wrong versions */
  10835. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10836. return;
  10837. }
  10838. /* Step 1.3: Could check for "Host", but we do not really nead this
  10839. * value for anything, so just ignore it. */
  10840. /* Step 2: If a callback is responsible, call it. */
  10841. if (is_callback_resource) {
  10842. /* Step 2.1 check and select subprotocol */
  10843. const char *protocols[64]; // max 64 headers
  10844. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10845. "Sec-WebSocket-Protocol",
  10846. protocols,
  10847. 64);
  10848. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10849. int cnt = 0;
  10850. int idx;
  10851. unsigned long len;
  10852. const char *sep, *curSubProtocol,
  10853. *acceptedWebSocketSubprotocol = NULL;
  10854. /* look for matching subprotocol */
  10855. do {
  10856. const char *protocol = protocols[cnt];
  10857. do {
  10858. sep = strchr(protocol, ',');
  10859. curSubProtocol = protocol;
  10860. len = sep ? (unsigned long)(sep - protocol)
  10861. : (unsigned long)strlen(protocol);
  10862. while (sep && isspace(*++sep))
  10863. ; // ignore leading whitespaces
  10864. protocol = sep;
  10865. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10866. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10867. && (strncmp(curSubProtocol,
  10868. subprotocols->subprotocols[idx],
  10869. len)
  10870. == 0)) {
  10871. acceptedWebSocketSubprotocol =
  10872. subprotocols->subprotocols[idx];
  10873. break;
  10874. }
  10875. }
  10876. } while (sep && !acceptedWebSocketSubprotocol);
  10877. } while (++cnt < nbSubprotocolHeader
  10878. && !acceptedWebSocketSubprotocol);
  10879. conn->request_info.acceptedWebSocketSubprotocol =
  10880. acceptedWebSocketSubprotocol;
  10881. } else if (nbSubprotocolHeader > 0) {
  10882. /* keep legacy behavior */
  10883. const char *protocol = protocols[0];
  10884. /* The protocol is a comma separated list of names. */
  10885. /* The server must only return one value from this list. */
  10886. /* First check if it is a list or just a single value. */
  10887. const char *sep = strrchr(protocol, ',');
  10888. if (sep == NULL) {
  10889. /* Just a single protocol -> accept it. */
  10890. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10891. } else {
  10892. /* Multiple protocols -> accept the last one. */
  10893. /* This is just a quick fix if the client offers multiple
  10894. * protocols. The handler should have a list of accepted
  10895. * protocols on his own
  10896. * and use it to select one protocol among those the client
  10897. * has
  10898. * offered.
  10899. */
  10900. while (isspace(*++sep)) {
  10901. ; /* ignore leading whitespaces */
  10902. }
  10903. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10904. }
  10905. }
  10906. if ((ws_connect_handler != NULL)
  10907. && (ws_connect_handler(conn, cbData) != 0)) {
  10908. /* C callback has returned non-zero, do not proceed with
  10909. * handshake.
  10910. */
  10911. /* Note that C callbacks are no longer called when Lua is
  10912. * responsible, so C can no longer filter callbacks for Lua. */
  10913. return;
  10914. }
  10915. }
  10916. #if defined(USE_LUA)
  10917. /* Step 3: No callback. Check if Lua is responsible. */
  10918. else {
  10919. /* Step 3.1: Check if Lua is responsible. */
  10920. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10921. lua_websock = match_prefix(
  10922. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10923. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10924. path);
  10925. }
  10926. if (lua_websock) {
  10927. /* Step 3.2: Lua is responsible: call it. */
  10928. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10929. if (!conn->lua_websocket_state) {
  10930. /* Lua rejected the new client */
  10931. return;
  10932. }
  10933. }
  10934. }
  10935. #endif
  10936. /* Step 4: Check if there is a responsible websocket handler. */
  10937. if (!is_callback_resource && !lua_websock) {
  10938. /* There is no callback, and Lua is not responsible either. */
  10939. /* Reply with a 404 Not Found. We are still at a standard
  10940. * HTTP request here, before the websocket handshake, so
  10941. * we can still send standard HTTP error replies. */
  10942. mg_send_http_error(conn, 404, "%s", "Not found");
  10943. return;
  10944. }
  10945. /* Step 5: The websocket connection has been accepted */
  10946. if (!send_websocket_handshake(conn, websock_key)) {
  10947. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10948. return;
  10949. }
  10950. /* Step 6: Call the ready handler */
  10951. if (is_callback_resource) {
  10952. if (ws_ready_handler != NULL) {
  10953. ws_ready_handler(conn, cbData);
  10954. }
  10955. #if defined(USE_LUA)
  10956. } else if (lua_websock) {
  10957. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10958. /* the ready handler returned false */
  10959. return;
  10960. }
  10961. #endif
  10962. }
  10963. /* Step 7: Enter the read loop */
  10964. if (is_callback_resource) {
  10965. read_websocket(conn, ws_data_handler, cbData);
  10966. #if defined(USE_LUA)
  10967. } else if (lua_websock) {
  10968. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10969. #endif
  10970. }
  10971. /* Step 8: Call the close handler */
  10972. if (ws_close_handler) {
  10973. ws_close_handler(conn, cbData);
  10974. }
  10975. }
  10976. static int
  10977. is_websocket_protocol(const struct mg_connection *conn)
  10978. {
  10979. const char *upgrade, *connection;
  10980. /* A websocket protocoll has the following HTTP headers:
  10981. *
  10982. * Connection: Upgrade
  10983. * Upgrade: Websocket
  10984. */
  10985. upgrade = mg_get_header(conn, "Upgrade");
  10986. if (upgrade == NULL) {
  10987. return 0; /* fail early, don't waste time checking other header
  10988. * fields
  10989. */
  10990. }
  10991. if (!mg_strcasestr(upgrade, "websocket")) {
  10992. return 0;
  10993. }
  10994. connection = mg_get_header(conn, "Connection");
  10995. if (connection == NULL) {
  10996. return 0;
  10997. }
  10998. if (!mg_strcasestr(connection, "upgrade")) {
  10999. return 0;
  11000. }
  11001. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11002. * "Sec-WebSocket-Version" are also required.
  11003. * Don't check them here, since even an unsupported websocket protocol
  11004. * request still IS a websocket request (in contrast to a standard HTTP
  11005. * request). It will fail later in handle_websocket_request.
  11006. */
  11007. return 1;
  11008. }
  11009. #endif /* !USE_WEBSOCKET */
  11010. static int
  11011. isbyte(int n)
  11012. {
  11013. return (n >= 0) && (n <= 255);
  11014. }
  11015. static int
  11016. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11017. {
  11018. int n, a, b, c, d, slash = 32, len = 0;
  11019. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11020. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11021. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11022. && (slash < 33)) {
  11023. len = n;
  11024. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11025. | (uint32_t)d;
  11026. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11027. }
  11028. return len;
  11029. }
  11030. static int
  11031. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11032. {
  11033. int throttle = 0;
  11034. struct vec vec, val;
  11035. uint32_t net, mask;
  11036. char mult;
  11037. double v;
  11038. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11039. mult = ',';
  11040. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11041. || (v < 0)
  11042. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11043. && (mult != ','))) {
  11044. continue;
  11045. }
  11046. v *= (lowercase(&mult) == 'k')
  11047. ? 1024
  11048. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11049. if (vec.len == 1 && vec.ptr[0] == '*') {
  11050. throttle = (int)v;
  11051. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11052. if ((remote_ip & mask) == net) {
  11053. throttle = (int)v;
  11054. }
  11055. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11056. throttle = (int)v;
  11057. }
  11058. }
  11059. return throttle;
  11060. }
  11061. static uint32_t
  11062. get_remote_ip(const struct mg_connection *conn)
  11063. {
  11064. if (!conn) {
  11065. return 0;
  11066. }
  11067. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11068. }
  11069. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11070. #include "handle_form.inl"
  11071. #if defined(MG_LEGACY_INTERFACE)
  11072. /* Implement the deprecated mg_upload function by calling the new
  11073. * mg_handle_form_request function. While mg_upload could only handle
  11074. * HTML forms sent as POST request in multipart/form-data format
  11075. * containing only file input elements, mg_handle_form_request can
  11076. * handle all form input elements and all standard request methods. */
  11077. struct mg_upload_user_data {
  11078. struct mg_connection *conn;
  11079. const char *destination_dir;
  11080. int num_uploaded_files;
  11081. };
  11082. /* Helper function for deprecated mg_upload. */
  11083. static int
  11084. mg_upload_field_found(const char *key,
  11085. const char *filename,
  11086. char *path,
  11087. size_t pathlen,
  11088. void *user_data)
  11089. {
  11090. int truncated = 0;
  11091. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11092. (void)key;
  11093. if (!filename) {
  11094. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11095. return FORM_FIELD_STORAGE_ABORT;
  11096. }
  11097. mg_snprintf(fud->conn,
  11098. &truncated,
  11099. path,
  11100. pathlen - 1,
  11101. "%s/%s",
  11102. fud->destination_dir,
  11103. filename);
  11104. if (truncated) {
  11105. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11106. return FORM_FIELD_STORAGE_ABORT;
  11107. }
  11108. return FORM_FIELD_STORAGE_STORE;
  11109. }
  11110. /* Helper function for deprecated mg_upload. */
  11111. static int
  11112. mg_upload_field_get(const char *key,
  11113. const char *value,
  11114. size_t value_size,
  11115. void *user_data)
  11116. {
  11117. /* Function should never be called */
  11118. (void)key;
  11119. (void)value;
  11120. (void)value_size;
  11121. (void)user_data;
  11122. return 0;
  11123. }
  11124. /* Helper function for deprecated mg_upload. */
  11125. static int
  11126. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11127. {
  11128. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11129. (void)file_size;
  11130. fud->num_uploaded_files++;
  11131. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11132. return 0;
  11133. }
  11134. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11135. int
  11136. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11137. {
  11138. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11139. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11140. mg_upload_field_get,
  11141. mg_upload_field_stored,
  11142. 0};
  11143. int ret;
  11144. fdh.user_data = (void *)&fud;
  11145. ret = mg_handle_form_request(conn, &fdh);
  11146. if (ret < 0) {
  11147. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11148. }
  11149. return fud.num_uploaded_files;
  11150. }
  11151. #endif
  11152. static int
  11153. get_first_ssl_listener_index(const struct mg_context *ctx)
  11154. {
  11155. unsigned int i;
  11156. int idx = -1;
  11157. if (ctx) {
  11158. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11159. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11160. }
  11161. }
  11162. return idx;
  11163. }
  11164. /* Return host (without port) */
  11165. /* Use mg_free to free the result */
  11166. static const char *
  11167. alloc_get_host(struct mg_connection *conn)
  11168. {
  11169. char buf[1025];
  11170. size_t buflen = sizeof(buf);
  11171. const char *host_header = get_header(conn->request_info.http_headers,
  11172. conn->request_info.num_headers,
  11173. "Host");
  11174. char *host;
  11175. if (host_header != NULL) {
  11176. char *pos;
  11177. /* Create a local copy of the "Host" header, since it might be
  11178. * modified here. */
  11179. mg_strlcpy(buf, host_header, buflen);
  11180. buf[buflen - 1] = '\0';
  11181. host = buf;
  11182. while (isspace(*host)) {
  11183. host++;
  11184. }
  11185. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11186. * is found. */
  11187. if (*host == '[') {
  11188. pos = strchr(host, ']');
  11189. if (!pos) {
  11190. /* Malformed hostname starts with '[', but no ']' found */
  11191. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11192. return NULL;
  11193. }
  11194. /* terminate after ']' */
  11195. pos[1] = 0;
  11196. } else {
  11197. /* Otherwise, a ':' separates hostname and port number */
  11198. pos = strchr(host, ':');
  11199. if (pos != NULL) {
  11200. *pos = '\0';
  11201. }
  11202. }
  11203. if (conn->ssl) {
  11204. /* This is a HTTPS connection, maybe we have a hostname
  11205. * from SNI (set in ssl_servername_callback). */
  11206. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11207. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11208. /* We are not using the default domain */
  11209. if (mg_strcasecmp(host, sslhost)) {
  11210. /* Mismatch between SNI domain and HTTP domain */
  11211. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11212. sslhost,
  11213. host);
  11214. return NULL;
  11215. }
  11216. }
  11217. DEBUG_TRACE("HTTPS Host: %s", host);
  11218. } else {
  11219. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11220. while (dom) {
  11221. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11222. /* Found matching domain */
  11223. DEBUG_TRACE("HTTP domain %s found",
  11224. dom->config[AUTHENTICATION_DOMAIN]);
  11225. /* TODO: Check if this is a HTTP or HTTPS domain */
  11226. conn->dom_ctx = dom;
  11227. break;
  11228. }
  11229. dom = dom->next;
  11230. }
  11231. DEBUG_TRACE("HTTP Host: %s", host);
  11232. }
  11233. } else {
  11234. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11235. host = buf;
  11236. DEBUG_TRACE("IP: %s", host);
  11237. }
  11238. return mg_strdup_ctx(host, conn->phys_ctx);
  11239. }
  11240. static void
  11241. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11242. {
  11243. char target_url[MG_BUF_LEN];
  11244. int truncated = 0;
  11245. conn->must_close = 1;
  11246. /* Send host, port, uri and (if it exists) ?query_string */
  11247. if (conn->host) {
  11248. /* Use "308 Permanent Redirect" */
  11249. int redirect_code = 308;
  11250. /* Create target URL */
  11251. mg_snprintf(
  11252. conn,
  11253. &truncated,
  11254. target_url,
  11255. sizeof(target_url),
  11256. "https://%s:%d%s%s%s",
  11257. conn->host,
  11258. #if defined(USE_IPV6)
  11259. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11260. == AF_INET6)
  11261. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11262. .lsa.sin6.sin6_port)
  11263. :
  11264. #endif
  11265. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11266. .lsa.sin.sin_port),
  11267. conn->request_info.local_uri,
  11268. (conn->request_info.query_string == NULL) ? "" : "?",
  11269. (conn->request_info.query_string == NULL)
  11270. ? ""
  11271. : conn->request_info.query_string);
  11272. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11273. * is used as buffer size) */
  11274. if (truncated) {
  11275. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11276. return;
  11277. }
  11278. /* Use redirect helper function */
  11279. mg_send_http_redirect(conn, target_url, redirect_code);
  11280. }
  11281. }
  11282. static void
  11283. handler_info_acquire(struct mg_handler_info *handler_info)
  11284. {
  11285. pthread_mutex_lock(&handler_info->refcount_mutex);
  11286. handler_info->refcount++;
  11287. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11288. }
  11289. static void
  11290. handler_info_release(struct mg_handler_info *handler_info)
  11291. {
  11292. pthread_mutex_lock(&handler_info->refcount_mutex);
  11293. handler_info->refcount--;
  11294. pthread_cond_signal(&handler_info->refcount_cond);
  11295. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11296. }
  11297. static void
  11298. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11299. {
  11300. pthread_mutex_lock(&handler_info->refcount_mutex);
  11301. while (handler_info->refcount) {
  11302. pthread_cond_wait(&handler_info->refcount_cond,
  11303. &handler_info->refcount_mutex);
  11304. }
  11305. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11306. }
  11307. static void
  11308. mg_set_handler_type(struct mg_context *phys_ctx,
  11309. struct mg_domain_context *dom_ctx,
  11310. const char *uri,
  11311. int handler_type,
  11312. int is_delete_request,
  11313. mg_request_handler handler,
  11314. struct mg_websocket_subprotocols *subprotocols,
  11315. mg_websocket_connect_handler connect_handler,
  11316. mg_websocket_ready_handler ready_handler,
  11317. mg_websocket_data_handler data_handler,
  11318. mg_websocket_close_handler close_handler,
  11319. mg_authorization_handler auth_handler,
  11320. void *cbdata)
  11321. {
  11322. struct mg_handler_info *tmp_rh, **lastref;
  11323. size_t urilen = strlen(uri);
  11324. if (handler_type == WEBSOCKET_HANDLER) {
  11325. DEBUG_ASSERT(handler == NULL);
  11326. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11327. || ready_handler != NULL || data_handler != NULL
  11328. || close_handler != NULL);
  11329. DEBUG_ASSERT(auth_handler == NULL);
  11330. if (handler != NULL) {
  11331. return;
  11332. }
  11333. if (!is_delete_request && (connect_handler == NULL)
  11334. && (ready_handler == NULL) && (data_handler == NULL)
  11335. && (close_handler == NULL)) {
  11336. return;
  11337. }
  11338. if (auth_handler != NULL) {
  11339. return;
  11340. }
  11341. } else if (handler_type == REQUEST_HANDLER) {
  11342. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11343. && data_handler == NULL && close_handler == NULL);
  11344. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11345. DEBUG_ASSERT(auth_handler == NULL);
  11346. if ((connect_handler != NULL) || (ready_handler != NULL)
  11347. || (data_handler != NULL) || (close_handler != NULL)) {
  11348. return;
  11349. }
  11350. if (!is_delete_request && (handler == NULL)) {
  11351. return;
  11352. }
  11353. if (auth_handler != NULL) {
  11354. return;
  11355. }
  11356. } else { /* AUTH_HANDLER */
  11357. DEBUG_ASSERT(handler == NULL);
  11358. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11359. && data_handler == NULL && close_handler == NULL);
  11360. DEBUG_ASSERT(auth_handler != NULL);
  11361. if (handler != NULL) {
  11362. return;
  11363. }
  11364. if ((connect_handler != NULL) || (ready_handler != NULL)
  11365. || (data_handler != NULL) || (close_handler != NULL)) {
  11366. return;
  11367. }
  11368. if (!is_delete_request && (auth_handler == NULL)) {
  11369. return;
  11370. }
  11371. }
  11372. if (!phys_ctx || !dom_ctx) {
  11373. return;
  11374. }
  11375. mg_lock_context(phys_ctx);
  11376. /* first try to find an existing handler */
  11377. lastref = &(dom_ctx->handlers);
  11378. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11379. if (tmp_rh->handler_type == handler_type) {
  11380. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11381. if (!is_delete_request) {
  11382. /* update existing handler */
  11383. if (handler_type == REQUEST_HANDLER) {
  11384. /* Wait for end of use before updating */
  11385. handler_info_wait_unused(tmp_rh);
  11386. /* Ok, the handler is no more use -> Update it */
  11387. tmp_rh->handler = handler;
  11388. } else if (handler_type == WEBSOCKET_HANDLER) {
  11389. tmp_rh->subprotocols = subprotocols;
  11390. tmp_rh->connect_handler = connect_handler;
  11391. tmp_rh->ready_handler = ready_handler;
  11392. tmp_rh->data_handler = data_handler;
  11393. tmp_rh->close_handler = close_handler;
  11394. } else { /* AUTH_HANDLER */
  11395. tmp_rh->auth_handler = auth_handler;
  11396. }
  11397. tmp_rh->cbdata = cbdata;
  11398. } else {
  11399. /* remove existing handler */
  11400. if (handler_type == REQUEST_HANDLER) {
  11401. /* Wait for end of use before removing */
  11402. handler_info_wait_unused(tmp_rh);
  11403. /* Ok, the handler is no more used -> Destroy resources
  11404. */
  11405. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11406. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11407. }
  11408. *lastref = tmp_rh->next;
  11409. mg_free(tmp_rh->uri);
  11410. mg_free(tmp_rh);
  11411. }
  11412. mg_unlock_context(phys_ctx);
  11413. return;
  11414. }
  11415. }
  11416. lastref = &(tmp_rh->next);
  11417. }
  11418. if (is_delete_request) {
  11419. /* no handler to set, this was a remove request to a non-existing
  11420. * handler */
  11421. mg_unlock_context(phys_ctx);
  11422. return;
  11423. }
  11424. tmp_rh =
  11425. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11426. 1,
  11427. phys_ctx);
  11428. if (tmp_rh == NULL) {
  11429. mg_unlock_context(phys_ctx);
  11430. mg_cry_internal(fc(phys_ctx),
  11431. "%s",
  11432. "Cannot create new request handler struct, OOM");
  11433. return;
  11434. }
  11435. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11436. if (!tmp_rh->uri) {
  11437. mg_unlock_context(phys_ctx);
  11438. mg_free(tmp_rh);
  11439. mg_cry_internal(fc(phys_ctx),
  11440. "%s",
  11441. "Cannot create new request handler struct, OOM");
  11442. return;
  11443. }
  11444. tmp_rh->uri_len = urilen;
  11445. if (handler_type == REQUEST_HANDLER) {
  11446. /* Init refcount mutex and condition */
  11447. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11448. mg_unlock_context(phys_ctx);
  11449. mg_free(tmp_rh);
  11450. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11451. return;
  11452. }
  11453. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11454. mg_unlock_context(phys_ctx);
  11455. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11456. mg_free(tmp_rh);
  11457. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11458. return;
  11459. }
  11460. tmp_rh->refcount = 0;
  11461. tmp_rh->handler = handler;
  11462. } else if (handler_type == WEBSOCKET_HANDLER) {
  11463. tmp_rh->subprotocols = subprotocols;
  11464. tmp_rh->connect_handler = connect_handler;
  11465. tmp_rh->ready_handler = ready_handler;
  11466. tmp_rh->data_handler = data_handler;
  11467. tmp_rh->close_handler = close_handler;
  11468. } else { /* AUTH_HANDLER */
  11469. tmp_rh->auth_handler = auth_handler;
  11470. }
  11471. tmp_rh->cbdata = cbdata;
  11472. tmp_rh->handler_type = handler_type;
  11473. tmp_rh->next = NULL;
  11474. *lastref = tmp_rh;
  11475. mg_unlock_context(phys_ctx);
  11476. }
  11477. void
  11478. mg_set_request_handler(struct mg_context *ctx,
  11479. const char *uri,
  11480. mg_request_handler handler,
  11481. void *cbdata)
  11482. {
  11483. mg_set_handler_type(ctx,
  11484. &(ctx->dd),
  11485. uri,
  11486. REQUEST_HANDLER,
  11487. handler == NULL,
  11488. handler,
  11489. NULL,
  11490. NULL,
  11491. NULL,
  11492. NULL,
  11493. NULL,
  11494. NULL,
  11495. cbdata);
  11496. }
  11497. void
  11498. mg_set_websocket_handler(struct mg_context *ctx,
  11499. const char *uri,
  11500. mg_websocket_connect_handler connect_handler,
  11501. mg_websocket_ready_handler ready_handler,
  11502. mg_websocket_data_handler data_handler,
  11503. mg_websocket_close_handler close_handler,
  11504. void *cbdata)
  11505. {
  11506. mg_set_websocket_handler_with_subprotocols(ctx,
  11507. uri,
  11508. NULL,
  11509. connect_handler,
  11510. ready_handler,
  11511. data_handler,
  11512. close_handler,
  11513. cbdata);
  11514. }
  11515. void
  11516. mg_set_websocket_handler_with_subprotocols(
  11517. struct mg_context *ctx,
  11518. const char *uri,
  11519. struct mg_websocket_subprotocols *subprotocols,
  11520. mg_websocket_connect_handler connect_handler,
  11521. mg_websocket_ready_handler ready_handler,
  11522. mg_websocket_data_handler data_handler,
  11523. mg_websocket_close_handler close_handler,
  11524. void *cbdata)
  11525. {
  11526. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11527. && (data_handler == NULL)
  11528. && (close_handler == NULL);
  11529. mg_set_handler_type(ctx,
  11530. &(ctx->dd),
  11531. uri,
  11532. WEBSOCKET_HANDLER,
  11533. is_delete_request,
  11534. NULL,
  11535. subprotocols,
  11536. connect_handler,
  11537. ready_handler,
  11538. data_handler,
  11539. close_handler,
  11540. NULL,
  11541. cbdata);
  11542. }
  11543. void
  11544. mg_set_auth_handler(struct mg_context *ctx,
  11545. const char *uri,
  11546. mg_authorization_handler handler,
  11547. void *cbdata)
  11548. {
  11549. mg_set_handler_type(ctx,
  11550. &(ctx->dd),
  11551. uri,
  11552. AUTH_HANDLER,
  11553. handler == NULL,
  11554. NULL,
  11555. NULL,
  11556. NULL,
  11557. NULL,
  11558. NULL,
  11559. NULL,
  11560. handler,
  11561. cbdata);
  11562. }
  11563. static int
  11564. get_request_handler(struct mg_connection *conn,
  11565. int handler_type,
  11566. mg_request_handler *handler,
  11567. struct mg_websocket_subprotocols **subprotocols,
  11568. mg_websocket_connect_handler *connect_handler,
  11569. mg_websocket_ready_handler *ready_handler,
  11570. mg_websocket_data_handler *data_handler,
  11571. mg_websocket_close_handler *close_handler,
  11572. mg_authorization_handler *auth_handler,
  11573. void **cbdata,
  11574. struct mg_handler_info **handler_info)
  11575. {
  11576. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11577. if (request_info) {
  11578. const char *uri = request_info->local_uri;
  11579. size_t urilen = strlen(uri);
  11580. struct mg_handler_info *tmp_rh;
  11581. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11582. return 0;
  11583. }
  11584. mg_lock_context(conn->phys_ctx);
  11585. /* first try for an exact match */
  11586. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11587. tmp_rh = tmp_rh->next) {
  11588. if (tmp_rh->handler_type == handler_type) {
  11589. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11590. if (handler_type == WEBSOCKET_HANDLER) {
  11591. *subprotocols = tmp_rh->subprotocols;
  11592. *connect_handler = tmp_rh->connect_handler;
  11593. *ready_handler = tmp_rh->ready_handler;
  11594. *data_handler = tmp_rh->data_handler;
  11595. *close_handler = tmp_rh->close_handler;
  11596. } else if (handler_type == REQUEST_HANDLER) {
  11597. *handler = tmp_rh->handler;
  11598. /* Acquire handler and give it back */
  11599. handler_info_acquire(tmp_rh);
  11600. *handler_info = tmp_rh;
  11601. } else { /* AUTH_HANDLER */
  11602. *auth_handler = tmp_rh->auth_handler;
  11603. }
  11604. *cbdata = tmp_rh->cbdata;
  11605. mg_unlock_context(conn->phys_ctx);
  11606. return 1;
  11607. }
  11608. }
  11609. }
  11610. /* next try for a partial match, we will accept uri/something */
  11611. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11612. tmp_rh = tmp_rh->next) {
  11613. if (tmp_rh->handler_type == handler_type) {
  11614. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11615. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11616. if (handler_type == WEBSOCKET_HANDLER) {
  11617. *subprotocols = tmp_rh->subprotocols;
  11618. *connect_handler = tmp_rh->connect_handler;
  11619. *ready_handler = tmp_rh->ready_handler;
  11620. *data_handler = tmp_rh->data_handler;
  11621. *close_handler = tmp_rh->close_handler;
  11622. } else if (handler_type == REQUEST_HANDLER) {
  11623. *handler = tmp_rh->handler;
  11624. /* Acquire handler and give it back */
  11625. handler_info_acquire(tmp_rh);
  11626. *handler_info = tmp_rh;
  11627. } else { /* AUTH_HANDLER */
  11628. *auth_handler = tmp_rh->auth_handler;
  11629. }
  11630. *cbdata = tmp_rh->cbdata;
  11631. mg_unlock_context(conn->phys_ctx);
  11632. return 1;
  11633. }
  11634. }
  11635. }
  11636. /* finally try for pattern match */
  11637. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11638. tmp_rh = tmp_rh->next) {
  11639. if (tmp_rh->handler_type == handler_type) {
  11640. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11641. if (handler_type == WEBSOCKET_HANDLER) {
  11642. *subprotocols = tmp_rh->subprotocols;
  11643. *connect_handler = tmp_rh->connect_handler;
  11644. *ready_handler = tmp_rh->ready_handler;
  11645. *data_handler = tmp_rh->data_handler;
  11646. *close_handler = tmp_rh->close_handler;
  11647. } else if (handler_type == REQUEST_HANDLER) {
  11648. *handler = tmp_rh->handler;
  11649. /* Acquire handler and give it back */
  11650. handler_info_acquire(tmp_rh);
  11651. *handler_info = tmp_rh;
  11652. } else { /* AUTH_HANDLER */
  11653. *auth_handler = tmp_rh->auth_handler;
  11654. }
  11655. *cbdata = tmp_rh->cbdata;
  11656. mg_unlock_context(conn->phys_ctx);
  11657. return 1;
  11658. }
  11659. }
  11660. }
  11661. mg_unlock_context(conn->phys_ctx);
  11662. }
  11663. return 0; /* none found */
  11664. }
  11665. /* Check if the script file is in a path, allowed for script files.
  11666. * This can be used if uploading files is possible not only for the server
  11667. * admin, and the upload mechanism does not check the file extension.
  11668. */
  11669. static int
  11670. is_in_script_path(const struct mg_connection *conn, const char *path)
  11671. {
  11672. /* TODO (Feature): Add config value for allowed script path.
  11673. * Default: All allowed. */
  11674. (void)conn;
  11675. (void)path;
  11676. return 1;
  11677. }
  11678. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11679. static int
  11680. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11681. void *cbdata)
  11682. {
  11683. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11684. if (pcallbacks->websocket_connect) {
  11685. return pcallbacks->websocket_connect(conn);
  11686. }
  11687. /* No handler set - assume "OK" */
  11688. return 0;
  11689. }
  11690. static void
  11691. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11692. {
  11693. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11694. if (pcallbacks->websocket_ready) {
  11695. pcallbacks->websocket_ready(conn);
  11696. }
  11697. }
  11698. static int
  11699. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11700. int bits,
  11701. char *data,
  11702. size_t len,
  11703. void *cbdata)
  11704. {
  11705. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11706. if (pcallbacks->websocket_data) {
  11707. return pcallbacks->websocket_data(conn, bits, data, len);
  11708. }
  11709. /* No handler set - assume "OK" */
  11710. return 1;
  11711. }
  11712. #endif
  11713. /* This is the heart of the Civetweb's logic.
  11714. * This function is called when the request is read, parsed and validated,
  11715. * and Civetweb must decide what action to take: serve a file, or
  11716. * a directory, or call embedded function, etcetera. */
  11717. static void
  11718. handle_request(struct mg_connection *conn)
  11719. {
  11720. struct mg_request_info *ri = &conn->request_info;
  11721. char path[PATH_MAX];
  11722. int uri_len, ssl_index;
  11723. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11724. is_put_or_delete_request = 0, is_callback_resource = 0;
  11725. int i;
  11726. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11727. mg_request_handler callback_handler = NULL;
  11728. struct mg_handler_info *handler_info = NULL;
  11729. struct mg_websocket_subprotocols *subprotocols;
  11730. mg_websocket_connect_handler ws_connect_handler = NULL;
  11731. mg_websocket_ready_handler ws_ready_handler = NULL;
  11732. mg_websocket_data_handler ws_data_handler = NULL;
  11733. mg_websocket_close_handler ws_close_handler = NULL;
  11734. void *callback_data = NULL;
  11735. mg_authorization_handler auth_handler = NULL;
  11736. void *auth_callback_data = NULL;
  11737. int handler_type;
  11738. time_t curtime = time(NULL);
  11739. char date[64];
  11740. path[0] = 0;
  11741. /* 1. get the request url */
  11742. /* 1.1. split into url and query string */
  11743. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11744. != NULL) {
  11745. *((char *)conn->request_info.query_string++) = '\0';
  11746. }
  11747. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11748. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11749. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11750. if (ssl_index >= 0) {
  11751. redirect_to_https_port(conn, ssl_index);
  11752. } else {
  11753. /* A http to https forward port has been specified,
  11754. * but no https port to forward to. */
  11755. mg_send_http_error(conn,
  11756. 503,
  11757. "%s",
  11758. "Error: SSL forward not configured properly");
  11759. mg_cry_internal(conn,
  11760. "%s",
  11761. "Can not redirect to SSL, no SSL port available");
  11762. }
  11763. return;
  11764. }
  11765. uri_len = (int)strlen(ri->local_uri);
  11766. /* 1.3. decode url (if config says so) */
  11767. if (should_decode_url(conn)) {
  11768. mg_url_decode(
  11769. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11770. }
  11771. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11772. * not possible */
  11773. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11774. /* step 1. completed, the url is known now */
  11775. uri_len = (int)strlen(ri->local_uri);
  11776. DEBUG_TRACE("URL: %s", ri->local_uri);
  11777. /* 2. if this ip has limited speed, set it for this connection */
  11778. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11779. get_remote_ip(conn),
  11780. ri->local_uri);
  11781. /* 3. call a "handle everything" callback, if registered */
  11782. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11783. /* Note that since V1.7 the "begin_request" function is called
  11784. * before an authorization check. If an authorization check is
  11785. * required, use a request_handler instead. */
  11786. i = conn->phys_ctx->callbacks.begin_request(conn);
  11787. if (i > 0) {
  11788. /* callback already processed the request. Store the
  11789. return value as a status code for the access log. */
  11790. conn->status_code = i;
  11791. discard_unread_request_data(conn);
  11792. return;
  11793. } else if (i == 0) {
  11794. /* civetweb should process the request */
  11795. } else {
  11796. /* unspecified - may change with the next version */
  11797. return;
  11798. }
  11799. }
  11800. /* request not yet handled by a handler or redirect, so the request
  11801. * is processed here */
  11802. /* 4. Check for CORS preflight requests and handle them (if configured).
  11803. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11804. */
  11805. if (!strcmp(ri->request_method, "OPTIONS")) {
  11806. /* Send a response to CORS preflights only if
  11807. * access_control_allow_methods is not NULL and not an empty string.
  11808. * In this case, scripts can still handle CORS. */
  11809. const char *cors_meth_cfg =
  11810. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11811. const char *cors_orig_cfg =
  11812. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11813. const char *cors_origin =
  11814. get_header(ri->http_headers, ri->num_headers, "Origin");
  11815. const char *cors_acrm = get_header(ri->http_headers,
  11816. ri->num_headers,
  11817. "Access-Control-Request-Method");
  11818. /* Todo: check if cors_origin is in cors_orig_cfg.
  11819. * Or, let the client check this. */
  11820. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11821. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11822. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11823. /* This is a valid CORS preflight, and the server is configured
  11824. * to
  11825. * handle it automatically. */
  11826. const char *cors_acrh =
  11827. get_header(ri->http_headers,
  11828. ri->num_headers,
  11829. "Access-Control-Request-Headers");
  11830. gmt_time_string(date, sizeof(date), &curtime);
  11831. mg_printf(conn,
  11832. "HTTP/1.1 200 OK\r\n"
  11833. "Date: %s\r\n"
  11834. "Access-Control-Allow-Origin: %s\r\n"
  11835. "Access-Control-Allow-Methods: %s\r\n"
  11836. "Content-Length: 0\r\n"
  11837. "Connection: %s\r\n",
  11838. date,
  11839. cors_orig_cfg,
  11840. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11841. suggest_connection_header(conn));
  11842. if (cors_acrh != NULL) {
  11843. /* CORS request is asking for additional headers */
  11844. const char *cors_hdr_cfg =
  11845. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11846. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11847. /* Allow only if access_control_allow_headers is
  11848. * not NULL and not an empty string. If this
  11849. * configuration is set to *, allow everything.
  11850. * Otherwise this configuration must be a list
  11851. * of allowed HTTP header names. */
  11852. mg_printf(conn,
  11853. "Access-Control-Allow-Headers: %s\r\n",
  11854. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11855. : cors_hdr_cfg));
  11856. }
  11857. }
  11858. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11859. mg_printf(conn, "\r\n");
  11860. return;
  11861. }
  11862. }
  11863. /* 5. interpret the url to find out how the request must be handled
  11864. */
  11865. /* 5.1. first test, if the request targets the regular http(s)://
  11866. * protocol namespace or the websocket ws(s):// protocol namespace.
  11867. */
  11868. is_websocket_request = is_websocket_protocol(conn);
  11869. #if defined(USE_WEBSOCKET)
  11870. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11871. #else
  11872. handler_type = REQUEST_HANDLER;
  11873. #endif /* defined(USE_WEBSOCKET) */
  11874. /* 5.2. check if the request will be handled by a callback */
  11875. if (get_request_handler(conn,
  11876. handler_type,
  11877. &callback_handler,
  11878. &subprotocols,
  11879. &ws_connect_handler,
  11880. &ws_ready_handler,
  11881. &ws_data_handler,
  11882. &ws_close_handler,
  11883. NULL,
  11884. &callback_data,
  11885. &handler_info)) {
  11886. /* 5.2.1. A callback will handle this request. All requests
  11887. * handled
  11888. * by a callback have to be considered as requests to a script
  11889. * resource. */
  11890. is_callback_resource = 1;
  11891. is_script_resource = 1;
  11892. is_put_or_delete_request = is_put_or_delete_method(conn);
  11893. } else {
  11894. no_callback_resource:
  11895. /* 5.2.2. No callback is responsible for this request. The URI
  11896. * addresses a file based resource (static content or Lua/cgi
  11897. * scripts in the file system). */
  11898. is_callback_resource = 0;
  11899. interpret_uri(conn,
  11900. path,
  11901. sizeof(path),
  11902. &file.stat,
  11903. &is_found,
  11904. &is_script_resource,
  11905. &is_websocket_request,
  11906. &is_put_or_delete_request);
  11907. }
  11908. /* 6. authorization check */
  11909. /* 6.1. a custom authorization handler is installed */
  11910. if (get_request_handler(conn,
  11911. AUTH_HANDLER,
  11912. NULL,
  11913. NULL,
  11914. NULL,
  11915. NULL,
  11916. NULL,
  11917. NULL,
  11918. &auth_handler,
  11919. &auth_callback_data,
  11920. NULL)) {
  11921. if (!auth_handler(conn, auth_callback_data)) {
  11922. return;
  11923. }
  11924. } else if (is_put_or_delete_request && !is_script_resource
  11925. && !is_callback_resource) {
  11926. /* 6.2. this request is a PUT/DELETE to a real file */
  11927. /* 6.2.1. thus, the server must have real files */
  11928. #if defined(NO_FILES)
  11929. if (1) {
  11930. #else
  11931. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11932. #endif
  11933. /* This server does not have any real files, thus the
  11934. * PUT/DELETE methods are not valid. */
  11935. mg_send_http_error(conn,
  11936. 405,
  11937. "%s method not allowed",
  11938. conn->request_info.request_method);
  11939. return;
  11940. }
  11941. #if !defined(NO_FILES)
  11942. /* 6.2.2. Check if put authorization for static files is
  11943. * available.
  11944. */
  11945. if (!is_authorized_for_put(conn)) {
  11946. send_authorization_request(conn, NULL);
  11947. return;
  11948. }
  11949. #endif
  11950. } else {
  11951. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11952. * or it is a PUT or DELETE request to a resource that does not
  11953. * correspond to a file. Check authorization. */
  11954. if (!check_authorization(conn, path)) {
  11955. send_authorization_request(conn, NULL);
  11956. return;
  11957. }
  11958. }
  11959. /* request is authorized or does not need authorization */
  11960. /* 7. check if there are request handlers for this uri */
  11961. if (is_callback_resource) {
  11962. if (!is_websocket_request) {
  11963. i = callback_handler(conn, callback_data);
  11964. /* Callback handler will not be used anymore. Release it */
  11965. handler_info_release(handler_info);
  11966. if (i > 0) {
  11967. /* Do nothing, callback has served the request. Store
  11968. * then return value as status code for the log and discard
  11969. * all data from the client not used by the callback. */
  11970. conn->status_code = i;
  11971. discard_unread_request_data(conn);
  11972. } else {
  11973. /* The handler did NOT handle the request. */
  11974. /* Some proper reactions would be:
  11975. * a) close the connections without sending anything
  11976. * b) send a 404 not found
  11977. * c) try if there is a file matching the URI
  11978. * It would be possible to do a, b or c in the callback
  11979. * implementation, and return 1 - we cannot do anything
  11980. * here, that is not possible in the callback.
  11981. *
  11982. * TODO: What would be the best reaction here?
  11983. * (Note: The reaction may change, if there is a better
  11984. *idea.)
  11985. */
  11986. /* For the moment, use option c: We look for a proper file,
  11987. * but since a file request is not always a script resource,
  11988. * the authorization check might be different. */
  11989. interpret_uri(conn,
  11990. path,
  11991. sizeof(path),
  11992. &file.stat,
  11993. &is_found,
  11994. &is_script_resource,
  11995. &is_websocket_request,
  11996. &is_put_or_delete_request);
  11997. callback_handler = NULL;
  11998. /* Here we are at a dead end:
  11999. * According to URI matching, a callback should be
  12000. * responsible for handling the request,
  12001. * we called it, but the callback declared itself
  12002. * not responsible.
  12003. * We use a goto here, to get out of this dead end,
  12004. * and continue with the default handling.
  12005. * A goto here is simpler and better to understand
  12006. * than some curious loop. */
  12007. goto no_callback_resource;
  12008. }
  12009. } else {
  12010. #if defined(USE_WEBSOCKET)
  12011. handle_websocket_request(conn,
  12012. path,
  12013. is_callback_resource,
  12014. subprotocols,
  12015. ws_connect_handler,
  12016. ws_ready_handler,
  12017. ws_data_handler,
  12018. ws_close_handler,
  12019. callback_data);
  12020. #endif
  12021. }
  12022. return;
  12023. }
  12024. /* 8. handle websocket requests */
  12025. #if defined(USE_WEBSOCKET)
  12026. if (is_websocket_request) {
  12027. if (is_script_resource) {
  12028. if (is_in_script_path(conn, path)) {
  12029. /* Websocket Lua script */
  12030. handle_websocket_request(conn,
  12031. path,
  12032. 0 /* Lua Script */,
  12033. NULL,
  12034. NULL,
  12035. NULL,
  12036. NULL,
  12037. NULL,
  12038. conn->phys_ctx->user_data);
  12039. } else {
  12040. /* Script was in an illegal path */
  12041. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12042. }
  12043. } else {
  12044. #if defined(MG_LEGACY_INTERFACE)
  12045. handle_websocket_request(
  12046. conn,
  12047. path,
  12048. !is_script_resource /* could be deprecated global callback */,
  12049. NULL,
  12050. deprecated_websocket_connect_wrapper,
  12051. deprecated_websocket_ready_wrapper,
  12052. deprecated_websocket_data_wrapper,
  12053. NULL,
  12054. conn->phys_ctx->user_data);
  12055. #else
  12056. mg_send_http_error(conn, 404, "%s", "Not found");
  12057. #endif
  12058. }
  12059. return;
  12060. } else
  12061. #endif
  12062. #if defined(NO_FILES)
  12063. /* 9a. In case the server uses only callbacks, this uri is
  12064. * unknown.
  12065. * Then, all request handling ends here. */
  12066. mg_send_http_error(conn, 404, "%s", "Not Found");
  12067. #else
  12068. /* 9b. This request is either for a static file or resource handled
  12069. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12070. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12071. mg_send_http_error(conn, 404, "%s", "Not Found");
  12072. return;
  12073. }
  12074. /* 10. Request is handled by a script */
  12075. if (is_script_resource) {
  12076. handle_file_based_request(conn, path, &file);
  12077. return;
  12078. }
  12079. /* 11. Handle put/delete/mkcol requests */
  12080. if (is_put_or_delete_request) {
  12081. /* 11.1. PUT method */
  12082. if (!strcmp(ri->request_method, "PUT")) {
  12083. put_file(conn, path);
  12084. return;
  12085. }
  12086. /* 11.2. DELETE method */
  12087. if (!strcmp(ri->request_method, "DELETE")) {
  12088. delete_file(conn, path);
  12089. return;
  12090. }
  12091. /* 11.3. MKCOL method */
  12092. if (!strcmp(ri->request_method, "MKCOL")) {
  12093. mkcol(conn, path);
  12094. return;
  12095. }
  12096. /* 11.4. PATCH method
  12097. * This method is not supported for static resources,
  12098. * only for scripts (Lua, CGI) and callbacks. */
  12099. mg_send_http_error(conn,
  12100. 405,
  12101. "%s method not allowed",
  12102. conn->request_info.request_method);
  12103. return;
  12104. }
  12105. /* 11. File does not exist, or it was configured that it should be
  12106. * hidden */
  12107. if (!is_found || (must_hide_file(conn, path))) {
  12108. mg_send_http_error(conn, 404, "%s", "Not found");
  12109. return;
  12110. }
  12111. /* 12. Directory uris should end with a slash */
  12112. if (file.stat.is_directory && (uri_len > 0)
  12113. && (ri->local_uri[uri_len - 1] != '/')) {
  12114. gmt_time_string(date, sizeof(date), &curtime);
  12115. mg_printf(conn,
  12116. "HTTP/1.1 301 Moved Permanently\r\n"
  12117. "Location: %s/\r\n"
  12118. "Date: %s\r\n"
  12119. /* "Cache-Control: private\r\n" (= default) */
  12120. "Content-Length: 0\r\n"
  12121. "Connection: %s\r\n",
  12122. ri->request_uri,
  12123. date,
  12124. suggest_connection_header(conn));
  12125. send_additional_header(conn);
  12126. mg_printf(conn, "\r\n");
  12127. return;
  12128. }
  12129. /* 13. Handle other methods than GET/HEAD */
  12130. /* 13.1. Handle PROPFIND */
  12131. if (!strcmp(ri->request_method, "PROPFIND")) {
  12132. handle_propfind(conn, path, &file.stat);
  12133. return;
  12134. }
  12135. /* 13.2. Handle OPTIONS for files */
  12136. if (!strcmp(ri->request_method, "OPTIONS")) {
  12137. /* This standard handler is only used for real files.
  12138. * Scripts should support the OPTIONS method themselves, to allow a
  12139. * maximum flexibility.
  12140. * Lua and CGI scripts may fully support CORS this way (including
  12141. * preflights). */
  12142. send_options(conn);
  12143. return;
  12144. }
  12145. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12146. if ((0 != strcmp(ri->request_method, "GET"))
  12147. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12148. mg_send_http_error(conn,
  12149. 405,
  12150. "%s method not allowed",
  12151. conn->request_info.request_method);
  12152. return;
  12153. }
  12154. /* 14. directories */
  12155. if (file.stat.is_directory) {
  12156. /* Substitute files have already been handled above. */
  12157. /* Here we can either generate and send a directory listing,
  12158. * or send an "access denied" error. */
  12159. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12160. "yes")) {
  12161. handle_directory_request(conn, path);
  12162. } else {
  12163. mg_send_http_error(conn,
  12164. 403,
  12165. "%s",
  12166. "Error: Directory listing denied");
  12167. }
  12168. return;
  12169. }
  12170. /* 15. read a normal file with GET or HEAD */
  12171. handle_file_based_request(conn, path, &file);
  12172. #endif /* !defined(NO_FILES) */
  12173. }
  12174. static void
  12175. handle_file_based_request(struct mg_connection *conn,
  12176. const char *path,
  12177. struct mg_file *file)
  12178. {
  12179. if (!conn || !conn->dom_ctx) {
  12180. return;
  12181. }
  12182. if (0) {
  12183. #if defined(USE_LUA)
  12184. } else if (match_prefix(
  12185. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12186. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12187. path)
  12188. > 0) {
  12189. if (is_in_script_path(conn, path)) {
  12190. /* Lua server page: an SSI like page containing mostly plain
  12191. * html
  12192. * code
  12193. * plus some tags with server generated contents. */
  12194. handle_lsp_request(conn, path, file, NULL);
  12195. } else {
  12196. /* Script was in an illegal path */
  12197. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12198. }
  12199. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12200. strlen(
  12201. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12202. path)
  12203. > 0) {
  12204. if (is_in_script_path(conn, path)) {
  12205. /* Lua in-server module script: a CGI like script used to
  12206. * generate
  12207. * the
  12208. * entire reply. */
  12209. mg_exec_lua_script(conn, path, NULL);
  12210. } else {
  12211. /* Script was in an illegal path */
  12212. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12213. }
  12214. #endif
  12215. #if defined(USE_DUKTAPE)
  12216. } else if (match_prefix(
  12217. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12218. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12219. path)
  12220. > 0) {
  12221. if (is_in_script_path(conn, path)) {
  12222. /* Call duktape to generate the page */
  12223. mg_exec_duktape_script(conn, path);
  12224. } else {
  12225. /* Script was in an illegal path */
  12226. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12227. }
  12228. #endif
  12229. #if !defined(NO_CGI)
  12230. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12231. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12232. path)
  12233. > 0) {
  12234. if (is_in_script_path(conn, path)) {
  12235. /* CGI scripts may support all HTTP methods */
  12236. handle_cgi_request(conn, path);
  12237. } else {
  12238. /* Script was in an illegal path */
  12239. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12240. }
  12241. #endif /* !NO_CGI */
  12242. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12243. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12244. path)
  12245. > 0) {
  12246. if (is_in_script_path(conn, path)) {
  12247. handle_ssi_file_request(conn, path, file);
  12248. } else {
  12249. /* Script was in an illegal path */
  12250. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12251. }
  12252. #if !defined(NO_CACHING)
  12253. } else if ((!conn->in_error_handler)
  12254. && is_not_modified(conn, &file->stat)) {
  12255. /* Send 304 "Not Modified" - this must not send any body data */
  12256. handle_not_modified_static_file_request(conn, file);
  12257. #endif /* !NO_CACHING */
  12258. } else {
  12259. handle_static_file_request(conn, path, file, NULL, NULL);
  12260. }
  12261. }
  12262. static void
  12263. close_all_listening_sockets(struct mg_context *ctx)
  12264. {
  12265. unsigned int i;
  12266. if (!ctx) {
  12267. return;
  12268. }
  12269. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12270. closesocket(ctx->listening_sockets[i].sock);
  12271. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12272. }
  12273. mg_free(ctx->listening_sockets);
  12274. ctx->listening_sockets = NULL;
  12275. mg_free(ctx->listening_socket_fds);
  12276. ctx->listening_socket_fds = NULL;
  12277. }
  12278. /* Valid listening port specification is: [ip_address:]port[s]
  12279. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12280. * Examples for IPv6: [::]:80, [::1]:80,
  12281. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12282. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12283. * In order to bind to both, IPv4 and IPv6, you can either add
  12284. * both ports using 8080,[::]:8080, or the short form +8080.
  12285. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12286. * one only accepting IPv4 the other only IPv6. +8080 creates
  12287. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12288. * environment, they might work differently, or might not work
  12289. * at all - it must be tested what options work best in the
  12290. * relevant network environment.
  12291. */
  12292. static int
  12293. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12294. {
  12295. unsigned int a, b, c, d, port;
  12296. int ch, len;
  12297. const char *cb;
  12298. #if defined(USE_IPV6)
  12299. char buf[100] = {0};
  12300. #endif
  12301. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12302. * Also, all-zeroes in the socket address means binding to all addresses
  12303. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12304. memset(so, 0, sizeof(*so));
  12305. so->lsa.sin.sin_family = AF_INET;
  12306. *ip_version = 0;
  12307. /* Initialize port and len as invalid. */
  12308. port = 0;
  12309. len = 0;
  12310. /* Test for different ways to format this string */
  12311. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12312. == 5) {
  12313. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12314. so->lsa.sin.sin_addr.s_addr =
  12315. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12316. so->lsa.sin.sin_port = htons((uint16_t)port);
  12317. *ip_version = 4;
  12318. #if defined(USE_IPV6)
  12319. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12320. && mg_inet_pton(
  12321. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12322. /* IPv6 address, examples: see above */
  12323. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12324. */
  12325. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12326. *ip_version = 6;
  12327. #endif
  12328. } else if ((vec->ptr[0] == '+')
  12329. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12330. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12331. /* Add 1 to len for the + character we skipped before */
  12332. len++;
  12333. #if defined(USE_IPV6)
  12334. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12335. so->lsa.sin6.sin6_family = AF_INET6;
  12336. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12337. *ip_version = 4 + 6;
  12338. #else
  12339. /* Bind to IPv4 only, since IPv6 is not built in. */
  12340. so->lsa.sin.sin_port = htons((uint16_t)port);
  12341. *ip_version = 4;
  12342. #endif
  12343. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12344. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12345. so->lsa.sin.sin_port = htons((uint16_t)port);
  12346. *ip_version = 4;
  12347. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12348. /* String could be a hostname. This check algotithm
  12349. * will only work for RFC 952 compliant hostnames,
  12350. * starting with a letter, containing only letters,
  12351. * digits and hyphen ('-'). Newer specs may allow
  12352. * more, but this is not guaranteed here, since it
  12353. * may interfere with rules for port option lists. */
  12354. /* According to RFC 1035, hostnames are restricted to 255 characters
  12355. * in total (63 between two dots). */
  12356. char hostname[256];
  12357. size_t hostnlen = (size_t)(cb - vec->ptr);
  12358. if (hostnlen >= sizeof(hostname)) {
  12359. /* This would be invalid in any case */
  12360. *ip_version = 0;
  12361. return 0;
  12362. }
  12363. memcpy(hostname, vec->ptr, hostnlen);
  12364. hostname[hostnlen] = 0;
  12365. if (mg_inet_pton(
  12366. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12367. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12368. *ip_version = 4;
  12369. so->lsa.sin.sin_family = AF_INET;
  12370. so->lsa.sin.sin_port = htons((uint16_t)port);
  12371. len += (int)(hostnlen + 1);
  12372. } else {
  12373. port = 0;
  12374. len = 0;
  12375. }
  12376. #if defined(USE_IPV6)
  12377. } else if (mg_inet_pton(AF_INET6,
  12378. vec->ptr,
  12379. &so->lsa.sin6,
  12380. sizeof(so->lsa.sin6))) {
  12381. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12382. *ip_version = 6;
  12383. so->lsa.sin6.sin6_family = AF_INET6;
  12384. so->lsa.sin.sin_port = htons((uint16_t)port);
  12385. len += (int)(hostnlen + 1);
  12386. } else {
  12387. port = 0;
  12388. len = 0;
  12389. }
  12390. #endif
  12391. }
  12392. } else {
  12393. /* Parsing failure. */
  12394. }
  12395. /* sscanf and the option splitting code ensure the following condition
  12396. */
  12397. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12398. *ip_version = 0;
  12399. return 0;
  12400. }
  12401. ch = vec->ptr[len]; /* Next character after the port number */
  12402. so->is_ssl = (ch == 's');
  12403. so->ssl_redir = (ch == 'r');
  12404. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12405. if (is_valid_port(port)
  12406. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12407. return 1;
  12408. }
  12409. /* Reset ip_version to 0 if there is an error */
  12410. *ip_version = 0;
  12411. return 0;
  12412. }
  12413. /* Is there any SSL port in use? */
  12414. static int
  12415. is_ssl_port_used(const char *ports)
  12416. {
  12417. if (ports) {
  12418. /* There are several different allowed syntax variants:
  12419. * - "80" for a single port using every network interface
  12420. * - "localhost:80" for a single port using only localhost
  12421. * - "80,localhost:8080" for two ports, one bound to localhost
  12422. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12423. * to IPv4 localhost, one to IPv6 localhost
  12424. * - "+80" use port 80 for IPv4 and IPv6
  12425. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12426. * for both: IPv4 and IPv4
  12427. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12428. * additionally port 8080 bound to localhost connections
  12429. *
  12430. * If we just look for 's' anywhere in the string, "localhost:80"
  12431. * will be detected as SSL (false positive).
  12432. * Looking for 's' after a digit may cause false positives in
  12433. * "my24service:8080".
  12434. * Looking from 's' backward if there are only ':' and numbers
  12435. * before will not work for "24service:8080" (non SSL, port 8080)
  12436. * or "24s" (SSL, port 24).
  12437. *
  12438. * Remark: Initially hostnames were not allowed to start with a
  12439. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12440. * Section 2.1).
  12441. *
  12442. * To get this correct, the entire string must be parsed as a whole,
  12443. * reading it as a list element for element and parsing with an
  12444. * algorithm equivalent to parse_port_string.
  12445. *
  12446. * In fact, we use local interface names here, not arbitrary hostnames,
  12447. * so in most cases the only name will be "localhost".
  12448. *
  12449. * So, for now, we use this simple algorithm, that may still return
  12450. * a false positive in bizarre cases.
  12451. */
  12452. int i;
  12453. int portslen = (int)strlen(ports);
  12454. char prevIsNumber = 0;
  12455. for (i = 0; i < portslen; i++) {
  12456. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12457. return 1;
  12458. }
  12459. if (ports[i] >= '0' && ports[i] <= '9') {
  12460. prevIsNumber = 1;
  12461. } else {
  12462. prevIsNumber = 0;
  12463. }
  12464. }
  12465. }
  12466. return 0;
  12467. }
  12468. static int
  12469. set_ports_option(struct mg_context *phys_ctx)
  12470. {
  12471. const char *list;
  12472. int on = 1;
  12473. #if defined(USE_IPV6)
  12474. int off = 0;
  12475. #endif
  12476. struct vec vec;
  12477. struct socket so, *ptr;
  12478. struct mg_pollfd *pfd;
  12479. union usa usa;
  12480. socklen_t len;
  12481. int ip_version;
  12482. int portsTotal = 0;
  12483. int portsOk = 0;
  12484. if (!phys_ctx) {
  12485. return 0;
  12486. }
  12487. memset(&so, 0, sizeof(so));
  12488. memset(&usa, 0, sizeof(usa));
  12489. len = sizeof(usa);
  12490. list = phys_ctx->dd.config[LISTENING_PORTS];
  12491. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12492. portsTotal++;
  12493. if (!parse_port_string(&vec, &so, &ip_version)) {
  12494. mg_cry_internal(
  12495. fc(phys_ctx),
  12496. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12497. (int)vec.len,
  12498. vec.ptr,
  12499. portsTotal,
  12500. "[IP_ADDRESS:]PORT[s|r]");
  12501. continue;
  12502. }
  12503. #if !defined(NO_SSL)
  12504. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12505. mg_cry_internal(fc(phys_ctx),
  12506. "Cannot add SSL socket (entry %i)",
  12507. portsTotal);
  12508. continue;
  12509. }
  12510. #endif
  12511. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12512. == INVALID_SOCKET) {
  12513. mg_cry_internal(fc(phys_ctx),
  12514. "cannot create socket (entry %i)",
  12515. portsTotal);
  12516. continue;
  12517. }
  12518. #if defined(_WIN32)
  12519. /* Windows SO_REUSEADDR lets many procs binds to a
  12520. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12521. * if someone already has the socket -- DTL */
  12522. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12523. * Windows might need a few seconds before
  12524. * the same port can be used again in the
  12525. * same process, so a short Sleep may be
  12526. * required between mg_stop and mg_start.
  12527. */
  12528. if (setsockopt(so.sock,
  12529. SOL_SOCKET,
  12530. SO_EXCLUSIVEADDRUSE,
  12531. (SOCK_OPT_TYPE)&on,
  12532. sizeof(on))
  12533. != 0) {
  12534. /* Set reuse option, but don't abort on errors. */
  12535. mg_cry_internal(
  12536. fc(phys_ctx),
  12537. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12538. portsTotal);
  12539. }
  12540. #else
  12541. if (setsockopt(so.sock,
  12542. SOL_SOCKET,
  12543. SO_REUSEADDR,
  12544. (SOCK_OPT_TYPE)&on,
  12545. sizeof(on))
  12546. != 0) {
  12547. /* Set reuse option, but don't abort on errors. */
  12548. mg_cry_internal(fc(phys_ctx),
  12549. "cannot set socket option SO_REUSEADDR (entry %i)",
  12550. portsTotal);
  12551. }
  12552. #endif
  12553. if (ip_version > 4) {
  12554. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12555. #if defined(USE_IPV6)
  12556. if (ip_version > 6) {
  12557. if (so.lsa.sa.sa_family == AF_INET6
  12558. && setsockopt(so.sock,
  12559. IPPROTO_IPV6,
  12560. IPV6_V6ONLY,
  12561. (void *)&off,
  12562. sizeof(off))
  12563. != 0) {
  12564. /* Set IPv6 only option, but don't abort on errors. */
  12565. mg_cry_internal(
  12566. fc(phys_ctx),
  12567. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12568. portsTotal);
  12569. }
  12570. } else {
  12571. if (so.lsa.sa.sa_family == AF_INET6
  12572. && setsockopt(so.sock,
  12573. IPPROTO_IPV6,
  12574. IPV6_V6ONLY,
  12575. (void *)&on,
  12576. sizeof(on))
  12577. != 0) {
  12578. /* Set IPv6 only option, but don't abort on errors. */
  12579. mg_cry_internal(
  12580. fc(phys_ctx),
  12581. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12582. portsTotal);
  12583. }
  12584. }
  12585. #else
  12586. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12587. closesocket(so.sock);
  12588. so.sock = INVALID_SOCKET;
  12589. continue;
  12590. #endif
  12591. }
  12592. if (so.lsa.sa.sa_family == AF_INET) {
  12593. len = sizeof(so.lsa.sin);
  12594. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12595. mg_cry_internal(fc(phys_ctx),
  12596. "cannot bind to %.*s: %d (%s)",
  12597. (int)vec.len,
  12598. vec.ptr,
  12599. (int)ERRNO,
  12600. strerror(errno));
  12601. closesocket(so.sock);
  12602. so.sock = INVALID_SOCKET;
  12603. continue;
  12604. }
  12605. }
  12606. #if defined(USE_IPV6)
  12607. else if (so.lsa.sa.sa_family == AF_INET6) {
  12608. len = sizeof(so.lsa.sin6);
  12609. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12610. mg_cry_internal(fc(phys_ctx),
  12611. "cannot bind to IPv6 %.*s: %d (%s)",
  12612. (int)vec.len,
  12613. vec.ptr,
  12614. (int)ERRNO,
  12615. strerror(errno));
  12616. closesocket(so.sock);
  12617. so.sock = INVALID_SOCKET;
  12618. continue;
  12619. }
  12620. }
  12621. #endif
  12622. else {
  12623. mg_cry_internal(
  12624. fc(phys_ctx),
  12625. "cannot bind: address family not supported (entry %i)",
  12626. portsTotal);
  12627. closesocket(so.sock);
  12628. so.sock = INVALID_SOCKET;
  12629. continue;
  12630. }
  12631. if (listen(so.sock, SOMAXCONN) != 0) {
  12632. mg_cry_internal(fc(phys_ctx),
  12633. "cannot listen to %.*s: %d (%s)",
  12634. (int)vec.len,
  12635. vec.ptr,
  12636. (int)ERRNO,
  12637. strerror(errno));
  12638. closesocket(so.sock);
  12639. so.sock = INVALID_SOCKET;
  12640. continue;
  12641. }
  12642. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12643. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12644. int err = (int)ERRNO;
  12645. mg_cry_internal(fc(phys_ctx),
  12646. "call to getsockname failed %.*s: %d (%s)",
  12647. (int)vec.len,
  12648. vec.ptr,
  12649. err,
  12650. strerror(errno));
  12651. closesocket(so.sock);
  12652. so.sock = INVALID_SOCKET;
  12653. continue;
  12654. }
  12655. /* Update lsa port in case of random free ports */
  12656. #if defined(USE_IPV6)
  12657. if (so.lsa.sa.sa_family == AF_INET6) {
  12658. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12659. } else
  12660. #endif
  12661. {
  12662. so.lsa.sin.sin_port = usa.sin.sin_port;
  12663. }
  12664. if ((ptr = (struct socket *)
  12665. mg_realloc_ctx(phys_ctx->listening_sockets,
  12666. (phys_ctx->num_listening_sockets + 1)
  12667. * sizeof(phys_ctx->listening_sockets[0]),
  12668. phys_ctx))
  12669. == NULL) {
  12670. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12671. closesocket(so.sock);
  12672. so.sock = INVALID_SOCKET;
  12673. continue;
  12674. }
  12675. if ((pfd = (struct mg_pollfd *)
  12676. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12677. (phys_ctx->num_listening_sockets + 1)
  12678. * sizeof(phys_ctx->listening_socket_fds[0]),
  12679. phys_ctx))
  12680. == NULL) {
  12681. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12682. closesocket(so.sock);
  12683. so.sock = INVALID_SOCKET;
  12684. mg_free(ptr);
  12685. continue;
  12686. }
  12687. set_close_on_exec(so.sock, fc(phys_ctx));
  12688. phys_ctx->listening_sockets = ptr;
  12689. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12690. phys_ctx->listening_socket_fds = pfd;
  12691. phys_ctx->num_listening_sockets++;
  12692. portsOk++;
  12693. }
  12694. if (portsOk != portsTotal) {
  12695. close_all_listening_sockets(phys_ctx);
  12696. portsOk = 0;
  12697. }
  12698. return portsOk;
  12699. }
  12700. static const char *
  12701. header_val(const struct mg_connection *conn, const char *header)
  12702. {
  12703. const char *header_value;
  12704. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12705. return "-";
  12706. } else {
  12707. return header_value;
  12708. }
  12709. }
  12710. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12711. static void log_access(const struct mg_connection *conn);
  12712. #include "external_log_access.inl"
  12713. #else
  12714. static void
  12715. log_access(const struct mg_connection *conn)
  12716. {
  12717. const struct mg_request_info *ri;
  12718. struct mg_file fi;
  12719. char date[64], src_addr[IP_ADDR_STR_LEN];
  12720. struct tm *tm;
  12721. const char *referer;
  12722. const char *user_agent;
  12723. char buf[4096];
  12724. if (!conn || !conn->dom_ctx) {
  12725. return;
  12726. }
  12727. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12728. if (mg_fopen(conn,
  12729. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12730. MG_FOPEN_MODE_APPEND,
  12731. &fi)
  12732. == 0) {
  12733. fi.access.fp = NULL;
  12734. }
  12735. } else {
  12736. fi.access.fp = NULL;
  12737. }
  12738. /* Log is written to a file and/or a callback. If both are not set,
  12739. * executing the rest of the function is pointless. */
  12740. if ((fi.access.fp == NULL)
  12741. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12742. return;
  12743. }
  12744. tm = localtime(&conn->conn_birth_time);
  12745. if (tm != NULL) {
  12746. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12747. } else {
  12748. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12749. date[sizeof(date) - 1] = '\0';
  12750. }
  12751. ri = &conn->request_info;
  12752. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12753. referer = header_val(conn, "Referer");
  12754. user_agent = header_val(conn, "User-Agent");
  12755. mg_snprintf(conn,
  12756. NULL, /* Ignore truncation in access log */
  12757. buf,
  12758. sizeof(buf),
  12759. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12760. src_addr,
  12761. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12762. date,
  12763. ri->request_method ? ri->request_method : "-",
  12764. ri->request_uri ? ri->request_uri : "-",
  12765. ri->query_string ? "?" : "",
  12766. ri->query_string ? ri->query_string : "",
  12767. ri->http_version,
  12768. conn->status_code,
  12769. conn->num_bytes_sent,
  12770. referer,
  12771. user_agent);
  12772. if (conn->phys_ctx->callbacks.log_access) {
  12773. conn->phys_ctx->callbacks.log_access(conn, buf);
  12774. }
  12775. if (fi.access.fp) {
  12776. int ok = 1;
  12777. flockfile(fi.access.fp);
  12778. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12779. ok = 0;
  12780. }
  12781. if (fflush(fi.access.fp) != 0) {
  12782. ok = 0;
  12783. }
  12784. funlockfile(fi.access.fp);
  12785. if (mg_fclose(&fi.access) != 0) {
  12786. ok = 0;
  12787. }
  12788. if (!ok) {
  12789. mg_cry_internal(conn,
  12790. "Error writing log file %s",
  12791. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12792. }
  12793. }
  12794. }
  12795. #endif /* Externally provided function */
  12796. /* Verify given socket address against the ACL.
  12797. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12798. */
  12799. static int
  12800. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12801. {
  12802. int allowed, flag;
  12803. uint32_t net, mask;
  12804. struct vec vec;
  12805. if (phys_ctx) {
  12806. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12807. /* If any ACL is set, deny by default */
  12808. allowed = (list == NULL) ? '+' : '-';
  12809. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12810. flag = vec.ptr[0];
  12811. if ((flag != '+' && flag != '-')
  12812. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12813. mg_cry_internal(fc(phys_ctx),
  12814. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12815. __func__);
  12816. return -1;
  12817. }
  12818. if (net == (remote_ip & mask)) {
  12819. allowed = flag;
  12820. }
  12821. }
  12822. return allowed == '+';
  12823. }
  12824. return -1;
  12825. }
  12826. #if !defined(_WIN32)
  12827. static int
  12828. set_uid_option(struct mg_context *phys_ctx)
  12829. {
  12830. int success = 0;
  12831. if (phys_ctx) {
  12832. /* We are currently running as curr_uid. */
  12833. const uid_t curr_uid = getuid();
  12834. /* If set, we want to run as run_as_user. */
  12835. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12836. const struct passwd *to_pw = NULL;
  12837. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12838. /* run_as_user does not exist on the system. We can't proceed
  12839. * further. */
  12840. mg_cry_internal(fc(phys_ctx),
  12841. "%s: unknown user [%s]",
  12842. __func__,
  12843. run_as_user);
  12844. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12845. /* There was either no request to change user, or we're already
  12846. * running as run_as_user. Nothing else to do.
  12847. */
  12848. success = 1;
  12849. } else {
  12850. /* Valid change request. */
  12851. if (setgid(to_pw->pw_gid) == -1) {
  12852. mg_cry_internal(fc(phys_ctx),
  12853. "%s: setgid(%s): %s",
  12854. __func__,
  12855. run_as_user,
  12856. strerror(errno));
  12857. } else if (setgroups(0, NULL) == -1) {
  12858. mg_cry_internal(fc(phys_ctx),
  12859. "%s: setgroups(): %s",
  12860. __func__,
  12861. strerror(errno));
  12862. } else if (setuid(to_pw->pw_uid) == -1) {
  12863. mg_cry_internal(fc(phys_ctx),
  12864. "%s: setuid(%s): %s",
  12865. __func__,
  12866. run_as_user,
  12867. strerror(errno));
  12868. } else {
  12869. success = 1;
  12870. }
  12871. }
  12872. }
  12873. return success;
  12874. }
  12875. #endif /* !_WIN32 */
  12876. static void
  12877. tls_dtor(void *key)
  12878. {
  12879. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12880. /* key == pthread_getspecific(sTlsKey); */
  12881. if (tls) {
  12882. if (tls->is_master == 2) {
  12883. tls->is_master = -3; /* Mark memory as dead */
  12884. mg_free(tls);
  12885. }
  12886. }
  12887. pthread_setspecific(sTlsKey, NULL);
  12888. }
  12889. #if !defined(NO_SSL)
  12890. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12891. struct mg_domain_context *dom_ctx,
  12892. const char *pem,
  12893. const char *chain);
  12894. static const char *ssl_error(void);
  12895. static int
  12896. refresh_trust(struct mg_connection *conn)
  12897. {
  12898. static int reload_lock = 0;
  12899. static long int data_check = 0;
  12900. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12901. struct stat cert_buf;
  12902. long int t;
  12903. const char *pem;
  12904. const char *chain;
  12905. int should_verify_peer;
  12906. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12907. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12908. * refresh_trust still can not work. */
  12909. return 0;
  12910. }
  12911. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12912. if (chain == NULL) {
  12913. /* pem is not NULL here */
  12914. chain = pem;
  12915. }
  12916. if (*chain == 0) {
  12917. chain = NULL;
  12918. }
  12919. t = data_check;
  12920. if (stat(pem, &cert_buf) != -1) {
  12921. t = (long int)cert_buf.st_mtime;
  12922. }
  12923. if (data_check != t) {
  12924. data_check = t;
  12925. should_verify_peer = 0;
  12926. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12927. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12928. == 0) {
  12929. should_verify_peer = 1;
  12930. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12931. "optional")
  12932. == 0) {
  12933. should_verify_peer = 1;
  12934. }
  12935. }
  12936. if (should_verify_peer) {
  12937. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12938. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12939. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12940. ca_file,
  12941. ca_path)
  12942. != 1) {
  12943. mg_cry_internal(
  12944. fc(conn->phys_ctx),
  12945. "SSL_CTX_load_verify_locations error: %s "
  12946. "ssl_verify_peer requires setting "
  12947. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12948. "present in "
  12949. "the .conf file?",
  12950. ssl_error());
  12951. return 0;
  12952. }
  12953. }
  12954. if (1 == mg_atomic_inc(p_reload_lock)) {
  12955. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12956. == 0) {
  12957. return 0;
  12958. }
  12959. *p_reload_lock = 0;
  12960. }
  12961. }
  12962. /* lock while cert is reloading */
  12963. while (*p_reload_lock) {
  12964. sleep(1);
  12965. }
  12966. return 1;
  12967. }
  12968. #if defined(OPENSSL_API_1_1)
  12969. #else
  12970. static pthread_mutex_t *ssl_mutexes;
  12971. #endif /* OPENSSL_API_1_1 */
  12972. static int
  12973. sslize(struct mg_connection *conn,
  12974. SSL_CTX *s,
  12975. int (*func)(SSL *),
  12976. volatile int *stop_server,
  12977. const struct mg_client_options *client_options)
  12978. {
  12979. int ret, err;
  12980. int short_trust;
  12981. unsigned timeout=1024;
  12982. unsigned i;
  12983. if (!conn) {
  12984. return 0;
  12985. }
  12986. short_trust =
  12987. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12988. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12989. if (short_trust) {
  12990. int trust_ret = refresh_trust(conn);
  12991. if (!trust_ret) {
  12992. return trust_ret;
  12993. }
  12994. }
  12995. conn->ssl = SSL_new(s);
  12996. if (conn->ssl == NULL) {
  12997. return 0;
  12998. }
  12999. SSL_set_app_data(conn->ssl, (char *)conn);
  13000. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13001. if (ret != 1) {
  13002. err = SSL_get_error(conn->ssl, ret);
  13003. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13004. SSL_free(conn->ssl);
  13005. conn->ssl = NULL;
  13006. OPENSSL_REMOVE_THREAD_STATE();
  13007. return 0;
  13008. }
  13009. if (client_options) {
  13010. if (client_options->host_name) {
  13011. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13012. }
  13013. }
  13014. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13015. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13016. /* NOTE: The loop below acts as a back-off, so we can end
  13017. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13018. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13019. }
  13020. /* SSL functions may fail and require to be called again:
  13021. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13022. * Here "func" could be SSL_connect or SSL_accept. */
  13023. for (i = 16; i <= timeout; i *= 2) {
  13024. ret = func(conn->ssl);
  13025. if (ret != 1) {
  13026. err = SSL_get_error(conn->ssl, ret);
  13027. if ((err == SSL_ERROR_WANT_CONNECT)
  13028. || (err == SSL_ERROR_WANT_ACCEPT)
  13029. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13030. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13031. /* Need to retry the function call "later".
  13032. * See https://linux.die.net/man/3/ssl_get_error
  13033. * This is typical for non-blocking sockets. */
  13034. if (*stop_server) {
  13035. /* Don't wait if the server is going to be stopped. */
  13036. break;
  13037. }
  13038. mg_sleep(i);
  13039. } else if (err == SSL_ERROR_SYSCALL) {
  13040. /* This is an IO error. Look at errno. */
  13041. err = errno;
  13042. mg_cry_internal(conn, "SSL syscall error %i", err);
  13043. break;
  13044. } else {
  13045. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13046. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13047. break;
  13048. }
  13049. } else {
  13050. /* success */
  13051. break;
  13052. }
  13053. }
  13054. if (ret != 1) {
  13055. SSL_free(conn->ssl);
  13056. conn->ssl = NULL;
  13057. OPENSSL_REMOVE_THREAD_STATE();
  13058. return 0;
  13059. }
  13060. return 1;
  13061. }
  13062. /* Return OpenSSL error message (from CRYPTO lib) */
  13063. static const char *
  13064. ssl_error(void)
  13065. {
  13066. unsigned long err;
  13067. err = ERR_get_error();
  13068. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13069. }
  13070. static int
  13071. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13072. {
  13073. int i;
  13074. const char hexdigit[] = "0123456789abcdef";
  13075. if ((memlen <= 0) || (buflen <= 0)) {
  13076. return 0;
  13077. }
  13078. if (buflen < (3 * memlen)) {
  13079. return 0;
  13080. }
  13081. for (i = 0; i < memlen; i++) {
  13082. if (i > 0) {
  13083. buf[3 * i - 1] = ' ';
  13084. }
  13085. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13086. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13087. }
  13088. buf[3 * memlen - 1] = 0;
  13089. return 1;
  13090. }
  13091. static void
  13092. ssl_get_client_cert_info(struct mg_connection *conn)
  13093. {
  13094. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13095. if (cert) {
  13096. char str_subject[1024];
  13097. char str_issuer[1024];
  13098. char str_finger[1024];
  13099. unsigned char buf[256];
  13100. char *str_serial = NULL;
  13101. unsigned int ulen;
  13102. int ilen;
  13103. unsigned char *tmp_buf;
  13104. unsigned char *tmp_p;
  13105. /* Handle to algorithm used for fingerprint */
  13106. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13107. /* Get Subject and issuer */
  13108. X509_NAME *subj = X509_get_subject_name(cert);
  13109. X509_NAME *iss = X509_get_issuer_name(cert);
  13110. /* Get serial number */
  13111. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13112. /* Translate serial number to a hex string */
  13113. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13114. str_serial = BN_bn2hex(serial_bn);
  13115. BN_free(serial_bn);
  13116. /* Translate subject and issuer to a string */
  13117. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13118. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13119. /* Calculate SHA1 fingerprint and store as a hex string */
  13120. ulen = 0;
  13121. /* ASN1_digest is deprecated. Do the calculation manually,
  13122. * using EVP_Digest. */
  13123. ilen = i2d_X509(cert, NULL);
  13124. tmp_buf = (ilen > 0)
  13125. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13126. conn->phys_ctx)
  13127. : NULL;
  13128. if (tmp_buf) {
  13129. tmp_p = tmp_buf;
  13130. (void)i2d_X509(cert, &tmp_p);
  13131. if (!EVP_Digest(
  13132. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13133. ulen = 0;
  13134. }
  13135. mg_free(tmp_buf);
  13136. }
  13137. if (!hexdump2string(
  13138. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13139. *str_finger = 0;
  13140. }
  13141. conn->request_info.client_cert = (struct mg_client_cert *)
  13142. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13143. if (conn->request_info.client_cert) {
  13144. conn->request_info.client_cert->peer_cert = (void *)cert;
  13145. conn->request_info.client_cert->subject =
  13146. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13147. conn->request_info.client_cert->issuer =
  13148. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13149. conn->request_info.client_cert->serial =
  13150. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13151. conn->request_info.client_cert->finger =
  13152. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13153. } else {
  13154. mg_cry_internal(conn,
  13155. "%s",
  13156. "Out of memory: Cannot allocate memory for client "
  13157. "certificate");
  13158. }
  13159. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13160. * see https://linux.die.net/man/3/bn_bn2hex */
  13161. OPENSSL_free(str_serial);
  13162. }
  13163. }
  13164. #if defined(OPENSSL_API_1_1)
  13165. #else
  13166. static void
  13167. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13168. {
  13169. (void)line;
  13170. (void)file;
  13171. if (mode & 1) {
  13172. /* 1 is CRYPTO_LOCK */
  13173. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13174. } else {
  13175. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13176. }
  13177. }
  13178. #endif /* OPENSSL_API_1_1 */
  13179. #if !defined(NO_SSL_DL)
  13180. static void *
  13181. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13182. {
  13183. union {
  13184. void *p;
  13185. void (*fp)(void);
  13186. } u;
  13187. void *dll_handle;
  13188. struct ssl_func *fp;
  13189. int ok;
  13190. int truncated = 0;
  13191. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13192. mg_snprintf(NULL,
  13193. NULL, /* No truncation check for ebuf */
  13194. ebuf,
  13195. ebuf_len,
  13196. "%s: cannot load %s",
  13197. __func__,
  13198. dll_name);
  13199. return NULL;
  13200. }
  13201. ok = 1;
  13202. for (fp = sw; fp->name != NULL; fp++) {
  13203. #if defined(_WIN32)
  13204. /* GetProcAddress() returns pointer to function */
  13205. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13206. #else
  13207. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13208. * pointers to function pointers. We need to use a union to make a
  13209. * cast. */
  13210. u.p = dlsym(dll_handle, fp->name);
  13211. #endif /* _WIN32 */
  13212. if (u.fp == NULL) {
  13213. if (ok) {
  13214. mg_snprintf(NULL,
  13215. &truncated,
  13216. ebuf,
  13217. ebuf_len,
  13218. "%s: %s: cannot find %s",
  13219. __func__,
  13220. dll_name,
  13221. fp->name);
  13222. ok = 0;
  13223. } else {
  13224. size_t cur_len = strlen(ebuf);
  13225. if (!truncated) {
  13226. mg_snprintf(NULL,
  13227. &truncated,
  13228. ebuf + cur_len,
  13229. ebuf_len - cur_len - 3,
  13230. ", %s",
  13231. fp->name);
  13232. if (truncated) {
  13233. /* If truncated, add "..." */
  13234. strcat(ebuf, "...");
  13235. }
  13236. }
  13237. }
  13238. /* Debug:
  13239. * printf("Missing function: %s\n", fp->name); */
  13240. } else {
  13241. fp->ptr = u.fp;
  13242. }
  13243. }
  13244. if (!ok) {
  13245. (void)dlclose(dll_handle);
  13246. return NULL;
  13247. }
  13248. return dll_handle;
  13249. }
  13250. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13251. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13252. #endif /* NO_SSL_DL */
  13253. #if defined(SSL_ALREADY_INITIALIZED)
  13254. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13255. #else
  13256. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13257. #endif
  13258. static int
  13259. initialize_ssl(char *ebuf, size_t ebuf_len)
  13260. {
  13261. #if defined(OPENSSL_API_1_1)
  13262. if (ebuf_len > 0) {
  13263. ebuf[0] = 0;
  13264. }
  13265. #if !defined(NO_SSL_DL)
  13266. if (!cryptolib_dll_handle) {
  13267. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13268. if (!cryptolib_dll_handle) {
  13269. mg_snprintf(NULL,
  13270. NULL, /* No truncation check for ebuf */
  13271. ebuf,
  13272. ebuf_len,
  13273. "%s: error loading library %s",
  13274. __func__,
  13275. CRYPTO_LIB);
  13276. DEBUG_TRACE("%s", ebuf);
  13277. return 0;
  13278. }
  13279. }
  13280. #endif /* NO_SSL_DL */
  13281. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13282. return 1;
  13283. }
  13284. #else /* not OPENSSL_API_1_1 */
  13285. int i, num_locks;
  13286. size_t size;
  13287. if (ebuf_len > 0) {
  13288. ebuf[0] = 0;
  13289. }
  13290. #if !defined(NO_SSL_DL)
  13291. if (!cryptolib_dll_handle) {
  13292. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13293. if (!cryptolib_dll_handle) {
  13294. mg_snprintf(NULL,
  13295. NULL, /* No truncation check for ebuf */
  13296. ebuf,
  13297. ebuf_len,
  13298. "%s: error loading library %s",
  13299. __func__,
  13300. CRYPTO_LIB);
  13301. DEBUG_TRACE("%s", ebuf);
  13302. return 0;
  13303. }
  13304. }
  13305. #endif /* NO_SSL_DL */
  13306. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13307. return 1;
  13308. }
  13309. /* Initialize locking callbacks, needed for thread safety.
  13310. * http://www.openssl.org/support/faq.html#PROG1
  13311. */
  13312. num_locks = CRYPTO_num_locks();
  13313. if (num_locks < 0) {
  13314. num_locks = 0;
  13315. }
  13316. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13317. /* allocate mutex array, if required */
  13318. if (num_locks == 0) {
  13319. /* No mutex array required */
  13320. ssl_mutexes = NULL;
  13321. } else {
  13322. /* Mutex array required - allocate it */
  13323. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13324. /* Check OOM */
  13325. if (ssl_mutexes == NULL) {
  13326. mg_snprintf(NULL,
  13327. NULL, /* No truncation check for ebuf */
  13328. ebuf,
  13329. ebuf_len,
  13330. "%s: cannot allocate mutexes: %s",
  13331. __func__,
  13332. ssl_error());
  13333. DEBUG_TRACE("%s", ebuf);
  13334. return 0;
  13335. }
  13336. /* initialize mutex array */
  13337. for (i = 0; i < num_locks; i++) {
  13338. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13339. mg_snprintf(NULL,
  13340. NULL, /* No truncation check for ebuf */
  13341. ebuf,
  13342. ebuf_len,
  13343. "%s: error initializing mutex %i of %i",
  13344. __func__,
  13345. i,
  13346. num_locks);
  13347. DEBUG_TRACE("%s", ebuf);
  13348. mg_free(ssl_mutexes);
  13349. return 0;
  13350. }
  13351. }
  13352. }
  13353. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13354. CRYPTO_set_id_callback(&mg_current_thread_id);
  13355. #endif /* OPENSSL_API_1_1 */
  13356. #if !defined(NO_SSL_DL)
  13357. if (!ssllib_dll_handle) {
  13358. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13359. if (!ssllib_dll_handle) {
  13360. #if !defined(OPENSSL_API_1_1)
  13361. mg_free(ssl_mutexes);
  13362. #endif
  13363. DEBUG_TRACE("%s", ebuf);
  13364. return 0;
  13365. }
  13366. }
  13367. #endif /* NO_SSL_DL */
  13368. #if defined(OPENSSL_API_1_1)
  13369. /* Initialize SSL library */
  13370. OPENSSL_init_ssl(0, NULL);
  13371. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13372. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13373. NULL);
  13374. #else
  13375. /* Initialize SSL library */
  13376. SSL_library_init();
  13377. SSL_load_error_strings();
  13378. #endif
  13379. return 1;
  13380. }
  13381. static int
  13382. ssl_use_pem_file(struct mg_context *phys_ctx,
  13383. struct mg_domain_context *dom_ctx,
  13384. const char *pem,
  13385. const char *chain)
  13386. {
  13387. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13388. mg_cry_internal(fc(phys_ctx),
  13389. "%s: cannot open certificate file %s: %s",
  13390. __func__,
  13391. pem,
  13392. ssl_error());
  13393. return 0;
  13394. }
  13395. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13396. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13397. mg_cry_internal(fc(phys_ctx),
  13398. "%s: cannot open private key file %s: %s",
  13399. __func__,
  13400. pem,
  13401. ssl_error());
  13402. return 0;
  13403. }
  13404. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13405. mg_cry_internal(fc(phys_ctx),
  13406. "%s: certificate and private key do not match: %s",
  13407. __func__,
  13408. pem);
  13409. return 0;
  13410. }
  13411. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13412. * chain files that contain private keys and certificates in
  13413. * SSL_CTX_use_certificate_chain_file.
  13414. * The CivetWeb-Server used pem-Files that contained both information.
  13415. * In order to make wolfSSL work, it is split in two files.
  13416. * One file that contains key and certificate used by the server and
  13417. * an optional chain file for the ssl stack.
  13418. */
  13419. if (chain) {
  13420. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13421. mg_cry_internal(fc(phys_ctx),
  13422. "%s: cannot use certificate chain file %s: %s",
  13423. __func__,
  13424. pem,
  13425. ssl_error());
  13426. return 0;
  13427. }
  13428. }
  13429. return 1;
  13430. }
  13431. #if defined(OPENSSL_API_1_1)
  13432. static unsigned long
  13433. ssl_get_protocol(int version_id)
  13434. {
  13435. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13436. if (version_id > 0)
  13437. ret |= SSL_OP_NO_SSLv2;
  13438. if (version_id > 1)
  13439. ret |= SSL_OP_NO_SSLv3;
  13440. if (version_id > 2)
  13441. ret |= SSL_OP_NO_TLSv1;
  13442. if (version_id > 3)
  13443. ret |= SSL_OP_NO_TLSv1_1;
  13444. return ret;
  13445. }
  13446. #else
  13447. static long
  13448. ssl_get_protocol(int version_id)
  13449. {
  13450. long ret = (long)SSL_OP_ALL;
  13451. if (version_id > 0)
  13452. ret |= SSL_OP_NO_SSLv2;
  13453. if (version_id > 1)
  13454. ret |= SSL_OP_NO_SSLv3;
  13455. if (version_id > 2)
  13456. ret |= SSL_OP_NO_TLSv1;
  13457. if (version_id > 3)
  13458. ret |= SSL_OP_NO_TLSv1_1;
  13459. return ret;
  13460. }
  13461. #endif /* OPENSSL_API_1_1 */
  13462. /* SSL callback documentation:
  13463. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13464. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13465. * https://linux.die.net/man/3/ssl_set_info_callback */
  13466. /* Note: There is no "const" for the first argument in the documentation
  13467. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13468. * / OpenSSL compatibility layers have it. Having a different definition will
  13469. * cause a warning in C and an error in C++. Use "const SSL *", while
  13470. * automatical conversion from "SSL *" works for all compilers, but not other
  13471. * way around */
  13472. static void
  13473. ssl_info_callback(const SSL *ssl, int what, int ret)
  13474. {
  13475. (void)ret;
  13476. if (what & SSL_CB_HANDSHAKE_START) {
  13477. SSL_get_app_data(ssl);
  13478. }
  13479. if (what & SSL_CB_HANDSHAKE_DONE) {
  13480. /* TODO: check for openSSL 1.1 */
  13481. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13482. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13483. }
  13484. }
  13485. static int
  13486. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13487. {
  13488. struct mg_context *ctx = (struct mg_context *)arg;
  13489. struct mg_domain_context *dom =
  13490. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13491. #if defined(GCC_DIAGNOSTIC)
  13492. #pragma GCC diagnostic push
  13493. #pragma GCC diagnostic ignored "-Wcast-align"
  13494. #endif /* defined(GCC_DIAGNOSTIC) */
  13495. /* We used an aligned pointer in SSL_set_app_data */
  13496. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13497. #if defined(GCC_DIAGNOSTIC)
  13498. #pragma GCC diagnostic pop
  13499. #endif /* defined(GCC_DIAGNOSTIC) */
  13500. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13501. (void)ad;
  13502. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13503. DEBUG_TRACE("%s", "internal error - assertion failed");
  13504. return SSL_TLSEXT_ERR_NOACK;
  13505. }
  13506. /* Old clients (Win XP) will not support SNI. Then, there
  13507. * is no server name available in the request - we can
  13508. * only work with the default certificate.
  13509. * Multiple HTTPS hosts on one IP+port are only possible
  13510. * with a certificate containing all alternative names.
  13511. */
  13512. if ((servername == NULL) || (*servername == 0)) {
  13513. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13514. conn->dom_ctx = &(ctx->dd);
  13515. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13516. return SSL_TLSEXT_ERR_NOACK;
  13517. }
  13518. DEBUG_TRACE("TLS connection to host %s", servername);
  13519. while (dom) {
  13520. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13521. /* Found matching domain */
  13522. DEBUG_TRACE("TLS domain %s found",
  13523. dom->config[AUTHENTICATION_DOMAIN]);
  13524. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13525. conn->dom_ctx = dom;
  13526. return SSL_TLSEXT_ERR_OK;
  13527. }
  13528. dom = dom->next;
  13529. }
  13530. /* Default domain */
  13531. DEBUG_TRACE("TLS default domain %s used",
  13532. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13533. conn->dom_ctx = &(ctx->dd);
  13534. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13535. return SSL_TLSEXT_ERR_OK;
  13536. }
  13537. /* Setup SSL CTX as required by CivetWeb */
  13538. static int
  13539. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13540. struct mg_domain_context *dom_ctx,
  13541. const char *pem,
  13542. const char *chain)
  13543. {
  13544. int callback_ret;
  13545. int should_verify_peer;
  13546. int peer_certificate_optional;
  13547. const char *ca_path;
  13548. const char *ca_file;
  13549. int use_default_verify_paths;
  13550. int verify_depth;
  13551. struct timespec now_mt;
  13552. md5_byte_t ssl_context_id[16];
  13553. md5_state_t md5state;
  13554. int protocol_ver;
  13555. #if defined(OPENSSL_API_1_1)
  13556. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13557. mg_cry_internal(fc(phys_ctx),
  13558. "SSL_CTX_new (server) error: %s",
  13559. ssl_error());
  13560. return 0;
  13561. }
  13562. #else
  13563. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13564. mg_cry_internal(fc(phys_ctx),
  13565. "SSL_CTX_new (server) error: %s",
  13566. ssl_error());
  13567. return 0;
  13568. }
  13569. #endif /* OPENSSL_API_1_1 */
  13570. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13571. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13572. | SSL_OP_NO_TLSv1_1);
  13573. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13574. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13575. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13576. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13577. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13578. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13579. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13580. #if !defined(NO_SSL_DL)
  13581. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13582. #endif /* NO_SSL_DL */
  13583. /* In SSL documentation examples callback defined without const specifier
  13584. * 'void (*)(SSL *, int, int)' See:
  13585. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13586. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13587. * But in the source code const SSL is used:
  13588. * 'void (*)(const SSL *, int, int)' See:
  13589. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13590. * Problem about wrong documentation described, but not resolved:
  13591. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13592. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13593. * But when compiled with modern C++ compiler, correct const should be
  13594. * provided
  13595. */
  13596. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13597. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13598. ssl_servername_callback);
  13599. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13600. /* If a callback has been specified, call it. */
  13601. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13602. ? 0
  13603. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13604. phys_ctx->user_data));
  13605. /* If callback returns 0, civetweb sets up the SSL certificate.
  13606. * If it returns 1, civetweb assumes the calback already did this.
  13607. * If it returns -1, initializing ssl fails. */
  13608. if (callback_ret < 0) {
  13609. mg_cry_internal(fc(phys_ctx),
  13610. "SSL callback returned error: %i",
  13611. callback_ret);
  13612. return 0;
  13613. }
  13614. if (callback_ret > 0) {
  13615. /* Callback did everything. */
  13616. return 1;
  13617. }
  13618. /* Use some combination of start time, domain and port as a SSL
  13619. * context ID. This should be unique on the current machine. */
  13620. md5_init(&md5state);
  13621. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13622. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13623. md5_append(&md5state,
  13624. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13625. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13626. md5_append(&md5state,
  13627. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13628. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13629. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13630. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13631. md5_finish(&md5state, ssl_context_id);
  13632. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13633. (unsigned char *)ssl_context_id,
  13634. sizeof(ssl_context_id));
  13635. if (pem != NULL) {
  13636. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13637. return 0;
  13638. }
  13639. }
  13640. /* Should we support client certificates? */
  13641. /* Default is "no". */
  13642. should_verify_peer = 0;
  13643. peer_certificate_optional = 0;
  13644. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13645. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13646. /* Yes, they are mandatory */
  13647. should_verify_peer = 1;
  13648. peer_certificate_optional = 0;
  13649. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13650. "optional")
  13651. == 0) {
  13652. /* Yes, they are optional */
  13653. should_verify_peer = 1;
  13654. peer_certificate_optional = 1;
  13655. }
  13656. }
  13657. use_default_verify_paths =
  13658. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13659. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13660. == 0);
  13661. if (should_verify_peer) {
  13662. ca_path = dom_ctx->config[SSL_CA_PATH];
  13663. ca_file = dom_ctx->config[SSL_CA_FILE];
  13664. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13665. != 1) {
  13666. mg_cry_internal(fc(phys_ctx),
  13667. "SSL_CTX_load_verify_locations error: %s "
  13668. "ssl_verify_peer requires setting "
  13669. "either ssl_ca_path or ssl_ca_file. "
  13670. "Is any of them present in the "
  13671. ".conf file?",
  13672. ssl_error());
  13673. return 0;
  13674. }
  13675. if (peer_certificate_optional) {
  13676. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13677. } else {
  13678. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13679. SSL_VERIFY_PEER
  13680. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13681. NULL);
  13682. }
  13683. if (use_default_verify_paths
  13684. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13685. mg_cry_internal(fc(phys_ctx),
  13686. "SSL_CTX_set_default_verify_paths error: %s",
  13687. ssl_error());
  13688. return 0;
  13689. }
  13690. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13691. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13692. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13693. }
  13694. }
  13695. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13696. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13697. dom_ctx->config[SSL_CIPHER_LIST])
  13698. != 1) {
  13699. mg_cry_internal(fc(phys_ctx),
  13700. "SSL_CTX_set_cipher_list error: %s",
  13701. ssl_error());
  13702. }
  13703. }
  13704. return 1;
  13705. }
  13706. /* Check if SSL is required.
  13707. * If so, dynamically load SSL library
  13708. * and set up ctx->ssl_ctx pointer. */
  13709. static int
  13710. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13711. {
  13712. void *ssl_ctx = 0;
  13713. int callback_ret;
  13714. const char *pem;
  13715. const char *chain;
  13716. char ebuf[128];
  13717. if (!phys_ctx) {
  13718. return 0;
  13719. }
  13720. if (!dom_ctx) {
  13721. dom_ctx = &(phys_ctx->dd);
  13722. }
  13723. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13724. /* No SSL port is set. No need to setup SSL. */
  13725. return 1;
  13726. }
  13727. /* Check for external SSL_CTX */
  13728. callback_ret =
  13729. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13730. ? 0
  13731. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13732. phys_ctx->user_data));
  13733. if (callback_ret < 0) {
  13734. mg_cry_internal(fc(phys_ctx),
  13735. "external_ssl_ctx callback returned error: %i",
  13736. callback_ret);
  13737. return 0;
  13738. } else if (callback_ret > 0) {
  13739. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13740. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13741. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13742. return 0;
  13743. }
  13744. return 1;
  13745. }
  13746. /* else: external_ssl_ctx does not exist or returns 0,
  13747. * CivetWeb should continue initializing SSL */
  13748. /* If PEM file is not specified and the init_ssl callback
  13749. * is not specified, setup will fail. */
  13750. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13751. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13752. /* No certificate and no callback:
  13753. * Essential data to set up TLS is missing.
  13754. */
  13755. mg_cry_internal(fc(phys_ctx),
  13756. "Initializing SSL failed: -%s is not set",
  13757. config_options[SSL_CERTIFICATE].name);
  13758. return 0;
  13759. }
  13760. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13761. if (chain == NULL) {
  13762. chain = pem;
  13763. }
  13764. if ((chain != NULL) && (*chain == 0)) {
  13765. chain = NULL;
  13766. }
  13767. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13768. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13769. return 0;
  13770. }
  13771. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13772. }
  13773. static void
  13774. uninitialize_ssl(void)
  13775. {
  13776. #if defined(OPENSSL_API_1_1)
  13777. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13778. /* Shutdown according to
  13779. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13780. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13781. */
  13782. CONF_modules_unload(1);
  13783. #else
  13784. int i;
  13785. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13786. /* Shutdown according to
  13787. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13788. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13789. */
  13790. CRYPTO_set_locking_callback(NULL);
  13791. CRYPTO_set_id_callback(NULL);
  13792. ENGINE_cleanup();
  13793. CONF_modules_unload(1);
  13794. ERR_free_strings();
  13795. EVP_cleanup();
  13796. CRYPTO_cleanup_all_ex_data();
  13797. OPENSSL_REMOVE_THREAD_STATE();
  13798. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13799. pthread_mutex_destroy(&ssl_mutexes[i]);
  13800. }
  13801. mg_free(ssl_mutexes);
  13802. ssl_mutexes = NULL;
  13803. #endif /* OPENSSL_API_1_1 */
  13804. }
  13805. }
  13806. #endif /* !NO_SSL */
  13807. static int
  13808. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13809. {
  13810. if (phys_ctx) {
  13811. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13812. const char *path;
  13813. if (!dom_ctx) {
  13814. dom_ctx = &(phys_ctx->dd);
  13815. }
  13816. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13817. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13818. mg_cry_internal(fc(phys_ctx),
  13819. "Cannot open %s: %s",
  13820. path,
  13821. strerror(ERRNO));
  13822. return 0;
  13823. }
  13824. return 1;
  13825. }
  13826. return 0;
  13827. }
  13828. static int
  13829. set_acl_option(struct mg_context *phys_ctx)
  13830. {
  13831. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13832. }
  13833. static void
  13834. reset_per_request_attributes(struct mg_connection *conn)
  13835. {
  13836. if (!conn) {
  13837. return;
  13838. }
  13839. conn->connection_type =
  13840. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13841. conn->num_bytes_sent = conn->consumed_content = 0;
  13842. conn->path_info = NULL;
  13843. conn->status_code = -1;
  13844. conn->content_len = -1;
  13845. conn->is_chunked = 0;
  13846. conn->must_close = 0;
  13847. conn->request_len = 0;
  13848. conn->throttle = 0;
  13849. conn->data_len = 0;
  13850. conn->chunk_remainder = 0;
  13851. conn->accept_gzip = 0;
  13852. conn->response_info.content_length = conn->request_info.content_length = -1;
  13853. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13854. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13855. conn->response_info.status_text = NULL;
  13856. conn->response_info.status_code = 0;
  13857. conn->request_info.remote_user = NULL;
  13858. conn->request_info.request_method = NULL;
  13859. conn->request_info.request_uri = NULL;
  13860. conn->request_info.local_uri = NULL;
  13861. #if defined(MG_LEGACY_INTERFACE)
  13862. /* Legacy before split into local_uri and request_uri */
  13863. conn->request_info.uri = NULL;
  13864. #endif
  13865. }
  13866. #if 0
  13867. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13868. * Leave this function here (commented out) for reference until
  13869. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13870. * no longer required.
  13871. */
  13872. static int
  13873. set_sock_timeout(SOCKET sock, int milliseconds)
  13874. {
  13875. int r0 = 0, r1, r2;
  13876. #if defined(_WIN32)
  13877. /* Windows specific */
  13878. DWORD tv = (DWORD)milliseconds;
  13879. #else
  13880. /* Linux, ... (not Windows) */
  13881. struct timeval tv;
  13882. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13883. * max. time waiting for the acknowledged of TCP data before the connection
  13884. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13885. * If this option is not set, the default timeout of 20-30 minutes is used.
  13886. */
  13887. /* #define TCP_USER_TIMEOUT (18) */
  13888. #if defined(TCP_USER_TIMEOUT)
  13889. unsigned int uto = (unsigned int)milliseconds;
  13890. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13891. #endif
  13892. memset(&tv, 0, sizeof(tv));
  13893. tv.tv_sec = milliseconds / 1000;
  13894. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13895. #endif /* _WIN32 */
  13896. r1 = setsockopt(
  13897. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13898. r2 = setsockopt(
  13899. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13900. return r0 || r1 || r2;
  13901. }
  13902. #endif
  13903. static int
  13904. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13905. {
  13906. if (setsockopt(sock,
  13907. IPPROTO_TCP,
  13908. TCP_NODELAY,
  13909. (SOCK_OPT_TYPE)&nodelay_on,
  13910. sizeof(nodelay_on))
  13911. != 0) {
  13912. /* Error */
  13913. return 1;
  13914. }
  13915. /* OK */
  13916. return 0;
  13917. }
  13918. static void
  13919. close_socket_gracefully(struct mg_connection *conn)
  13920. {
  13921. #if defined(_WIN32)
  13922. char buf[MG_BUF_LEN];
  13923. int n;
  13924. #endif
  13925. struct linger linger;
  13926. int error_code = 0;
  13927. int linger_timeout = -2;
  13928. socklen_t opt_len = sizeof(error_code);
  13929. if (!conn) {
  13930. return;
  13931. }
  13932. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13933. * "Note that enabling a nonzero timeout on a nonblocking socket
  13934. * is not recommended.", so set it to blocking now */
  13935. set_blocking_mode(conn->client.sock);
  13936. /* Send FIN to the client */
  13937. shutdown(conn->client.sock, SHUTDOWN_WR);
  13938. #if defined(_WIN32)
  13939. /* Read and discard pending incoming data. If we do not do that and
  13940. * close
  13941. * the socket, the data in the send buffer may be discarded. This
  13942. * behaviour is seen on Windows, when client keeps sending data
  13943. * when server decides to close the connection; then when client
  13944. * does recv() it gets no data back. */
  13945. do {
  13946. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13947. } while (n > 0);
  13948. #endif
  13949. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13950. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13951. }
  13952. /* Set linger option according to configuration */
  13953. if (linger_timeout >= 0) {
  13954. /* Set linger option to avoid socket hanging out after close. This
  13955. * prevent ephemeral port exhaust problem under high QPS. */
  13956. linger.l_onoff = 1;
  13957. #if defined(_MSC_VER)
  13958. #pragma warning(push)
  13959. #pragma warning(disable : 4244)
  13960. #endif
  13961. #if defined(GCC_DIAGNOSTIC)
  13962. #pragma GCC diagnostic push
  13963. #pragma GCC diagnostic ignored "-Wconversion"
  13964. #endif
  13965. /* Data type of linger structure elements may differ,
  13966. * so we don't know what cast we need here.
  13967. * Disable type conversion warnings. */
  13968. linger.l_linger = (linger_timeout + 999) / 1000;
  13969. #if defined(GCC_DIAGNOSTIC)
  13970. #pragma GCC diagnostic pop
  13971. #endif
  13972. #if defined(_MSC_VER)
  13973. #pragma warning(pop)
  13974. #endif
  13975. } else {
  13976. linger.l_onoff = 0;
  13977. linger.l_linger = 0;
  13978. }
  13979. if (linger_timeout < -1) {
  13980. /* Default: don't configure any linger */
  13981. } else if (getsockopt(conn->client.sock,
  13982. SOL_SOCKET,
  13983. SO_ERROR,
  13984. #if defined(_WIN32) /* WinSock uses different data type here */
  13985. (char *)&error_code,
  13986. #else
  13987. &error_code,
  13988. #endif
  13989. &opt_len)
  13990. != 0) {
  13991. /* Cannot determine if socket is already closed. This should
  13992. * not occur and never did in a test. Log an error message
  13993. * and continue. */
  13994. mg_cry_internal(conn,
  13995. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13996. __func__,
  13997. strerror(ERRNO));
  13998. } else if (error_code == ECONNRESET) {
  13999. /* Socket already closed by client/peer, close socket without linger
  14000. */
  14001. } else {
  14002. /* Set linger timeout */
  14003. if (setsockopt(conn->client.sock,
  14004. SOL_SOCKET,
  14005. SO_LINGER,
  14006. (char *)&linger,
  14007. sizeof(linger))
  14008. != 0) {
  14009. mg_cry_internal(
  14010. conn,
  14011. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14012. __func__,
  14013. linger.l_onoff,
  14014. linger.l_linger,
  14015. strerror(ERRNO));
  14016. }
  14017. }
  14018. /* Now we know that our FIN is ACK-ed, safe to close */
  14019. closesocket(conn->client.sock);
  14020. conn->client.sock = INVALID_SOCKET;
  14021. }
  14022. static void
  14023. close_connection(struct mg_connection *conn)
  14024. {
  14025. #if defined(USE_SERVER_STATS)
  14026. conn->conn_state = 6; /* to close */
  14027. #endif
  14028. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14029. if (conn->lua_websocket_state) {
  14030. lua_websocket_close(conn, conn->lua_websocket_state);
  14031. conn->lua_websocket_state = NULL;
  14032. }
  14033. #endif
  14034. mg_lock_connection(conn);
  14035. /* Set close flag, so keep-alive loops will stop */
  14036. conn->must_close = 1;
  14037. /* call the connection_close callback if assigned */
  14038. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14039. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14040. conn->phys_ctx->callbacks.connection_close(conn);
  14041. }
  14042. }
  14043. /* Reset user data, after close callback is called.
  14044. * Do not reuse it. If the user needs a destructor,
  14045. * it must be done in the connection_close callback. */
  14046. mg_set_user_connection_data(conn, NULL);
  14047. #if defined(USE_SERVER_STATS)
  14048. conn->conn_state = 7; /* closing */
  14049. #endif
  14050. #if !defined(NO_SSL)
  14051. if (conn->ssl != NULL) {
  14052. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14053. */
  14054. SSL_shutdown(conn->ssl);
  14055. SSL_free(conn->ssl);
  14056. OPENSSL_REMOVE_THREAD_STATE();
  14057. conn->ssl = NULL;
  14058. }
  14059. #endif
  14060. if (conn->client.sock != INVALID_SOCKET) {
  14061. close_socket_gracefully(conn);
  14062. conn->client.sock = INVALID_SOCKET;
  14063. }
  14064. if (conn->host) {
  14065. mg_free((void *)conn->host);
  14066. conn->host = NULL;
  14067. }
  14068. mg_unlock_connection(conn);
  14069. #if defined(USE_SERVER_STATS)
  14070. conn->conn_state = 8; /* closed */
  14071. #endif
  14072. }
  14073. void
  14074. mg_close_connection(struct mg_connection *conn)
  14075. {
  14076. #if defined(USE_WEBSOCKET)
  14077. struct mg_context *client_ctx = NULL;
  14078. #endif /* defined(USE_WEBSOCKET) */
  14079. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14080. return;
  14081. }
  14082. #if defined(USE_WEBSOCKET)
  14083. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14084. if (conn->in_websocket_handling) {
  14085. /* Set close flag, so the server thread can exit. */
  14086. conn->must_close = 1;
  14087. return;
  14088. }
  14089. }
  14090. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14091. unsigned int i;
  14092. /* ws/wss client */
  14093. client_ctx = conn->phys_ctx;
  14094. /* client context: loops must end */
  14095. client_ctx->stop_flag = 1;
  14096. conn->must_close = 1;
  14097. /* We need to get the client thread out of the select/recv call
  14098. * here. */
  14099. /* Since we use a sleep quantum of some seconds to check for recv
  14100. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14101. /* join worker thread */
  14102. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  14103. if (client_ctx->worker_threadids[i] != 0) {
  14104. mg_join_thread(client_ctx->worker_threadids[i]);
  14105. }
  14106. }
  14107. }
  14108. #endif /* defined(USE_WEBSOCKET) */
  14109. close_connection(conn);
  14110. #if !defined(NO_SSL)
  14111. if (conn->client_ssl_ctx != NULL) {
  14112. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  14113. }
  14114. #endif
  14115. #if defined(USE_WEBSOCKET)
  14116. if (client_ctx != NULL) {
  14117. /* free context */
  14118. mg_free(client_ctx->worker_threadids);
  14119. mg_free(client_ctx);
  14120. (void)pthread_mutex_destroy(&conn->mutex);
  14121. mg_free(conn);
  14122. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14123. mg_free(conn);
  14124. }
  14125. #else
  14126. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14127. mg_free(conn);
  14128. }
  14129. #endif /* defined(USE_WEBSOCKET) */
  14130. }
  14131. /* Only for memory statistics */
  14132. static struct mg_context common_client_context;
  14133. static struct mg_connection *
  14134. mg_connect_client_impl(const struct mg_client_options *client_options,
  14135. int use_ssl,
  14136. char *ebuf,
  14137. size_t ebuf_len)
  14138. {
  14139. struct mg_connection *conn = NULL;
  14140. SOCKET sock;
  14141. union usa sa;
  14142. struct sockaddr *psa;
  14143. socklen_t len;
  14144. unsigned max_req_size =
  14145. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14146. /* Size of structures, aligned to 8 bytes */
  14147. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14148. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14149. conn = (struct mg_connection *)mg_calloc_ctx(
  14150. 1, conn_size + ctx_size + max_req_size, &common_client_context);
  14151. if (conn == NULL) {
  14152. mg_snprintf(NULL,
  14153. NULL, /* No truncation check for ebuf */
  14154. ebuf,
  14155. ebuf_len,
  14156. "calloc(): %s",
  14157. strerror(ERRNO));
  14158. return NULL;
  14159. }
  14160. #if defined(GCC_DIAGNOSTIC)
  14161. #pragma GCC diagnostic push
  14162. #pragma GCC diagnostic ignored "-Wcast-align"
  14163. #endif /* defined(GCC_DIAGNOSTIC) */
  14164. /* conn_size is aligned to 8 bytes */
  14165. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14166. #if defined(GCC_DIAGNOSTIC)
  14167. #pragma GCC diagnostic pop
  14168. #endif /* defined(GCC_DIAGNOSTIC) */
  14169. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14170. conn->buf_size = (int)max_req_size;
  14171. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14172. conn->dom_ctx = &(conn->phys_ctx->dd);
  14173. if (!connect_socket(&common_client_context,
  14174. client_options->host,
  14175. client_options->port,
  14176. use_ssl,
  14177. ebuf,
  14178. ebuf_len,
  14179. &sock,
  14180. &sa)) {
  14181. /* ebuf is set by connect_socket,
  14182. * free all memory and return NULL; */
  14183. mg_free(conn);
  14184. return NULL;
  14185. }
  14186. #if !defined(NO_SSL)
  14187. #if defined(OPENSSL_API_1_1)
  14188. if (use_ssl
  14189. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14190. mg_snprintf(NULL,
  14191. NULL, /* No truncation check for ebuf */
  14192. ebuf,
  14193. ebuf_len,
  14194. "SSL_CTX_new error");
  14195. closesocket(sock);
  14196. mg_free(conn);
  14197. return NULL;
  14198. }
  14199. #else
  14200. if (use_ssl
  14201. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14202. == NULL) {
  14203. mg_snprintf(NULL,
  14204. NULL, /* No truncation check for ebuf */
  14205. ebuf,
  14206. ebuf_len,
  14207. "SSL_CTX_new error");
  14208. closesocket(sock);
  14209. mg_free(conn);
  14210. return NULL;
  14211. }
  14212. #endif /* OPENSSL_API_1_1 */
  14213. #endif /* NO_SSL */
  14214. #if defined(USE_IPV6)
  14215. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14216. : sizeof(conn->client.rsa.sin6);
  14217. psa = (sa.sa.sa_family == AF_INET)
  14218. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14219. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14220. #else
  14221. len = sizeof(conn->client.rsa.sin);
  14222. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14223. #endif
  14224. conn->client.sock = sock;
  14225. conn->client.lsa = sa;
  14226. if (getsockname(sock, psa, &len) != 0) {
  14227. mg_cry_internal(conn,
  14228. "%s: getsockname() failed: %s",
  14229. __func__,
  14230. strerror(ERRNO));
  14231. }
  14232. conn->client.is_ssl = use_ssl ? 1 : 0;
  14233. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14234. mg_snprintf(NULL,
  14235. NULL, /* No truncation check for ebuf */
  14236. ebuf,
  14237. ebuf_len,
  14238. "Can not create mutex");
  14239. #if !defined(NO_SSL)
  14240. SSL_CTX_free(conn->client_ssl_ctx);
  14241. #endif
  14242. closesocket(sock);
  14243. mg_free(conn);
  14244. return NULL;
  14245. }
  14246. #if !defined(NO_SSL)
  14247. if (use_ssl) {
  14248. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14249. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14250. * SSL_CTX_set_verify call is needed to switch off server
  14251. * certificate checking, which is off by default in OpenSSL and
  14252. * on in yaSSL. */
  14253. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14254. * SSL_VERIFY_PEER, verify_ssl_server); */
  14255. if (client_options->client_cert) {
  14256. if (!ssl_use_pem_file(&common_client_context,
  14257. &(common_client_context.dd),
  14258. client_options->client_cert,
  14259. NULL)) {
  14260. mg_snprintf(NULL,
  14261. NULL, /* No truncation check for ebuf */
  14262. ebuf,
  14263. ebuf_len,
  14264. "Can not use SSL client certificate");
  14265. SSL_CTX_free(conn->client_ssl_ctx);
  14266. closesocket(sock);
  14267. mg_free(conn);
  14268. return NULL;
  14269. }
  14270. }
  14271. if (client_options->server_cert) {
  14272. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14273. client_options->server_cert,
  14274. NULL);
  14275. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14276. } else {
  14277. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14278. }
  14279. if (!sslize(conn,
  14280. conn->client_ssl_ctx,
  14281. SSL_connect,
  14282. &(conn->phys_ctx->stop_flag),
  14283. client_options)) {
  14284. mg_snprintf(NULL,
  14285. NULL, /* No truncation check for ebuf */
  14286. ebuf,
  14287. ebuf_len,
  14288. "SSL connection error");
  14289. SSL_CTX_free(conn->client_ssl_ctx);
  14290. closesocket(sock);
  14291. mg_free(conn);
  14292. return NULL;
  14293. }
  14294. }
  14295. #endif
  14296. if (0 != set_non_blocking_mode(sock)) {
  14297. mg_cry_internal(conn,
  14298. "Cannot set non-blocking mode for client %s:%i",
  14299. client_options->host,
  14300. client_options->port);
  14301. }
  14302. return conn;
  14303. }
  14304. CIVETWEB_API struct mg_connection *
  14305. mg_connect_client_secure(const struct mg_client_options *client_options,
  14306. char *error_buffer,
  14307. size_t error_buffer_size)
  14308. {
  14309. return mg_connect_client_impl(client_options,
  14310. 1,
  14311. error_buffer,
  14312. error_buffer_size);
  14313. }
  14314. struct mg_connection *
  14315. mg_connect_client(const char *host,
  14316. int port,
  14317. int use_ssl,
  14318. char *error_buffer,
  14319. size_t error_buffer_size)
  14320. {
  14321. struct mg_client_options opts;
  14322. memset(&opts, 0, sizeof(opts));
  14323. opts.host = host;
  14324. opts.port = port;
  14325. return mg_connect_client_impl(&opts,
  14326. use_ssl,
  14327. error_buffer,
  14328. error_buffer_size);
  14329. }
  14330. static const struct {
  14331. const char *proto;
  14332. size_t proto_len;
  14333. unsigned default_port;
  14334. } abs_uri_protocols[] = {{"http://", 7, 80},
  14335. {"https://", 8, 443},
  14336. {"ws://", 5, 80},
  14337. {"wss://", 6, 443},
  14338. {NULL, 0, 0}};
  14339. /* Check if the uri is valid.
  14340. * return 0 for invalid uri,
  14341. * return 1 for *,
  14342. * return 2 for relative uri,
  14343. * return 3 for absolute uri without port,
  14344. * return 4 for absolute uri with port */
  14345. static int
  14346. get_uri_type(const char *uri)
  14347. {
  14348. int i;
  14349. const char *hostend, *portbegin;
  14350. char *portend;
  14351. unsigned long port;
  14352. /* According to the HTTP standard
  14353. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14354. * URI can be an asterisk (*) or should start with slash (relative uri),
  14355. * or it should start with the protocol (absolute uri). */
  14356. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14357. /* asterisk */
  14358. return 1;
  14359. }
  14360. /* Valid URIs according to RFC 3986
  14361. * (https://www.ietf.org/rfc/rfc3986.txt)
  14362. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14363. * and unreserved characters A-Z a-z 0-9 and -._~
  14364. * and % encoded symbols.
  14365. */
  14366. for (i = 0; uri[i] != 0; i++) {
  14367. if (uri[i] < 33) {
  14368. /* control characters and spaces are invalid */
  14369. return 0;
  14370. }
  14371. if (uri[i] > 126) {
  14372. /* non-ascii characters must be % encoded */
  14373. return 0;
  14374. } else {
  14375. switch (uri[i]) {
  14376. case '"': /* 34 */
  14377. case '<': /* 60 */
  14378. case '>': /* 62 */
  14379. case '\\': /* 92 */
  14380. case '^': /* 94 */
  14381. case '`': /* 96 */
  14382. case '{': /* 123 */
  14383. case '|': /* 124 */
  14384. case '}': /* 125 */
  14385. return 0;
  14386. default:
  14387. /* character is ok */
  14388. break;
  14389. }
  14390. }
  14391. }
  14392. /* A relative uri starts with a / character */
  14393. if (uri[0] == '/') {
  14394. /* relative uri */
  14395. return 2;
  14396. }
  14397. /* It could be an absolute uri: */
  14398. /* This function only checks if the uri is valid, not if it is
  14399. * addressing the current server. So civetweb can also be used
  14400. * as a proxy server. */
  14401. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14402. if (mg_strncasecmp(uri,
  14403. abs_uri_protocols[i].proto,
  14404. abs_uri_protocols[i].proto_len)
  14405. == 0) {
  14406. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14407. if (!hostend) {
  14408. return 0;
  14409. }
  14410. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14411. if (!portbegin) {
  14412. return 3;
  14413. }
  14414. port = strtoul(portbegin + 1, &portend, 10);
  14415. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14416. return 0;
  14417. }
  14418. return 4;
  14419. }
  14420. }
  14421. return 0;
  14422. }
  14423. /* Return NULL or the relative uri at the current server */
  14424. static const char *
  14425. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14426. {
  14427. const char *server_domain;
  14428. size_t server_domain_len;
  14429. size_t request_domain_len = 0;
  14430. unsigned long port = 0;
  14431. int i, auth_domain_check_enabled;
  14432. const char *hostbegin = NULL;
  14433. const char *hostend = NULL;
  14434. const char *portbegin;
  14435. char *portend;
  14436. auth_domain_check_enabled =
  14437. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14438. /* DNS is case insensitive, so use case insensitive string compare here
  14439. */
  14440. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14441. if (mg_strncasecmp(uri,
  14442. abs_uri_protocols[i].proto,
  14443. abs_uri_protocols[i].proto_len)
  14444. == 0) {
  14445. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14446. hostend = strchr(hostbegin, '/');
  14447. if (!hostend) {
  14448. return 0;
  14449. }
  14450. portbegin = strchr(hostbegin, ':');
  14451. if ((!portbegin) || (portbegin > hostend)) {
  14452. port = abs_uri_protocols[i].default_port;
  14453. request_domain_len = (size_t)(hostend - hostbegin);
  14454. } else {
  14455. port = strtoul(portbegin + 1, &portend, 10);
  14456. if ((portend != hostend) || (port <= 0)
  14457. || !is_valid_port(port)) {
  14458. return 0;
  14459. }
  14460. request_domain_len = (size_t)(portbegin - hostbegin);
  14461. }
  14462. /* protocol found, port set */
  14463. break;
  14464. }
  14465. }
  14466. if (!port) {
  14467. /* port remains 0 if the protocol is not found */
  14468. return 0;
  14469. }
  14470. /* Check if the request is directed to a different server. */
  14471. /* First check if the port is the same (IPv4 and IPv6). */
  14472. #if defined(USE_IPV6)
  14473. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14474. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14475. /* Request is directed to a different port */
  14476. return 0;
  14477. }
  14478. } else
  14479. #endif
  14480. {
  14481. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14482. /* Request is directed to a different port */
  14483. return 0;
  14484. }
  14485. }
  14486. /* Finally check if the server corresponds to the authentication
  14487. * domain of the server (the server domain).
  14488. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14489. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14490. * but do not allow substrings (like
  14491. * http://notmydomain.com/path/file.ext
  14492. * or http://mydomain.com.fake/path/file.ext).
  14493. */
  14494. if (auth_domain_check_enabled) {
  14495. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14496. server_domain_len = strlen(server_domain);
  14497. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14498. return 0;
  14499. }
  14500. if ((request_domain_len == server_domain_len)
  14501. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14502. /* Request is directed to this server - full name match. */
  14503. } else {
  14504. if (request_domain_len < (server_domain_len + 2)) {
  14505. /* Request is directed to another server: The server name
  14506. * is longer than the request name.
  14507. * Drop this case here to avoid overflows in the
  14508. * following checks. */
  14509. return 0;
  14510. }
  14511. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14512. /* Request is directed to another server: It could be a
  14513. * substring
  14514. * like notmyserver.com */
  14515. return 0;
  14516. }
  14517. if (0
  14518. != memcmp(server_domain,
  14519. hostbegin + request_domain_len - server_domain_len,
  14520. server_domain_len)) {
  14521. /* Request is directed to another server:
  14522. * The server name is different. */
  14523. return 0;
  14524. }
  14525. }
  14526. }
  14527. return hostend;
  14528. }
  14529. static int
  14530. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14531. {
  14532. if (ebuf_len > 0) {
  14533. ebuf[0] = '\0';
  14534. }
  14535. *err = 0;
  14536. reset_per_request_attributes(conn);
  14537. if (!conn) {
  14538. mg_snprintf(conn,
  14539. NULL, /* No truncation check for ebuf */
  14540. ebuf,
  14541. ebuf_len,
  14542. "%s",
  14543. "Internal error");
  14544. *err = 500;
  14545. return 0;
  14546. }
  14547. /* Set the time the request was received. This value should be used for
  14548. * timeouts. */
  14549. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14550. conn->request_len =
  14551. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14552. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14553. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14554. mg_snprintf(conn,
  14555. NULL, /* No truncation check for ebuf */
  14556. ebuf,
  14557. ebuf_len,
  14558. "%s",
  14559. "Invalid message size");
  14560. *err = 500;
  14561. return 0;
  14562. }
  14563. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14564. mg_snprintf(conn,
  14565. NULL, /* No truncation check for ebuf */
  14566. ebuf,
  14567. ebuf_len,
  14568. "%s",
  14569. "Message too large");
  14570. *err = 413;
  14571. return 0;
  14572. }
  14573. if (conn->request_len <= 0) {
  14574. if (conn->data_len > 0) {
  14575. mg_snprintf(conn,
  14576. NULL, /* No truncation check for ebuf */
  14577. ebuf,
  14578. ebuf_len,
  14579. "%s",
  14580. "Malformed message");
  14581. *err = 400;
  14582. } else {
  14583. /* Server did not recv anything -> just close the connection */
  14584. conn->must_close = 1;
  14585. mg_snprintf(conn,
  14586. NULL, /* No truncation check for ebuf */
  14587. ebuf,
  14588. ebuf_len,
  14589. "%s",
  14590. "No data received");
  14591. *err = 0;
  14592. }
  14593. return 0;
  14594. }
  14595. return 1;
  14596. }
  14597. static int
  14598. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14599. {
  14600. const char *cl;
  14601. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14602. return 0;
  14603. }
  14604. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14605. <= 0) {
  14606. mg_snprintf(conn,
  14607. NULL, /* No truncation check for ebuf */
  14608. ebuf,
  14609. ebuf_len,
  14610. "%s",
  14611. "Bad request");
  14612. *err = 400;
  14613. return 0;
  14614. }
  14615. /* Message is a valid request */
  14616. /* Is there a "host" ? */
  14617. conn->host = alloc_get_host(conn);
  14618. if (!conn->host) {
  14619. mg_snprintf(conn,
  14620. NULL, /* No truncation check for ebuf */
  14621. ebuf,
  14622. ebuf_len,
  14623. "%s",
  14624. "Bad request: Host mismatch");
  14625. *err = 400;
  14626. return 0;
  14627. }
  14628. /* Do we know the content length? */
  14629. if ((cl = get_header(conn->request_info.http_headers,
  14630. conn->request_info.num_headers,
  14631. "Content-Length"))
  14632. != NULL) {
  14633. /* Request/response has content length set */
  14634. char *endptr = NULL;
  14635. conn->content_len = strtoll(cl, &endptr, 10);
  14636. if (endptr == cl) {
  14637. mg_snprintf(conn,
  14638. NULL, /* No truncation check for ebuf */
  14639. ebuf,
  14640. ebuf_len,
  14641. "%s",
  14642. "Bad request");
  14643. *err = 411;
  14644. return 0;
  14645. }
  14646. /* Publish the content length back to the request info. */
  14647. conn->request_info.content_length = conn->content_len;
  14648. } else if ((cl = get_header(conn->request_info.http_headers,
  14649. conn->request_info.num_headers,
  14650. "Transfer-Encoding"))
  14651. != NULL
  14652. && !mg_strcasecmp(cl, "chunked")) {
  14653. conn->is_chunked = 1;
  14654. conn->content_len = -1; /* unknown content length */
  14655. } else {
  14656. const struct mg_http_method_info *meth =
  14657. get_http_method_info(conn->request_info.request_method);
  14658. if (!meth) {
  14659. /* No valid HTTP method */
  14660. mg_snprintf(conn,
  14661. NULL, /* No truncation check for ebuf */
  14662. ebuf,
  14663. ebuf_len,
  14664. "%s",
  14665. "Bad request");
  14666. *err = 411;
  14667. return 0;
  14668. }
  14669. if (meth->request_has_body) {
  14670. /* POST or PUT request without content length set */
  14671. conn->content_len = -1; /* unknown content length */
  14672. } else {
  14673. /* Other request */
  14674. conn->content_len = 0; /* No content */
  14675. }
  14676. }
  14677. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14678. return 1;
  14679. }
  14680. /* conn is assumed to be valid in this internal function */
  14681. static int
  14682. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14683. {
  14684. const char *cl;
  14685. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14686. return 0;
  14687. }
  14688. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14689. <= 0) {
  14690. mg_snprintf(conn,
  14691. NULL, /* No truncation check for ebuf */
  14692. ebuf,
  14693. ebuf_len,
  14694. "%s",
  14695. "Bad response");
  14696. *err = 400;
  14697. return 0;
  14698. }
  14699. /* Message is a valid response */
  14700. /* Do we know the content length? */
  14701. if ((cl = get_header(conn->response_info.http_headers,
  14702. conn->response_info.num_headers,
  14703. "Content-Length"))
  14704. != NULL) {
  14705. /* Request/response has content length set */
  14706. char *endptr = NULL;
  14707. conn->content_len = strtoll(cl, &endptr, 10);
  14708. if (endptr == cl) {
  14709. mg_snprintf(conn,
  14710. NULL, /* No truncation check for ebuf */
  14711. ebuf,
  14712. ebuf_len,
  14713. "%s",
  14714. "Bad request");
  14715. *err = 411;
  14716. return 0;
  14717. }
  14718. /* Publish the content length back to the response info. */
  14719. conn->response_info.content_length = conn->content_len;
  14720. /* TODO: check if it is still used in response_info */
  14721. conn->request_info.content_length = conn->content_len;
  14722. } else if ((cl = get_header(conn->response_info.http_headers,
  14723. conn->response_info.num_headers,
  14724. "Transfer-Encoding"))
  14725. != NULL
  14726. && !mg_strcasecmp(cl, "chunked")) {
  14727. conn->is_chunked = 1;
  14728. conn->content_len = -1; /* unknown content length */
  14729. } else {
  14730. conn->content_len = -1; /* unknown content length */
  14731. }
  14732. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14733. return 1;
  14734. }
  14735. int
  14736. mg_get_response(struct mg_connection *conn,
  14737. char *ebuf,
  14738. size_t ebuf_len,
  14739. int timeout)
  14740. {
  14741. int err, ret;
  14742. char txt[32]; /* will not overflow */
  14743. char *save_timeout;
  14744. char *new_timeout;
  14745. if (ebuf_len > 0) {
  14746. ebuf[0] = '\0';
  14747. }
  14748. if (!conn) {
  14749. mg_snprintf(conn,
  14750. NULL, /* No truncation check for ebuf */
  14751. ebuf,
  14752. ebuf_len,
  14753. "%s",
  14754. "Parameter error");
  14755. return -1;
  14756. }
  14757. /* Implementation of API function for HTTP clients */
  14758. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14759. if (timeout >= 0) {
  14760. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14761. new_timeout = txt;
  14762. /* Not required for non-blocking sockets.
  14763. set_sock_timeout(conn->client.sock, timeout);
  14764. */
  14765. } else {
  14766. new_timeout = NULL;
  14767. }
  14768. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14769. ret = get_response(conn, ebuf, ebuf_len, &err);
  14770. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14771. #if defined(MG_LEGACY_INTERFACE)
  14772. /* TODO: 1) uri is deprecated;
  14773. * 2) here, ri.uri is the http response code */
  14774. conn->request_info.uri = conn->request_info.request_uri;
  14775. #endif
  14776. conn->request_info.local_uri = conn->request_info.request_uri;
  14777. /* TODO (mid): Define proper return values - maybe return length?
  14778. * For the first test use <0 for error and >0 for OK */
  14779. return (ret == 0) ? -1 : +1;
  14780. }
  14781. struct mg_connection *
  14782. mg_download(const char *host,
  14783. int port,
  14784. int use_ssl,
  14785. char *ebuf,
  14786. size_t ebuf_len,
  14787. const char *fmt,
  14788. ...)
  14789. {
  14790. struct mg_connection *conn;
  14791. va_list ap;
  14792. int i;
  14793. int reqerr;
  14794. if (ebuf_len > 0) {
  14795. ebuf[0] = '\0';
  14796. }
  14797. va_start(ap, fmt);
  14798. /* open a connection */
  14799. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14800. if (conn != NULL) {
  14801. i = mg_vprintf(conn, fmt, ap);
  14802. if (i <= 0) {
  14803. mg_snprintf(conn,
  14804. NULL, /* No truncation check for ebuf */
  14805. ebuf,
  14806. ebuf_len,
  14807. "%s",
  14808. "Error sending request");
  14809. } else {
  14810. get_response(conn, ebuf, ebuf_len, &reqerr);
  14811. #if defined(MG_LEGACY_INTERFACE)
  14812. /* TODO: 1) uri is deprecated;
  14813. * 2) here, ri.uri is the http response code */
  14814. conn->request_info.uri = conn->request_info.request_uri;
  14815. #endif
  14816. conn->request_info.local_uri = conn->request_info.request_uri;
  14817. }
  14818. }
  14819. /* if an error occurred, close the connection */
  14820. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14821. mg_close_connection(conn);
  14822. conn = NULL;
  14823. }
  14824. va_end(ap);
  14825. return conn;
  14826. }
  14827. struct websocket_client_thread_data {
  14828. struct mg_connection *conn;
  14829. mg_websocket_data_handler data_handler;
  14830. mg_websocket_close_handler close_handler;
  14831. void *callback_data;
  14832. };
  14833. #if defined(USE_WEBSOCKET)
  14834. #if defined(_WIN32)
  14835. static unsigned __stdcall websocket_client_thread(void *data)
  14836. #else
  14837. static void *
  14838. websocket_client_thread(void *data)
  14839. #endif
  14840. {
  14841. struct websocket_client_thread_data *cdata =
  14842. (struct websocket_client_thread_data *)data;
  14843. #if !defined(_WIN32)
  14844. struct sigaction sa;
  14845. /* Ignore SIGPIPE */
  14846. memset(&sa, 0, sizeof(sa));
  14847. sa.sa_handler = SIG_IGN;
  14848. sigaction(SIGPIPE, &sa, NULL);
  14849. #endif
  14850. mg_set_thread_name("ws-clnt");
  14851. if (cdata->conn->phys_ctx) {
  14852. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14853. /* 3 indicates a websocket client thread */
  14854. /* TODO: check if conn->phys_ctx can be set */
  14855. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14856. 3);
  14857. }
  14858. }
  14859. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14860. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14861. if (cdata->close_handler != NULL) {
  14862. cdata->close_handler(cdata->conn, cdata->callback_data);
  14863. }
  14864. /* The websocket_client context has only this thread. If it runs out,
  14865. set the stop_flag to 2 (= "stopped"). */
  14866. cdata->conn->phys_ctx->stop_flag = 2;
  14867. mg_free((void *)cdata);
  14868. #if defined(_WIN32)
  14869. return 0;
  14870. #else
  14871. return NULL;
  14872. #endif
  14873. }
  14874. #endif
  14875. struct mg_connection *
  14876. mg_connect_websocket_client(const char *host,
  14877. int port,
  14878. int use_ssl,
  14879. char *error_buffer,
  14880. size_t error_buffer_size,
  14881. const char *path,
  14882. const char *origin,
  14883. mg_websocket_data_handler data_func,
  14884. mg_websocket_close_handler close_func,
  14885. void *user_data)
  14886. {
  14887. struct mg_connection *conn = NULL;
  14888. #if defined(USE_WEBSOCKET)
  14889. struct mg_context *newctx = NULL;
  14890. struct websocket_client_thread_data *thread_data;
  14891. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14892. static const char *handshake_req;
  14893. if (origin != NULL) {
  14894. handshake_req = "GET %s HTTP/1.1\r\n"
  14895. "Host: %s\r\n"
  14896. "Upgrade: websocket\r\n"
  14897. "Connection: Upgrade\r\n"
  14898. "Sec-WebSocket-Key: %s\r\n"
  14899. "Sec-WebSocket-Version: 13\r\n"
  14900. "Origin: %s\r\n"
  14901. "\r\n";
  14902. } else {
  14903. handshake_req = "GET %s HTTP/1.1\r\n"
  14904. "Host: %s\r\n"
  14905. "Upgrade: websocket\r\n"
  14906. "Connection: Upgrade\r\n"
  14907. "Sec-WebSocket-Key: %s\r\n"
  14908. "Sec-WebSocket-Version: 13\r\n"
  14909. "\r\n";
  14910. }
  14911. #if defined(__clang__)
  14912. #pragma clang diagnostic push
  14913. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14914. #endif
  14915. /* Establish the client connection and request upgrade */
  14916. conn = mg_download(host,
  14917. port,
  14918. use_ssl,
  14919. error_buffer,
  14920. error_buffer_size,
  14921. handshake_req,
  14922. path,
  14923. host,
  14924. magic,
  14925. origin);
  14926. #if defined(__clang__)
  14927. #pragma clang diagnostic pop
  14928. #endif
  14929. /* Connection object will be null if something goes wrong */
  14930. if (conn == NULL) {
  14931. if (!*error_buffer) {
  14932. /* There should be already an error message */
  14933. mg_snprintf(conn,
  14934. NULL, /* No truncation check for ebuf */
  14935. error_buffer,
  14936. error_buffer_size,
  14937. "Unexpected error");
  14938. }
  14939. return NULL;
  14940. }
  14941. if (conn->response_info.status_code != 101) {
  14942. /* We sent an "upgrade" request. For a correct websocket
  14943. * protocol handshake, we expect a "101 Continue" response.
  14944. * Otherwise it is a protocol violation. Maybe the HTTP
  14945. * Server does not know websockets. */
  14946. if (!*error_buffer) {
  14947. /* set an error, if not yet set */
  14948. mg_snprintf(conn,
  14949. NULL, /* No truncation check for ebuf */
  14950. error_buffer,
  14951. error_buffer_size,
  14952. "Unexpected server reply");
  14953. }
  14954. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14955. mg_free(conn);
  14956. return NULL;
  14957. }
  14958. /* For client connections, mg_context is fake. Since we need to set a
  14959. * callback function, we need to create a copy and modify it. */
  14960. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14961. if (!newctx) {
  14962. DEBUG_TRACE("%s\r\n", "Out of memory");
  14963. mg_free(conn);
  14964. return NULL;
  14965. }
  14966. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14967. newctx->user_data = user_data;
  14968. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14969. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14970. newctx->worker_threadids =
  14971. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14972. sizeof(pthread_t),
  14973. newctx);
  14974. conn->phys_ctx = newctx;
  14975. conn->dom_ctx = &(newctx->dd);
  14976. thread_data = (struct websocket_client_thread_data *)
  14977. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14978. if (!thread_data) {
  14979. DEBUG_TRACE("%s\r\n", "Out of memory");
  14980. mg_free(newctx);
  14981. mg_free(conn);
  14982. return NULL;
  14983. }
  14984. thread_data->conn = conn;
  14985. thread_data->data_handler = data_func;
  14986. thread_data->close_handler = close_func;
  14987. thread_data->callback_data = user_data;
  14988. /* Start a thread to read the websocket client connection
  14989. * This thread will automatically stop when mg_disconnect is
  14990. * called on the client connection */
  14991. if (mg_start_thread_with_id(websocket_client_thread,
  14992. (void *)thread_data,
  14993. newctx->worker_threadids)
  14994. != 0) {
  14995. mg_free((void *)thread_data);
  14996. mg_free((void *)newctx->worker_threadids);
  14997. mg_free((void *)newctx);
  14998. mg_free((void *)conn);
  14999. conn = NULL;
  15000. DEBUG_TRACE("%s",
  15001. "Websocket client connect thread could not be started\r\n");
  15002. }
  15003. #else
  15004. /* Appease "unused parameter" warnings */
  15005. (void)host;
  15006. (void)port;
  15007. (void)use_ssl;
  15008. (void)error_buffer;
  15009. (void)error_buffer_size;
  15010. (void)path;
  15011. (void)origin;
  15012. (void)user_data;
  15013. (void)data_func;
  15014. (void)close_func;
  15015. #endif
  15016. return conn;
  15017. }
  15018. /* Prepare connection data structure */
  15019. static void
  15020. init_connection(struct mg_connection *conn)
  15021. {
  15022. /* Is keep alive allowed by the server */
  15023. int keep_alive_enabled =
  15024. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15025. if (!keep_alive_enabled) {
  15026. conn->must_close = 1;
  15027. }
  15028. /* Important: on new connection, reset the receiving buffer. Credit
  15029. * goes to crule42. */
  15030. conn->data_len = 0;
  15031. conn->handled_requests = 0;
  15032. mg_set_user_connection_data(conn, NULL);
  15033. #if defined(USE_SERVER_STATS)
  15034. conn->conn_state = 2; /* init */
  15035. #endif
  15036. /* call the init_connection callback if assigned */
  15037. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15038. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15039. void *conn_data = NULL;
  15040. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15041. mg_set_user_connection_data(conn, conn_data);
  15042. }
  15043. }
  15044. }
  15045. /* Process a connection - may handle multiple requests
  15046. * using the same connection.
  15047. * Must be called with a valid connection (conn and
  15048. * conn->phys_ctx must be valid).
  15049. */
  15050. static void
  15051. process_new_connection(struct mg_connection *conn)
  15052. {
  15053. struct mg_request_info *ri = &conn->request_info;
  15054. int keep_alive, discard_len;
  15055. char ebuf[100];
  15056. const char *hostend;
  15057. int reqerr, uri_type;
  15058. #if defined(USE_SERVER_STATS)
  15059. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15060. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15061. if (mcon > (conn->phys_ctx->max_connections)) {
  15062. /* could use atomic compare exchange, but this
  15063. * seems overkill for statistics data */
  15064. conn->phys_ctx->max_connections = mcon;
  15065. }
  15066. #endif
  15067. init_connection(conn);
  15068. DEBUG_TRACE("Start processing connection from %s",
  15069. conn->request_info.remote_addr);
  15070. /* Loop over multiple requests sent using the same connection
  15071. * (while "keep alive"). */
  15072. do {
  15073. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15074. conn->handled_requests + 1);
  15075. #if defined(USE_SERVER_STATS)
  15076. conn->conn_state = 3; /* ready */
  15077. #endif
  15078. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15079. /* The request sent by the client could not be understood by
  15080. * the server, or it was incomplete or a timeout. Send an
  15081. * error message and close the connection. */
  15082. if (reqerr > 0) {
  15083. DEBUG_ASSERT(ebuf[0] != '\0');
  15084. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15085. }
  15086. } else if (strcmp(ri->http_version, "1.0")
  15087. && strcmp(ri->http_version, "1.1")) {
  15088. mg_snprintf(conn,
  15089. NULL, /* No truncation check for ebuf */
  15090. ebuf,
  15091. sizeof(ebuf),
  15092. "Bad HTTP version: [%s]",
  15093. ri->http_version);
  15094. mg_send_http_error(conn, 505, "%s", ebuf);
  15095. }
  15096. if (ebuf[0] == '\0') {
  15097. uri_type = get_uri_type(conn->request_info.request_uri);
  15098. switch (uri_type) {
  15099. case 1:
  15100. /* Asterisk */
  15101. conn->request_info.local_uri = NULL;
  15102. break;
  15103. case 2:
  15104. /* relative uri */
  15105. conn->request_info.local_uri = conn->request_info.request_uri;
  15106. break;
  15107. case 3:
  15108. case 4:
  15109. /* absolute uri (with/without port) */
  15110. hostend = get_rel_url_at_current_server(
  15111. conn->request_info.request_uri, conn);
  15112. if (hostend) {
  15113. conn->request_info.local_uri = hostend;
  15114. } else {
  15115. conn->request_info.local_uri = NULL;
  15116. }
  15117. break;
  15118. default:
  15119. mg_snprintf(conn,
  15120. NULL, /* No truncation check for ebuf */
  15121. ebuf,
  15122. sizeof(ebuf),
  15123. "Invalid URI");
  15124. mg_send_http_error(conn, 400, "%s", ebuf);
  15125. conn->request_info.local_uri = NULL;
  15126. break;
  15127. }
  15128. #if defined(MG_LEGACY_INTERFACE)
  15129. /* Legacy before split into local_uri and request_uri */
  15130. conn->request_info.uri = conn->request_info.local_uri;
  15131. #endif
  15132. }
  15133. DEBUG_TRACE("http: %s, error: %s",
  15134. (ri->http_version ? ri->http_version : "none"),
  15135. (ebuf[0] ? ebuf : "none"));
  15136. if (ebuf[0] == '\0') {
  15137. if (conn->request_info.local_uri) {
  15138. /* handle request to local server */
  15139. #if defined(USE_SERVER_STATS)
  15140. conn->conn_state = 4; /* processing */
  15141. #endif
  15142. handle_request(conn);
  15143. #if defined(USE_SERVER_STATS)
  15144. conn->conn_state = 5; /* processed */
  15145. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15146. conn->consumed_content);
  15147. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15148. conn->num_bytes_sent);
  15149. #endif
  15150. DEBUG_TRACE("%s", "handle_request done");
  15151. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15152. conn->phys_ctx->callbacks.end_request(conn,
  15153. conn->status_code);
  15154. DEBUG_TRACE("%s", "end_request callback done");
  15155. }
  15156. log_access(conn);
  15157. } else {
  15158. /* TODO: handle non-local request (PROXY) */
  15159. conn->must_close = 1;
  15160. }
  15161. } else {
  15162. conn->must_close = 1;
  15163. }
  15164. if (ri->remote_user != NULL) {
  15165. mg_free((void *)ri->remote_user);
  15166. /* Important! When having connections with and without auth
  15167. * would cause double free and then crash */
  15168. ri->remote_user = NULL;
  15169. }
  15170. /* NOTE(lsm): order is important here. should_keep_alive() call
  15171. * is using parsed request, which will be invalid after
  15172. * memmove's below.
  15173. * Therefore, memorize should_keep_alive() result now for later
  15174. * use in loop exit condition. */
  15175. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15176. && (conn->content_len >= 0);
  15177. /* Discard all buffered data for this request */
  15178. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15179. && ((conn->request_len + conn->content_len)
  15180. < (int64_t)conn->data_len))
  15181. ? (int)(conn->request_len + conn->content_len)
  15182. : conn->data_len;
  15183. DEBUG_ASSERT(discard_len >= 0);
  15184. if (discard_len < 0) {
  15185. DEBUG_TRACE("internal error: discard_len = %li",
  15186. (long int)discard_len);
  15187. break;
  15188. }
  15189. conn->data_len -= discard_len;
  15190. if (conn->data_len > 0) {
  15191. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15192. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15193. }
  15194. DEBUG_ASSERT(conn->data_len >= 0);
  15195. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15196. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15197. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15198. (long int)conn->data_len,
  15199. (long int)conn->buf_size);
  15200. break;
  15201. }
  15202. conn->handled_requests++;
  15203. } while (keep_alive);
  15204. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15205. conn->request_info.remote_addr,
  15206. difftime(time(NULL), conn->conn_birth_time));
  15207. close_connection(conn);
  15208. #if defined(USE_SERVER_STATS)
  15209. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15210. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15211. #endif
  15212. }
  15213. #if defined(ALTERNATIVE_QUEUE)
  15214. static void
  15215. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15216. {
  15217. unsigned int i;
  15218. while (!ctx->stop_flag) {
  15219. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15220. /* find a free worker slot and signal it */
  15221. if (ctx->client_socks[i].in_use == 2) {
  15222. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15223. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15224. ctx->client_socks[i] = *sp;
  15225. ctx->client_socks[i].in_use = 1;
  15226. /* socket has been moved to the consumer */
  15227. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15228. (void)event_signal(ctx->client_wait_events[i]);
  15229. return;
  15230. }
  15231. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15232. }
  15233. }
  15234. /* queue is full */
  15235. mg_sleep(1);
  15236. }
  15237. /* must consume */
  15238. set_blocking_mode(sp->sock);
  15239. closesocket(sp->sock);
  15240. }
  15241. static int
  15242. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15243. {
  15244. DEBUG_TRACE("%s", "going idle");
  15245. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15246. ctx->client_socks[thread_index].in_use = 2;
  15247. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15248. event_wait(ctx->client_wait_events[thread_index]);
  15249. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15250. *sp = ctx->client_socks[thread_index];
  15251. if (ctx->stop_flag) {
  15252. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15253. if (sp->in_use == 1) {
  15254. /* must consume */
  15255. set_blocking_mode(sp->sock);
  15256. closesocket(sp->sock);
  15257. }
  15258. return 0;
  15259. }
  15260. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15261. if (sp->in_use == 1) {
  15262. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15263. return 1;
  15264. }
  15265. /* must not reach here */
  15266. DEBUG_ASSERT(0);
  15267. return 0;
  15268. }
  15269. #else /* ALTERNATIVE_QUEUE */
  15270. /* Worker threads take accepted socket from the queue */
  15271. static int
  15272. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15273. {
  15274. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15275. (void)thread_index;
  15276. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15277. DEBUG_TRACE("%s", "going idle");
  15278. /* If the queue is empty, wait. We're idle at this point. */
  15279. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15280. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15281. }
  15282. /* If we're stopping, sq_head may be equal to sq_tail. */
  15283. if (ctx->sq_head > ctx->sq_tail) {
  15284. /* Copy socket from the queue and increment tail */
  15285. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15286. ctx->sq_tail++;
  15287. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15288. /* Wrap pointers if needed */
  15289. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15290. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15291. ctx->sq_head -= QUEUE_SIZE(ctx);
  15292. }
  15293. }
  15294. (void)pthread_cond_signal(&ctx->sq_empty);
  15295. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15296. return !ctx->stop_flag;
  15297. #undef QUEUE_SIZE
  15298. }
  15299. /* Master thread adds accepted socket to a queue */
  15300. static void
  15301. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15302. {
  15303. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15304. if (!ctx) {
  15305. return;
  15306. }
  15307. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15308. /* If the queue is full, wait */
  15309. while ((ctx->stop_flag == 0)
  15310. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15311. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15312. }
  15313. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15314. /* Copy socket to the queue and increment head */
  15315. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15316. ctx->sq_head++;
  15317. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15318. }
  15319. (void)pthread_cond_signal(&ctx->sq_full);
  15320. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15321. #undef QUEUE_SIZE
  15322. }
  15323. #endif /* ALTERNATIVE_QUEUE */
  15324. struct worker_thread_args {
  15325. struct mg_context *ctx;
  15326. int index;
  15327. };
  15328. static void *
  15329. worker_thread_run(struct worker_thread_args *thread_args)
  15330. {
  15331. struct mg_context *ctx = thread_args->ctx;
  15332. struct mg_connection *conn;
  15333. struct mg_workerTLS tls;
  15334. #if defined(MG_LEGACY_INTERFACE)
  15335. uint32_t addr;
  15336. #endif
  15337. mg_set_thread_name("worker");
  15338. tls.is_master = 0;
  15339. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15340. #if defined(_WIN32)
  15341. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15342. #endif
  15343. /* Initialize thread local storage before calling any callback */
  15344. pthread_setspecific(sTlsKey, &tls);
  15345. if (ctx->callbacks.init_thread) {
  15346. /* call init_thread for a worker thread (type 1) */
  15347. ctx->callbacks.init_thread(ctx, 1);
  15348. }
  15349. /* Connection structure has been pre-allocated */
  15350. if (((int)thread_args->index < 0)
  15351. || ((unsigned)thread_args->index
  15352. >= (unsigned)ctx->cfg_worker_threads)) {
  15353. mg_cry_internal(fc(ctx),
  15354. "Internal error: Invalid worker index %i",
  15355. (int)thread_args->index);
  15356. return NULL;
  15357. }
  15358. conn = ctx->worker_connections + thread_args->index;
  15359. /* Request buffers are not pre-allocated. They are private to the
  15360. * request and do not contain any state information that might be
  15361. * of interest to anyone observing a server status. */
  15362. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15363. if (conn->buf == NULL) {
  15364. mg_cry_internal(fc(ctx),
  15365. "Out of memory: Cannot allocate buffer for worker %i",
  15366. (int)thread_args->index);
  15367. return NULL;
  15368. }
  15369. conn->buf_size = (int)ctx->max_request_size;
  15370. conn->phys_ctx = ctx;
  15371. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15372. conn->host = NULL; /* until we have more information. */
  15373. conn->thread_index = thread_args->index;
  15374. conn->request_info.user_data = ctx->user_data;
  15375. /* Allocate a mutex for this connection to allow communication both
  15376. * within the request handler and from elsewhere in the application
  15377. */
  15378. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15379. mg_free(conn->buf);
  15380. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15381. return NULL;
  15382. }
  15383. #if defined(USE_SERVER_STATS)
  15384. conn->conn_state = 1; /* not consumed */
  15385. #endif
  15386. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15387. * signal sq_empty condvar to wake up the master waiting in
  15388. * produce_socket() */
  15389. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  15390. conn->conn_birth_time = time(NULL);
  15391. /* Fill in IP, port info early so even if SSL setup below fails,
  15392. * error handler would have the corresponding info.
  15393. * Thanks to Johannes Winkelmann for the patch.
  15394. */
  15395. #if defined(USE_IPV6)
  15396. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15397. conn->request_info.remote_port =
  15398. ntohs(conn->client.rsa.sin6.sin6_port);
  15399. } else
  15400. #endif
  15401. {
  15402. conn->request_info.remote_port =
  15403. ntohs(conn->client.rsa.sin.sin_port);
  15404. }
  15405. sockaddr_to_string(conn->request_info.remote_addr,
  15406. sizeof(conn->request_info.remote_addr),
  15407. &conn->client.rsa);
  15408. DEBUG_TRACE("Start processing connection from %s",
  15409. conn->request_info.remote_addr);
  15410. conn->request_info.is_ssl = conn->client.is_ssl;
  15411. if (conn->client.is_ssl) {
  15412. #if !defined(NO_SSL)
  15413. /* HTTPS connection */
  15414. if (sslize(conn,
  15415. conn->dom_ctx->ssl_ctx,
  15416. SSL_accept,
  15417. &(conn->phys_ctx->stop_flag),
  15418. NULL)) {
  15419. /* conn->dom_ctx is set in get_request */
  15420. /* Get SSL client certificate information (if set) */
  15421. ssl_get_client_cert_info(conn);
  15422. /* process HTTPS connection */
  15423. process_new_connection(conn);
  15424. /* Free client certificate info */
  15425. if (conn->request_info.client_cert) {
  15426. mg_free((void *)(conn->request_info.client_cert->subject));
  15427. mg_free((void *)(conn->request_info.client_cert->issuer));
  15428. mg_free((void *)(conn->request_info.client_cert->serial));
  15429. mg_free((void *)(conn->request_info.client_cert->finger));
  15430. /* Free certificate memory */
  15431. X509_free(
  15432. (X509 *)conn->request_info.client_cert->peer_cert);
  15433. conn->request_info.client_cert->peer_cert = 0;
  15434. conn->request_info.client_cert->subject = 0;
  15435. conn->request_info.client_cert->issuer = 0;
  15436. conn->request_info.client_cert->serial = 0;
  15437. conn->request_info.client_cert->finger = 0;
  15438. mg_free(conn->request_info.client_cert);
  15439. conn->request_info.client_cert = 0;
  15440. }
  15441. } else {
  15442. /* make sure the connection is cleaned up on SSL failure */
  15443. close_connection(conn);
  15444. }
  15445. #endif
  15446. } else {
  15447. /* process HTTP connection */
  15448. process_new_connection(conn);
  15449. }
  15450. DEBUG_TRACE("%s", "Connection closed");
  15451. }
  15452. pthread_setspecific(sTlsKey, NULL);
  15453. #if defined(_WIN32)
  15454. CloseHandle(tls.pthread_cond_helper_mutex);
  15455. #endif
  15456. pthread_mutex_destroy(&conn->mutex);
  15457. /* Free the request buffer. */
  15458. conn->buf_size = 0;
  15459. mg_free(conn->buf);
  15460. conn->buf = NULL;
  15461. #if defined(USE_SERVER_STATS)
  15462. conn->conn_state = 9; /* done */
  15463. #endif
  15464. DEBUG_TRACE("%s", "exiting");
  15465. return NULL;
  15466. }
  15467. /* Threads have different return types on Windows and Unix. */
  15468. #if defined(_WIN32)
  15469. static unsigned __stdcall worker_thread(void *thread_func_param)
  15470. {
  15471. struct worker_thread_args *pwta =
  15472. (struct worker_thread_args *)thread_func_param;
  15473. worker_thread_run(pwta);
  15474. mg_free(thread_func_param);
  15475. return 0;
  15476. }
  15477. #else
  15478. static void *
  15479. worker_thread(void *thread_func_param)
  15480. {
  15481. struct worker_thread_args *pwta =
  15482. (struct worker_thread_args *)thread_func_param;
  15483. struct sigaction sa;
  15484. /* Ignore SIGPIPE */
  15485. memset(&sa, 0, sizeof(sa));
  15486. sa.sa_handler = SIG_IGN;
  15487. sigaction(SIGPIPE, &sa, NULL);
  15488. worker_thread_run(pwta);
  15489. mg_free(thread_func_param);
  15490. return NULL;
  15491. }
  15492. #endif /* _WIN32 */
  15493. /* This is an internal function, thus all arguments are expected to be
  15494. * valid - a NULL check is not required. */
  15495. static void
  15496. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15497. {
  15498. struct socket so;
  15499. char src_addr[IP_ADDR_STR_LEN];
  15500. socklen_t len = sizeof(so.rsa);
  15501. int on = 1;
  15502. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15503. == INVALID_SOCKET) {
  15504. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15505. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15506. mg_cry_internal(fc(ctx),
  15507. "%s: %s is not allowed to connect",
  15508. __func__,
  15509. src_addr);
  15510. closesocket(so.sock);
  15511. } else {
  15512. /* Put so socket structure into the queue */
  15513. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15514. set_close_on_exec(so.sock, fc(ctx));
  15515. so.is_ssl = listener->is_ssl;
  15516. so.ssl_redir = listener->ssl_redir;
  15517. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15518. mg_cry_internal(fc(ctx),
  15519. "%s: getsockname() failed: %s",
  15520. __func__,
  15521. strerror(ERRNO));
  15522. }
  15523. /* Set TCP keep-alive. This is needed because if HTTP-level
  15524. * keep-alive
  15525. * is enabled, and client resets the connection, server won't get
  15526. * TCP FIN or RST and will keep the connection open forever. With
  15527. * TCP keep-alive, next keep-alive handshake will figure out that
  15528. * the client is down and will close the server end.
  15529. * Thanks to Igor Klopov who suggested the patch. */
  15530. if (setsockopt(so.sock,
  15531. SOL_SOCKET,
  15532. SO_KEEPALIVE,
  15533. (SOCK_OPT_TYPE)&on,
  15534. sizeof(on))
  15535. != 0) {
  15536. mg_cry_internal(
  15537. fc(ctx),
  15538. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15539. __func__,
  15540. strerror(ERRNO));
  15541. }
  15542. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15543. * to effectively fill up the underlying IP packet payload and
  15544. * reduce the overhead of sending lots of small buffers. However
  15545. * this hurts the server's throughput (ie. operations per second)
  15546. * when HTTP 1.1 persistent connections are used and the responses
  15547. * are relatively small (eg. less than 1400 bytes).
  15548. */
  15549. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15550. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15551. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15552. mg_cry_internal(
  15553. fc(ctx),
  15554. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15555. __func__,
  15556. strerror(ERRNO));
  15557. }
  15558. }
  15559. /* We are using non-blocking sockets. Thus, the
  15560. * set_sock_timeout(so.sock, timeout);
  15561. * call is no longer required. */
  15562. /* The "non blocking" property should already be
  15563. * inherited from the parent socket. Set it for
  15564. * non-compliant socket implementations. */
  15565. set_non_blocking_mode(so.sock);
  15566. so.in_use = 0;
  15567. produce_socket(ctx, &so);
  15568. }
  15569. }
  15570. static void
  15571. master_thread_run(void *thread_func_param)
  15572. {
  15573. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15574. struct mg_workerTLS tls;
  15575. struct mg_pollfd *pfd;
  15576. unsigned int i;
  15577. unsigned int workerthreadcount;
  15578. if (!ctx) {
  15579. return;
  15580. }
  15581. mg_set_thread_name("master");
  15582. /* Increase priority of the master thread */
  15583. #if defined(_WIN32)
  15584. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15585. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15586. int min_prio = sched_get_priority_min(SCHED_RR);
  15587. int max_prio = sched_get_priority_max(SCHED_RR);
  15588. if ((min_prio >= 0) && (max_prio >= 0)
  15589. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15590. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15591. struct sched_param sched_param = {0};
  15592. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15593. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15594. }
  15595. #endif
  15596. /* Initialize thread local storage */
  15597. #if defined(_WIN32)
  15598. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15599. #endif
  15600. tls.is_master = 1;
  15601. pthread_setspecific(sTlsKey, &tls);
  15602. if (ctx->callbacks.init_thread) {
  15603. /* Callback for the master thread (type 0) */
  15604. ctx->callbacks.init_thread(ctx, 0);
  15605. }
  15606. /* Server starts *now* */
  15607. ctx->start_time = time(NULL);
  15608. /* Start the server */
  15609. pfd = ctx->listening_socket_fds;
  15610. while (ctx->stop_flag == 0) {
  15611. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15612. pfd[i].fd = ctx->listening_sockets[i].sock;
  15613. pfd[i].events = POLLIN;
  15614. }
  15615. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15616. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15617. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15618. * successful poll, and POLLIN is defined as
  15619. * (POLLRDNORM | POLLRDBAND)
  15620. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15621. * pfd[i].revents == POLLIN. */
  15622. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15623. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15624. }
  15625. }
  15626. }
  15627. }
  15628. /* Here stop_flag is 1 - Initiate shutdown. */
  15629. DEBUG_TRACE("%s", "stopping workers");
  15630. /* Stop signal received: somebody called mg_stop. Quit. */
  15631. close_all_listening_sockets(ctx);
  15632. /* Wakeup workers that are waiting for connections to handle. */
  15633. #if defined(ALTERNATIVE_QUEUE)
  15634. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15635. event_signal(ctx->client_wait_events[i]);
  15636. }
  15637. #else
  15638. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15639. pthread_cond_broadcast(&ctx->sq_full);
  15640. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15641. #endif
  15642. /* Join all worker threads to avoid leaking threads. */
  15643. workerthreadcount = ctx->cfg_worker_threads;
  15644. for (i = 0; i < workerthreadcount; i++) {
  15645. if (ctx->worker_threadids[i] != 0) {
  15646. mg_join_thread(ctx->worker_threadids[i]);
  15647. }
  15648. }
  15649. #if defined(USE_LUA)
  15650. /* Free Lua state of lua background task */
  15651. if (ctx->lua_background_state) {
  15652. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15653. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15654. if (lua_istable(lstate, -1)) {
  15655. reg_boolean(lstate, "shutdown", 1);
  15656. lua_pop(lstate, 1);
  15657. mg_sleep(2);
  15658. }
  15659. lua_close(lstate);
  15660. ctx->lua_background_state = 0;
  15661. }
  15662. #endif
  15663. DEBUG_TRACE("%s", "exiting");
  15664. #if defined(_WIN32)
  15665. CloseHandle(tls.pthread_cond_helper_mutex);
  15666. #endif
  15667. pthread_setspecific(sTlsKey, NULL);
  15668. /* Signal mg_stop() that we're done.
  15669. * WARNING: This must be the very last thing this
  15670. * thread does, as ctx becomes invalid after this line. */
  15671. ctx->stop_flag = 2;
  15672. }
  15673. /* Threads have different return types on Windows and Unix. */
  15674. #if defined(_WIN32)
  15675. static unsigned __stdcall master_thread(void *thread_func_param)
  15676. {
  15677. master_thread_run(thread_func_param);
  15678. return 0;
  15679. }
  15680. #else
  15681. static void *
  15682. master_thread(void *thread_func_param)
  15683. {
  15684. struct sigaction sa;
  15685. /* Ignore SIGPIPE */
  15686. memset(&sa, 0, sizeof(sa));
  15687. sa.sa_handler = SIG_IGN;
  15688. sigaction(SIGPIPE, &sa, NULL);
  15689. master_thread_run(thread_func_param);
  15690. return NULL;
  15691. }
  15692. #endif /* _WIN32 */
  15693. static void
  15694. free_context(struct mg_context *ctx)
  15695. {
  15696. int i;
  15697. struct mg_handler_info *tmp_rh;
  15698. if (ctx == NULL) {
  15699. return;
  15700. }
  15701. if (ctx->callbacks.exit_context) {
  15702. ctx->callbacks.exit_context(ctx);
  15703. }
  15704. /* All threads exited, no sync is needed. Destroy thread mutex and
  15705. * condvars
  15706. */
  15707. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15708. #if defined(ALTERNATIVE_QUEUE)
  15709. mg_free(ctx->client_socks);
  15710. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15711. event_destroy(ctx->client_wait_events[i]);
  15712. }
  15713. mg_free(ctx->client_wait_events);
  15714. #else
  15715. (void)pthread_cond_destroy(&ctx->sq_empty);
  15716. (void)pthread_cond_destroy(&ctx->sq_full);
  15717. #endif
  15718. /* Destroy other context global data structures mutex */
  15719. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15720. #if defined(USE_TIMERS)
  15721. timers_exit(ctx);
  15722. #endif
  15723. /* Deallocate config parameters */
  15724. for (i = 0; i < NUM_OPTIONS; i++) {
  15725. if (ctx->dd.config[i] != NULL) {
  15726. #if defined(_MSC_VER)
  15727. #pragma warning(suppress : 6001)
  15728. #endif
  15729. mg_free(ctx->dd.config[i]);
  15730. }
  15731. }
  15732. /* Deallocate request handlers */
  15733. while (ctx->dd.handlers) {
  15734. tmp_rh = ctx->dd.handlers;
  15735. ctx->dd.handlers = tmp_rh->next;
  15736. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15737. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15738. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15739. }
  15740. mg_free(tmp_rh->uri);
  15741. mg_free(tmp_rh);
  15742. }
  15743. #if !defined(NO_SSL)
  15744. /* Deallocate SSL context */
  15745. if (ctx->dd.ssl_ctx != NULL) {
  15746. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15747. int callback_ret =
  15748. (ctx->callbacks.external_ssl_ctx == NULL)
  15749. ? 0
  15750. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15751. if (callback_ret == 0) {
  15752. SSL_CTX_free(ctx->dd.ssl_ctx);
  15753. }
  15754. /* else: ignore error and ommit SSL_CTX_free in case
  15755. * callback_ret is 1 */
  15756. }
  15757. #endif /* !NO_SSL */
  15758. /* Deallocate worker thread ID array */
  15759. if (ctx->worker_threadids != NULL) {
  15760. mg_free(ctx->worker_threadids);
  15761. }
  15762. /* Deallocate worker thread ID array */
  15763. if (ctx->worker_connections != NULL) {
  15764. mg_free(ctx->worker_connections);
  15765. }
  15766. /* deallocate system name string */
  15767. mg_free(ctx->systemName);
  15768. /* Deallocate context itself */
  15769. mg_free(ctx);
  15770. }
  15771. void
  15772. mg_stop(struct mg_context *ctx)
  15773. {
  15774. pthread_t mt;
  15775. if (!ctx) {
  15776. return;
  15777. }
  15778. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15779. * two threads is not allowed. */
  15780. mt = ctx->masterthreadid;
  15781. if (mt == 0) {
  15782. return;
  15783. }
  15784. ctx->masterthreadid = 0;
  15785. /* Set stop flag, so all threads know they have to exit. */
  15786. ctx->stop_flag = 1;
  15787. /* Wait until everything has stopped. */
  15788. while (ctx->stop_flag != 2) {
  15789. (void)mg_sleep(10);
  15790. }
  15791. mg_join_thread(mt);
  15792. free_context(ctx);
  15793. #if defined(_WIN32)
  15794. (void)WSACleanup();
  15795. #endif /* _WIN32 */
  15796. }
  15797. static void
  15798. get_system_name(char **sysName)
  15799. {
  15800. #if defined(_WIN32)
  15801. #if !defined(__SYMBIAN32__)
  15802. #if defined(_WIN32_WCE)
  15803. *sysName = mg_strdup("WinCE");
  15804. #else
  15805. char name[128];
  15806. DWORD dwVersion = 0;
  15807. DWORD dwMajorVersion = 0;
  15808. DWORD dwMinorVersion = 0;
  15809. DWORD dwBuild = 0;
  15810. BOOL wowRet, isWoW = FALSE;
  15811. #if defined(_MSC_VER)
  15812. #pragma warning(push)
  15813. /* GetVersion was declared deprecated */
  15814. #pragma warning(disable : 4996)
  15815. #endif
  15816. dwVersion = GetVersion();
  15817. #if defined(_MSC_VER)
  15818. #pragma warning(pop)
  15819. #endif
  15820. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15821. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15822. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15823. (void)dwBuild;
  15824. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15825. sprintf(name,
  15826. "Windows %u.%u%s",
  15827. (unsigned)dwMajorVersion,
  15828. (unsigned)dwMinorVersion,
  15829. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15830. *sysName = mg_strdup(name);
  15831. #endif
  15832. #else
  15833. *sysName = mg_strdup("Symbian");
  15834. #endif
  15835. #else
  15836. struct utsname name;
  15837. memset(&name, 0, sizeof(name));
  15838. uname(&name);
  15839. *sysName = mg_strdup(name.sysname);
  15840. #endif
  15841. }
  15842. struct mg_context *
  15843. mg_start(const struct mg_callbacks *callbacks,
  15844. void *user_data,
  15845. const char **options)
  15846. {
  15847. struct mg_context *ctx;
  15848. const char *name, *value, *default_value;
  15849. int idx, ok, workerthreadcount;
  15850. unsigned int i;
  15851. int itmp;
  15852. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15853. struct mg_workerTLS tls;
  15854. #if defined(_WIN32)
  15855. WSADATA data;
  15856. WSAStartup(MAKEWORD(2, 2), &data);
  15857. #endif /* _WIN32 */
  15858. /* Allocate context and initialize reasonable general case defaults. */
  15859. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15860. return NULL;
  15861. }
  15862. /* Random number generator will initialize at the first call */
  15863. ctx->dd.auth_nonce_mask =
  15864. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15865. if (mg_init_library_called == 0) {
  15866. /* Legacy INIT, if mg_start is called without mg_init_library.
  15867. * Note: This may cause a memory leak */
  15868. const char *ports_option =
  15869. config_options[LISTENING_PORTS].default_value;
  15870. if (options) {
  15871. const char **run_options = options;
  15872. const char *optname = config_options[LISTENING_PORTS].name;
  15873. /* Try to find the "listening_ports" option */
  15874. while (*run_options) {
  15875. if (!strcmp(*run_options, optname)) {
  15876. ports_option = run_options[1];
  15877. }
  15878. run_options += 2;
  15879. }
  15880. }
  15881. if (is_ssl_port_used(ports_option)) {
  15882. /* Initialize with SSL support */
  15883. mg_init_library(MG_FEATURES_TLS);
  15884. } else {
  15885. /* Initialize without SSL support */
  15886. mg_init_library(MG_FEATURES_DEFAULT);
  15887. }
  15888. }
  15889. tls.is_master = -1;
  15890. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15891. #if defined(_WIN32)
  15892. tls.pthread_cond_helper_mutex = NULL;
  15893. #endif
  15894. pthread_setspecific(sTlsKey, &tls);
  15895. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15896. #if !defined(ALTERNATIVE_QUEUE)
  15897. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15898. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15899. #endif
  15900. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15901. if (!ok) {
  15902. /* Fatal error - abort start. However, this situation should never
  15903. * occur in practice. */
  15904. mg_cry_internal(fc(ctx),
  15905. "%s",
  15906. "Cannot initialize thread synchronization objects");
  15907. mg_free(ctx);
  15908. pthread_setspecific(sTlsKey, NULL);
  15909. return NULL;
  15910. }
  15911. if (callbacks) {
  15912. ctx->callbacks = *callbacks;
  15913. exit_callback = callbacks->exit_context;
  15914. ctx->callbacks.exit_context = 0;
  15915. }
  15916. ctx->user_data = user_data;
  15917. ctx->dd.handlers = NULL;
  15918. ctx->dd.next = NULL;
  15919. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15920. ctx->dd.shared_lua_websockets = NULL;
  15921. #endif
  15922. /* Store options */
  15923. while (options && (name = *options++) != NULL) {
  15924. if ((idx = get_option_index(name)) == -1) {
  15925. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15926. free_context(ctx);
  15927. pthread_setspecific(sTlsKey, NULL);
  15928. return NULL;
  15929. } else if ((value = *options++) == NULL) {
  15930. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15931. free_context(ctx);
  15932. pthread_setspecific(sTlsKey, NULL);
  15933. return NULL;
  15934. }
  15935. if (ctx->dd.config[idx] != NULL) {
  15936. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15937. mg_free(ctx->dd.config[idx]);
  15938. }
  15939. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15940. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15941. }
  15942. /* Set default value if needed */
  15943. for (i = 0; config_options[i].name != NULL; i++) {
  15944. default_value = config_options[i].default_value;
  15945. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15946. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15947. }
  15948. }
  15949. /* Request size option */
  15950. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15951. if (itmp < 1024) {
  15952. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15953. free_context(ctx);
  15954. pthread_setspecific(sTlsKey, NULL);
  15955. return NULL;
  15956. }
  15957. ctx->max_request_size = (unsigned)itmp;
  15958. /* Worker thread count option */
  15959. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15960. if (workerthreadcount > MAX_WORKER_THREADS) {
  15961. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15962. free_context(ctx);
  15963. pthread_setspecific(sTlsKey, NULL);
  15964. return NULL;
  15965. }
  15966. if (workerthreadcount <= 0) {
  15967. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15968. free_context(ctx);
  15969. pthread_setspecific(sTlsKey, NULL);
  15970. return NULL;
  15971. }
  15972. /* Document root */
  15973. #if defined(NO_FILES)
  15974. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15975. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15976. free_context(ctx);
  15977. pthread_setspecific(sTlsKey, NULL);
  15978. return NULL;
  15979. }
  15980. #endif
  15981. get_system_name(&ctx->systemName);
  15982. #if defined(USE_LUA)
  15983. /* If a Lua background script has been configured, start it. */
  15984. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15985. char ebuf[256];
  15986. struct vec opt_vec;
  15987. struct vec eq_vec;
  15988. const char *sparams;
  15989. lua_State *state = mg_prepare_lua_context_script(
  15990. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15991. if (!state) {
  15992. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15993. free_context(ctx);
  15994. pthread_setspecific(sTlsKey, NULL);
  15995. return NULL;
  15996. }
  15997. ctx->lua_background_state = (void *)state;
  15998. lua_newtable(state);
  15999. reg_boolean(state, "shutdown", 0);
  16000. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16001. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16002. reg_llstring(
  16003. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16004. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16005. break;
  16006. }
  16007. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16008. } else {
  16009. ctx->lua_background_state = 0;
  16010. }
  16011. #endif
  16012. /* NOTE(lsm): order is important here. SSL certificates must
  16013. * be initialized before listening ports. UID must be set last. */
  16014. if (!set_gpass_option(ctx, NULL) ||
  16015. #if !defined(NO_SSL)
  16016. !init_ssl_ctx(ctx, NULL) ||
  16017. #endif
  16018. !set_ports_option(ctx) ||
  16019. #if !defined(_WIN32)
  16020. !set_uid_option(ctx) ||
  16021. #endif
  16022. !set_acl_option(ctx)) {
  16023. free_context(ctx);
  16024. pthread_setspecific(sTlsKey, NULL);
  16025. return NULL;
  16026. }
  16027. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16028. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16029. sizeof(pthread_t),
  16030. ctx);
  16031. if (ctx->worker_threadids == NULL) {
  16032. mg_cry_internal(fc(ctx),
  16033. "%s",
  16034. "Not enough memory for worker thread ID array");
  16035. free_context(ctx);
  16036. pthread_setspecific(sTlsKey, NULL);
  16037. return NULL;
  16038. }
  16039. ctx->worker_connections =
  16040. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16041. sizeof(struct mg_connection),
  16042. ctx);
  16043. if (ctx->worker_connections == NULL) {
  16044. mg_cry_internal(fc(ctx),
  16045. "%s",
  16046. "Not enough memory for worker thread connection array");
  16047. free_context(ctx);
  16048. pthread_setspecific(sTlsKey, NULL);
  16049. return NULL;
  16050. }
  16051. #if defined(ALTERNATIVE_QUEUE)
  16052. ctx->client_wait_events =
  16053. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  16054. ctx->cfg_worker_threads,
  16055. ctx);
  16056. if (ctx->client_wait_events == NULL) {
  16057. mg_cry_internal(fc(ctx),
  16058. "%s",
  16059. "Not enough memory for worker event array");
  16060. mg_free(ctx->worker_threadids);
  16061. free_context(ctx);
  16062. pthread_setspecific(sTlsKey, NULL);
  16063. return NULL;
  16064. }
  16065. ctx->client_socks =
  16066. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16067. ctx->cfg_worker_threads,
  16068. ctx);
  16069. if (ctx->client_socks == NULL) {
  16070. mg_cry_internal(fc(ctx),
  16071. "%s",
  16072. "Not enough memory for worker socket array");
  16073. mg_free(ctx->client_wait_events);
  16074. mg_free(ctx->worker_threadids);
  16075. free_context(ctx);
  16076. pthread_setspecific(sTlsKey, NULL);
  16077. return NULL;
  16078. }
  16079. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16080. ctx->client_wait_events[i] = event_create();
  16081. if (ctx->client_wait_events[i] == 0) {
  16082. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  16083. while (i > 0) {
  16084. i--;
  16085. event_destroy(ctx->client_wait_events[i]);
  16086. }
  16087. mg_free(ctx->client_socks);
  16088. mg_free(ctx->client_wait_events);
  16089. mg_free(ctx->worker_threadids);
  16090. free_context(ctx);
  16091. pthread_setspecific(sTlsKey, NULL);
  16092. return NULL;
  16093. }
  16094. }
  16095. #endif
  16096. #if defined(USE_TIMERS)
  16097. if (timers_init(ctx) != 0) {
  16098. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  16099. free_context(ctx);
  16100. pthread_setspecific(sTlsKey, NULL);
  16101. return NULL;
  16102. }
  16103. #endif
  16104. /* Context has been created - init user libraries */
  16105. if (ctx->callbacks.init_context) {
  16106. ctx->callbacks.init_context(ctx);
  16107. }
  16108. ctx->callbacks.exit_context = exit_callback;
  16109. ctx->context_type = CONTEXT_SERVER; /* server context */
  16110. /* Start master (listening) thread */
  16111. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16112. /* Start worker threads */
  16113. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16114. struct worker_thread_args *wta = (struct worker_thread_args *)
  16115. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  16116. if (wta) {
  16117. wta->ctx = ctx;
  16118. wta->index = (int)i;
  16119. }
  16120. if ((wta == NULL)
  16121. || (mg_start_thread_with_id(worker_thread,
  16122. wta,
  16123. &ctx->worker_threadids[i])
  16124. != 0)) {
  16125. /* thread was not created */
  16126. if (wta != NULL) {
  16127. mg_free(wta);
  16128. }
  16129. if (i > 0) {
  16130. mg_cry_internal(fc(ctx),
  16131. "Cannot start worker thread %i: error %ld",
  16132. i + 1,
  16133. (long)ERRNO);
  16134. } else {
  16135. mg_cry_internal(fc(ctx),
  16136. "Cannot create threads: error %ld",
  16137. (long)ERRNO);
  16138. free_context(ctx);
  16139. pthread_setspecific(sTlsKey, NULL);
  16140. return NULL;
  16141. }
  16142. break;
  16143. }
  16144. }
  16145. pthread_setspecific(sTlsKey, NULL);
  16146. return ctx;
  16147. }
  16148. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16149. /* Add an additional domain to an already running web server. */
  16150. int
  16151. mg_start_domain(struct mg_context *ctx, const char **options)
  16152. {
  16153. const char *name;
  16154. const char *value;
  16155. const char *default_value;
  16156. struct mg_domain_context *new_dom;
  16157. struct mg_domain_context *dom;
  16158. int idx, i;
  16159. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16160. return -1;
  16161. }
  16162. new_dom = (struct mg_domain_context *)
  16163. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16164. if (!new_dom) {
  16165. /* Out of memory */
  16166. return -6;
  16167. }
  16168. /* Store options - TODO: unite duplicate code */
  16169. while (options && (name = *options++) != NULL) {
  16170. if ((idx = get_option_index(name)) == -1) {
  16171. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16172. mg_free(new_dom);
  16173. return -2;
  16174. } else if ((value = *options++) == NULL) {
  16175. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16176. mg_free(new_dom);
  16177. return -2;
  16178. }
  16179. if (new_dom->config[idx] != NULL) {
  16180. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16181. mg_free(new_dom->config[idx]);
  16182. }
  16183. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16184. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16185. }
  16186. /* Authentication domain is mandatory */
  16187. /* TODO: Maybe use a new option hostname? */
  16188. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16189. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16190. mg_free(new_dom);
  16191. return -4;
  16192. }
  16193. /* Set default value if needed. Take the config value from
  16194. * ctx as a default value. */
  16195. for (i = 0; config_options[i].name != NULL; i++) {
  16196. default_value = ctx->dd.config[i];
  16197. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16198. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16199. }
  16200. }
  16201. new_dom->handlers = NULL;
  16202. new_dom->next = NULL;
  16203. new_dom->nonce_count = 0;
  16204. new_dom->auth_nonce_mask =
  16205. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16206. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16207. new_dom->shared_lua_websockets = NULL;
  16208. #endif
  16209. if (!init_ssl_ctx(ctx, new_dom)) {
  16210. /* Init SSL failed */
  16211. mg_free(new_dom);
  16212. return -3;
  16213. }
  16214. /* Add element to linked list. */
  16215. mg_lock_context(ctx);
  16216. idx = 0;
  16217. dom = &(ctx->dd);
  16218. for (;;) {
  16219. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16220. dom->config[AUTHENTICATION_DOMAIN])) {
  16221. /* Domain collision */
  16222. mg_cry_internal(fc(ctx),
  16223. "domain %s already in use",
  16224. new_dom->config[AUTHENTICATION_DOMAIN]);
  16225. mg_free(new_dom);
  16226. return -5;
  16227. }
  16228. /* Count number of domains */
  16229. idx++;
  16230. if (dom->next == NULL) {
  16231. dom->next = new_dom;
  16232. break;
  16233. }
  16234. dom = dom->next;
  16235. }
  16236. mg_unlock_context(ctx);
  16237. /* Return domain number */
  16238. return idx;
  16239. }
  16240. #endif
  16241. /* Feature check API function */
  16242. unsigned
  16243. mg_check_feature(unsigned feature)
  16244. {
  16245. static const unsigned feature_set = 0
  16246. /* Set bits for available features according to API documentation.
  16247. * This bit mask is created at compile time, according to the active
  16248. * preprocessor defines. It is a single const value at runtime. */
  16249. #if !defined(NO_FILES)
  16250. | MG_FEATURES_FILES
  16251. #endif
  16252. #if !defined(NO_SSL)
  16253. | MG_FEATURES_SSL
  16254. #endif
  16255. #if !defined(NO_CGI)
  16256. | MG_FEATURES_CGI
  16257. #endif
  16258. #if defined(USE_IPV6)
  16259. | MG_FEATURES_IPV6
  16260. #endif
  16261. #if defined(USE_WEBSOCKET)
  16262. | MG_FEATURES_WEBSOCKET
  16263. #endif
  16264. #if defined(USE_LUA)
  16265. | MG_FEATURES_LUA
  16266. #endif
  16267. #if defined(USE_DUKTAPE)
  16268. | MG_FEATURES_SSJS
  16269. #endif
  16270. #if !defined(NO_CACHING)
  16271. | MG_FEATURES_CACHE
  16272. #endif
  16273. #if defined(USE_SERVER_STATS)
  16274. | MG_FEATURES_STATS
  16275. #endif
  16276. #if defined(USE_ZLIB)
  16277. | MG_FEATURES_COMPRESSION
  16278. #endif
  16279. /* Set some extra bits not defined in the API documentation.
  16280. * These bits may change without further notice. */
  16281. #if defined(MG_LEGACY_INTERFACE)
  16282. | 0x00008000u
  16283. #endif
  16284. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16285. | 0x00004000u
  16286. #endif
  16287. #if defined(MEMORY_DEBUGGING)
  16288. | 0x00001000u
  16289. #endif
  16290. #if defined(USE_TIMERS)
  16291. | 0x00020000u
  16292. #endif
  16293. #if !defined(NO_NONCE_CHECK)
  16294. | 0x00040000u
  16295. #endif
  16296. #if !defined(NO_POPEN)
  16297. | 0x00080000u
  16298. #endif
  16299. ;
  16300. return (feature & feature_set);
  16301. }
  16302. /* strcat with additional NULL check to avoid clang scan-build warning. */
  16303. #define strcat0(a, b) \
  16304. { \
  16305. if ((a != NULL) && (b != NULL)) { \
  16306. strcat(a, b); \
  16307. } \
  16308. }
  16309. /* Get system information. It can be printed or stored by the caller.
  16310. * Return the size of available information. */
  16311. static int
  16312. mg_get_system_info_impl(char *buffer, int buflen)
  16313. {
  16314. char block[256];
  16315. int system_info_length = 0;
  16316. #if defined(_WIN32)
  16317. const char *eol = "\r\n";
  16318. #else
  16319. const char *eol = "\n";
  16320. #endif
  16321. const char *eoobj = "}";
  16322. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16323. if ((buffer == NULL) || (buflen < 1)) {
  16324. buflen = 0;
  16325. } else {
  16326. *buffer = 0;
  16327. }
  16328. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16329. system_info_length += (int)strlen(block);
  16330. if (system_info_length < buflen) {
  16331. strcat0(buffer, block);
  16332. }
  16333. /* Server version */
  16334. {
  16335. const char *version = mg_version();
  16336. mg_snprintf(NULL,
  16337. NULL,
  16338. block,
  16339. sizeof(block),
  16340. "\"version\" : \"%s\",%s",
  16341. version,
  16342. eol);
  16343. system_info_length += (int)strlen(block);
  16344. if (system_info_length < buflen) {
  16345. strcat0(buffer, block);
  16346. }
  16347. }
  16348. /* System info */
  16349. {
  16350. #if defined(_WIN32)
  16351. DWORD dwVersion = 0;
  16352. DWORD dwMajorVersion = 0;
  16353. DWORD dwMinorVersion = 0;
  16354. SYSTEM_INFO si;
  16355. GetSystemInfo(&si);
  16356. #if defined(_MSC_VER)
  16357. #pragma warning(push)
  16358. /* GetVersion was declared deprecated */
  16359. #pragma warning(disable : 4996)
  16360. #endif
  16361. dwVersion = GetVersion();
  16362. #if defined(_MSC_VER)
  16363. #pragma warning(pop)
  16364. #endif
  16365. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16366. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16367. mg_snprintf(NULL,
  16368. NULL,
  16369. block,
  16370. sizeof(block),
  16371. "\"os\" : \"Windows %u.%u\",%s",
  16372. (unsigned)dwMajorVersion,
  16373. (unsigned)dwMinorVersion,
  16374. eol);
  16375. system_info_length += (int)strlen(block);
  16376. if (system_info_length < buflen) {
  16377. strcat0(buffer, block);
  16378. }
  16379. mg_snprintf(NULL,
  16380. NULL,
  16381. block,
  16382. sizeof(block),
  16383. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  16384. (unsigned)si.wProcessorArchitecture,
  16385. (unsigned)si.dwNumberOfProcessors,
  16386. (unsigned)si.dwActiveProcessorMask,
  16387. eol);
  16388. system_info_length += (int)strlen(block);
  16389. if (system_info_length < buflen) {
  16390. strcat0(buffer, block);
  16391. }
  16392. #else
  16393. struct utsname name;
  16394. memset(&name, 0, sizeof(name));
  16395. uname(&name);
  16396. mg_snprintf(NULL,
  16397. NULL,
  16398. block,
  16399. sizeof(block),
  16400. "\"os\" : \"%s %s (%s) - %s\",%s",
  16401. name.sysname,
  16402. name.version,
  16403. name.release,
  16404. name.machine,
  16405. eol);
  16406. system_info_length += (int)strlen(block);
  16407. if (system_info_length < buflen) {
  16408. strcat0(buffer, block);
  16409. }
  16410. #endif
  16411. }
  16412. /* Features */
  16413. {
  16414. mg_snprintf(NULL,
  16415. NULL,
  16416. block,
  16417. sizeof(block),
  16418. "\"features\" : %lu,%s"
  16419. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  16420. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16421. eol,
  16422. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16423. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16424. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16425. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16426. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16427. : "",
  16428. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16429. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16430. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16431. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  16432. eol);
  16433. system_info_length += (int)strlen(block);
  16434. if (system_info_length < buflen) {
  16435. strcat0(buffer, block);
  16436. }
  16437. #if defined(USE_LUA)
  16438. mg_snprintf(NULL,
  16439. NULL,
  16440. block,
  16441. sizeof(block),
  16442. "\"lua_version\" : \"%u (%s)\",%s",
  16443. (unsigned)LUA_VERSION_NUM,
  16444. LUA_RELEASE,
  16445. eol);
  16446. system_info_length += (int)strlen(block);
  16447. if (system_info_length < buflen) {
  16448. strcat0(buffer, block);
  16449. }
  16450. #endif
  16451. #if defined(USE_DUKTAPE)
  16452. mg_snprintf(NULL,
  16453. NULL,
  16454. block,
  16455. sizeof(block),
  16456. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  16457. (unsigned)DUK_VERSION / 10000,
  16458. ((unsigned)DUK_VERSION / 100) % 100,
  16459. (unsigned)DUK_VERSION % 100,
  16460. eol);
  16461. system_info_length += (int)strlen(block);
  16462. if (system_info_length < buflen) {
  16463. strcat0(buffer, block);
  16464. }
  16465. #endif
  16466. }
  16467. /* Build date */
  16468. {
  16469. #if defined(GCC_DIAGNOSTIC)
  16470. #if GCC_VERSION >= 40900
  16471. #pragma GCC diagnostic push
  16472. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16473. #pragma GCC diagnostic ignored "-Wdate-time"
  16474. #endif
  16475. #endif
  16476. mg_snprintf(NULL,
  16477. NULL,
  16478. block,
  16479. sizeof(block),
  16480. "\"build\" : \"%s\",%s",
  16481. __DATE__,
  16482. eol);
  16483. #if defined(GCC_DIAGNOSTIC)
  16484. #if GCC_VERSION >= 40900
  16485. #pragma GCC diagnostic pop
  16486. #endif
  16487. #endif
  16488. system_info_length += (int)strlen(block);
  16489. if (system_info_length < buflen) {
  16490. strcat0(buffer, block);
  16491. }
  16492. }
  16493. /* Compiler information */
  16494. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16495. {
  16496. #if defined(_MSC_VER)
  16497. mg_snprintf(NULL,
  16498. NULL,
  16499. block,
  16500. sizeof(block),
  16501. "\"compiler\" : \"MSC: %u (%u)\",%s",
  16502. (unsigned)_MSC_VER,
  16503. (unsigned)_MSC_FULL_VER,
  16504. eol);
  16505. system_info_length += (int)strlen(block);
  16506. if (system_info_length < buflen) {
  16507. strcat0(buffer, block);
  16508. }
  16509. #elif defined(__MINGW64__)
  16510. mg_snprintf(NULL,
  16511. NULL,
  16512. block,
  16513. sizeof(block),
  16514. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  16515. (unsigned)__MINGW64_VERSION_MAJOR,
  16516. (unsigned)__MINGW64_VERSION_MINOR,
  16517. eol);
  16518. system_info_length += (int)strlen(block);
  16519. if (system_info_length < buflen) {
  16520. strcat0(buffer, block);
  16521. }
  16522. mg_snprintf(NULL,
  16523. NULL,
  16524. block,
  16525. sizeof(block),
  16526. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16527. (unsigned)__MINGW32_MAJOR_VERSION,
  16528. (unsigned)__MINGW32_MINOR_VERSION,
  16529. eol);
  16530. system_info_length += (int)strlen(block);
  16531. if (system_info_length < buflen) {
  16532. strcat0(buffer, block);
  16533. }
  16534. #elif defined(__MINGW32__)
  16535. mg_snprintf(NULL,
  16536. NULL,
  16537. block,
  16538. sizeof(block),
  16539. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16540. (unsigned)__MINGW32_MAJOR_VERSION,
  16541. (unsigned)__MINGW32_MINOR_VERSION,
  16542. eol);
  16543. system_info_length += (int)strlen(block);
  16544. if (system_info_length < buflen) {
  16545. strcat0(buffer, block);
  16546. }
  16547. #elif defined(__clang__)
  16548. mg_snprintf(NULL,
  16549. NULL,
  16550. block,
  16551. sizeof(block),
  16552. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16553. __clang_major__,
  16554. __clang_minor__,
  16555. __clang_patchlevel__,
  16556. __clang_version__,
  16557. eol);
  16558. system_info_length += (int)strlen(block);
  16559. if (system_info_length < buflen) {
  16560. strcat0(buffer, block);
  16561. }
  16562. #elif defined(__GNUC__)
  16563. mg_snprintf(NULL,
  16564. NULL,
  16565. block,
  16566. sizeof(block),
  16567. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16568. (unsigned)__GNUC__,
  16569. (unsigned)__GNUC_MINOR__,
  16570. (unsigned)__GNUC_PATCHLEVEL__,
  16571. eol);
  16572. system_info_length += (int)strlen(block);
  16573. if (system_info_length < buflen) {
  16574. strcat0(buffer, block);
  16575. }
  16576. #elif defined(__INTEL_COMPILER)
  16577. mg_snprintf(NULL,
  16578. NULL,
  16579. block,
  16580. sizeof(block),
  16581. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16582. (unsigned)__INTEL_COMPILER,
  16583. eol);
  16584. system_info_length += (int)strlen(block);
  16585. if (system_info_length < buflen) {
  16586. strcat0(buffer, block);
  16587. }
  16588. #elif defined(__BORLANDC__)
  16589. mg_snprintf(NULL,
  16590. NULL,
  16591. block,
  16592. sizeof(block),
  16593. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16594. (unsigned)__BORLANDC__,
  16595. eol);
  16596. system_info_length += (int)strlen(block);
  16597. if (system_info_length < buflen) {
  16598. strcat0(buffer, block);
  16599. }
  16600. #elif defined(__SUNPRO_C)
  16601. mg_snprintf(NULL,
  16602. NULL,
  16603. block,
  16604. sizeof(block),
  16605. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16606. (unsigned)__SUNPRO_C,
  16607. eol);
  16608. system_info_length += (int)strlen(block);
  16609. if (system_info_length < buflen) {
  16610. strcat0(buffer, block);
  16611. }
  16612. #else
  16613. mg_snprintf(NULL,
  16614. NULL,
  16615. block,
  16616. sizeof(block),
  16617. "\"compiler\" : \"other\",%s",
  16618. eol);
  16619. system_info_length += (int)strlen(block);
  16620. if (system_info_length < buflen) {
  16621. strcat0(buffer, block);
  16622. }
  16623. #endif
  16624. }
  16625. /* Determine 32/64 bit data mode.
  16626. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16627. {
  16628. mg_snprintf(NULL,
  16629. NULL,
  16630. block,
  16631. sizeof(block),
  16632. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16633. "char:%u/%u, "
  16634. "ptr:%u, size:%u, time:%u\"%s",
  16635. (unsigned)sizeof(short),
  16636. (unsigned)sizeof(int),
  16637. (unsigned)sizeof(long),
  16638. (unsigned)sizeof(long long),
  16639. (unsigned)sizeof(float),
  16640. (unsigned)sizeof(double),
  16641. (unsigned)sizeof(long double),
  16642. (unsigned)sizeof(char),
  16643. (unsigned)sizeof(wchar_t),
  16644. (unsigned)sizeof(void *),
  16645. (unsigned)sizeof(size_t),
  16646. (unsigned)sizeof(time_t),
  16647. eol);
  16648. system_info_length += (int)strlen(block);
  16649. if (system_info_length < buflen) {
  16650. strcat0(buffer, block);
  16651. }
  16652. }
  16653. /* Terminate string */
  16654. if ((buflen > 0) && buffer && buffer[0]) {
  16655. if (system_info_length < buflen) {
  16656. strcat0(buffer, eoobj);
  16657. strcat0(buffer, eol);
  16658. }
  16659. }
  16660. system_info_length += reserved_len;
  16661. return system_info_length;
  16662. }
  16663. #if defined(USE_SERVER_STATS)
  16664. /* Get context information. It can be printed or stored by the caller.
  16665. * Return the size of available information. */
  16666. static int
  16667. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16668. {
  16669. char block[256];
  16670. int context_info_length = 0;
  16671. #if defined(_WIN32)
  16672. const char *eol = "\r\n";
  16673. #else
  16674. const char *eol = "\n";
  16675. #endif
  16676. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16677. const char *eoobj = "}";
  16678. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16679. if ((buffer == NULL) || (buflen < 1)) {
  16680. buflen = 0;
  16681. } else {
  16682. *buffer = 0;
  16683. }
  16684. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16685. context_info_length += (int)strlen(block);
  16686. if (context_info_length < buflen) {
  16687. strcat0(buffer, block);
  16688. }
  16689. if (ms) { /* <-- should be always true */
  16690. /* Memory information */
  16691. mg_snprintf(NULL,
  16692. NULL,
  16693. block,
  16694. sizeof(block),
  16695. "\"memory\" : {%s"
  16696. "\"blocks\" : %i,%s"
  16697. "\"used\" : %" INT64_FMT ",%s"
  16698. "\"maxUsed\" : %" INT64_FMT "%s"
  16699. "}%s%s",
  16700. eol,
  16701. ms->blockCount,
  16702. eol,
  16703. ms->totalMemUsed,
  16704. eol,
  16705. ms->maxMemUsed,
  16706. eol,
  16707. (ctx ? "," : ""),
  16708. eol);
  16709. context_info_length += (int)strlen(block);
  16710. if (context_info_length + reserved_len < buflen) {
  16711. strcat0(buffer, block);
  16712. }
  16713. }
  16714. if (ctx) {
  16715. /* Declare all variables at begin of the block, to comply
  16716. * with old C standards. */
  16717. char start_time_str[64] = {0};
  16718. char now_str[64] = {0};
  16719. time_t start_time = ctx->start_time;
  16720. time_t now = time(NULL);
  16721. /* Connections information */
  16722. mg_snprintf(NULL,
  16723. NULL,
  16724. block,
  16725. sizeof(block),
  16726. "\"connections\" : {%s"
  16727. "\"active\" : %i,%s"
  16728. "\"maxActive\" : %i,%s"
  16729. "\"total\" : %" INT64_FMT "%s"
  16730. "},%s",
  16731. eol,
  16732. ctx->active_connections,
  16733. eol,
  16734. ctx->max_connections,
  16735. eol,
  16736. ctx->total_connections,
  16737. eol,
  16738. eol);
  16739. context_info_length += (int)strlen(block);
  16740. if (context_info_length + reserved_len < buflen) {
  16741. strcat0(buffer, block);
  16742. }
  16743. /* Requests information */
  16744. mg_snprintf(NULL,
  16745. NULL,
  16746. block,
  16747. sizeof(block),
  16748. "\"requests\" : {%s"
  16749. "\"total\" : %" INT64_FMT "%s"
  16750. "},%s",
  16751. eol,
  16752. ctx->total_requests,
  16753. eol,
  16754. eol);
  16755. context_info_length += (int)strlen(block);
  16756. if (context_info_length + reserved_len < buflen) {
  16757. strcat0(buffer, block);
  16758. }
  16759. /* Data information */
  16760. mg_snprintf(NULL,
  16761. NULL,
  16762. block,
  16763. sizeof(block),
  16764. "\"data\" : {%s"
  16765. "\"read\" : %" INT64_FMT "%s,"
  16766. "\"written\" : %" INT64_FMT "%s"
  16767. "},%s",
  16768. eol,
  16769. ctx->total_data_read,
  16770. eol,
  16771. ctx->total_data_written,
  16772. eol,
  16773. eol);
  16774. context_info_length += (int)strlen(block);
  16775. if (context_info_length + reserved_len < buflen) {
  16776. strcat0(buffer, block);
  16777. }
  16778. /* Execution time information */
  16779. gmt_time_string(start_time_str,
  16780. sizeof(start_time_str) - 1,
  16781. &start_time);
  16782. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16783. mg_snprintf(NULL,
  16784. NULL,
  16785. block,
  16786. sizeof(block),
  16787. "\"time\" : {%s"
  16788. "\"uptime\" : %.0f,%s"
  16789. "\"start\" : \"%s\",%s"
  16790. "\"now\" : \"%s\"%s"
  16791. "}%s",
  16792. eol,
  16793. difftime(now, start_time),
  16794. eol,
  16795. start_time_str,
  16796. eol,
  16797. now_str,
  16798. eol,
  16799. eol);
  16800. context_info_length += (int)strlen(block);
  16801. if (context_info_length + reserved_len < buflen) {
  16802. strcat0(buffer, block);
  16803. }
  16804. }
  16805. /* Terminate string */
  16806. if ((buflen > 0) && buffer && buffer[0]) {
  16807. if (context_info_length < buflen) {
  16808. strcat0(buffer, eoobj);
  16809. strcat0(buffer, eol);
  16810. }
  16811. }
  16812. context_info_length += reserved_len;
  16813. return context_info_length;
  16814. }
  16815. #endif
  16816. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16817. /* Get connection information. It can be printed or stored by the caller.
  16818. * Return the size of available information. */
  16819. static int
  16820. mg_get_connection_info_impl(const struct mg_context *ctx,
  16821. int idx,
  16822. char *buffer,
  16823. int buflen)
  16824. {
  16825. const struct mg_connection *conn;
  16826. const struct mg_request_info *ri;
  16827. char block[256];
  16828. int connection_info_length = 0;
  16829. int state = 0;
  16830. const char *state_str = "unknown";
  16831. #if defined(_WIN32)
  16832. const char *eol = "\r\n";
  16833. #else
  16834. const char *eol = "\n";
  16835. #endif
  16836. const char *eoobj = "}";
  16837. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16838. if ((buffer == NULL) || (buflen < 1)) {
  16839. buflen = 0;
  16840. } else {
  16841. *buffer = 0;
  16842. }
  16843. if ((ctx == NULL) || (idx < 0)) {
  16844. /* Parameter error */
  16845. return 0;
  16846. }
  16847. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16848. /* Out of range */
  16849. return 0;
  16850. }
  16851. /* Take connection [idx]. This connection is not locked in
  16852. * any way, so some other thread might use it. */
  16853. conn = (ctx->worker_connections) + idx;
  16854. /* Initialize output string */
  16855. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16856. connection_info_length += (int)strlen(block);
  16857. if (connection_info_length < buflen) {
  16858. strcat0(buffer, block);
  16859. }
  16860. /* Init variables */
  16861. ri = &(conn->request_info);
  16862. #if defined(USE_SERVER_STATS)
  16863. state = conn->conn_state;
  16864. /* State as string */
  16865. switch (state) {
  16866. case 0:
  16867. state_str = "undefined";
  16868. break;
  16869. case 1:
  16870. state_str = "not used";
  16871. break;
  16872. case 2:
  16873. state_str = "init";
  16874. break;
  16875. case 3:
  16876. state_str = "ready";
  16877. break;
  16878. case 4:
  16879. state_str = "processing";
  16880. break;
  16881. case 5:
  16882. state_str = "processed";
  16883. break;
  16884. case 6:
  16885. state_str = "to close";
  16886. break;
  16887. case 7:
  16888. state_str = "closing";
  16889. break;
  16890. case 8:
  16891. state_str = "closed";
  16892. break;
  16893. case 9:
  16894. state_str = "done";
  16895. break;
  16896. }
  16897. #endif
  16898. /* Connection info */
  16899. if ((state >= 3) && (state < 9)) {
  16900. mg_snprintf(NULL,
  16901. NULL,
  16902. block,
  16903. sizeof(block),
  16904. "\"connection\" : {%s"
  16905. "\"remote\" : {%s"
  16906. "\"protocol\" : \"%s\",%s"
  16907. "\"addr\" : \"%s\",%s"
  16908. "\"port\" : %u%s"
  16909. "},%s"
  16910. "\"handled_requests\" : %u%s"
  16911. "},%s",
  16912. eol,
  16913. eol,
  16914. get_proto_name(conn),
  16915. eol,
  16916. ri->remote_addr,
  16917. eol,
  16918. ri->remote_port,
  16919. eol,
  16920. eol,
  16921. conn->handled_requests,
  16922. eol,
  16923. eol);
  16924. connection_info_length += (int)strlen(block);
  16925. if (connection_info_length + reserved_len < buflen) {
  16926. strcat0(buffer, block);
  16927. }
  16928. }
  16929. /* Request info */
  16930. if ((state >= 4) && (state < 6)) {
  16931. mg_snprintf(NULL,
  16932. NULL,
  16933. block,
  16934. sizeof(block),
  16935. "\"request_info\" : {%s"
  16936. "\"method\" : \"%s\",%s"
  16937. "\"uri\" : \"%s\",%s"
  16938. "\"query\" : %s%s%s%s"
  16939. "},%s",
  16940. eol,
  16941. ri->request_method,
  16942. eol,
  16943. ri->request_uri,
  16944. eol,
  16945. ri->query_string ? "\"" : "",
  16946. ri->query_string ? ri->query_string : "null",
  16947. ri->query_string ? "\"" : "",
  16948. eol,
  16949. eol);
  16950. connection_info_length += (int)strlen(block);
  16951. if (connection_info_length + reserved_len < buflen) {
  16952. strcat0(buffer, block);
  16953. }
  16954. }
  16955. /* Execution time information */
  16956. if ((state >= 2) && (state < 9)) {
  16957. char start_time_str[64] = {0};
  16958. char now_str[64] = {0};
  16959. time_t start_time = conn->conn_birth_time;
  16960. time_t now = time(NULL);
  16961. gmt_time_string(start_time_str,
  16962. sizeof(start_time_str) - 1,
  16963. &start_time);
  16964. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16965. mg_snprintf(NULL,
  16966. NULL,
  16967. block,
  16968. sizeof(block),
  16969. "\"time\" : {%s"
  16970. "\"uptime\" : %.0f,%s"
  16971. "\"start\" : \"%s\",%s"
  16972. "\"now\" : \"%s\"%s"
  16973. "},%s",
  16974. eol,
  16975. difftime(now, start_time),
  16976. eol,
  16977. start_time_str,
  16978. eol,
  16979. now_str,
  16980. eol,
  16981. eol);
  16982. connection_info_length += (int)strlen(block);
  16983. if (connection_info_length + reserved_len < buflen) {
  16984. strcat0(buffer, block);
  16985. }
  16986. }
  16987. /* Remote user name */
  16988. if ((ri->remote_user) && (state < 9)) {
  16989. mg_snprintf(NULL,
  16990. NULL,
  16991. block,
  16992. sizeof(block),
  16993. "\"user\" : {%s"
  16994. "\"name\" : \"%s\",%s"
  16995. "},%s",
  16996. eol,
  16997. ri->remote_user,
  16998. eol,
  16999. eol);
  17000. connection_info_length += (int)strlen(block);
  17001. if (connection_info_length + reserved_len < buflen) {
  17002. strcat0(buffer, block);
  17003. }
  17004. }
  17005. /* Data block */
  17006. if (state >= 3) {
  17007. mg_snprintf(NULL,
  17008. NULL,
  17009. block,
  17010. sizeof(block),
  17011. "\"data\" : {%s"
  17012. "\"read\" : %" INT64_FMT ",%s"
  17013. "\"written\" : %" INT64_FMT "%s"
  17014. "},%s",
  17015. eol,
  17016. conn->consumed_content,
  17017. eol,
  17018. conn->num_bytes_sent,
  17019. eol,
  17020. eol);
  17021. connection_info_length += (int)strlen(block);
  17022. if (connection_info_length + reserved_len < buflen) {
  17023. strcat0(buffer, block);
  17024. }
  17025. }
  17026. /* State */
  17027. mg_snprintf(NULL,
  17028. NULL,
  17029. block,
  17030. sizeof(block),
  17031. "\"state\" : \"%s\"%s",
  17032. state_str,
  17033. eol);
  17034. connection_info_length += (int)strlen(block);
  17035. if (connection_info_length + reserved_len < buflen) {
  17036. strcat0(buffer, block);
  17037. }
  17038. /* Terminate string */
  17039. if ((buflen > 0) && buffer && buffer[0]) {
  17040. if (connection_info_length < buflen) {
  17041. strcat0(buffer, eoobj);
  17042. strcat0(buffer, eol);
  17043. }
  17044. }
  17045. connection_info_length += reserved_len;
  17046. return connection_info_length;
  17047. }
  17048. #endif
  17049. /* Get system information. It can be printed or stored by the caller.
  17050. * Return the size of available information. */
  17051. int
  17052. mg_get_system_info(char *buffer, int buflen)
  17053. {
  17054. if ((buffer == NULL) || (buflen < 1)) {
  17055. return mg_get_system_info_impl(NULL, 0);
  17056. } else {
  17057. /* Reset buffer, so we can always use strcat. */
  17058. buffer[0] = 0;
  17059. return mg_get_system_info_impl(buffer, buflen);
  17060. }
  17061. }
  17062. /* Get context information. It can be printed or stored by the caller.
  17063. * Return the size of available information. */
  17064. int
  17065. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17066. {
  17067. #if defined(USE_SERVER_STATS)
  17068. if ((buffer == NULL) || (buflen < 1)) {
  17069. return mg_get_context_info_impl(ctx, NULL, 0);
  17070. } else {
  17071. /* Reset buffer, so we can always use strcat. */
  17072. buffer[0] = 0;
  17073. return mg_get_context_info_impl(ctx, buffer, buflen);
  17074. }
  17075. #else
  17076. (void)ctx;
  17077. if ((buffer != NULL) && (buflen > 0)) {
  17078. buffer[0] = 0;
  17079. }
  17080. return 0;
  17081. #endif
  17082. }
  17083. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17084. int
  17085. mg_get_connection_info(const struct mg_context *ctx,
  17086. int idx,
  17087. char *buffer,
  17088. int buflen)
  17089. {
  17090. if ((buffer == NULL) || (buflen < 1)) {
  17091. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  17092. } else {
  17093. /* Reset buffer, so we can always use strcat. */
  17094. buffer[0] = 0;
  17095. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  17096. }
  17097. }
  17098. #endif
  17099. /* Initialize this library. This function does not need to be thread safe.
  17100. */
  17101. unsigned
  17102. mg_init_library(unsigned features)
  17103. {
  17104. #if !defined(NO_SSL)
  17105. char ebuf[128];
  17106. #endif
  17107. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17108. unsigned features_inited = features_to_init;
  17109. if (mg_init_library_called <= 0) {
  17110. /* Not initialized yet */
  17111. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17112. return 0;
  17113. }
  17114. }
  17115. mg_global_lock();
  17116. if (mg_init_library_called <= 0) {
  17117. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17118. /* Fatal error - abort start. However, this situation should
  17119. * never occur in practice. */
  17120. mg_global_unlock();
  17121. return 0;
  17122. }
  17123. #if defined(_WIN32)
  17124. InitializeCriticalSection(&global_log_file_lock);
  17125. #endif
  17126. #if !defined(_WIN32)
  17127. pthread_mutexattr_init(&pthread_mutex_attr);
  17128. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17129. #endif
  17130. #if defined(USE_LUA)
  17131. lua_init_optional_libraries();
  17132. #endif
  17133. }
  17134. mg_global_unlock();
  17135. #if !defined(NO_SSL)
  17136. if (features_to_init & MG_FEATURES_SSL) {
  17137. if (!mg_ssl_initialized) {
  17138. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17139. mg_ssl_initialized = 1;
  17140. } else {
  17141. (void)ebuf;
  17142. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17143. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17144. }
  17145. } else {
  17146. /* ssl already initialized */
  17147. }
  17148. }
  17149. #endif
  17150. /* Start WinSock for Windows */
  17151. mg_global_lock();
  17152. if (mg_init_library_called <= 0) {
  17153. #if defined(_WIN32)
  17154. WSADATA data;
  17155. WSAStartup(MAKEWORD(2, 2), &data);
  17156. #endif /* _WIN32 */
  17157. mg_init_library_called = 1;
  17158. } else {
  17159. mg_init_library_called++;
  17160. }
  17161. mg_global_unlock();
  17162. return features_inited;
  17163. }
  17164. /* Un-initialize this library. */
  17165. unsigned
  17166. mg_exit_library(void)
  17167. {
  17168. if (mg_init_library_called <= 0) {
  17169. return 0;
  17170. }
  17171. mg_global_lock();
  17172. mg_init_library_called--;
  17173. if (mg_init_library_called == 0) {
  17174. #if defined(_WIN32)
  17175. (void)WSACleanup();
  17176. #endif /* _WIN32 */
  17177. #if !defined(NO_SSL)
  17178. if (mg_ssl_initialized) {
  17179. uninitialize_ssl();
  17180. mg_ssl_initialized = 0;
  17181. }
  17182. #endif
  17183. #if defined(_WIN32)
  17184. (void)DeleteCriticalSection(&global_log_file_lock);
  17185. #endif /* _WIN32 */
  17186. #if !defined(_WIN32)
  17187. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17188. #endif
  17189. (void)pthread_key_delete(sTlsKey);
  17190. #if defined(USE_LUA)
  17191. lua_exit_optional_libraries();
  17192. #endif
  17193. mg_global_unlock();
  17194. (void)pthread_mutex_destroy(&global_lock_mutex);
  17195. return 1;
  17196. }
  17197. mg_global_unlock();
  17198. return 1;
  17199. }
  17200. /* End of civetweb.c */