civetweb.c 529 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900
  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((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 = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4324. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4325. s1++;
  4326. s2++;
  4327. } while ((diff == 0) && (s1[-1] != L'\0'));
  4328. return diff;
  4329. }
  4330. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4331. * wbuf and wbuf_len is a target buffer and its length. */
  4332. static void
  4333. path_to_unicode(const struct mg_connection *conn,
  4334. const char *path,
  4335. wchar_t *wbuf,
  4336. size_t wbuf_len)
  4337. {
  4338. char buf[PATH_MAX], buf2[PATH_MAX];
  4339. wchar_t wbuf2[W_PATH_MAX + 1];
  4340. DWORD long_len, err;
  4341. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4342. mg_strlcpy(buf, path, sizeof(buf));
  4343. change_slashes_to_backslashes(buf);
  4344. /* Convert to Unicode and back. If doubly-converted string does not
  4345. * match the original, something is fishy, reject. */
  4346. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4347. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4348. WideCharToMultiByte(
  4349. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4350. if (strcmp(buf, buf2) != 0) {
  4351. wbuf[0] = L'\0';
  4352. }
  4353. /* Windows file systems are not case sensitive, but you can still use
  4354. * uppercase and lowercase letters (on all modern file systems).
  4355. * The server can check if the URI uses the same upper/lowercase
  4356. * letters an the file system, effectively making Windows servers
  4357. * case sensitive (like Linux servers are). It is still not possible
  4358. * to use two files with the same name in different cases on Windows
  4359. * (like /a and /A) - this would be possible in Linux.
  4360. * As a default, Windows is not case sensitive, but the case sensitive
  4361. * file name check can be activated by an additional configuration. */
  4362. if (conn) {
  4363. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4364. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4365. "yes")) {
  4366. /* Use case sensitive compare function */
  4367. fcompare = wcscmp;
  4368. }
  4369. }
  4370. (void)conn; /* conn is currently unused */
  4371. #if !defined(_WIN32_WCE)
  4372. /* Only accept a full file path, not a Windows short (8.3) path. */
  4373. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4374. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4375. if (long_len == 0) {
  4376. err = GetLastError();
  4377. if (err == ERROR_FILE_NOT_FOUND) {
  4378. /* File does not exist. This is not always a problem here. */
  4379. return;
  4380. }
  4381. }
  4382. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4383. /* Short name is used. */
  4384. wbuf[0] = L'\0';
  4385. }
  4386. #else
  4387. (void)long_len;
  4388. (void)wbuf2;
  4389. (void)err;
  4390. if (strchr(path, '~')) {
  4391. wbuf[0] = L'\0';
  4392. }
  4393. #endif
  4394. }
  4395. static int
  4396. mg_stat(const struct mg_connection *conn,
  4397. const char *path,
  4398. struct mg_file_stat *filep)
  4399. {
  4400. wchar_t wbuf[W_PATH_MAX];
  4401. WIN32_FILE_ATTRIBUTE_DATA info;
  4402. time_t creation_time;
  4403. size_t len;
  4404. if (!filep) {
  4405. return 0;
  4406. }
  4407. memset(filep, 0, sizeof(*filep));
  4408. if (conn && is_file_in_memory(conn, path)) {
  4409. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4410. * memset */
  4411. /* Quick fix (for 1.9.x): */
  4412. /* mg_stat must fill all fields, also for files in memory */
  4413. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4414. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4415. filep->size = tmp_file.stat.size;
  4416. filep->location = 2;
  4417. /* TODO: for 1.10: restructure how files in memory are handled */
  4418. /* The "file in memory" feature is a candidate for deletion.
  4419. * Please join the discussion at
  4420. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4421. */
  4422. filep->last_modified = time(NULL); /* TODO */
  4423. /* last_modified = now ... assumes the file may change during
  4424. * runtime,
  4425. * so every mg_fopen call may return different data */
  4426. /* last_modified = conn->phys_ctx.start_time;
  4427. * May be used it the data does not change during runtime. This
  4428. * allows
  4429. * browser caching. Since we do not know, we have to assume the file
  4430. * in memory may change. */
  4431. return 1;
  4432. }
  4433. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4434. /* Windows happily opens files with some garbage at the end of file name.
  4435. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4436. * "a.cgi", despite one would expect an error back. */
  4437. len = strlen(path);
  4438. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4439. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4440. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4441. filep->last_modified =
  4442. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4443. info.ftLastWriteTime.dwHighDateTime);
  4444. /* On Windows, the file creation time can be higher than the
  4445. * modification time, e.g. when a file is copied.
  4446. * Since the Last-Modified timestamp is used for caching
  4447. * it should be based on the most recent timestamp. */
  4448. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4449. info.ftCreationTime.dwHighDateTime);
  4450. if (creation_time > filep->last_modified) {
  4451. filep->last_modified = creation_time;
  4452. }
  4453. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4454. return 1;
  4455. }
  4456. return 0;
  4457. }
  4458. static int
  4459. mg_remove(const struct mg_connection *conn, const char *path)
  4460. {
  4461. wchar_t wbuf[W_PATH_MAX];
  4462. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4463. return DeleteFileW(wbuf) ? 0 : -1;
  4464. }
  4465. static int
  4466. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4467. {
  4468. wchar_t wbuf[W_PATH_MAX];
  4469. (void)mode;
  4470. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4471. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4472. }
  4473. /* Create substitutes for POSIX functions in Win32. */
  4474. #if defined(GCC_DIAGNOSTIC)
  4475. /* Show no warning in case system functions are not used. */
  4476. #pragma GCC diagnostic push
  4477. #pragma GCC diagnostic ignored "-Wunused-function"
  4478. #endif
  4479. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4480. FUNCTION_MAY_BE_UNUSED
  4481. static DIR *
  4482. mg_opendir(const struct mg_connection *conn, const char *name)
  4483. {
  4484. DIR *dir = NULL;
  4485. wchar_t wpath[W_PATH_MAX];
  4486. DWORD attrs;
  4487. if (name == NULL) {
  4488. SetLastError(ERROR_BAD_ARGUMENTS);
  4489. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4490. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4491. } else {
  4492. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4493. attrs = GetFileAttributesW(wpath);
  4494. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4495. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4496. (void)wcscat(wpath, L"\\*");
  4497. dir->handle = FindFirstFileW(wpath, &dir->info);
  4498. dir->result.d_name[0] = '\0';
  4499. } else {
  4500. mg_free(dir);
  4501. dir = NULL;
  4502. }
  4503. }
  4504. return dir;
  4505. }
  4506. FUNCTION_MAY_BE_UNUSED
  4507. static int
  4508. mg_closedir(DIR *dir)
  4509. {
  4510. int result = 0;
  4511. if (dir != NULL) {
  4512. if (dir->handle != INVALID_HANDLE_VALUE)
  4513. result = FindClose(dir->handle) ? 0 : -1;
  4514. mg_free(dir);
  4515. } else {
  4516. result = -1;
  4517. SetLastError(ERROR_BAD_ARGUMENTS);
  4518. }
  4519. return result;
  4520. }
  4521. FUNCTION_MAY_BE_UNUSED
  4522. static struct dirent *
  4523. mg_readdir(DIR *dir)
  4524. {
  4525. struct dirent *result = 0;
  4526. if (dir) {
  4527. if (dir->handle != INVALID_HANDLE_VALUE) {
  4528. result = &dir->result;
  4529. (void)WideCharToMultiByte(CP_UTF8,
  4530. 0,
  4531. dir->info.cFileName,
  4532. -1,
  4533. result->d_name,
  4534. sizeof(result->d_name),
  4535. NULL,
  4536. NULL);
  4537. if (!FindNextFileW(dir->handle, &dir->info)) {
  4538. (void)FindClose(dir->handle);
  4539. dir->handle = INVALID_HANDLE_VALUE;
  4540. }
  4541. } else {
  4542. SetLastError(ERROR_FILE_NOT_FOUND);
  4543. }
  4544. } else {
  4545. SetLastError(ERROR_BAD_ARGUMENTS);
  4546. }
  4547. return result;
  4548. }
  4549. #if !defined(HAVE_POLL)
  4550. #undef POLLIN
  4551. #undef POLLPRI
  4552. #undef POLLOUT
  4553. #define POLLIN (1) /* Data ready - read will not block. */
  4554. #define POLLPRI (2) /* Priority data ready. */
  4555. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4556. FUNCTION_MAY_BE_UNUSED
  4557. static int
  4558. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4559. {
  4560. struct timeval tv;
  4561. fd_set rset;
  4562. fd_set wset;
  4563. unsigned int i;
  4564. int result;
  4565. SOCKET maxfd = 0;
  4566. memset(&tv, 0, sizeof(tv));
  4567. tv.tv_sec = milliseconds / 1000;
  4568. tv.tv_usec = (milliseconds % 1000) * 1000;
  4569. FD_ZERO(&rset);
  4570. FD_ZERO(&wset);
  4571. for (i = 0; i < n; i++) {
  4572. if (pfd[i].events & POLLIN) {
  4573. FD_SET((SOCKET)pfd[i].fd, &rset);
  4574. } else if (pfd[i].events & POLLOUT) {
  4575. FD_SET((SOCKET)pfd[i].fd, &wset);
  4576. }
  4577. pfd[i].revents = 0;
  4578. if (pfd[i].fd > maxfd) {
  4579. maxfd = pfd[i].fd;
  4580. }
  4581. }
  4582. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4583. for (i = 0; i < n; i++) {
  4584. if (FD_ISSET(pfd[i].fd, &rset)) {
  4585. pfd[i].revents |= POLLIN;
  4586. }
  4587. if (FD_ISSET(pfd[i].fd, &wset)) {
  4588. pfd[i].revents |= POLLOUT;
  4589. }
  4590. }
  4591. }
  4592. /* We should subtract the time used in select from remaining
  4593. * "milliseconds", in particular if called from mg_poll with a
  4594. * timeout quantum.
  4595. * Unfortunately, the remaining time is not stored in "tv" in all
  4596. * implementations, so the result in "tv" must be considered undefined.
  4597. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4598. return result;
  4599. }
  4600. #endif /* HAVE_POLL */
  4601. #if defined(GCC_DIAGNOSTIC)
  4602. /* Enable unused function warning again */
  4603. #pragma GCC diagnostic pop
  4604. #endif
  4605. static void
  4606. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4607. {
  4608. (void)conn; /* Unused. */
  4609. #if defined(_WIN32_WCE)
  4610. (void)sock;
  4611. #else
  4612. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4613. #endif
  4614. }
  4615. int
  4616. mg_start_thread(mg_thread_func_t f, void *p)
  4617. {
  4618. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4619. /* Compile-time option to control stack size, e.g.
  4620. * -DUSE_STACK_SIZE=16384
  4621. */
  4622. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4623. == ((uintptr_t)(-1L)))
  4624. ? -1
  4625. : 0);
  4626. #else
  4627. return (
  4628. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4629. ? -1
  4630. : 0);
  4631. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4632. }
  4633. /* Start a thread storing the thread context. */
  4634. static int
  4635. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4636. void *p,
  4637. pthread_t *threadidptr)
  4638. {
  4639. uintptr_t uip;
  4640. HANDLE threadhandle;
  4641. int result = -1;
  4642. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4643. threadhandle = (HANDLE)uip;
  4644. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4645. *threadidptr = threadhandle;
  4646. result = 0;
  4647. }
  4648. return result;
  4649. }
  4650. /* Wait for a thread to finish. */
  4651. static int
  4652. mg_join_thread(pthread_t threadid)
  4653. {
  4654. int result;
  4655. DWORD dwevent;
  4656. result = -1;
  4657. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4658. if (dwevent == WAIT_FAILED) {
  4659. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4660. } else {
  4661. if (dwevent == WAIT_OBJECT_0) {
  4662. CloseHandle(threadid);
  4663. result = 0;
  4664. }
  4665. }
  4666. return result;
  4667. }
  4668. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4669. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4670. /* Create substitutes for POSIX functions in Win32. */
  4671. #if defined(GCC_DIAGNOSTIC)
  4672. /* Show no warning in case system functions are not used. */
  4673. #pragma GCC diagnostic push
  4674. #pragma GCC diagnostic ignored "-Wunused-function"
  4675. #endif
  4676. FUNCTION_MAY_BE_UNUSED
  4677. static HANDLE
  4678. dlopen(const char *dll_name, int flags)
  4679. {
  4680. wchar_t wbuf[W_PATH_MAX];
  4681. (void)flags;
  4682. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4683. return LoadLibraryW(wbuf);
  4684. }
  4685. FUNCTION_MAY_BE_UNUSED
  4686. static int
  4687. dlclose(void *handle)
  4688. {
  4689. int result;
  4690. if (FreeLibrary((HMODULE)handle) != 0) {
  4691. result = 0;
  4692. } else {
  4693. result = -1;
  4694. }
  4695. return result;
  4696. }
  4697. #if defined(GCC_DIAGNOSTIC)
  4698. /* Enable unused function warning again */
  4699. #pragma GCC diagnostic pop
  4700. #endif
  4701. #endif
  4702. #if !defined(NO_CGI)
  4703. #define SIGKILL (0)
  4704. static int
  4705. kill(pid_t pid, int sig_num)
  4706. {
  4707. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4708. (void)CloseHandle((HANDLE)pid);
  4709. return 0;
  4710. }
  4711. #if !defined(WNOHANG)
  4712. #define WNOHANG (1)
  4713. #endif
  4714. static pid_t
  4715. waitpid(pid_t pid, int *status, int flags)
  4716. {
  4717. DWORD timeout = INFINITE;
  4718. DWORD waitres;
  4719. (void)status; /* Currently not used by any client here */
  4720. if ((flags | WNOHANG) == WNOHANG) {
  4721. timeout = 0;
  4722. }
  4723. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4724. if (waitres == WAIT_OBJECT_0) {
  4725. return pid;
  4726. }
  4727. if (waitres == WAIT_TIMEOUT) {
  4728. return 0;
  4729. }
  4730. return (pid_t)-1;
  4731. }
  4732. static void
  4733. trim_trailing_whitespaces(char *s)
  4734. {
  4735. char *e = s + strlen(s);
  4736. while ((e > s) && isspace((unsigned char)e[-1])) {
  4737. *(--e) = '\0';
  4738. }
  4739. }
  4740. static pid_t
  4741. spawn_process(struct mg_connection *conn,
  4742. const char *prog,
  4743. char *envblk,
  4744. char *envp[],
  4745. int fdin[2],
  4746. int fdout[2],
  4747. int fderr[2],
  4748. const char *dir)
  4749. {
  4750. HANDLE me;
  4751. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4752. cmdline[PATH_MAX], buf[PATH_MAX];
  4753. int truncated;
  4754. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4755. STARTUPINFOA si;
  4756. PROCESS_INFORMATION pi = {0};
  4757. (void)envp;
  4758. memset(&si, 0, sizeof(si));
  4759. si.cb = sizeof(si);
  4760. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4761. si.wShowWindow = SW_HIDE;
  4762. me = GetCurrentProcess();
  4763. DuplicateHandle(me,
  4764. (HANDLE)_get_osfhandle(fdin[0]),
  4765. me,
  4766. &si.hStdInput,
  4767. 0,
  4768. TRUE,
  4769. DUPLICATE_SAME_ACCESS);
  4770. DuplicateHandle(me,
  4771. (HANDLE)_get_osfhandle(fdout[1]),
  4772. me,
  4773. &si.hStdOutput,
  4774. 0,
  4775. TRUE,
  4776. DUPLICATE_SAME_ACCESS);
  4777. DuplicateHandle(me,
  4778. (HANDLE)_get_osfhandle(fderr[1]),
  4779. me,
  4780. &si.hStdError,
  4781. 0,
  4782. TRUE,
  4783. DUPLICATE_SAME_ACCESS);
  4784. /* Mark handles that should not be inherited. See
  4785. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4786. */
  4787. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4788. HANDLE_FLAG_INHERIT,
  4789. 0);
  4790. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4791. HANDLE_FLAG_INHERIT,
  4792. 0);
  4793. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4794. HANDLE_FLAG_INHERIT,
  4795. 0);
  4796. /* If CGI file is a script, try to read the interpreter line */
  4797. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4798. if (interp == NULL) {
  4799. buf[0] = buf[1] = '\0';
  4800. /* Read the first line of the script into the buffer */
  4801. mg_snprintf(
  4802. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4803. if (truncated) {
  4804. pi.hProcess = (pid_t)-1;
  4805. goto spawn_cleanup;
  4806. }
  4807. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4808. #if defined(MG_USE_OPEN_FILE)
  4809. p = (char *)file.access.membuf;
  4810. #else
  4811. p = (char *)NULL;
  4812. #endif
  4813. mg_fgets(buf, sizeof(buf), &file, &p);
  4814. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4815. buf[sizeof(buf) - 1] = '\0';
  4816. }
  4817. if ((buf[0] == '#') && (buf[1] == '!')) {
  4818. trim_trailing_whitespaces(buf + 2);
  4819. } else {
  4820. buf[2] = '\0';
  4821. }
  4822. interp = buf + 2;
  4823. }
  4824. if (interp[0] != '\0') {
  4825. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4826. interp = full_interp;
  4827. }
  4828. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4829. if (interp[0] != '\0') {
  4830. mg_snprintf(conn,
  4831. &truncated,
  4832. cmdline,
  4833. sizeof(cmdline),
  4834. "\"%s\" \"%s\\%s\"",
  4835. interp,
  4836. full_dir,
  4837. prog);
  4838. } else {
  4839. mg_snprintf(conn,
  4840. &truncated,
  4841. cmdline,
  4842. sizeof(cmdline),
  4843. "\"%s\\%s\"",
  4844. full_dir,
  4845. prog);
  4846. }
  4847. if (truncated) {
  4848. pi.hProcess = (pid_t)-1;
  4849. goto spawn_cleanup;
  4850. }
  4851. DEBUG_TRACE("Running [%s]", cmdline);
  4852. if (CreateProcessA(NULL,
  4853. cmdline,
  4854. NULL,
  4855. NULL,
  4856. TRUE,
  4857. CREATE_NEW_PROCESS_GROUP,
  4858. envblk,
  4859. NULL,
  4860. &si,
  4861. &pi)
  4862. == 0) {
  4863. mg_cry_internal(
  4864. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4865. pi.hProcess = (pid_t)-1;
  4866. /* goto spawn_cleanup; */
  4867. }
  4868. spawn_cleanup:
  4869. (void)CloseHandle(si.hStdOutput);
  4870. (void)CloseHandle(si.hStdError);
  4871. (void)CloseHandle(si.hStdInput);
  4872. if (pi.hThread != NULL) {
  4873. (void)CloseHandle(pi.hThread);
  4874. }
  4875. return (pid_t)pi.hProcess;
  4876. }
  4877. #endif /* !NO_CGI */
  4878. static int
  4879. set_blocking_mode(SOCKET sock)
  4880. {
  4881. unsigned long non_blocking = 0;
  4882. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4883. }
  4884. static int
  4885. set_non_blocking_mode(SOCKET sock)
  4886. {
  4887. unsigned long non_blocking = 1;
  4888. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4889. }
  4890. #else
  4891. static int
  4892. mg_stat(const struct mg_connection *conn,
  4893. const char *path,
  4894. struct mg_file_stat *filep)
  4895. {
  4896. struct stat st;
  4897. if (!filep) {
  4898. return 0;
  4899. }
  4900. memset(filep, 0, sizeof(*filep));
  4901. if (conn && is_file_in_memory(conn, path)) {
  4902. /* Quick fix (for 1.9.x): */
  4903. /* mg_stat must fill all fields, also for files in memory */
  4904. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4905. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4906. filep->size = tmp_file.stat.size;
  4907. filep->last_modified = time(NULL);
  4908. filep->location = 2;
  4909. /* TODO: remove legacy "files in memory" feature */
  4910. return 1;
  4911. }
  4912. if (0 == stat(path, &st)) {
  4913. filep->size = (uint64_t)(st.st_size);
  4914. filep->last_modified = st.st_mtime;
  4915. filep->is_directory = S_ISDIR(st.st_mode);
  4916. return 1;
  4917. }
  4918. return 0;
  4919. }
  4920. static void
  4921. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4922. {
  4923. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4924. if (conn) {
  4925. mg_cry_internal(conn,
  4926. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4927. __func__,
  4928. strerror(ERRNO));
  4929. }
  4930. }
  4931. }
  4932. int
  4933. mg_start_thread(mg_thread_func_t func, void *param)
  4934. {
  4935. pthread_t thread_id;
  4936. pthread_attr_t attr;
  4937. int result;
  4938. (void)pthread_attr_init(&attr);
  4939. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4940. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4941. /* Compile-time option to control stack size,
  4942. * e.g. -DUSE_STACK_SIZE=16384 */
  4943. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4944. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4945. result = pthread_create(&thread_id, &attr, func, param);
  4946. pthread_attr_destroy(&attr);
  4947. return result;
  4948. }
  4949. /* Start a thread storing the thread context. */
  4950. static int
  4951. mg_start_thread_with_id(mg_thread_func_t func,
  4952. void *param,
  4953. pthread_t *threadidptr)
  4954. {
  4955. pthread_t thread_id;
  4956. pthread_attr_t attr;
  4957. int result;
  4958. (void)pthread_attr_init(&attr);
  4959. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4960. /* Compile-time option to control stack size,
  4961. * e.g. -DUSE_STACK_SIZE=16384 */
  4962. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4963. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4964. result = pthread_create(&thread_id, &attr, func, param);
  4965. pthread_attr_destroy(&attr);
  4966. if ((result == 0) && (threadidptr != NULL)) {
  4967. *threadidptr = thread_id;
  4968. }
  4969. return result;
  4970. }
  4971. /* Wait for a thread to finish. */
  4972. static int
  4973. mg_join_thread(pthread_t threadid)
  4974. {
  4975. int result;
  4976. result = pthread_join(threadid, NULL);
  4977. return result;
  4978. }
  4979. #if !defined(NO_CGI)
  4980. static pid_t
  4981. spawn_process(struct mg_connection *conn,
  4982. const char *prog,
  4983. char *envblk,
  4984. char *envp[],
  4985. int fdin[2],
  4986. int fdout[2],
  4987. int fderr[2],
  4988. const char *dir)
  4989. {
  4990. pid_t pid;
  4991. const char *interp;
  4992. (void)envblk;
  4993. if (conn == NULL) {
  4994. return 0;
  4995. }
  4996. if ((pid = fork()) == -1) {
  4997. /* Parent */
  4998. mg_send_http_error(conn,
  4999. 500,
  5000. "Error: Creating CGI process\nfork(): %s",
  5001. strerror(ERRNO));
  5002. } else if (pid == 0) {
  5003. /* Child */
  5004. if (chdir(dir) != 0) {
  5005. mg_cry_internal(
  5006. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5007. } else if (dup2(fdin[0], 0) == -1) {
  5008. mg_cry_internal(conn,
  5009. "%s: dup2(%d, 0): %s",
  5010. __func__,
  5011. fdin[0],
  5012. strerror(ERRNO));
  5013. } else if (dup2(fdout[1], 1) == -1) {
  5014. mg_cry_internal(conn,
  5015. "%s: dup2(%d, 1): %s",
  5016. __func__,
  5017. fdout[1],
  5018. strerror(ERRNO));
  5019. } else if (dup2(fderr[1], 2) == -1) {
  5020. mg_cry_internal(conn,
  5021. "%s: dup2(%d, 2): %s",
  5022. __func__,
  5023. fderr[1],
  5024. strerror(ERRNO));
  5025. } else {
  5026. struct sigaction sa;
  5027. /* Keep stderr and stdout in two different pipes.
  5028. * Stdout will be sent back to the client,
  5029. * stderr should go into a server error log. */
  5030. (void)close(fdin[0]);
  5031. (void)close(fdout[1]);
  5032. (void)close(fderr[1]);
  5033. /* Close write end fdin and read end fdout and fderr */
  5034. (void)close(fdin[1]);
  5035. (void)close(fdout[0]);
  5036. (void)close(fderr[0]);
  5037. /* After exec, all signal handlers are restored to their default
  5038. * values, with one exception of SIGCHLD. According to
  5039. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5040. * will leave unchanged after exec if it was set to be ignored.
  5041. * Restore it to default action. */
  5042. memset(&sa, 0, sizeof(sa));
  5043. sa.sa_handler = SIG_DFL;
  5044. sigaction(SIGCHLD, &sa, NULL);
  5045. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5046. if (interp == NULL) {
  5047. (void)execle(prog, prog, NULL, envp);
  5048. mg_cry_internal(conn,
  5049. "%s: execle(%s): %s",
  5050. __func__,
  5051. prog,
  5052. strerror(ERRNO));
  5053. } else {
  5054. (void)execle(interp, interp, prog, NULL, envp);
  5055. mg_cry_internal(conn,
  5056. "%s: execle(%s %s): %s",
  5057. __func__,
  5058. interp,
  5059. prog,
  5060. strerror(ERRNO));
  5061. }
  5062. }
  5063. exit(EXIT_FAILURE);
  5064. }
  5065. return pid;
  5066. }
  5067. #endif /* !NO_CGI */
  5068. static int
  5069. set_non_blocking_mode(SOCKET sock)
  5070. {
  5071. int flags = fcntl(sock, F_GETFL, 0);
  5072. if (flags < 0) {
  5073. return -1;
  5074. }
  5075. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5076. return -1;
  5077. }
  5078. return 0;
  5079. }
  5080. static int
  5081. set_blocking_mode(SOCKET sock)
  5082. {
  5083. int flags = fcntl(sock, F_GETFL, 0);
  5084. if (flags < 0) {
  5085. return -1;
  5086. }
  5087. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5088. return -1;
  5089. }
  5090. return 0;
  5091. }
  5092. #endif /* _WIN32 / else */
  5093. /* End of initial operating system specific define block. */
  5094. /* Get a random number (independent of C rand function) */
  5095. static uint64_t
  5096. get_random(void)
  5097. {
  5098. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5099. static uint64_t lcg = 0; /* Linear congruential generator */
  5100. uint64_t now = mg_get_current_time_ns();
  5101. if (lfsr == 0) {
  5102. /* lfsr will be only 0 if has not been initialized,
  5103. * so this code is called only once. */
  5104. lfsr = mg_get_current_time_ns();
  5105. lcg = mg_get_current_time_ns();
  5106. } else {
  5107. /* Get the next step of both random number generators. */
  5108. lfsr = (lfsr >> 1)
  5109. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5110. << 63);
  5111. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5112. }
  5113. /* Combining two pseudo-random number generators and a high resolution
  5114. * part
  5115. * of the current server time will make it hard (impossible?) to guess
  5116. * the
  5117. * next number. */
  5118. return (lfsr ^ lcg ^ now);
  5119. }
  5120. static int
  5121. mg_poll(struct mg_pollfd *pfd,
  5122. unsigned int n,
  5123. int milliseconds,
  5124. volatile int *stop_server)
  5125. {
  5126. /* Call poll, but only for a maximum time of a few seconds.
  5127. * This will allow to stop the server after some seconds, instead
  5128. * of having to wait for a long socket timeout. */
  5129. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5130. do {
  5131. int result;
  5132. if (*stop_server) {
  5133. /* Shut down signal */
  5134. return -2;
  5135. }
  5136. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5137. ms_now = milliseconds;
  5138. }
  5139. result = poll(pfd, n, ms_now);
  5140. if (result != 0) {
  5141. /* Poll returned either success (1) or error (-1).
  5142. * Forward both to the caller. */
  5143. return result;
  5144. }
  5145. /* Poll returned timeout (0). */
  5146. if (milliseconds > 0) {
  5147. milliseconds -= ms_now;
  5148. }
  5149. } while (milliseconds != 0);
  5150. /* timeout: return 0 */
  5151. return 0;
  5152. }
  5153. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5154. * descriptor.
  5155. * Return value:
  5156. * >=0 .. number of bytes successfully written
  5157. * -1 .. timeout
  5158. * -2 .. error
  5159. */
  5160. static int
  5161. push_inner(struct mg_context *ctx,
  5162. FILE *fp,
  5163. SOCKET sock,
  5164. SSL *ssl,
  5165. const char *buf,
  5166. int len,
  5167. double timeout)
  5168. {
  5169. uint64_t start = 0, now = 0, timeout_ns = 0;
  5170. int n, err;
  5171. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5172. #if defined(_WIN32)
  5173. typedef int len_t;
  5174. #else
  5175. typedef size_t len_t;
  5176. #endif
  5177. if (timeout > 0) {
  5178. now = mg_get_current_time_ns();
  5179. start = now;
  5180. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5181. }
  5182. if (ctx == NULL) {
  5183. return -2;
  5184. }
  5185. #if defined(NO_SSL)
  5186. if (ssl) {
  5187. return -2;
  5188. }
  5189. #endif
  5190. /* Try to read until it succeeds, fails, times out, or the server
  5191. * shuts down. */
  5192. for (;;) {
  5193. #if !defined(NO_SSL)
  5194. if (ssl != NULL) {
  5195. n = SSL_write(ssl, buf, len);
  5196. if (n <= 0) {
  5197. err = SSL_get_error(ssl, n);
  5198. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5199. err = ERRNO;
  5200. } else if ((err == SSL_ERROR_WANT_READ)
  5201. || (err == SSL_ERROR_WANT_WRITE)) {
  5202. n = 0;
  5203. } else {
  5204. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5205. return -2;
  5206. }
  5207. } else {
  5208. err = 0;
  5209. }
  5210. } else
  5211. #endif
  5212. if (fp != NULL) {
  5213. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5214. if (ferror(fp)) {
  5215. n = -1;
  5216. err = ERRNO;
  5217. } else {
  5218. err = 0;
  5219. }
  5220. } else {
  5221. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5222. err = (n < 0) ? ERRNO : 0;
  5223. #if defined(_WIN32)
  5224. if (err == WSAEWOULDBLOCK) {
  5225. err = 0;
  5226. n = 0;
  5227. }
  5228. #else
  5229. if (err == EWOULDBLOCK) {
  5230. err = 0;
  5231. n = 0;
  5232. }
  5233. #endif
  5234. if (n < 0) {
  5235. /* shutdown of the socket at client side */
  5236. return -2;
  5237. }
  5238. }
  5239. if (ctx->stop_flag) {
  5240. return -2;
  5241. }
  5242. if ((n > 0) || ((n == 0) && (len == 0))) {
  5243. /* some data has been read, or no data was requested */
  5244. return n;
  5245. }
  5246. if (n < 0) {
  5247. /* socket error - check errno */
  5248. DEBUG_TRACE("send() failed, error %d", err);
  5249. /* TODO (mid): error handling depending on the error code.
  5250. * These codes are different between Windows and Linux.
  5251. * Currently there is no problem with failing send calls,
  5252. * if there is a reproducible situation, it should be
  5253. * investigated in detail.
  5254. */
  5255. return -2;
  5256. }
  5257. /* Only in case n=0 (timeout), repeat calling the write function */
  5258. /* If send failed, wait before retry */
  5259. if (fp != NULL) {
  5260. /* For files, just wait a fixed time.
  5261. * Maybe it helps, maybe not. */
  5262. mg_sleep(5);
  5263. } else {
  5264. /* For sockets, wait for the socket using poll */
  5265. struct mg_pollfd pfd[1];
  5266. int pollres;
  5267. pfd[0].fd = sock;
  5268. pfd[0].events = POLLOUT;
  5269. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5270. if (ctx->stop_flag) {
  5271. return -2;
  5272. }
  5273. if (pollres > 0) {
  5274. continue;
  5275. }
  5276. }
  5277. if (timeout > 0) {
  5278. now = mg_get_current_time_ns();
  5279. if ((now - start) > timeout_ns) {
  5280. /* Timeout */
  5281. break;
  5282. }
  5283. }
  5284. }
  5285. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5286. used */
  5287. return -1;
  5288. }
  5289. static int64_t
  5290. push_all(struct mg_context *ctx,
  5291. FILE *fp,
  5292. SOCKET sock,
  5293. SSL *ssl,
  5294. const char *buf,
  5295. int64_t len)
  5296. {
  5297. double timeout = -1.0;
  5298. int64_t n, nwritten = 0;
  5299. if (ctx == NULL) {
  5300. return -1;
  5301. }
  5302. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5303. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5304. }
  5305. while ((len > 0) && (ctx->stop_flag == 0)) {
  5306. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5307. if (n < 0) {
  5308. if (nwritten == 0) {
  5309. nwritten = n; /* Propagate the error */
  5310. }
  5311. break;
  5312. } else if (n == 0) {
  5313. break; /* No more data to write */
  5314. } else {
  5315. nwritten += n;
  5316. len -= n;
  5317. }
  5318. }
  5319. return nwritten;
  5320. }
  5321. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5322. * Return value:
  5323. * >=0 .. number of bytes successfully read
  5324. * -1 .. timeout
  5325. * -2 .. error
  5326. */
  5327. static int
  5328. pull_inner(FILE *fp,
  5329. struct mg_connection *conn,
  5330. char *buf,
  5331. int len,
  5332. double timeout)
  5333. {
  5334. int nread, err = 0;
  5335. #if defined(_WIN32)
  5336. typedef int len_t;
  5337. #else
  5338. typedef size_t len_t;
  5339. #endif
  5340. #if !defined(NO_SSL)
  5341. int ssl_pending;
  5342. #endif
  5343. /* We need an additional wait loop around this, because in some cases
  5344. * with TLSwe may get data from the socket but not from SSL_read.
  5345. * In this case we need to repeat at least once.
  5346. */
  5347. if (fp != NULL) {
  5348. #if !defined(_WIN32_WCE)
  5349. /* Use read() instead of fread(), because if we're reading from the
  5350. * CGI pipe, fread() may block until IO buffer is filled up. We
  5351. * cannot afford to block and must pass all read bytes immediately
  5352. * to the client. */
  5353. nread = (int)read(fileno(fp), buf, (size_t)len);
  5354. #else
  5355. /* WinCE does not support CGI pipes */
  5356. nread = (int)fread(buf, 1, (size_t)len, fp);
  5357. #endif
  5358. err = (nread < 0) ? ERRNO : 0;
  5359. if ((nread == 0) && (len > 0)) {
  5360. /* Should get data, but got EOL */
  5361. return -2;
  5362. }
  5363. #if !defined(NO_SSL)
  5364. } else if ((conn->ssl != NULL)
  5365. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5366. /* We already know there is no more data buffered in conn->buf
  5367. * but there is more available in the SSL layer. So don't poll
  5368. * conn->client.sock yet. */
  5369. if (ssl_pending > len) {
  5370. ssl_pending = len;
  5371. }
  5372. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5373. if (nread <= 0) {
  5374. err = SSL_get_error(conn->ssl, nread);
  5375. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5376. err = ERRNO;
  5377. } else if ((err == SSL_ERROR_WANT_READ)
  5378. || (err == SSL_ERROR_WANT_WRITE)) {
  5379. nread = 0;
  5380. } else {
  5381. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5382. return -1;
  5383. }
  5384. } else {
  5385. err = 0;
  5386. }
  5387. } else if (conn->ssl != NULL) {
  5388. struct mg_pollfd pfd[1];
  5389. int pollres;
  5390. pfd[0].fd = conn->client.sock;
  5391. pfd[0].events = POLLIN;
  5392. pollres = mg_poll(pfd,
  5393. 1,
  5394. (int)(timeout * 1000.0),
  5395. &(conn->phys_ctx->stop_flag));
  5396. if (conn->phys_ctx->stop_flag) {
  5397. return -2;
  5398. }
  5399. if (pollres > 0) {
  5400. nread = SSL_read(conn->ssl, buf, len);
  5401. if (nread <= 0) {
  5402. err = SSL_get_error(conn->ssl, nread);
  5403. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5404. err = ERRNO;
  5405. } else if ((err == SSL_ERROR_WANT_READ)
  5406. || (err == SSL_ERROR_WANT_WRITE)) {
  5407. nread = 0;
  5408. } else {
  5409. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5410. return -2;
  5411. }
  5412. } else {
  5413. err = 0;
  5414. }
  5415. } else if (pollres < 0) {
  5416. /* Error */
  5417. return -2;
  5418. } else {
  5419. /* pollres = 0 means timeout */
  5420. nread = 0;
  5421. }
  5422. #endif
  5423. } else {
  5424. struct mg_pollfd pfd[1];
  5425. int pollres;
  5426. pfd[0].fd = conn->client.sock;
  5427. pfd[0].events = POLLIN;
  5428. pollres = mg_poll(pfd,
  5429. 1,
  5430. (int)(timeout * 1000.0),
  5431. &(conn->phys_ctx->stop_flag));
  5432. if (conn->phys_ctx->stop_flag) {
  5433. return -2;
  5434. }
  5435. if (pollres > 0) {
  5436. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5437. err = (nread < 0) ? ERRNO : 0;
  5438. if (nread <= 0) {
  5439. /* shutdown of the socket at client side */
  5440. return -2;
  5441. }
  5442. } else if (pollres < 0) {
  5443. /* error callint poll */
  5444. return -2;
  5445. } else {
  5446. /* pollres = 0 means timeout */
  5447. nread = 0;
  5448. }
  5449. }
  5450. if (conn->phys_ctx->stop_flag) {
  5451. return -2;
  5452. }
  5453. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5454. /* some data has been read, or no data was requested */
  5455. return nread;
  5456. }
  5457. if (nread < 0) {
  5458. /* socket error - check errno */
  5459. #if defined(_WIN32)
  5460. if (err == WSAEWOULDBLOCK) {
  5461. /* TODO (low): check if this is still required */
  5462. /* standard case if called from close_socket_gracefully */
  5463. return -2;
  5464. } else if (err == WSAETIMEDOUT) {
  5465. /* TODO (low): check if this is still required */
  5466. /* timeout is handled by the while loop */
  5467. return 0;
  5468. } else if (err == WSAECONNABORTED) {
  5469. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5470. return -2;
  5471. } else {
  5472. DEBUG_TRACE("recv() failed, error %d", err);
  5473. return -2;
  5474. }
  5475. #else
  5476. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5477. * if the timeout is reached and if the socket was set to non-
  5478. * blocking in close_socket_gracefully, so we can not distinguish
  5479. * here. We have to wait for the timeout in both cases for now.
  5480. */
  5481. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5482. /* TODO (low): check if this is still required */
  5483. /* EAGAIN/EWOULDBLOCK:
  5484. * standard case if called from close_socket_gracefully
  5485. * => should return -1 */
  5486. /* or timeout occurred
  5487. * => the code must stay in the while loop */
  5488. /* EINTR can be generated on a socket with a timeout set even
  5489. * when SA_RESTART is effective for all relevant signals
  5490. * (see signal(7)).
  5491. * => stay in the while loop */
  5492. } else {
  5493. DEBUG_TRACE("recv() failed, error %d", err);
  5494. return -2;
  5495. }
  5496. #endif
  5497. }
  5498. /* Timeout occurred, but no data available. */
  5499. return -1;
  5500. }
  5501. static int
  5502. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5503. {
  5504. int n, nread = 0;
  5505. double timeout = -1.0;
  5506. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5507. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5508. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5509. }
  5510. if (timeout >= 0.0) {
  5511. start_time = mg_get_current_time_ns();
  5512. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5513. }
  5514. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5515. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5516. if (n == -2) {
  5517. if (nread == 0) {
  5518. nread = -1; /* Propagate the error */
  5519. }
  5520. break;
  5521. } else if (n == -1) {
  5522. /* timeout */
  5523. if (timeout >= 0.0) {
  5524. now = mg_get_current_time_ns();
  5525. if ((now - start_time) <= timeout_ns) {
  5526. continue;
  5527. }
  5528. }
  5529. break;
  5530. } else if (n == 0) {
  5531. break; /* No more data to read */
  5532. } else {
  5533. conn->consumed_content += n;
  5534. nread += n;
  5535. len -= n;
  5536. }
  5537. }
  5538. return nread;
  5539. }
  5540. static void
  5541. discard_unread_request_data(struct mg_connection *conn)
  5542. {
  5543. char buf[MG_BUF_LEN];
  5544. size_t to_read;
  5545. int nread;
  5546. if (conn == NULL) {
  5547. return;
  5548. }
  5549. to_read = sizeof(buf);
  5550. if (conn->is_chunked) {
  5551. /* Chunked encoding: 3=chunk read completely
  5552. * completely */
  5553. while (conn->is_chunked != 3) {
  5554. nread = mg_read(conn, buf, to_read);
  5555. if (nread <= 0) {
  5556. break;
  5557. }
  5558. }
  5559. } else {
  5560. /* Not chunked: content length is known */
  5561. while (conn->consumed_content < conn->content_len) {
  5562. if (to_read
  5563. > (size_t)(conn->content_len - conn->consumed_content)) {
  5564. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5565. }
  5566. nread = mg_read(conn, buf, to_read);
  5567. if (nread <= 0) {
  5568. break;
  5569. }
  5570. }
  5571. }
  5572. }
  5573. static int
  5574. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5575. {
  5576. int64_t n, buffered_len, nread;
  5577. int64_t len64 =
  5578. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5579. * int, we may not read more
  5580. * bytes */
  5581. const char *body;
  5582. if (conn == NULL) {
  5583. return 0;
  5584. }
  5585. /* If Content-Length is not set for a request with body data
  5586. * (e.g., a PUT or POST request), we do not know in advance
  5587. * how much data should be read. */
  5588. if (conn->consumed_content == 0) {
  5589. if (conn->is_chunked == 1) {
  5590. conn->content_len = len64;
  5591. conn->is_chunked = 2;
  5592. } else if (conn->content_len == -1) {
  5593. /* The body data is completed when the connection
  5594. * is closed. */
  5595. conn->content_len = INT64_MAX;
  5596. conn->must_close = 1;
  5597. }
  5598. }
  5599. nread = 0;
  5600. if (conn->consumed_content < conn->content_len) {
  5601. /* Adjust number of bytes to read. */
  5602. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5603. if (left_to_read < len64) {
  5604. /* Do not read more than the total content length of the
  5605. * request.
  5606. */
  5607. len64 = left_to_read;
  5608. }
  5609. /* Return buffered data */
  5610. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5611. - conn->consumed_content;
  5612. if (buffered_len > 0) {
  5613. if (len64 < buffered_len) {
  5614. buffered_len = len64;
  5615. }
  5616. body = conn->buf + conn->request_len + conn->consumed_content;
  5617. memcpy(buf, body, (size_t)buffered_len);
  5618. len64 -= buffered_len;
  5619. conn->consumed_content += buffered_len;
  5620. nread += buffered_len;
  5621. buf = (char *)buf + buffered_len;
  5622. }
  5623. /* We have returned all buffered data. Read new data from the remote
  5624. * socket.
  5625. */
  5626. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5627. nread += n;
  5628. } else {
  5629. nread = ((nread > 0) ? nread : n);
  5630. }
  5631. }
  5632. return (int)nread;
  5633. }
  5634. static char
  5635. mg_getc(struct mg_connection *conn)
  5636. {
  5637. char c;
  5638. if (conn == NULL) {
  5639. return 0;
  5640. }
  5641. if (mg_read_inner(conn, &c, 1) <= 0) {
  5642. return (char)0;
  5643. }
  5644. return c;
  5645. }
  5646. int
  5647. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5648. {
  5649. if (len > INT_MAX) {
  5650. len = INT_MAX;
  5651. }
  5652. if (conn == NULL) {
  5653. return 0;
  5654. }
  5655. if (conn->is_chunked) {
  5656. size_t all_read = 0;
  5657. while (len > 0) {
  5658. if (conn->is_chunked == 3) {
  5659. /* No more data left to read */
  5660. return 0;
  5661. }
  5662. if (conn->chunk_remainder) {
  5663. /* copy from the remainder of the last received chunk */
  5664. long read_ret;
  5665. size_t read_now =
  5666. ((conn->chunk_remainder > len) ? (len)
  5667. : (conn->chunk_remainder));
  5668. conn->content_len += (int)read_now;
  5669. read_ret =
  5670. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5671. if (read_ret < 1) {
  5672. /* read error */
  5673. return -1;
  5674. }
  5675. all_read += (size_t)read_ret;
  5676. conn->chunk_remainder -= (size_t)read_ret;
  5677. len -= (size_t)read_ret;
  5678. if (conn->chunk_remainder == 0) {
  5679. /* Add data bytes in the current chunk have been read,
  5680. * so we are expecting \r\n now. */
  5681. char x1, x2;
  5682. conn->content_len += 2;
  5683. x1 = mg_getc(conn);
  5684. x2 = mg_getc(conn);
  5685. if ((x1 != '\r') || (x2 != '\n')) {
  5686. /* Protocol violation */
  5687. return -1;
  5688. }
  5689. }
  5690. } else {
  5691. /* fetch a new chunk */
  5692. int i = 0;
  5693. char lenbuf[64];
  5694. char *end = 0;
  5695. unsigned long chunkSize = 0;
  5696. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5697. conn->content_len++;
  5698. lenbuf[i] = mg_getc(conn);
  5699. if ((i > 0) && (lenbuf[i] == '\r')
  5700. && (lenbuf[i - 1] != '\r')) {
  5701. continue;
  5702. }
  5703. if ((i > 1) && (lenbuf[i] == '\n')
  5704. && (lenbuf[i - 1] == '\r')) {
  5705. lenbuf[i + 1] = 0;
  5706. chunkSize = strtoul(lenbuf, &end, 16);
  5707. if (chunkSize == 0) {
  5708. /* regular end of content */
  5709. conn->is_chunked = 3;
  5710. }
  5711. break;
  5712. }
  5713. if (!isxdigit((unsigned char)lenbuf[i])) {
  5714. /* illegal character for chunk length */
  5715. return -1;
  5716. }
  5717. }
  5718. if ((end == NULL) || (*end != '\r')) {
  5719. /* chunksize not set correctly */
  5720. return -1;
  5721. }
  5722. if (chunkSize == 0) {
  5723. break;
  5724. }
  5725. conn->chunk_remainder = chunkSize;
  5726. }
  5727. }
  5728. return (int)all_read;
  5729. }
  5730. return mg_read_inner(conn, buf, len);
  5731. }
  5732. int
  5733. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5734. {
  5735. time_t now;
  5736. int64_t n, total, allowed;
  5737. if (conn == NULL) {
  5738. return 0;
  5739. }
  5740. if (conn->throttle > 0) {
  5741. if ((now = time(NULL)) != conn->last_throttle_time) {
  5742. conn->last_throttle_time = now;
  5743. conn->last_throttle_bytes = 0;
  5744. }
  5745. allowed = conn->throttle - conn->last_throttle_bytes;
  5746. if (allowed > (int64_t)len) {
  5747. allowed = (int64_t)len;
  5748. }
  5749. if ((total = push_all(conn->phys_ctx,
  5750. NULL,
  5751. conn->client.sock,
  5752. conn->ssl,
  5753. (const char *)buf,
  5754. (int64_t)allowed))
  5755. == allowed) {
  5756. buf = (const char *)buf + total;
  5757. conn->last_throttle_bytes += total;
  5758. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5759. allowed = (conn->throttle > ((int64_t)len - total))
  5760. ? (int64_t)len - total
  5761. : conn->throttle;
  5762. if ((n = push_all(conn->phys_ctx,
  5763. NULL,
  5764. conn->client.sock,
  5765. conn->ssl,
  5766. (const char *)buf,
  5767. (int64_t)allowed))
  5768. != allowed) {
  5769. break;
  5770. }
  5771. sleep(1);
  5772. conn->last_throttle_bytes = allowed;
  5773. conn->last_throttle_time = time(NULL);
  5774. buf = (const char *)buf + n;
  5775. total += n;
  5776. }
  5777. }
  5778. } else {
  5779. total = push_all(conn->phys_ctx,
  5780. NULL,
  5781. conn->client.sock,
  5782. conn->ssl,
  5783. (const char *)buf,
  5784. (int64_t)len);
  5785. }
  5786. if (total > 0) {
  5787. conn->num_bytes_sent += total;
  5788. }
  5789. return (int)total;
  5790. }
  5791. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5792. int
  5793. mg_send_chunk(struct mg_connection *conn,
  5794. const char *chunk,
  5795. unsigned int chunk_len)
  5796. {
  5797. char lenbuf[16];
  5798. size_t lenbuf_len;
  5799. int ret;
  5800. int t;
  5801. /* First store the length information in a text buffer. */
  5802. sprintf(lenbuf, "%x\r\n", chunk_len);
  5803. lenbuf_len = strlen(lenbuf);
  5804. /* Then send length information, chunk and terminating \r\n. */
  5805. ret = mg_write(conn, lenbuf, lenbuf_len);
  5806. if (ret != (int)lenbuf_len) {
  5807. return -1;
  5808. }
  5809. t = ret;
  5810. ret = mg_write(conn, chunk, chunk_len);
  5811. if (ret != (int)chunk_len) {
  5812. return -1;
  5813. }
  5814. t += ret;
  5815. ret = mg_write(conn, "\r\n", 2);
  5816. if (ret != 2) {
  5817. return -1;
  5818. }
  5819. t += ret;
  5820. return t;
  5821. }
  5822. #if defined(GCC_DIAGNOSTIC)
  5823. /* This block forwards format strings to printf implementations,
  5824. * so we need to disable the format-nonliteral warning. */
  5825. #pragma GCC diagnostic push
  5826. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5827. #endif
  5828. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5829. static int
  5830. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5831. {
  5832. va_list ap_copy;
  5833. size_t size = MG_BUF_LEN / 4;
  5834. int len = -1;
  5835. *buf = NULL;
  5836. while (len < 0) {
  5837. if (*buf) {
  5838. mg_free(*buf);
  5839. }
  5840. size *= 4;
  5841. *buf = (char *)mg_malloc(size);
  5842. if (!*buf) {
  5843. break;
  5844. }
  5845. va_copy(ap_copy, ap);
  5846. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5847. va_end(ap_copy);
  5848. (*buf)[size - 1] = 0;
  5849. }
  5850. return len;
  5851. }
  5852. /* Print message to buffer. If buffer is large enough to hold the message,
  5853. * return buffer. If buffer is to small, allocate large enough buffer on
  5854. * heap,
  5855. * and return allocated buffer. */
  5856. static int
  5857. alloc_vprintf(char **out_buf,
  5858. char *prealloc_buf,
  5859. size_t prealloc_size,
  5860. const char *fmt,
  5861. va_list ap)
  5862. {
  5863. va_list ap_copy;
  5864. int len;
  5865. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5866. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5867. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5868. * Therefore, we make two passes: on first pass, get required message
  5869. * length.
  5870. * On second pass, actually print the message. */
  5871. va_copy(ap_copy, ap);
  5872. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5873. va_end(ap_copy);
  5874. if (len < 0) {
  5875. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5876. * Switch to alternative code path that uses incremental
  5877. * allocations.
  5878. */
  5879. va_copy(ap_copy, ap);
  5880. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5881. va_end(ap_copy);
  5882. } else if ((size_t)(len) >= prealloc_size) {
  5883. /* The pre-allocated buffer not large enough. */
  5884. /* Allocate a new buffer. */
  5885. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5886. if (!*out_buf) {
  5887. /* Allocation failed. Return -1 as "out of memory" error. */
  5888. return -1;
  5889. }
  5890. /* Buffer allocation successful. Store the string there. */
  5891. va_copy(ap_copy, ap);
  5892. IGNORE_UNUSED_RESULT(
  5893. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5894. va_end(ap_copy);
  5895. } else {
  5896. /* The pre-allocated buffer is large enough.
  5897. * Use it to store the string and return the address. */
  5898. va_copy(ap_copy, ap);
  5899. IGNORE_UNUSED_RESULT(
  5900. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5901. va_end(ap_copy);
  5902. *out_buf = prealloc_buf;
  5903. }
  5904. return len;
  5905. }
  5906. #if defined(GCC_DIAGNOSTIC)
  5907. /* Enable format-nonliteral warning again. */
  5908. #pragma GCC diagnostic pop
  5909. #endif
  5910. static int
  5911. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5912. {
  5913. char mem[MG_BUF_LEN];
  5914. char *buf = NULL;
  5915. int len;
  5916. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5917. len = mg_write(conn, buf, (size_t)len);
  5918. }
  5919. if ((buf != mem) && (buf != NULL)) {
  5920. mg_free(buf);
  5921. }
  5922. return len;
  5923. }
  5924. int
  5925. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5926. {
  5927. va_list ap;
  5928. int result;
  5929. va_start(ap, fmt);
  5930. result = mg_vprintf(conn, fmt, ap);
  5931. va_end(ap);
  5932. return result;
  5933. }
  5934. int
  5935. mg_url_decode(const char *src,
  5936. int src_len,
  5937. char *dst,
  5938. int dst_len,
  5939. int is_form_url_encoded)
  5940. {
  5941. int i, j, a, b;
  5942. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5943. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5944. if ((i < src_len - 2) && (src[i] == '%')
  5945. && isxdigit((unsigned char)src[i + 1])
  5946. && isxdigit((unsigned char)src[i + 2])) {
  5947. a = tolower((unsigned char)src[i + 1]);
  5948. b = tolower((unsigned char)src[i + 2]);
  5949. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5950. i += 2;
  5951. } else if (is_form_url_encoded && (src[i] == '+')) {
  5952. dst[j] = ' ';
  5953. } else {
  5954. dst[j] = src[i];
  5955. }
  5956. }
  5957. dst[j] = '\0'; /* Null-terminate the destination */
  5958. return (i >= src_len) ? j : -1;
  5959. }
  5960. int
  5961. mg_get_var(const char *data,
  5962. size_t data_len,
  5963. const char *name,
  5964. char *dst,
  5965. size_t dst_len)
  5966. {
  5967. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5968. }
  5969. int
  5970. mg_get_var2(const char *data,
  5971. size_t data_len,
  5972. const char *name,
  5973. char *dst,
  5974. size_t dst_len,
  5975. size_t occurrence)
  5976. {
  5977. const char *p, *e, *s;
  5978. size_t name_len;
  5979. int len;
  5980. if ((dst == NULL) || (dst_len == 0)) {
  5981. len = -2;
  5982. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5983. len = -1;
  5984. dst[0] = '\0';
  5985. } else {
  5986. name_len = strlen(name);
  5987. e = data + data_len;
  5988. len = -1;
  5989. dst[0] = '\0';
  5990. /* data is "var1=val1&var2=val2...". Find variable first */
  5991. for (p = data; p + name_len < e; p++) {
  5992. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5993. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5994. /* Point p to variable value */
  5995. p += name_len + 1;
  5996. /* Point s to the end of the value */
  5997. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5998. if (s == NULL) {
  5999. s = e;
  6000. }
  6001. DEBUG_ASSERT(s >= p);
  6002. if (s < p) {
  6003. return -3;
  6004. }
  6005. /* Decode variable into destination buffer */
  6006. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6007. /* Redirect error code from -1 to -2 (destination buffer too
  6008. * small). */
  6009. if (len == -1) {
  6010. len = -2;
  6011. }
  6012. break;
  6013. }
  6014. }
  6015. }
  6016. return len;
  6017. }
  6018. /* HCP24: some changes to compare hole var_name */
  6019. int
  6020. mg_get_cookie(const char *cookie_header,
  6021. const char *var_name,
  6022. char *dst,
  6023. size_t dst_size)
  6024. {
  6025. const char *s, *p, *end;
  6026. int name_len, len = -1;
  6027. if ((dst == NULL) || (dst_size == 0)) {
  6028. return -2;
  6029. }
  6030. dst[0] = '\0';
  6031. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6032. return -1;
  6033. }
  6034. name_len = (int)strlen(var_name);
  6035. end = s + strlen(s);
  6036. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6037. if (s[name_len] == '=') {
  6038. /* HCP24: now check is it a substring or a full cookie name */
  6039. if ((s == cookie_header) || (s[-1] == ' ')) {
  6040. s += name_len + 1;
  6041. if ((p = strchr(s, ' ')) == NULL) {
  6042. p = end;
  6043. }
  6044. if (p[-1] == ';') {
  6045. p--;
  6046. }
  6047. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6048. s++;
  6049. p--;
  6050. }
  6051. if ((size_t)(p - s) < dst_size) {
  6052. len = (int)(p - s);
  6053. mg_strlcpy(dst, s, (size_t)len + 1);
  6054. } else {
  6055. len = -3;
  6056. }
  6057. break;
  6058. }
  6059. }
  6060. }
  6061. return len;
  6062. }
  6063. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6064. static void
  6065. base64_encode(const unsigned char *src, int src_len, char *dst)
  6066. {
  6067. static const char *b64 =
  6068. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6069. int i, j, a, b, c;
  6070. for (i = j = 0; i < src_len; i += 3) {
  6071. a = src[i];
  6072. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6073. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6074. dst[j++] = b64[a >> 2];
  6075. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6076. if (i + 1 < src_len) {
  6077. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6078. }
  6079. if (i + 2 < src_len) {
  6080. dst[j++] = b64[c & 63];
  6081. }
  6082. }
  6083. while (j % 4 != 0) {
  6084. dst[j++] = '=';
  6085. }
  6086. dst[j++] = '\0';
  6087. }
  6088. #endif
  6089. #if defined(USE_LUA)
  6090. static unsigned char
  6091. b64reverse(char letter)
  6092. {
  6093. if ((letter >= 'A') && (letter <= 'Z')) {
  6094. return letter - 'A';
  6095. }
  6096. if ((letter >= 'a') && (letter <= 'z')) {
  6097. return letter - 'a' + 26;
  6098. }
  6099. if ((letter >= '0') && (letter <= '9')) {
  6100. return letter - '0' + 52;
  6101. }
  6102. if (letter == '+') {
  6103. return 62;
  6104. }
  6105. if (letter == '/') {
  6106. return 63;
  6107. }
  6108. if (letter == '=') {
  6109. return 255; /* normal end */
  6110. }
  6111. return 254; /* error */
  6112. }
  6113. static int
  6114. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6115. {
  6116. int i;
  6117. unsigned char a, b, c, d;
  6118. *dst_len = 0;
  6119. for (i = 0; i < src_len; i += 4) {
  6120. a = b64reverse(src[i]);
  6121. if (a >= 254) {
  6122. return i;
  6123. }
  6124. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6125. if (b >= 254) {
  6126. return i + 1;
  6127. }
  6128. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6129. if (c == 254) {
  6130. return i + 2;
  6131. }
  6132. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6133. if (d == 254) {
  6134. return i + 3;
  6135. }
  6136. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6137. if (c != 255) {
  6138. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6139. if (d != 255) {
  6140. dst[(*dst_len)++] = (c << 6) + d;
  6141. }
  6142. }
  6143. }
  6144. return -1;
  6145. }
  6146. #endif
  6147. static int
  6148. is_put_or_delete_method(const struct mg_connection *conn)
  6149. {
  6150. if (conn) {
  6151. const char *s = conn->request_info.request_method;
  6152. return (s != NULL)
  6153. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6154. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6155. }
  6156. return 0;
  6157. }
  6158. #if !defined(NO_FILES)
  6159. static int
  6160. extention_matches_script(
  6161. struct mg_connection *conn, /* in: request (must be valid) */
  6162. const char *filename /* in: filename (must be valid) */
  6163. )
  6164. {
  6165. #if !defined(NO_CGI)
  6166. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6167. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6168. filename)
  6169. > 0) {
  6170. return 1;
  6171. }
  6172. #endif
  6173. #if defined(USE_LUA)
  6174. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6175. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6176. filename)
  6177. > 0) {
  6178. return 1;
  6179. }
  6180. #endif
  6181. #if defined(USE_DUKTAPE)
  6182. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6183. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6184. filename)
  6185. > 0) {
  6186. return 1;
  6187. }
  6188. #endif
  6189. /* filename and conn could be unused, if all preocessor conditions
  6190. * are false (no script language supported). */
  6191. (void)filename;
  6192. (void)conn;
  6193. return 0;
  6194. }
  6195. /* For given directory path, substitute it to valid index file.
  6196. * Return 1 if index file has been found, 0 if not found.
  6197. * If the file is found, it's stats is returned in stp. */
  6198. static int
  6199. substitute_index_file(struct mg_connection *conn,
  6200. char *path,
  6201. size_t path_len,
  6202. struct mg_file_stat *filestat)
  6203. {
  6204. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6205. struct vec filename_vec;
  6206. size_t n = strlen(path);
  6207. int found = 0;
  6208. /* The 'path' given to us points to the directory. Remove all trailing
  6209. * directory separator characters from the end of the path, and
  6210. * then append single directory separator character. */
  6211. while ((n > 0) && (path[n - 1] == '/')) {
  6212. n--;
  6213. }
  6214. path[n] = '/';
  6215. /* Traverse index files list. For each entry, append it to the given
  6216. * path and see if the file exists. If it exists, break the loop */
  6217. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6218. /* Ignore too long entries that may overflow path buffer */
  6219. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6220. continue;
  6221. }
  6222. /* Prepare full path to the index file */
  6223. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6224. /* Does it exist? */
  6225. if (mg_stat(conn, path, filestat)) {
  6226. /* Yes it does, break the loop */
  6227. found = 1;
  6228. break;
  6229. }
  6230. }
  6231. /* If no index file exists, restore directory path */
  6232. if (!found) {
  6233. path[n] = '\0';
  6234. }
  6235. return found;
  6236. }
  6237. #endif
  6238. static void
  6239. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6240. char *filename, /* out: filename */
  6241. size_t filename_buf_len, /* in: size of filename buffer */
  6242. struct mg_file_stat *filestat, /* out: file status structure */
  6243. int *is_found, /* out: file found (directly) */
  6244. int *is_script_resource, /* out: handled by a script? */
  6245. int *is_websocket_request, /* out: websocket connetion? */
  6246. int *is_put_or_delete_request /* out: put/delete a file? */
  6247. )
  6248. {
  6249. char const *accept_encoding;
  6250. #if !defined(NO_FILES)
  6251. const char *uri = conn->request_info.local_uri;
  6252. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6253. const char *rewrite;
  6254. struct vec a, b;
  6255. ptrdiff_t match_len;
  6256. char gz_path[PATH_MAX];
  6257. int truncated;
  6258. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6259. char *tmp_str;
  6260. size_t tmp_str_len, sep_pos;
  6261. int allow_substitute_script_subresources;
  6262. #endif
  6263. #else
  6264. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6265. #endif
  6266. /* Step 1: Set all initially unknown outputs to zero */
  6267. memset(filestat, 0, sizeof(*filestat));
  6268. *filename = 0;
  6269. *is_found = 0;
  6270. *is_script_resource = 0;
  6271. /* Step 2: Check if the request attempts to modify the file system */
  6272. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6273. /* Step 3: Check if it is a websocket request, and modify the document
  6274. * root if required */
  6275. #if defined(USE_WEBSOCKET)
  6276. *is_websocket_request = is_websocket_protocol(conn);
  6277. #if !defined(NO_FILES)
  6278. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6279. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6280. }
  6281. #endif /* !NO_FILES */
  6282. #else /* USE_WEBSOCKET */
  6283. *is_websocket_request = 0;
  6284. #endif /* USE_WEBSOCKET */
  6285. /* Step 4: Check if gzip encoded response is allowed */
  6286. conn->accept_gzip = 0;
  6287. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6288. if (strstr(accept_encoding, "gzip") != NULL) {
  6289. conn->accept_gzip = 1;
  6290. }
  6291. }
  6292. #if !defined(NO_FILES)
  6293. /* Step 5: If there is no root directory, don't look for files. */
  6294. /* Note that root == NULL is a regular use case here. This occurs,
  6295. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6296. * config is not required. */
  6297. if (root == NULL) {
  6298. /* all file related outputs have already been set to 0, just return
  6299. */
  6300. return;
  6301. }
  6302. /* Step 6: Determine the local file path from the root path and the
  6303. * request uri. */
  6304. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6305. * part of the path one byte on the right. */
  6306. mg_snprintf(
  6307. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6308. if (truncated) {
  6309. goto interpret_cleanup;
  6310. }
  6311. /* Step 7: URI rewriting */
  6312. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6313. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6314. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6315. mg_snprintf(conn,
  6316. &truncated,
  6317. filename,
  6318. filename_buf_len - 1,
  6319. "%.*s%s",
  6320. (int)b.len,
  6321. b.ptr,
  6322. uri + match_len);
  6323. break;
  6324. }
  6325. }
  6326. if (truncated) {
  6327. goto interpret_cleanup;
  6328. }
  6329. /* Step 8: Check if the file exists at the server */
  6330. /* Local file path and name, corresponding to requested URI
  6331. * is now stored in "filename" variable. */
  6332. if (mg_stat(conn, filename, filestat)) {
  6333. int uri_len = (int)strlen(uri);
  6334. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6335. /* 8.1: File exists. */
  6336. *is_found = 1;
  6337. /* 8.2: Check if it is a script type. */
  6338. if (extention_matches_script(conn, filename)) {
  6339. /* The request addresses a CGI resource, Lua script or
  6340. * server-side javascript.
  6341. * The URI corresponds to the script itself (like
  6342. * /path/script.cgi), and there is no additional resource
  6343. * path (like /path/script.cgi/something).
  6344. * Requests that modify (replace or delete) a resource, like
  6345. * PUT and DELETE requests, should replace/delete the script
  6346. * file.
  6347. * Requests that read or write from/to a resource, like GET and
  6348. * POST requests, should call the script and return the
  6349. * generated response. */
  6350. *is_script_resource = (!*is_put_or_delete_request);
  6351. }
  6352. /* 8.3: If the request target is a directory, there could be
  6353. * a substitute file (index.html, index.cgi, ...). */
  6354. if (filestat->is_directory && is_uri_end_slash) {
  6355. /* Use a local copy here, since substitute_index_file will
  6356. * change the content of the file status */
  6357. struct mg_file_stat tmp_filestat;
  6358. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6359. if (substitute_index_file(
  6360. conn, filename, filename_buf_len, &tmp_filestat)) {
  6361. /* Substitute file found. Copy stat to the output, then
  6362. * check if the file is a script file */
  6363. *filestat = tmp_filestat;
  6364. if (extention_matches_script(conn, filename)) {
  6365. /* Substitute file is a script file */
  6366. *is_script_resource = 1;
  6367. } else {
  6368. /* Substitute file is a regular file */
  6369. *is_script_resource = 0;
  6370. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6371. }
  6372. }
  6373. /* If there is no substitute file, the server could return
  6374. * a directory listing in a later step */
  6375. }
  6376. return;
  6377. }
  6378. /* Step 9: Check for zipped files: */
  6379. /* If we can't find the actual file, look for the file
  6380. * with the same name but a .gz extension. If we find it,
  6381. * use that and set the gzipped flag in the file struct
  6382. * to indicate that the response need to have the content-
  6383. * encoding: gzip header.
  6384. * We can only do this if the browser declares support. */
  6385. if (conn->accept_gzip) {
  6386. mg_snprintf(
  6387. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6388. if (truncated) {
  6389. goto interpret_cleanup;
  6390. }
  6391. if (mg_stat(conn, gz_path, filestat)) {
  6392. if (filestat) {
  6393. filestat->is_gzipped = 1;
  6394. *is_found = 1;
  6395. }
  6396. /* Currently gz files can not be scripts. */
  6397. return;
  6398. }
  6399. }
  6400. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6401. /* Step 10: Script resources may handle sub-resources */
  6402. /* Support PATH_INFO for CGI scripts. */
  6403. tmp_str_len = strlen(filename);
  6404. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6405. if (!tmp_str) {
  6406. /* Out of memory */
  6407. goto interpret_cleanup;
  6408. }
  6409. memcpy(tmp_str, filename, tmp_str_len + 1);
  6410. /* Check config, if index scripts may have sub-resources */
  6411. allow_substitute_script_subresources =
  6412. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6413. "yes");
  6414. sep_pos = tmp_str_len;
  6415. while (sep_pos > 0) {
  6416. sep_pos--;
  6417. if (tmp_str[sep_pos] == '/') {
  6418. int is_script = 0, does_exist = 0;
  6419. tmp_str[sep_pos] = 0;
  6420. if (tmp_str[0]) {
  6421. is_script = extention_matches_script(conn, tmp_str);
  6422. does_exist = mg_stat(conn, tmp_str, filestat);
  6423. }
  6424. if (does_exist && is_script) {
  6425. filename[sep_pos] = 0;
  6426. memmove(filename + sep_pos + 2,
  6427. filename + sep_pos + 1,
  6428. strlen(filename + sep_pos + 1) + 1);
  6429. conn->path_info = filename + sep_pos + 1;
  6430. filename[sep_pos + 1] = '/';
  6431. *is_script_resource = 1;
  6432. *is_found = 1;
  6433. break;
  6434. }
  6435. if (allow_substitute_script_subresources) {
  6436. if (substitute_index_file(
  6437. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6438. /* some intermediate directory has an index file */
  6439. if (extention_matches_script(conn, tmp_str)) {
  6440. char *tmp_str2;
  6441. DEBUG_TRACE("Substitute script %s serving path %s",
  6442. tmp_str,
  6443. filename);
  6444. /* this index file is a script */
  6445. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6446. conn->phys_ctx);
  6447. mg_snprintf(conn,
  6448. &truncated,
  6449. filename,
  6450. filename_buf_len,
  6451. "%s//%s",
  6452. tmp_str,
  6453. tmp_str2);
  6454. mg_free(tmp_str2);
  6455. if (truncated) {
  6456. mg_free(tmp_str);
  6457. goto interpret_cleanup;
  6458. }
  6459. sep_pos = strlen(tmp_str);
  6460. filename[sep_pos] = 0;
  6461. conn->path_info = filename + sep_pos + 1;
  6462. *is_script_resource = 1;
  6463. *is_found = 1;
  6464. break;
  6465. } else {
  6466. DEBUG_TRACE("Substitute file %s serving path %s",
  6467. tmp_str,
  6468. filename);
  6469. /* non-script files will not have sub-resources */
  6470. filename[sep_pos] = 0;
  6471. conn->path_info = 0;
  6472. *is_script_resource = 0;
  6473. *is_found = 0;
  6474. break;
  6475. }
  6476. }
  6477. }
  6478. tmp_str[sep_pos] = '/';
  6479. }
  6480. }
  6481. mg_free(tmp_str);
  6482. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6483. #endif /* !defined(NO_FILES) */
  6484. return;
  6485. #if !defined(NO_FILES)
  6486. /* Reset all outputs */
  6487. interpret_cleanup:
  6488. memset(filestat, 0, sizeof(*filestat));
  6489. *filename = 0;
  6490. *is_found = 0;
  6491. *is_script_resource = 0;
  6492. *is_websocket_request = 0;
  6493. *is_put_or_delete_request = 0;
  6494. #endif /* !defined(NO_FILES) */
  6495. }
  6496. /* Check whether full request is buffered. Return:
  6497. * -1 if request or response is malformed
  6498. * 0 if request or response is not yet fully buffered
  6499. * >0 actual request length, including last \r\n\r\n */
  6500. static int
  6501. get_http_header_len(const char *buf, int buflen)
  6502. {
  6503. int i;
  6504. for (i = 0; i < buflen; i++) {
  6505. /* Do an unsigned comparison in some conditions below */
  6506. const unsigned char c = (unsigned char)buf[i];
  6507. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6508. && !isprint(c)) {
  6509. /* abort scan as soon as one malformed character is found */
  6510. return -1;
  6511. }
  6512. if (i < buflen - 1) {
  6513. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6514. /* Two newline, no carriage return - not standard compliant,
  6515. * but
  6516. * it
  6517. * should be accepted */
  6518. return i + 2;
  6519. }
  6520. }
  6521. if (i < buflen - 3) {
  6522. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6523. && (buf[i + 3] == '\n')) {
  6524. /* Two \r\n - standard compliant */
  6525. return i + 4;
  6526. }
  6527. }
  6528. }
  6529. return 0;
  6530. }
  6531. #if !defined(NO_CACHING)
  6532. /* Convert month to the month number. Return -1 on error, or month number */
  6533. static int
  6534. get_month_index(const char *s)
  6535. {
  6536. size_t i;
  6537. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6538. if (!strcmp(s, month_names[i])) {
  6539. return (int)i;
  6540. }
  6541. }
  6542. return -1;
  6543. }
  6544. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6545. static time_t
  6546. parse_date_string(const char *datetime)
  6547. {
  6548. char month_str[32] = {0};
  6549. int second, minute, hour, day, month, year;
  6550. time_t result = (time_t)0;
  6551. struct tm tm;
  6552. if ((sscanf(datetime,
  6553. "%d/%3s/%d %d:%d:%d",
  6554. &day,
  6555. month_str,
  6556. &year,
  6557. &hour,
  6558. &minute,
  6559. &second)
  6560. == 6)
  6561. || (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. "%*3s, %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. "%d-%3s-%d %d:%d:%d",
  6581. &day,
  6582. month_str,
  6583. &year,
  6584. &hour,
  6585. &minute,
  6586. &second)
  6587. == 6)) {
  6588. month = get_month_index(month_str);
  6589. if ((month >= 0) && (year >= 1970)) {
  6590. memset(&tm, 0, sizeof(tm));
  6591. tm.tm_year = year - 1900;
  6592. tm.tm_mon = month;
  6593. tm.tm_mday = day;
  6594. tm.tm_hour = hour;
  6595. tm.tm_min = minute;
  6596. tm.tm_sec = second;
  6597. result = timegm(&tm);
  6598. }
  6599. }
  6600. return result;
  6601. }
  6602. #endif /* !NO_CACHING */
  6603. /* Protect against directory disclosure attack by removing '..',
  6604. * excessive '/' and '\' characters */
  6605. static void
  6606. remove_double_dots_and_double_slashes(char *s)
  6607. {
  6608. char *p = s;
  6609. while ((s[0] == '.') && (s[1] == '.')) {
  6610. s++;
  6611. }
  6612. while (*s != '\0') {
  6613. *p++ = *s++;
  6614. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6615. /* Skip all following slashes, backslashes and double-dots */
  6616. while (s[0] != '\0') {
  6617. if ((s[0] == '/') || (s[0] == '\\')) {
  6618. s++;
  6619. } else if ((s[0] == '.') && (s[1] == '.')) {
  6620. s += 2;
  6621. } else {
  6622. break;
  6623. }
  6624. }
  6625. }
  6626. }
  6627. *p = '\0';
  6628. }
  6629. static const struct {
  6630. const char *extension;
  6631. size_t ext_len;
  6632. const char *mime_type;
  6633. } builtin_mime_types[] = {
  6634. /* IANA registered MIME types
  6635. * (http://www.iana.org/assignments/media-types)
  6636. * application types */
  6637. {".doc", 4, "application/msword"},
  6638. {".eps", 4, "application/postscript"},
  6639. {".exe", 4, "application/octet-stream"},
  6640. {".js", 3, "application/javascript"},
  6641. {".json", 5, "application/json"},
  6642. {".pdf", 4, "application/pdf"},
  6643. {".ps", 3, "application/postscript"},
  6644. {".rtf", 4, "application/rtf"},
  6645. {".xhtml", 6, "application/xhtml+xml"},
  6646. {".xsl", 4, "application/xml"},
  6647. {".xslt", 5, "application/xml"},
  6648. /* fonts */
  6649. {".ttf", 4, "application/font-sfnt"},
  6650. {".cff", 4, "application/font-sfnt"},
  6651. {".otf", 4, "application/font-sfnt"},
  6652. {".aat", 4, "application/font-sfnt"},
  6653. {".sil", 4, "application/font-sfnt"},
  6654. {".pfr", 4, "application/font-tdpfr"},
  6655. {".woff", 5, "application/font-woff"},
  6656. /* audio */
  6657. {".mp3", 4, "audio/mpeg"},
  6658. {".oga", 4, "audio/ogg"},
  6659. {".ogg", 4, "audio/ogg"},
  6660. /* image */
  6661. {".gif", 4, "image/gif"},
  6662. {".ief", 4, "image/ief"},
  6663. {".jpeg", 5, "image/jpeg"},
  6664. {".jpg", 4, "image/jpeg"},
  6665. {".jpm", 4, "image/jpm"},
  6666. {".jpx", 4, "image/jpx"},
  6667. {".png", 4, "image/png"},
  6668. {".svg", 4, "image/svg+xml"},
  6669. {".tif", 4, "image/tiff"},
  6670. {".tiff", 5, "image/tiff"},
  6671. /* model */
  6672. {".wrl", 4, "model/vrml"},
  6673. /* text */
  6674. {".css", 4, "text/css"},
  6675. {".csv", 4, "text/csv"},
  6676. {".htm", 4, "text/html"},
  6677. {".html", 5, "text/html"},
  6678. {".sgm", 4, "text/sgml"},
  6679. {".shtm", 5, "text/html"},
  6680. {".shtml", 6, "text/html"},
  6681. {".txt", 4, "text/plain"},
  6682. {".xml", 4, "text/xml"},
  6683. /* video */
  6684. {".mov", 4, "video/quicktime"},
  6685. {".mp4", 4, "video/mp4"},
  6686. {".mpeg", 5, "video/mpeg"},
  6687. {".mpg", 4, "video/mpeg"},
  6688. {".ogv", 4, "video/ogg"},
  6689. {".qt", 3, "video/quicktime"},
  6690. /* not registered types
  6691. * (http://reference.sitepoint.com/html/mime-types-full,
  6692. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6693. {".arj", 4, "application/x-arj-compressed"},
  6694. {".gz", 3, "application/x-gunzip"},
  6695. {".rar", 4, "application/x-arj-compressed"},
  6696. {".swf", 4, "application/x-shockwave-flash"},
  6697. {".tar", 4, "application/x-tar"},
  6698. {".tgz", 4, "application/x-tar-gz"},
  6699. {".torrent", 8, "application/x-bittorrent"},
  6700. {".ppt", 4, "application/x-mspowerpoint"},
  6701. {".xls", 4, "application/x-msexcel"},
  6702. {".zip", 4, "application/x-zip-compressed"},
  6703. {".aac",
  6704. 4,
  6705. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6706. {".aif", 4, "audio/x-aif"},
  6707. {".m3u", 4, "audio/x-mpegurl"},
  6708. {".mid", 4, "audio/x-midi"},
  6709. {".ra", 3, "audio/x-pn-realaudio"},
  6710. {".ram", 4, "audio/x-pn-realaudio"},
  6711. {".wav", 4, "audio/x-wav"},
  6712. {".bmp", 4, "image/bmp"},
  6713. {".ico", 4, "image/x-icon"},
  6714. {".pct", 4, "image/x-pct"},
  6715. {".pict", 5, "image/pict"},
  6716. {".rgb", 4, "image/x-rgb"},
  6717. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6718. {".asf", 4, "video/x-ms-asf"},
  6719. {".avi", 4, "video/x-msvideo"},
  6720. {".m4v", 4, "video/x-m4v"},
  6721. {NULL, 0, NULL}};
  6722. const char *
  6723. mg_get_builtin_mime_type(const char *path)
  6724. {
  6725. const char *ext;
  6726. size_t i, path_len;
  6727. path_len = strlen(path);
  6728. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6729. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6730. if ((path_len > builtin_mime_types[i].ext_len)
  6731. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6732. return builtin_mime_types[i].mime_type;
  6733. }
  6734. }
  6735. return "text/plain";
  6736. }
  6737. /* Look at the "path" extension and figure what mime type it has.
  6738. * Store mime type in the vector. */
  6739. static void
  6740. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6741. {
  6742. struct vec ext_vec, mime_vec;
  6743. const char *list, *ext;
  6744. size_t path_len;
  6745. path_len = strlen(path);
  6746. if ((conn == NULL) || (vec == NULL)) {
  6747. if (vec != NULL) {
  6748. memset(vec, '\0', sizeof(struct vec));
  6749. }
  6750. return;
  6751. }
  6752. /* Scan user-defined mime types first, in case user wants to
  6753. * override default mime types. */
  6754. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6755. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6756. /* ext now points to the path suffix */
  6757. ext = path + path_len - ext_vec.len;
  6758. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6759. *vec = mime_vec;
  6760. return;
  6761. }
  6762. }
  6763. vec->ptr = mg_get_builtin_mime_type(path);
  6764. vec->len = strlen(vec->ptr);
  6765. }
  6766. /* Stringify binary data. Output buffer must be twice as big as input,
  6767. * because each byte takes 2 bytes in string representation */
  6768. static void
  6769. bin2str(char *to, const unsigned char *p, size_t len)
  6770. {
  6771. static const char *hex = "0123456789abcdef";
  6772. for (; len--; p++) {
  6773. *to++ = hex[p[0] >> 4];
  6774. *to++ = hex[p[0] & 0x0f];
  6775. }
  6776. *to = '\0';
  6777. }
  6778. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6779. */
  6780. char *
  6781. mg_md5(char buf[33], ...)
  6782. {
  6783. md5_byte_t hash[16];
  6784. const char *p;
  6785. va_list ap;
  6786. md5_state_t ctx;
  6787. md5_init(&ctx);
  6788. va_start(ap, buf);
  6789. while ((p = va_arg(ap, const char *)) != NULL) {
  6790. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6791. }
  6792. va_end(ap);
  6793. md5_finish(&ctx, hash);
  6794. bin2str(buf, hash, sizeof(hash));
  6795. return buf;
  6796. }
  6797. /* Check the user's password, return 1 if OK */
  6798. static int
  6799. check_password(const char *method,
  6800. const char *ha1,
  6801. const char *uri,
  6802. const char *nonce,
  6803. const char *nc,
  6804. const char *cnonce,
  6805. const char *qop,
  6806. const char *response)
  6807. {
  6808. char ha2[32 + 1], expected_response[32 + 1];
  6809. /* Some of the parameters may be NULL */
  6810. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6811. || (qop == NULL) || (response == NULL)) {
  6812. return 0;
  6813. }
  6814. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6815. if (strlen(response) != 32) {
  6816. return 0;
  6817. }
  6818. mg_md5(ha2, method, ":", uri, NULL);
  6819. mg_md5(expected_response,
  6820. ha1,
  6821. ":",
  6822. nonce,
  6823. ":",
  6824. nc,
  6825. ":",
  6826. cnonce,
  6827. ":",
  6828. qop,
  6829. ":",
  6830. ha2,
  6831. NULL);
  6832. return mg_strcasecmp(response, expected_response) == 0;
  6833. }
  6834. /* Use the global passwords file, if specified by auth_gpass option,
  6835. * or search for .htpasswd in the requested directory. */
  6836. static void
  6837. open_auth_file(struct mg_connection *conn,
  6838. const char *path,
  6839. struct mg_file *filep)
  6840. {
  6841. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6842. char name[PATH_MAX];
  6843. const char *p, *e,
  6844. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6845. int truncated;
  6846. if (gpass != NULL) {
  6847. /* Use global passwords file */
  6848. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6849. #if defined(DEBUG)
  6850. /* Use mg_cry_internal here, since gpass has been configured. */
  6851. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6852. #endif
  6853. }
  6854. /* Important: using local struct mg_file to test path for
  6855. * is_directory flag. If filep is used, mg_stat() makes it
  6856. * appear as if auth file was opened.
  6857. * TODO(mid): Check if this is still required after rewriting
  6858. * mg_stat */
  6859. } else if (mg_stat(conn, path, &filep->stat)
  6860. && filep->stat.is_directory) {
  6861. mg_snprintf(conn,
  6862. &truncated,
  6863. name,
  6864. sizeof(name),
  6865. "%s/%s",
  6866. path,
  6867. PASSWORDS_FILE_NAME);
  6868. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6869. #if defined(DEBUG)
  6870. /* Don't use mg_cry_internal here, but only a trace, since this
  6871. * is
  6872. * a typical case. It will occur for every directory
  6873. * without a password file. */
  6874. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6875. #endif
  6876. }
  6877. } else {
  6878. /* Try to find .htpasswd in requested directory. */
  6879. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6880. if (e[0] == '/') {
  6881. break;
  6882. }
  6883. }
  6884. mg_snprintf(conn,
  6885. &truncated,
  6886. name,
  6887. sizeof(name),
  6888. "%.*s/%s",
  6889. (int)(e - p),
  6890. p,
  6891. PASSWORDS_FILE_NAME);
  6892. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6893. #if defined(DEBUG)
  6894. /* Don't use mg_cry_internal here, but only a trace, since this
  6895. * is
  6896. * a typical case. It will occur for every directory
  6897. * without a password file. */
  6898. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6899. #endif
  6900. }
  6901. }
  6902. }
  6903. }
  6904. /* Parsed Authorization header */
  6905. struct ah {
  6906. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6907. };
  6908. /* Return 1 on success. Always initializes the ah structure. */
  6909. static int
  6910. parse_auth_header(struct mg_connection *conn,
  6911. char *buf,
  6912. size_t buf_size,
  6913. struct ah *ah)
  6914. {
  6915. char *name, *value, *s;
  6916. const char *auth_header;
  6917. uint64_t nonce;
  6918. if (!ah || !conn) {
  6919. return 0;
  6920. }
  6921. (void)memset(ah, 0, sizeof(*ah));
  6922. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6923. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6924. return 0;
  6925. }
  6926. /* Make modifiable copy of the auth header */
  6927. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6928. s = buf;
  6929. /* Parse authorization header */
  6930. for (;;) {
  6931. /* Gobble initial spaces */
  6932. while (isspace((unsigned char)*s)) {
  6933. s++;
  6934. }
  6935. name = skip_quoted(&s, "=", " ", 0);
  6936. /* Value is either quote-delimited, or ends at first comma or space.
  6937. */
  6938. if (s[0] == '\"') {
  6939. s++;
  6940. value = skip_quoted(&s, "\"", " ", '\\');
  6941. if (s[0] == ',') {
  6942. s++;
  6943. }
  6944. } else {
  6945. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6946. * spaces */
  6947. }
  6948. if (*name == '\0') {
  6949. break;
  6950. }
  6951. if (!strcmp(name, "username")) {
  6952. ah->user = value;
  6953. } else if (!strcmp(name, "cnonce")) {
  6954. ah->cnonce = value;
  6955. } else if (!strcmp(name, "response")) {
  6956. ah->response = value;
  6957. } else if (!strcmp(name, "uri")) {
  6958. ah->uri = value;
  6959. } else if (!strcmp(name, "qop")) {
  6960. ah->qop = value;
  6961. } else if (!strcmp(name, "nc")) {
  6962. ah->nc = value;
  6963. } else if (!strcmp(name, "nonce")) {
  6964. ah->nonce = value;
  6965. }
  6966. }
  6967. #if !defined(NO_NONCE_CHECK)
  6968. /* Read the nonce from the response. */
  6969. if (ah->nonce == NULL) {
  6970. return 0;
  6971. }
  6972. s = NULL;
  6973. nonce = strtoull(ah->nonce, &s, 10);
  6974. if ((s == NULL) || (*s != 0)) {
  6975. return 0;
  6976. }
  6977. /* Convert the nonce from the client to a number. */
  6978. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6979. /* The converted number corresponds to the time the nounce has been
  6980. * created. This should not be earlier than the server start. */
  6981. /* Server side nonce check is valuable in all situations but one:
  6982. * if the server restarts frequently, but the client should not see
  6983. * that, so the server should accept nonces from previous starts. */
  6984. /* However, the reasonable default is to not accept a nonce from a
  6985. * previous start, so if anyone changed the access rights between
  6986. * two restarts, a new login is required. */
  6987. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6988. /* nonce is from a previous start of the server and no longer valid
  6989. * (replay attack?) */
  6990. return 0;
  6991. }
  6992. /* Check if the nonce is too high, so it has not (yet) been used by the
  6993. * server. */
  6994. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6995. + conn->dom_ctx->nonce_count)) {
  6996. return 0;
  6997. }
  6998. #else
  6999. (void)nonce;
  7000. #endif
  7001. /* CGI needs it as REMOTE_USER */
  7002. if (ah->user != NULL) {
  7003. conn->request_info.remote_user =
  7004. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7005. } else {
  7006. return 0;
  7007. }
  7008. return 1;
  7009. }
  7010. static const char *
  7011. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7012. {
  7013. #if defined(MG_USE_OPEN_FILE)
  7014. const char *eof;
  7015. size_t len;
  7016. const char *memend;
  7017. #else
  7018. (void)p; /* parameter is unused */
  7019. #endif
  7020. if (!filep) {
  7021. return NULL;
  7022. }
  7023. #if defined(MG_USE_OPEN_FILE)
  7024. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7025. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7026. /* Search for \n from p till the end of stream */
  7027. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7028. if (eof != NULL) {
  7029. eof += 1; /* Include \n */
  7030. } else {
  7031. eof = memend; /* Copy remaining data */
  7032. }
  7033. len =
  7034. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7035. memcpy(buf, *p, len);
  7036. buf[len] = '\0';
  7037. *p += len;
  7038. return len ? eof : NULL;
  7039. } else /* filep->access.fp block below */
  7040. #endif
  7041. if (filep->access.fp != NULL) {
  7042. return fgets(buf, (int)size, filep->access.fp);
  7043. } else {
  7044. return NULL;
  7045. }
  7046. }
  7047. /* Define the initial recursion depth for procesesing htpasswd files that
  7048. * include other htpasswd
  7049. * (or even the same) files. It is not difficult to provide a file or files
  7050. * s.t. they force civetweb
  7051. * to infinitely recurse and then crash.
  7052. */
  7053. #define INITIAL_DEPTH 9
  7054. #if INITIAL_DEPTH <= 0
  7055. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7056. #endif
  7057. struct read_auth_file_struct {
  7058. struct mg_connection *conn;
  7059. struct ah ah;
  7060. const char *domain;
  7061. char buf[256 + 256 + 40];
  7062. const char *f_user;
  7063. const char *f_domain;
  7064. const char *f_ha1;
  7065. };
  7066. static int
  7067. read_auth_file(struct mg_file *filep,
  7068. struct read_auth_file_struct *workdata,
  7069. int depth)
  7070. {
  7071. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7072. int is_authorized = 0;
  7073. struct mg_file fp;
  7074. size_t l;
  7075. if (!filep || !workdata || (0 == depth)) {
  7076. return 0;
  7077. }
  7078. /* Loop over passwords file */
  7079. #if defined(MG_USE_OPEN_FILE)
  7080. p = (char *)filep->access.membuf;
  7081. #endif
  7082. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7083. l = strlen(workdata->buf);
  7084. while (l > 0) {
  7085. if (isspace((unsigned char)workdata->buf[l - 1])
  7086. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7087. l--;
  7088. workdata->buf[l] = 0;
  7089. } else
  7090. break;
  7091. }
  7092. if (l < 1) {
  7093. continue;
  7094. }
  7095. workdata->f_user = workdata->buf;
  7096. if (workdata->f_user[0] == ':') {
  7097. /* user names may not contain a ':' and may not be empty,
  7098. * so lines starting with ':' may be used for a special purpose
  7099. */
  7100. if (workdata->f_user[1] == '#') {
  7101. /* :# is a comment */
  7102. continue;
  7103. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7104. if (mg_fopen(workdata->conn,
  7105. workdata->f_user + 9,
  7106. MG_FOPEN_MODE_READ,
  7107. &fp)) {
  7108. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7109. (void)mg_fclose(
  7110. &fp.access); /* ignore error on read only file */
  7111. /* No need to continue processing files once we have a
  7112. * match, since nothing will reset it back
  7113. * to 0.
  7114. */
  7115. if (is_authorized) {
  7116. return is_authorized;
  7117. }
  7118. } else {
  7119. mg_cry_internal(workdata->conn,
  7120. "%s: cannot open authorization file: %s",
  7121. __func__,
  7122. workdata->buf);
  7123. }
  7124. continue;
  7125. }
  7126. /* everything is invalid for the moment (might change in the
  7127. * future) */
  7128. mg_cry_internal(workdata->conn,
  7129. "%s: syntax error in authorization file: %s",
  7130. __func__,
  7131. workdata->buf);
  7132. continue;
  7133. }
  7134. workdata->f_domain = strchr(workdata->f_user, ':');
  7135. if (workdata->f_domain == NULL) {
  7136. mg_cry_internal(workdata->conn,
  7137. "%s: syntax error in authorization file: %s",
  7138. __func__,
  7139. workdata->buf);
  7140. continue;
  7141. }
  7142. *(char *)(workdata->f_domain) = 0;
  7143. (workdata->f_domain)++;
  7144. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7145. if (workdata->f_ha1 == NULL) {
  7146. mg_cry_internal(workdata->conn,
  7147. "%s: syntax error in authorization file: %s",
  7148. __func__,
  7149. workdata->buf);
  7150. continue;
  7151. }
  7152. *(char *)(workdata->f_ha1) = 0;
  7153. (workdata->f_ha1)++;
  7154. if (!strcmp(workdata->ah.user, workdata->f_user)
  7155. && !strcmp(workdata->domain, workdata->f_domain)) {
  7156. return check_password(workdata->conn->request_info.request_method,
  7157. workdata->f_ha1,
  7158. workdata->ah.uri,
  7159. workdata->ah.nonce,
  7160. workdata->ah.nc,
  7161. workdata->ah.cnonce,
  7162. workdata->ah.qop,
  7163. workdata->ah.response);
  7164. }
  7165. }
  7166. return is_authorized;
  7167. }
  7168. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7169. static int
  7170. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7171. {
  7172. struct read_auth_file_struct workdata;
  7173. char buf[MG_BUF_LEN];
  7174. if (!conn || !conn->dom_ctx) {
  7175. return 0;
  7176. }
  7177. memset(&workdata, 0, sizeof(workdata));
  7178. workdata.conn = conn;
  7179. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7180. return 0;
  7181. }
  7182. if (realm) {
  7183. workdata.domain = realm;
  7184. } else {
  7185. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7186. }
  7187. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7188. }
  7189. /* Public function to check http digest authentication header */
  7190. int
  7191. mg_check_digest_access_authentication(struct mg_connection *conn,
  7192. const char *realm,
  7193. const char *filename)
  7194. {
  7195. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7196. int auth;
  7197. if (!conn || !filename) {
  7198. return -1;
  7199. }
  7200. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7201. return -2;
  7202. }
  7203. auth = authorize(conn, &file, realm);
  7204. mg_fclose(&file.access);
  7205. return auth;
  7206. }
  7207. /* Return 1 if request is authorised, 0 otherwise. */
  7208. static int
  7209. check_authorization(struct mg_connection *conn, const char *path)
  7210. {
  7211. char fname[PATH_MAX];
  7212. struct vec uri_vec, filename_vec;
  7213. const char *list;
  7214. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7215. int authorized = 1, truncated;
  7216. if (!conn || !conn->dom_ctx) {
  7217. return 0;
  7218. }
  7219. list = conn->dom_ctx->config[PROTECT_URI];
  7220. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7221. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7222. mg_snprintf(conn,
  7223. &truncated,
  7224. fname,
  7225. sizeof(fname),
  7226. "%.*s",
  7227. (int)filename_vec.len,
  7228. filename_vec.ptr);
  7229. if (truncated
  7230. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7231. mg_cry_internal(conn,
  7232. "%s: cannot open %s: %s",
  7233. __func__,
  7234. fname,
  7235. strerror(errno));
  7236. }
  7237. break;
  7238. }
  7239. }
  7240. if (!is_file_opened(&file.access)) {
  7241. open_auth_file(conn, path, &file);
  7242. }
  7243. if (is_file_opened(&file.access)) {
  7244. authorized = authorize(conn, &file, NULL);
  7245. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7246. }
  7247. return authorized;
  7248. }
  7249. /* Internal function. Assumes conn is valid */
  7250. static void
  7251. send_authorization_request(struct mg_connection *conn, const char *realm)
  7252. {
  7253. char date[64];
  7254. time_t curtime = time(NULL);
  7255. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7256. if (!realm) {
  7257. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7258. }
  7259. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7260. nonce += conn->dom_ctx->nonce_count;
  7261. ++conn->dom_ctx->nonce_count;
  7262. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7263. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7264. conn->status_code = 401;
  7265. conn->must_close = 1;
  7266. gmt_time_string(date, sizeof(date), &curtime);
  7267. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7268. send_no_cache_header(conn);
  7269. send_additional_header(conn);
  7270. mg_printf(conn,
  7271. "Date: %s\r\n"
  7272. "Connection: %s\r\n"
  7273. "Content-Length: 0\r\n"
  7274. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7275. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7276. date,
  7277. suggest_connection_header(conn),
  7278. realm,
  7279. nonce);
  7280. }
  7281. /* Interface function. Parameters are provided by the user, so do
  7282. * at least some basic checks.
  7283. */
  7284. int
  7285. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7286. const char *realm)
  7287. {
  7288. if (conn && conn->dom_ctx) {
  7289. send_authorization_request(conn, realm);
  7290. return 0;
  7291. }
  7292. return -1;
  7293. }
  7294. #if !defined(NO_FILES)
  7295. static int
  7296. is_authorized_for_put(struct mg_connection *conn)
  7297. {
  7298. if (conn) {
  7299. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7300. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7301. int ret = 0;
  7302. if (passfile != NULL
  7303. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7304. ret = authorize(conn, &file, NULL);
  7305. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7306. }
  7307. return ret;
  7308. }
  7309. return 0;
  7310. }
  7311. #endif
  7312. int
  7313. mg_modify_passwords_file(const char *fname,
  7314. const char *domain,
  7315. const char *user,
  7316. const char *pass)
  7317. {
  7318. int found, i;
  7319. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7320. FILE *fp, *fp2;
  7321. found = 0;
  7322. fp = fp2 = NULL;
  7323. /* Regard empty password as no password - remove user record. */
  7324. if ((pass != NULL) && (pass[0] == '\0')) {
  7325. pass = NULL;
  7326. }
  7327. /* Other arguments must not be empty */
  7328. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7329. return 0;
  7330. }
  7331. /* Using the given file format, user name and domain must not contain
  7332. * ':'
  7333. */
  7334. if (strchr(user, ':') != NULL) {
  7335. return 0;
  7336. }
  7337. if (strchr(domain, ':') != NULL) {
  7338. return 0;
  7339. }
  7340. /* Do not allow control characters like newline in user name and domain.
  7341. * Do not allow excessively long names either. */
  7342. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7343. if (iscntrl((unsigned char)user[i])) {
  7344. return 0;
  7345. }
  7346. }
  7347. if (user[i]) {
  7348. return 0;
  7349. }
  7350. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7351. if (iscntrl((unsigned char)domain[i])) {
  7352. return 0;
  7353. }
  7354. }
  7355. if (domain[i]) {
  7356. return 0;
  7357. }
  7358. /* The maximum length of the path to the password file is limited */
  7359. if ((strlen(fname) + 4) >= PATH_MAX) {
  7360. return 0;
  7361. }
  7362. /* Create a temporary file name. Length has been checked before. */
  7363. strcpy(tmp, fname);
  7364. strcat(tmp, ".tmp");
  7365. /* Create the file if does not exist */
  7366. /* Use of fopen here is OK, since fname is only ASCII */
  7367. if ((fp = fopen(fname, "a+")) != NULL) {
  7368. (void)fclose(fp);
  7369. }
  7370. /* Open the given file and temporary file */
  7371. if ((fp = fopen(fname, "r")) == NULL) {
  7372. return 0;
  7373. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7374. fclose(fp);
  7375. return 0;
  7376. }
  7377. /* Copy the stuff to temporary file */
  7378. while (fgets(line, sizeof(line), fp) != NULL) {
  7379. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7380. continue;
  7381. }
  7382. u[255] = 0;
  7383. d[255] = 0;
  7384. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7385. found++;
  7386. if (pass != NULL) {
  7387. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7388. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7389. }
  7390. } else {
  7391. fprintf(fp2, "%s", line);
  7392. }
  7393. }
  7394. /* If new user, just add it */
  7395. if (!found && (pass != NULL)) {
  7396. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7397. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7398. }
  7399. /* Close files */
  7400. fclose(fp);
  7401. fclose(fp2);
  7402. /* Put the temp file in place of real file */
  7403. IGNORE_UNUSED_RESULT(remove(fname));
  7404. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7405. return 1;
  7406. }
  7407. static int
  7408. is_valid_port(unsigned long port)
  7409. {
  7410. return (port <= 0xffff);
  7411. }
  7412. static int
  7413. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7414. {
  7415. struct addrinfo hints, *res, *ressave;
  7416. int func_ret = 0;
  7417. int gai_ret;
  7418. memset(&hints, 0, sizeof(struct addrinfo));
  7419. hints.ai_family = af;
  7420. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7421. if (gai_ret != 0) {
  7422. /* gai_strerror could be used to convert gai_ret to a string */
  7423. /* POSIX return values: see
  7424. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7425. */
  7426. /* Windows return values: see
  7427. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7428. */
  7429. return 0;
  7430. }
  7431. ressave = res;
  7432. while (res) {
  7433. if (dstlen >= (size_t)res->ai_addrlen) {
  7434. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7435. func_ret = 1;
  7436. }
  7437. res = res->ai_next;
  7438. }
  7439. freeaddrinfo(ressave);
  7440. return func_ret;
  7441. }
  7442. static int
  7443. connect_socket(struct mg_context *ctx /* may be NULL */,
  7444. const char *host,
  7445. int port,
  7446. int use_ssl,
  7447. char *ebuf,
  7448. size_t ebuf_len,
  7449. SOCKET *sock /* output: socket, must not be NULL */,
  7450. union usa *sa /* output: socket address, must not be NULL */
  7451. )
  7452. {
  7453. int ip_ver = 0;
  7454. int conn_ret = -1;
  7455. int ret;
  7456. *sock = INVALID_SOCKET;
  7457. memset(sa, 0, sizeof(*sa));
  7458. if (ebuf_len > 0) {
  7459. *ebuf = 0;
  7460. }
  7461. if (host == NULL) {
  7462. mg_snprintf(NULL,
  7463. NULL, /* No truncation check for ebuf */
  7464. ebuf,
  7465. ebuf_len,
  7466. "%s",
  7467. "NULL host");
  7468. return 0;
  7469. }
  7470. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7471. mg_snprintf(NULL,
  7472. NULL, /* No truncation check for ebuf */
  7473. ebuf,
  7474. ebuf_len,
  7475. "%s",
  7476. "invalid port");
  7477. return 0;
  7478. }
  7479. #if !defined(NO_SSL)
  7480. #if !defined(NO_SSL_DL)
  7481. #if defined(OPENSSL_API_1_1)
  7482. if (use_ssl && (TLS_client_method == NULL)) {
  7483. mg_snprintf(NULL,
  7484. NULL, /* No truncation check for ebuf */
  7485. ebuf,
  7486. ebuf_len,
  7487. "%s",
  7488. "SSL is not initialized");
  7489. return 0;
  7490. }
  7491. #else
  7492. if (use_ssl && (SSLv23_client_method == NULL)) {
  7493. mg_snprintf(NULL,
  7494. NULL, /* No truncation check for ebuf */
  7495. ebuf,
  7496. ebuf_len,
  7497. "%s",
  7498. "SSL is not initialized");
  7499. return 0;
  7500. }
  7501. #endif /* OPENSSL_API_1_1 */
  7502. #else
  7503. (void)use_ssl;
  7504. #endif /* NO_SSL_DL */
  7505. #else
  7506. (void)use_ssl;
  7507. #endif /* !defined(NO_SSL) */
  7508. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7509. sa->sin.sin_family = AF_INET;
  7510. sa->sin.sin_port = htons((uint16_t)port);
  7511. ip_ver = 4;
  7512. #if defined(USE_IPV6)
  7513. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7514. sa->sin6.sin6_family = AF_INET6;
  7515. sa->sin6.sin6_port = htons((uint16_t)port);
  7516. ip_ver = 6;
  7517. } else if (host[0] == '[') {
  7518. /* While getaddrinfo on Windows will work with [::1],
  7519. * getaddrinfo on Linux only works with ::1 (without []). */
  7520. size_t l = strlen(host + 1);
  7521. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7522. if (h) {
  7523. h[l - 1] = 0;
  7524. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7525. sa->sin6.sin6_family = AF_INET6;
  7526. sa->sin6.sin6_port = htons((uint16_t)port);
  7527. ip_ver = 6;
  7528. }
  7529. mg_free(h);
  7530. }
  7531. #endif
  7532. }
  7533. if (ip_ver == 0) {
  7534. mg_snprintf(NULL,
  7535. NULL, /* No truncation check for ebuf */
  7536. ebuf,
  7537. ebuf_len,
  7538. "%s",
  7539. "host not found");
  7540. return 0;
  7541. }
  7542. if (ip_ver == 4) {
  7543. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7544. }
  7545. #if defined(USE_IPV6)
  7546. else if (ip_ver == 6) {
  7547. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7548. }
  7549. #endif
  7550. if (*sock == INVALID_SOCKET) {
  7551. mg_snprintf(NULL,
  7552. NULL, /* No truncation check for ebuf */
  7553. ebuf,
  7554. ebuf_len,
  7555. "socket(): %s",
  7556. strerror(ERRNO));
  7557. return 0;
  7558. }
  7559. if (0 != set_non_blocking_mode(*sock)) {
  7560. mg_snprintf(NULL,
  7561. NULL, /* No truncation check for ebuf */
  7562. ebuf,
  7563. ebuf_len,
  7564. "Cannot set socket to non-blocking: %s",
  7565. strerror(ERRNO));
  7566. closesocket(*sock);
  7567. *sock = INVALID_SOCKET;
  7568. return 0;
  7569. }
  7570. set_close_on_exec(*sock, fc(ctx));
  7571. if (ip_ver == 4) {
  7572. /* connected with IPv4 */
  7573. conn_ret = connect(*sock,
  7574. (struct sockaddr *)((void *)&sa->sin),
  7575. sizeof(sa->sin));
  7576. }
  7577. #if defined(USE_IPV6)
  7578. else if (ip_ver == 6) {
  7579. /* connected with IPv6 */
  7580. conn_ret = connect(*sock,
  7581. (struct sockaddr *)((void *)&sa->sin6),
  7582. sizeof(sa->sin6));
  7583. }
  7584. #endif
  7585. #if defined(_WIN32)
  7586. if (conn_ret != 0) {
  7587. DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */
  7588. conn_ret = (int)err;
  7589. #if !defined(EINPROGRESS)
  7590. #define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */
  7591. #endif /* if !defined(EINPROGRESS) */
  7592. }
  7593. #endif
  7594. if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) {
  7595. /* Data for getsockopt */
  7596. int sockerr = -1;
  7597. void *psockerr = &sockerr;
  7598. #if defined(_WIN32)
  7599. int len = (int)sizeof(sockerr);
  7600. #else
  7601. socklen_t len = (socklen_t)sizeof(sockerr);
  7602. #endif
  7603. /* Data for poll */
  7604. struct mg_pollfd pfd[1];
  7605. int pollres;
  7606. int ms_wait = 10000; /* 10 second timeout */
  7607. /* For a non-blocking socket, the connect sequence is:
  7608. * 1) call connect (will not block)
  7609. * 2) wait until the socket is ready for writing (select or poll)
  7610. * 3) check connection state with getsockopt
  7611. */
  7612. pfd[0].fd = *sock;
  7613. pfd[0].events = POLLOUT;
  7614. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  7615. if (pollres != 1) {
  7616. /* Not connected */
  7617. mg_snprintf(NULL,
  7618. NULL, /* No truncation check for ebuf */
  7619. ebuf,
  7620. ebuf_len,
  7621. "connect(%s:%d): timeout",
  7622. host,
  7623. port);
  7624. closesocket(*sock);
  7625. *sock = INVALID_SOCKET;
  7626. return 0;
  7627. }
  7628. #if defined(_WIN32)
  7629. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7630. #else
  7631. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7632. #endif
  7633. if ((ret != 0) || (sockerr != 0)) {
  7634. /* Not connected */
  7635. mg_snprintf(NULL,
  7636. NULL, /* No truncation check for ebuf */
  7637. ebuf,
  7638. ebuf_len,
  7639. "connect(%s:%d): error %s",
  7640. host,
  7641. port,
  7642. strerror(sockerr));
  7643. closesocket(*sock);
  7644. *sock = INVALID_SOCKET;
  7645. return 0;
  7646. }
  7647. }
  7648. return 1;
  7649. }
  7650. int
  7651. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7652. {
  7653. static const char *dont_escape = "._-$,;~()";
  7654. static const char *hex = "0123456789abcdef";
  7655. char *pos = dst;
  7656. const char *end = dst + dst_len - 1;
  7657. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7658. if (isalnum((unsigned char)*src)
  7659. || (strchr(dont_escape, *src) != NULL)) {
  7660. *pos = *src;
  7661. } else if (pos + 2 < end) {
  7662. pos[0] = '%';
  7663. pos[1] = hex[(unsigned char)*src >> 4];
  7664. pos[2] = hex[(unsigned char)*src & 0xf];
  7665. pos += 2;
  7666. } else {
  7667. break;
  7668. }
  7669. }
  7670. *pos = '\0';
  7671. return (*src == '\0') ? (int)(pos - dst) : -1;
  7672. }
  7673. /* Return 0 on success, non-zero if an error occurs. */
  7674. static int
  7675. print_dir_entry(struct de *de)
  7676. {
  7677. size_t hrefsize;
  7678. char *href;
  7679. char size[64], mod[64];
  7680. #if defined(REENTRANT_TIME)
  7681. struct tm _tm;
  7682. struct tm *tm = &_tm;
  7683. #else
  7684. struct tm *tm;
  7685. #endif
  7686. hrefsize = PATH_MAX * 3; /* worst case */
  7687. href = (char *)mg_malloc(hrefsize);
  7688. if (href == NULL) {
  7689. return -1;
  7690. }
  7691. if (de->file.is_directory) {
  7692. mg_snprintf(de->conn,
  7693. NULL, /* Buffer is big enough */
  7694. size,
  7695. sizeof(size),
  7696. "%s",
  7697. "[DIRECTORY]");
  7698. } else {
  7699. /* We use (signed) cast below because MSVC 6 compiler cannot
  7700. * convert unsigned __int64 to double. Sigh. */
  7701. if (de->file.size < 1024) {
  7702. mg_snprintf(de->conn,
  7703. NULL, /* Buffer is big enough */
  7704. size,
  7705. sizeof(size),
  7706. "%d",
  7707. (int)de->file.size);
  7708. } else if (de->file.size < 0x100000) {
  7709. mg_snprintf(de->conn,
  7710. NULL, /* Buffer is big enough */
  7711. size,
  7712. sizeof(size),
  7713. "%.1fk",
  7714. (double)de->file.size / 1024.0);
  7715. } else if (de->file.size < 0x40000000) {
  7716. mg_snprintf(de->conn,
  7717. NULL, /* Buffer is big enough */
  7718. size,
  7719. sizeof(size),
  7720. "%.1fM",
  7721. (double)de->file.size / 1048576);
  7722. } else {
  7723. mg_snprintf(de->conn,
  7724. NULL, /* Buffer is big enough */
  7725. size,
  7726. sizeof(size),
  7727. "%.1fG",
  7728. (double)de->file.size / 1073741824);
  7729. }
  7730. }
  7731. /* Note: mg_snprintf will not cause a buffer overflow above.
  7732. * So, string truncation checks are not required here. */
  7733. #if defined(REENTRANT_TIME)
  7734. localtime_r(&de->file.last_modified, tm);
  7735. #else
  7736. tm = localtime(&de->file.last_modified);
  7737. #endif
  7738. if (tm != NULL) {
  7739. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7740. } else {
  7741. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7742. mod[sizeof(mod) - 1] = '\0';
  7743. }
  7744. mg_url_encode(de->file_name, href, hrefsize);
  7745. mg_printf(de->conn,
  7746. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7747. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7748. href,
  7749. de->file.is_directory ? "/" : "",
  7750. de->file_name,
  7751. de->file.is_directory ? "/" : "",
  7752. mod,
  7753. size);
  7754. mg_free(href);
  7755. return 0;
  7756. }
  7757. /* This function is called from send_directory() and used for
  7758. * sorting directory entries by size, or name, or modification time.
  7759. * On windows, __cdecl specification is needed in case if project is built
  7760. * with __stdcall convention. qsort always requires __cdels callback. */
  7761. static int WINCDECL
  7762. compare_dir_entries(const void *p1, const void *p2)
  7763. {
  7764. if (p1 && p2) {
  7765. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7766. const char *query_string = a->conn->request_info.query_string;
  7767. int cmp_result = 0;
  7768. if (query_string == NULL) {
  7769. query_string = "na";
  7770. }
  7771. if (a->file.is_directory && !b->file.is_directory) {
  7772. return -1; /* Always put directories on top */
  7773. } else if (!a->file.is_directory && b->file.is_directory) {
  7774. return 1; /* Always put directories on top */
  7775. } else if (*query_string == 'n') {
  7776. cmp_result = strcmp(a->file_name, b->file_name);
  7777. } else if (*query_string == 's') {
  7778. cmp_result = (a->file.size == b->file.size)
  7779. ? 0
  7780. : ((a->file.size > b->file.size) ? 1 : -1);
  7781. } else if (*query_string == 'd') {
  7782. cmp_result =
  7783. (a->file.last_modified == b->file.last_modified)
  7784. ? 0
  7785. : ((a->file.last_modified > b->file.last_modified) ? 1
  7786. : -1);
  7787. }
  7788. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7789. }
  7790. return 0;
  7791. }
  7792. static int
  7793. must_hide_file(struct mg_connection *conn, const char *path)
  7794. {
  7795. if (conn && conn->dom_ctx) {
  7796. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7797. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7798. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7799. || ((pattern != NULL)
  7800. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7801. }
  7802. return 0;
  7803. }
  7804. static int
  7805. scan_directory(struct mg_connection *conn,
  7806. const char *dir,
  7807. void *data,
  7808. int (*cb)(struct de *, void *))
  7809. {
  7810. char path[PATH_MAX];
  7811. struct dirent *dp;
  7812. DIR *dirp;
  7813. struct de de;
  7814. int truncated;
  7815. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7816. return 0;
  7817. } else {
  7818. de.conn = conn;
  7819. while ((dp = mg_readdir(dirp)) != NULL) {
  7820. /* Do not show current dir and hidden files */
  7821. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7822. || must_hide_file(conn, dp->d_name)) {
  7823. continue;
  7824. }
  7825. mg_snprintf(
  7826. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7827. /* If we don't memset stat structure to zero, mtime will have
  7828. * garbage and strftime() will segfault later on in
  7829. * print_dir_entry(). memset is required only if mg_stat()
  7830. * fails. For more details, see
  7831. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7832. memset(&de.file, 0, sizeof(de.file));
  7833. if (truncated) {
  7834. /* If the path is not complete, skip processing. */
  7835. continue;
  7836. }
  7837. if (!mg_stat(conn, path, &de.file)) {
  7838. mg_cry_internal(conn,
  7839. "%s: mg_stat(%s) failed: %s",
  7840. __func__,
  7841. path,
  7842. strerror(ERRNO));
  7843. }
  7844. de.file_name = dp->d_name;
  7845. cb(&de, data);
  7846. }
  7847. (void)mg_closedir(dirp);
  7848. }
  7849. return 1;
  7850. }
  7851. #if !defined(NO_FILES)
  7852. static int
  7853. remove_directory(struct mg_connection *conn, const char *dir)
  7854. {
  7855. char path[PATH_MAX];
  7856. struct dirent *dp;
  7857. DIR *dirp;
  7858. struct de de;
  7859. int truncated;
  7860. int ok = 1;
  7861. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7862. return 0;
  7863. } else {
  7864. de.conn = conn;
  7865. while ((dp = mg_readdir(dirp)) != NULL) {
  7866. /* Do not show current dir (but show hidden files as they will
  7867. * also be removed) */
  7868. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7869. continue;
  7870. }
  7871. mg_snprintf(
  7872. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7873. /* If we don't memset stat structure to zero, mtime will have
  7874. * garbage and strftime() will segfault later on in
  7875. * print_dir_entry(). memset is required only if mg_stat()
  7876. * fails. For more details, see
  7877. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7878. memset(&de.file, 0, sizeof(de.file));
  7879. if (truncated) {
  7880. /* Do not delete anything shorter */
  7881. ok = 0;
  7882. continue;
  7883. }
  7884. if (!mg_stat(conn, path, &de.file)) {
  7885. mg_cry_internal(conn,
  7886. "%s: mg_stat(%s) failed: %s",
  7887. __func__,
  7888. path,
  7889. strerror(ERRNO));
  7890. ok = 0;
  7891. }
  7892. if (de.file.is_directory) {
  7893. if (remove_directory(conn, path) == 0) {
  7894. ok = 0;
  7895. }
  7896. } else {
  7897. /* This will fail file is the file is in memory */
  7898. if (mg_remove(conn, path) == 0) {
  7899. ok = 0;
  7900. }
  7901. }
  7902. }
  7903. (void)mg_closedir(dirp);
  7904. IGNORE_UNUSED_RESULT(rmdir(dir));
  7905. }
  7906. return ok;
  7907. }
  7908. #endif
  7909. struct dir_scan_data {
  7910. struct de *entries;
  7911. unsigned int num_entries;
  7912. unsigned int arr_size;
  7913. };
  7914. /* Behaves like realloc(), but frees original pointer on failure */
  7915. static void *
  7916. realloc2(void *ptr, size_t size)
  7917. {
  7918. void *new_ptr = mg_realloc(ptr, size);
  7919. if (new_ptr == NULL) {
  7920. mg_free(ptr);
  7921. }
  7922. return new_ptr;
  7923. }
  7924. static int
  7925. dir_scan_callback(struct de *de, void *data)
  7926. {
  7927. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7928. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7929. dsd->arr_size *= 2;
  7930. dsd->entries =
  7931. (struct de *)realloc2(dsd->entries,
  7932. dsd->arr_size * sizeof(dsd->entries[0]));
  7933. }
  7934. if (dsd->entries == NULL) {
  7935. /* TODO(lsm, low): propagate an error to the caller */
  7936. dsd->num_entries = 0;
  7937. } else {
  7938. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7939. dsd->entries[dsd->num_entries].file = de->file;
  7940. dsd->entries[dsd->num_entries].conn = de->conn;
  7941. dsd->num_entries++;
  7942. }
  7943. return 0;
  7944. }
  7945. static void
  7946. handle_directory_request(struct mg_connection *conn, const char *dir)
  7947. {
  7948. unsigned int i;
  7949. int sort_direction;
  7950. struct dir_scan_data data = {NULL, 0, 128};
  7951. char date[64];
  7952. time_t curtime = time(NULL);
  7953. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7954. mg_send_http_error(conn,
  7955. 500,
  7956. "Error: Cannot open directory\nopendir(%s): %s",
  7957. dir,
  7958. strerror(ERRNO));
  7959. return;
  7960. }
  7961. gmt_time_string(date, sizeof(date), &curtime);
  7962. if (!conn) {
  7963. return;
  7964. }
  7965. sort_direction = ((conn->request_info.query_string != NULL)
  7966. && (conn->request_info.query_string[1] == 'd'))
  7967. ? 'a'
  7968. : 'd';
  7969. conn->must_close = 1;
  7970. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7971. send_static_cache_header(conn);
  7972. send_additional_header(conn);
  7973. mg_printf(conn,
  7974. "Date: %s\r\n"
  7975. "Connection: close\r\n"
  7976. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7977. date);
  7978. mg_printf(conn,
  7979. "<html><head><title>Index of %s</title>"
  7980. "<style>th {text-align: left;}</style></head>"
  7981. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7982. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7983. "<th><a href=\"?d%c\">Modified</a></th>"
  7984. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7985. "<tr><td colspan=\"3\"><hr></td></tr>",
  7986. conn->request_info.local_uri,
  7987. conn->request_info.local_uri,
  7988. sort_direction,
  7989. sort_direction,
  7990. sort_direction);
  7991. /* Print first entry - link to a parent directory */
  7992. mg_printf(conn,
  7993. "<tr><td><a href=\"%s\">%s</a></td>"
  7994. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7995. "..",
  7996. "Parent directory",
  7997. "-",
  7998. "-");
  7999. /* Sort and print directory entries */
  8000. if (data.entries != NULL) {
  8001. qsort(data.entries,
  8002. (size_t)data.num_entries,
  8003. sizeof(data.entries[0]),
  8004. compare_dir_entries);
  8005. for (i = 0; i < data.num_entries; i++) {
  8006. print_dir_entry(&data.entries[i]);
  8007. mg_free(data.entries[i].file_name);
  8008. }
  8009. mg_free(data.entries);
  8010. }
  8011. mg_printf(conn, "%s", "</table></body></html>");
  8012. conn->status_code = 200;
  8013. }
  8014. /* Send len bytes from the opened file to the client. */
  8015. static void
  8016. send_file_data(struct mg_connection *conn,
  8017. struct mg_file *filep,
  8018. int64_t offset,
  8019. int64_t len)
  8020. {
  8021. char buf[MG_BUF_LEN];
  8022. int to_read, num_read, num_written;
  8023. int64_t size;
  8024. if (!filep || !conn) {
  8025. return;
  8026. }
  8027. /* Sanity check the offset */
  8028. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8029. : (int64_t)(filep->stat.size);
  8030. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8031. #if defined(MG_USE_OPEN_FILE)
  8032. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8033. /* file stored in memory */
  8034. if (len > size - offset) {
  8035. len = size - offset;
  8036. }
  8037. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8038. } else /* else block below */
  8039. #endif
  8040. if (len > 0 && filep->access.fp != NULL) {
  8041. /* file stored on disk */
  8042. #if defined(__linux__)
  8043. /* sendfile is only available for Linux */
  8044. if ((conn->ssl == 0) && (conn->throttle == 0)
  8045. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8046. "yes"))) {
  8047. off_t sf_offs = (off_t)offset;
  8048. ssize_t sf_sent;
  8049. int sf_file = fileno(filep->access.fp);
  8050. int loop_cnt = 0;
  8051. do {
  8052. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8053. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8054. size_t sf_tosend =
  8055. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8056. sf_sent =
  8057. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8058. if (sf_sent > 0) {
  8059. len -= sf_sent;
  8060. offset += sf_sent;
  8061. } else if (loop_cnt == 0) {
  8062. /* This file can not be sent using sendfile.
  8063. * This might be the case for pseudo-files in the
  8064. * /sys/ and /proc/ file system.
  8065. * Use the regular user mode copy code instead. */
  8066. break;
  8067. } else if (sf_sent == 0) {
  8068. /* No error, but 0 bytes sent. May be EOF? */
  8069. return;
  8070. }
  8071. loop_cnt++;
  8072. } while ((len > 0) && (sf_sent >= 0));
  8073. if (sf_sent > 0) {
  8074. return; /* OK */
  8075. }
  8076. /* sf_sent<0 means error, thus fall back to the classic way */
  8077. /* This is always the case, if sf_file is not a "normal" file,
  8078. * e.g., for sending data from the output of a CGI process. */
  8079. offset = (int64_t)sf_offs;
  8080. }
  8081. #endif
  8082. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8083. mg_cry_internal(conn,
  8084. "%s: fseeko() failed: %s",
  8085. __func__,
  8086. strerror(ERRNO));
  8087. mg_send_http_error(
  8088. conn,
  8089. 500,
  8090. "%s",
  8091. "Error: Unable to access file at requested position.");
  8092. } else {
  8093. while (len > 0) {
  8094. /* Calculate how much to read from the file in the buffer */
  8095. to_read = sizeof(buf);
  8096. if ((int64_t)to_read > len) {
  8097. to_read = (int)len;
  8098. }
  8099. /* Read from file, exit the loop on error */
  8100. if ((num_read =
  8101. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8102. <= 0) {
  8103. break;
  8104. }
  8105. /* Send read bytes to the client, exit the loop on error */
  8106. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8107. != num_read) {
  8108. break;
  8109. }
  8110. /* Both read and were successful, adjust counters */
  8111. len -= num_written;
  8112. }
  8113. }
  8114. }
  8115. }
  8116. static int
  8117. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8118. {
  8119. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8120. }
  8121. static void
  8122. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8123. {
  8124. if ((filestat != NULL) && (buf != NULL)) {
  8125. mg_snprintf(NULL,
  8126. NULL, /* All calls to construct_etag use 64 byte buffer */
  8127. buf,
  8128. buf_len,
  8129. "\"%lx.%" INT64_FMT "\"",
  8130. (unsigned long)filestat->last_modified,
  8131. filestat->size);
  8132. }
  8133. }
  8134. static void
  8135. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8136. {
  8137. if (filep != NULL && filep->fp != NULL) {
  8138. #if defined(_WIN32)
  8139. (void)conn; /* Unused. */
  8140. #else
  8141. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8142. mg_cry_internal(conn,
  8143. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8144. __func__,
  8145. strerror(ERRNO));
  8146. }
  8147. #endif
  8148. }
  8149. }
  8150. #if defined(USE_ZLIB)
  8151. #include "mod_zlib.inl"
  8152. #endif
  8153. static void
  8154. handle_static_file_request(struct mg_connection *conn,
  8155. const char *path,
  8156. struct mg_file *filep,
  8157. const char *mime_type,
  8158. const char *additional_headers)
  8159. {
  8160. char date[64], lm[64], etag[64];
  8161. char range[128]; /* large enough, so there will be no overflow */
  8162. const char *msg = "OK", *hdr;
  8163. time_t curtime = time(NULL);
  8164. int64_t cl, r1, r2;
  8165. struct vec mime_vec;
  8166. int n, truncated;
  8167. char gz_path[PATH_MAX];
  8168. const char *encoding = "";
  8169. const char *cors_orig_cfg;
  8170. const char *cors1, *cors2, *cors3;
  8171. int is_head_request;
  8172. #if defined(USE_ZLIB)
  8173. /* Compression is allowed, unless there is a reason not to use compression.
  8174. * If the file is already compressed, too small or a "range" request was
  8175. * made, on the fly compression is not possible. */
  8176. int allow_on_the_fly_compression = 1;
  8177. #endif
  8178. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8179. return;
  8180. }
  8181. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8182. if (mime_type == NULL) {
  8183. get_mime_type(conn, path, &mime_vec);
  8184. } else {
  8185. mime_vec.ptr = mime_type;
  8186. mime_vec.len = strlen(mime_type);
  8187. }
  8188. if (filep->stat.size > INT64_MAX) {
  8189. mg_send_http_error(conn,
  8190. 500,
  8191. "Error: File size is too large to send\n%" INT64_FMT,
  8192. filep->stat.size);
  8193. return;
  8194. }
  8195. cl = (int64_t)filep->stat.size;
  8196. conn->status_code = 200;
  8197. range[0] = '\0';
  8198. #if defined(USE_ZLIB)
  8199. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8200. * it's important to rewrite the filename after resolving
  8201. * the mime type from it, to preserve the actual file's type */
  8202. if (!conn->accept_gzip) {
  8203. allow_on_the_fly_compression = 0;
  8204. }
  8205. #endif
  8206. if (filep->stat.is_gzipped) {
  8207. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8208. if (truncated) {
  8209. mg_send_http_error(conn,
  8210. 500,
  8211. "Error: Path of zipped file too long (%s)",
  8212. path);
  8213. return;
  8214. }
  8215. path = gz_path;
  8216. encoding = "Content-Encoding: gzip\r\n";
  8217. #if defined(USE_ZLIB)
  8218. /* File is already compressed. No "on the fly" compression. */
  8219. allow_on_the_fly_compression = 0;
  8220. #endif
  8221. }
  8222. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8223. mg_send_http_error(conn,
  8224. 500,
  8225. "Error: Cannot open file\nfopen(%s): %s",
  8226. path,
  8227. strerror(ERRNO));
  8228. return;
  8229. }
  8230. fclose_on_exec(&filep->access, conn);
  8231. /* If "Range" request was made: parse header, send only selected part
  8232. * of the file. */
  8233. r1 = r2 = 0;
  8234. hdr = mg_get_header(conn, "Range");
  8235. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  8236. && (r1 >= 0) && (r2 >= 0)) {
  8237. /* actually, range requests don't play well with a pre-gzipped
  8238. * file (since the range is specified in the uncompressed space) */
  8239. if (filep->stat.is_gzipped) {
  8240. mg_send_http_error(
  8241. conn,
  8242. 416, /* 416 = Range Not Satisfiable */
  8243. "%s",
  8244. "Error: Range requests in gzipped files are not supported");
  8245. (void)mg_fclose(
  8246. &filep->access); /* ignore error on read only file */
  8247. return;
  8248. }
  8249. conn->status_code = 206;
  8250. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8251. mg_snprintf(conn,
  8252. NULL, /* range buffer is big enough */
  8253. range,
  8254. sizeof(range),
  8255. "Content-Range: bytes "
  8256. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8257. r1,
  8258. r1 + cl - 1,
  8259. filep->stat.size);
  8260. msg = "Partial Content";
  8261. #if defined(USE_ZLIB)
  8262. /* Do not compress ranges. */
  8263. allow_on_the_fly_compression = 0;
  8264. #endif
  8265. }
  8266. /* Do not compress small files. Small files do not benefit from file
  8267. * compression, but there is still some overhead. */
  8268. #if defined(USE_ZLIB)
  8269. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8270. /* File is below the size limit. */
  8271. allow_on_the_fly_compression = 0;
  8272. }
  8273. #endif
  8274. /* Standard CORS header */
  8275. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8276. hdr = mg_get_header(conn, "Origin");
  8277. if (cors_orig_cfg && *cors_orig_cfg && hdr) {
  8278. /* Cross-origin resource sharing (CORS), see
  8279. * http://www.html5rocks.com/en/tutorials/cors/,
  8280. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8281. * -
  8282. * preflight is not supported for files. */
  8283. cors1 = "Access-Control-Allow-Origin: ";
  8284. cors2 = cors_orig_cfg;
  8285. cors3 = "\r\n";
  8286. } else {
  8287. cors1 = cors2 = cors3 = "";
  8288. }
  8289. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8290. * according to
  8291. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8292. gmt_time_string(date, sizeof(date), &curtime);
  8293. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8294. construct_etag(etag, sizeof(etag), &filep->stat);
  8295. /* Send header */
  8296. (void)mg_printf(conn,
  8297. "HTTP/1.1 %d %s\r\n"
  8298. "%s%s%s" /* CORS */
  8299. "Date: %s\r\n"
  8300. "Last-Modified: %s\r\n"
  8301. "Etag: %s\r\n"
  8302. "Content-Type: %.*s\r\n"
  8303. "Connection: %s\r\n",
  8304. conn->status_code,
  8305. msg,
  8306. cors1,
  8307. cors2,
  8308. cors3,
  8309. date,
  8310. lm,
  8311. etag,
  8312. (int)mime_vec.len,
  8313. mime_vec.ptr,
  8314. suggest_connection_header(conn));
  8315. send_static_cache_header(conn);
  8316. send_additional_header(conn);
  8317. #if defined(USE_ZLIB)
  8318. /* On the fly compression allowed */
  8319. if (allow_on_the_fly_compression) {
  8320. /* For on the fly compression, we don't know the content size in
  8321. * advance, so we have to use chunked encoding */
  8322. (void)mg_printf(conn,
  8323. "Content-Encoding: gzip\r\n"
  8324. "Transfer-Encoding: chunked\r\n");
  8325. } else
  8326. #endif
  8327. {
  8328. /* Without on-the-fly compression, we know the content-length
  8329. * and we can use ranges (with on-the-fly compression we cannot).
  8330. * So we send these response headers only in this case. */
  8331. (void)mg_printf(conn,
  8332. "Content-Length: %" INT64_FMT "\r\n"
  8333. "Accept-Ranges: bytes\r\n"
  8334. "%s" /* range */
  8335. "%s" /* encoding */,
  8336. cl,
  8337. range,
  8338. encoding);
  8339. }
  8340. /* The previous code must not add any header starting with X- to make
  8341. * sure no one of the additional_headers is included twice */
  8342. if (additional_headers != NULL) {
  8343. (void)mg_printf(conn,
  8344. "%.*s\r\n\r\n",
  8345. (int)strlen(additional_headers),
  8346. additional_headers);
  8347. } else {
  8348. (void)mg_printf(conn, "\r\n");
  8349. }
  8350. if (!is_head_request) {
  8351. #if defined(USE_ZLIB)
  8352. if (allow_on_the_fly_compression) {
  8353. /* Compress and send */
  8354. send_compressed_data(conn, filep);
  8355. } else
  8356. #endif
  8357. {
  8358. /* Send file directly */
  8359. send_file_data(conn, filep, r1, cl);
  8360. }
  8361. }
  8362. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8363. }
  8364. int
  8365. mg_send_file_body(struct mg_connection *conn, const char *path)
  8366. {
  8367. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8368. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8369. return -1;
  8370. }
  8371. fclose_on_exec(&file.access, conn);
  8372. send_file_data(conn, &file, 0, INT64_MAX);
  8373. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8374. return 0; /* >= 0 for OK */
  8375. }
  8376. #if !defined(NO_CACHING)
  8377. /* Return True if we should reply 304 Not Modified. */
  8378. static int
  8379. is_not_modified(const struct mg_connection *conn,
  8380. const struct mg_file_stat *filestat)
  8381. {
  8382. char etag[64];
  8383. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8384. const char *inm = mg_get_header(conn, "If-None-Match");
  8385. construct_etag(etag, sizeof(etag), filestat);
  8386. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8387. || ((ims != NULL)
  8388. && (filestat->last_modified <= parse_date_string(ims)));
  8389. }
  8390. static void
  8391. handle_not_modified_static_file_request(struct mg_connection *conn,
  8392. struct mg_file *filep)
  8393. {
  8394. char date[64], lm[64], etag[64];
  8395. time_t curtime = time(NULL);
  8396. if ((conn == NULL) || (filep == NULL)) {
  8397. return;
  8398. }
  8399. conn->status_code = 304;
  8400. gmt_time_string(date, sizeof(date), &curtime);
  8401. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8402. construct_etag(etag, sizeof(etag), &filep->stat);
  8403. (void)mg_printf(conn,
  8404. "HTTP/1.1 %d %s\r\n"
  8405. "Date: %s\r\n",
  8406. conn->status_code,
  8407. mg_get_response_code_text(conn, conn->status_code),
  8408. date);
  8409. send_static_cache_header(conn);
  8410. send_additional_header(conn);
  8411. (void)mg_printf(conn,
  8412. "Last-Modified: %s\r\n"
  8413. "Etag: %s\r\n"
  8414. "Connection: %s\r\n"
  8415. "\r\n",
  8416. lm,
  8417. etag,
  8418. suggest_connection_header(conn));
  8419. }
  8420. #endif
  8421. void
  8422. mg_send_file(struct mg_connection *conn, const char *path)
  8423. {
  8424. mg_send_mime_file2(conn, path, NULL, NULL);
  8425. }
  8426. void
  8427. mg_send_mime_file(struct mg_connection *conn,
  8428. const char *path,
  8429. const char *mime_type)
  8430. {
  8431. mg_send_mime_file2(conn, path, mime_type, NULL);
  8432. }
  8433. void
  8434. mg_send_mime_file2(struct mg_connection *conn,
  8435. const char *path,
  8436. const char *mime_type,
  8437. const char *additional_headers)
  8438. {
  8439. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8440. if (!conn) {
  8441. /* No conn */
  8442. return;
  8443. }
  8444. if (mg_stat(conn, path, &file.stat)) {
  8445. #if !defined(NO_CACHING)
  8446. if (is_not_modified(conn, &file.stat)) {
  8447. /* Send 304 "Not Modified" - this must not send any body data */
  8448. handle_not_modified_static_file_request(conn, &file);
  8449. } else
  8450. #endif /* NO_CACHING */
  8451. if (file.stat.is_directory) {
  8452. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8453. "yes")) {
  8454. handle_directory_request(conn, path);
  8455. } else {
  8456. mg_send_http_error(conn,
  8457. 403,
  8458. "%s",
  8459. "Error: Directory listing denied");
  8460. }
  8461. } else {
  8462. handle_static_file_request(
  8463. conn, path, &file, mime_type, additional_headers);
  8464. }
  8465. } else {
  8466. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8467. }
  8468. }
  8469. /* For a given PUT path, create all intermediate subdirectories.
  8470. * Return 0 if the path itself is a directory.
  8471. * Return 1 if the path leads to a file.
  8472. * Return -1 for if the path is too long.
  8473. * Return -2 if path can not be created.
  8474. */
  8475. static int
  8476. put_dir(struct mg_connection *conn, const char *path)
  8477. {
  8478. char buf[PATH_MAX];
  8479. const char *s, *p;
  8480. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8481. size_t len;
  8482. int res = 1;
  8483. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8484. len = (size_t)(p - path);
  8485. if (len >= sizeof(buf)) {
  8486. /* path too long */
  8487. res = -1;
  8488. break;
  8489. }
  8490. memcpy(buf, path, len);
  8491. buf[len] = '\0';
  8492. /* Try to create intermediate directory */
  8493. DEBUG_TRACE("mkdir(%s)", buf);
  8494. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8495. /* path does not exixt and can not be created */
  8496. res = -2;
  8497. break;
  8498. }
  8499. /* Is path itself a directory? */
  8500. if (p[1] == '\0') {
  8501. res = 0;
  8502. }
  8503. }
  8504. return res;
  8505. }
  8506. static void
  8507. remove_bad_file(const struct mg_connection *conn, const char *path)
  8508. {
  8509. int r = mg_remove(conn, path);
  8510. if (r != 0) {
  8511. mg_cry_internal(conn,
  8512. "%s: Cannot remove invalid file %s",
  8513. __func__,
  8514. path);
  8515. }
  8516. }
  8517. long long
  8518. mg_store_body(struct mg_connection *conn, const char *path)
  8519. {
  8520. char buf[MG_BUF_LEN];
  8521. long long len = 0;
  8522. int ret, n;
  8523. struct mg_file fi;
  8524. if (conn->consumed_content != 0) {
  8525. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8526. return -11;
  8527. }
  8528. ret = put_dir(conn, path);
  8529. if (ret < 0) {
  8530. /* -1 for path too long,
  8531. * -2 for path can not be created. */
  8532. return ret;
  8533. }
  8534. if (ret != 1) {
  8535. /* Return 0 means, path itself is a directory. */
  8536. return 0;
  8537. }
  8538. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8539. return -12;
  8540. }
  8541. ret = mg_read(conn, buf, sizeof(buf));
  8542. while (ret > 0) {
  8543. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8544. if (n != ret) {
  8545. (void)mg_fclose(
  8546. &fi.access); /* File is bad and will be removed anyway. */
  8547. remove_bad_file(conn, path);
  8548. return -13;
  8549. }
  8550. len += ret;
  8551. ret = mg_read(conn, buf, sizeof(buf));
  8552. }
  8553. /* File is open for writing. If fclose fails, there was probably an
  8554. * error flushing the buffer to disk, so the file on disk might be
  8555. * broken. Delete it and return an error to the caller. */
  8556. if (mg_fclose(&fi.access) != 0) {
  8557. remove_bad_file(conn, path);
  8558. return -14;
  8559. }
  8560. return len;
  8561. }
  8562. /* Parse a buffer:
  8563. * Forward the string pointer till the end of a word, then
  8564. * terminate it and forward till the begin of the next word.
  8565. */
  8566. static int
  8567. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8568. {
  8569. /* Forward until a space is found - use isgraph here */
  8570. /* See http://www.cplusplus.com/reference/cctype/ */
  8571. while (isgraph((unsigned char)**ppw)) {
  8572. (*ppw)++;
  8573. }
  8574. /* Check end of word */
  8575. if (eol) {
  8576. /* must be a end of line */
  8577. if ((**ppw != '\r') && (**ppw != '\n')) {
  8578. return -1;
  8579. }
  8580. } else {
  8581. /* must be a end of a word, but not a line */
  8582. if (**ppw != ' ') {
  8583. return -1;
  8584. }
  8585. }
  8586. /* Terminate and forward to the next word */
  8587. do {
  8588. **ppw = 0;
  8589. (*ppw)++;
  8590. } while (isspace((unsigned char)**ppw));
  8591. /* Check after term */
  8592. if (!eol) {
  8593. /* if it's not the end of line, there must be a next word */
  8594. if (!isgraph((unsigned char)**ppw)) {
  8595. return -1;
  8596. }
  8597. }
  8598. /* ok */
  8599. return 1;
  8600. }
  8601. /* Parse HTTP headers from the given buffer, advance buf pointer
  8602. * to the point where parsing stopped.
  8603. * All parameters must be valid pointers (not NULL).
  8604. * Return <0 on error. */
  8605. static int
  8606. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8607. {
  8608. int i;
  8609. int num_headers = 0;
  8610. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8611. char *dp = *buf;
  8612. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8613. dp++;
  8614. }
  8615. if (dp == *buf) {
  8616. /* End of headers reached. */
  8617. break;
  8618. }
  8619. if (*dp != ':') {
  8620. /* This is not a valid field. */
  8621. return -1;
  8622. }
  8623. /* End of header key (*dp == ':') */
  8624. /* Truncate here and set the key name */
  8625. *dp = 0;
  8626. hdr[i].name = *buf;
  8627. do {
  8628. dp++;
  8629. } while (*dp == ' ');
  8630. /* The rest of the line is the value */
  8631. hdr[i].value = dp;
  8632. *buf = dp + strcspn(dp, "\r\n");
  8633. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8634. *buf = NULL;
  8635. }
  8636. num_headers = i + 1;
  8637. if (*buf) {
  8638. (*buf)[0] = 0;
  8639. (*buf)[1] = 0;
  8640. *buf += 2;
  8641. } else {
  8642. *buf = dp;
  8643. break;
  8644. }
  8645. if ((*buf)[0] == '\r') {
  8646. /* This is the end of the header */
  8647. break;
  8648. }
  8649. }
  8650. return num_headers;
  8651. }
  8652. struct mg_http_method_info {
  8653. const char *name;
  8654. int request_has_body;
  8655. int response_has_body;
  8656. int is_safe;
  8657. int is_idempotent;
  8658. int is_cacheable;
  8659. };
  8660. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8661. static struct mg_http_method_info http_methods[] = {
  8662. /* HTTP (RFC 2616) */
  8663. {"GET", 0, 1, 1, 1, 1},
  8664. {"POST", 1, 1, 0, 0, 0},
  8665. {"PUT", 1, 0, 0, 1, 0},
  8666. {"DELETE", 0, 0, 0, 1, 0},
  8667. {"HEAD", 0, 0, 1, 1, 1},
  8668. {"OPTIONS", 0, 0, 1, 1, 0},
  8669. {"CONNECT", 1, 1, 0, 0, 0},
  8670. /* TRACE method (RFC 2616) is not supported for security reasons */
  8671. /* PATCH method (RFC 5789) */
  8672. {"PATCH", 1, 0, 0, 0, 0},
  8673. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8674. /* WEBDAV (RFC 2518) */
  8675. {"PROPFIND", 0, 1, 1, 1, 0},
  8676. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8677. * Some PROPFIND results MAY be cached, with care,
  8678. * as there is no cache validation mechanism for
  8679. * most properties. This method is both safe and
  8680. * idempotent (see Section 9.1 of [RFC2616]). */
  8681. {"MKCOL", 0, 0, 0, 1, 0},
  8682. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8683. * When MKCOL is invoked without a request body,
  8684. * the newly created collection SHOULD have no
  8685. * members. A MKCOL request message may contain
  8686. * a message body. The precise behavior of a MKCOL
  8687. * request when the body is present is undefined,
  8688. * ... ==> We do not support MKCOL with body data.
  8689. * This method is idempotent, but not safe (see
  8690. * Section 9.1 of [RFC2616]). Responses to this
  8691. * method MUST NOT be cached. */
  8692. /* Unsupported WEBDAV Methods: */
  8693. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8694. /* + 11 methods from RFC 3253 */
  8695. /* ORDERPATCH (RFC 3648) */
  8696. /* ACL (RFC 3744) */
  8697. /* SEARCH (RFC 5323) */
  8698. /* + MicroSoft extensions
  8699. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8700. /* REPORT method (RFC 3253) */
  8701. {"REPORT", 1, 1, 1, 1, 1},
  8702. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8703. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8704. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8705. * to be useful for REST in case a "GET request with body" is
  8706. * required. */
  8707. {NULL, 0, 0, 0, 0, 0}
  8708. /* end of list */
  8709. };
  8710. static const struct mg_http_method_info *
  8711. get_http_method_info(const char *method)
  8712. {
  8713. /* Check if the method is known to the server. The list of all known
  8714. * HTTP methods can be found here at
  8715. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8716. */
  8717. const struct mg_http_method_info *m = http_methods;
  8718. while (m->name) {
  8719. if (!strcmp(m->name, method)) {
  8720. return m;
  8721. }
  8722. m++;
  8723. }
  8724. return NULL;
  8725. }
  8726. static int
  8727. is_valid_http_method(const char *method)
  8728. {
  8729. return (get_http_method_info(method) != NULL);
  8730. }
  8731. /* Parse HTTP request, fill in mg_request_info structure.
  8732. * This function modifies the buffer by NUL-terminating
  8733. * HTTP request components, header names and header values.
  8734. * Parameters:
  8735. * buf (in/out): pointer to the HTTP header to parse and split
  8736. * len (in): length of HTTP header buffer
  8737. * re (out): parsed header as mg_request_info
  8738. * buf and ri must be valid pointers (not NULL), len>0.
  8739. * Returns <0 on error. */
  8740. static int
  8741. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8742. {
  8743. int request_length;
  8744. int init_skip = 0;
  8745. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8746. * remote_port */
  8747. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8748. NULL;
  8749. ri->num_headers = 0;
  8750. /* RFC says that all initial whitespaces should be ingored */
  8751. /* This included all leading \r and \n (isspace) */
  8752. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8753. while ((len > 0) && isspace((unsigned char)*buf)) {
  8754. buf++;
  8755. len--;
  8756. init_skip++;
  8757. }
  8758. if (len == 0) {
  8759. /* Incomplete request */
  8760. return 0;
  8761. }
  8762. /* Control characters are not allowed, including zero */
  8763. if (iscntrl((unsigned char)*buf)) {
  8764. return -1;
  8765. }
  8766. /* Find end of HTTP header */
  8767. request_length = get_http_header_len(buf, len);
  8768. if (request_length <= 0) {
  8769. return request_length;
  8770. }
  8771. buf[request_length - 1] = '\0';
  8772. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8773. return -1;
  8774. }
  8775. /* The first word has to be the HTTP method */
  8776. ri->request_method = buf;
  8777. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8778. return -1;
  8779. }
  8780. /* Check for a valid http method */
  8781. if (!is_valid_http_method(ri->request_method)) {
  8782. return -1;
  8783. }
  8784. /* The second word is the URI */
  8785. ri->request_uri = buf;
  8786. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8787. return -1;
  8788. }
  8789. /* Next would be the HTTP version */
  8790. ri->http_version = buf;
  8791. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8792. return -1;
  8793. }
  8794. /* Check for a valid HTTP version key */
  8795. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8796. /* Invalid request */
  8797. return -1;
  8798. }
  8799. ri->http_version += 5;
  8800. /* Parse all HTTP headers */
  8801. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8802. if (ri->num_headers < 0) {
  8803. /* Error while parsing headers */
  8804. return -1;
  8805. }
  8806. return request_length + init_skip;
  8807. }
  8808. static int
  8809. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8810. {
  8811. int response_length;
  8812. int init_skip = 0;
  8813. char *tmp, *tmp2;
  8814. long l;
  8815. /* Initialize elements. */
  8816. ri->http_version = ri->status_text = NULL;
  8817. ri->num_headers = ri->status_code = 0;
  8818. /* RFC says that all initial whitespaces should be ingored */
  8819. /* This included all leading \r and \n (isspace) */
  8820. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8821. while ((len > 0) && isspace((unsigned char)*buf)) {
  8822. buf++;
  8823. len--;
  8824. init_skip++;
  8825. }
  8826. if (len == 0) {
  8827. /* Incomplete request */
  8828. return 0;
  8829. }
  8830. /* Control characters are not allowed, including zero */
  8831. if (iscntrl((unsigned char)*buf)) {
  8832. return -1;
  8833. }
  8834. /* Find end of HTTP header */
  8835. response_length = get_http_header_len(buf, len);
  8836. if (response_length <= 0) {
  8837. return response_length;
  8838. }
  8839. buf[response_length - 1] = '\0';
  8840. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8841. return -1;
  8842. }
  8843. /* The first word is the HTTP version */
  8844. /* Check for a valid HTTP version key */
  8845. if (strncmp(buf, "HTTP/", 5) != 0) {
  8846. /* Invalid request */
  8847. return -1;
  8848. }
  8849. buf += 5;
  8850. if (!isgraph((unsigned char)buf[0])) {
  8851. /* Invalid request */
  8852. return -1;
  8853. }
  8854. ri->http_version = buf;
  8855. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8856. return -1;
  8857. }
  8858. /* The second word is the status as a number */
  8859. tmp = buf;
  8860. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8861. return -1;
  8862. }
  8863. l = strtol(tmp, &tmp2, 10);
  8864. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8865. /* Everything else but a 3 digit code is invalid */
  8866. return -1;
  8867. }
  8868. ri->status_code = (int)l;
  8869. /* The rest of the line is the status text */
  8870. ri->status_text = buf;
  8871. /* Find end of status text */
  8872. /* isgraph or isspace = isprint */
  8873. while (isprint((unsigned char)*buf)) {
  8874. buf++;
  8875. }
  8876. if ((*buf != '\r') && (*buf != '\n')) {
  8877. return -1;
  8878. }
  8879. /* Terminate string and forward buf to next line */
  8880. do {
  8881. *buf = 0;
  8882. buf++;
  8883. } while (isspace((unsigned char)*buf));
  8884. /* Parse all HTTP headers */
  8885. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8886. if (ri->num_headers < 0) {
  8887. /* Error while parsing headers */
  8888. return -1;
  8889. }
  8890. return response_length + init_skip;
  8891. }
  8892. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8893. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8894. * buffer (which marks the end of HTTP request). Buffer buf may already
  8895. * have some data. The length of the data is stored in nread.
  8896. * Upon every read operation, increase nread by the number of bytes read. */
  8897. static int
  8898. read_message(FILE *fp,
  8899. struct mg_connection *conn,
  8900. char *buf,
  8901. int bufsiz,
  8902. int *nread)
  8903. {
  8904. int request_len, n = 0;
  8905. struct timespec last_action_time;
  8906. double request_timeout;
  8907. if (!conn) {
  8908. return 0;
  8909. }
  8910. memset(&last_action_time, 0, sizeof(last_action_time));
  8911. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8912. /* value of request_timeout is in seconds, config in milliseconds */
  8913. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8914. } else {
  8915. request_timeout = -1.0;
  8916. }
  8917. if (conn->handled_requests > 0) {
  8918. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8919. request_timeout =
  8920. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8921. }
  8922. }
  8923. request_len = get_http_header_len(buf, *nread);
  8924. /* first time reading from this connection */
  8925. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8926. while (request_len == 0) {
  8927. /* Full request not yet received */
  8928. if (conn->phys_ctx->stop_flag != 0) {
  8929. /* Server is to be stopped. */
  8930. return -1;
  8931. }
  8932. if (*nread >= bufsiz) {
  8933. /* Request too long */
  8934. return -2;
  8935. }
  8936. n = pull_inner(
  8937. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8938. if (n == -2) {
  8939. /* Receive error */
  8940. return -1;
  8941. }
  8942. if (n > 0) {
  8943. *nread += n;
  8944. request_len = get_http_header_len(buf, *nread);
  8945. } else {
  8946. request_len = 0;
  8947. }
  8948. if ((request_len == 0) && (request_timeout >= 0)) {
  8949. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8950. > request_timeout) {
  8951. /* Timeout */
  8952. return -1;
  8953. }
  8954. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8955. }
  8956. }
  8957. return request_len;
  8958. }
  8959. #if !defined(NO_CGI) || !defined(NO_FILES)
  8960. static int
  8961. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8962. {
  8963. const char *expect, *body;
  8964. char buf[MG_BUF_LEN];
  8965. int to_read, nread, success = 0;
  8966. int64_t buffered_len;
  8967. double timeout = -1.0;
  8968. if (!conn) {
  8969. return 0;
  8970. }
  8971. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8972. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8973. }
  8974. expect = mg_get_header(conn, "Expect");
  8975. DEBUG_ASSERT(fp != NULL);
  8976. if (!fp) {
  8977. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8978. return 0;
  8979. }
  8980. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8981. /* Content length is not specified by the client. */
  8982. mg_send_http_error(conn,
  8983. 411,
  8984. "%s",
  8985. "Error: Client did not specify content length");
  8986. } else if ((expect != NULL)
  8987. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8988. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8989. */
  8990. mg_send_http_error(conn,
  8991. 417,
  8992. "Error: Can not fulfill expectation %s",
  8993. expect);
  8994. } else {
  8995. if (expect != NULL) {
  8996. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8997. conn->status_code = 100;
  8998. } else {
  8999. conn->status_code = 200;
  9000. }
  9001. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  9002. - conn->consumed_content;
  9003. DEBUG_ASSERT(buffered_len >= 0);
  9004. DEBUG_ASSERT(conn->consumed_content == 0);
  9005. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  9006. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9007. return 0;
  9008. }
  9009. if (buffered_len > 0) {
  9010. if ((int64_t)buffered_len > conn->content_len) {
  9011. buffered_len = (int)conn->content_len;
  9012. }
  9013. body = conn->buf + conn->request_len + conn->consumed_content;
  9014. push_all(
  9015. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  9016. conn->consumed_content += buffered_len;
  9017. }
  9018. nread = 0;
  9019. while (conn->consumed_content < conn->content_len) {
  9020. to_read = sizeof(buf);
  9021. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  9022. to_read = (int)(conn->content_len - conn->consumed_content);
  9023. }
  9024. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  9025. if (nread == -2) {
  9026. /* error */
  9027. break;
  9028. }
  9029. if (nread > 0) {
  9030. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  9031. != nread) {
  9032. break;
  9033. }
  9034. }
  9035. conn->consumed_content += nread;
  9036. }
  9037. if (conn->consumed_content == conn->content_len) {
  9038. success = (nread >= 0);
  9039. }
  9040. /* Each error code path in this function must send an error */
  9041. if (!success) {
  9042. /* NOTE: Maybe some data has already been sent. */
  9043. /* TODO (low): If some data has been sent, a correct error
  9044. * reply can no longer be sent, so just close the connection */
  9045. mg_send_http_error(conn, 500, "%s", "");
  9046. }
  9047. }
  9048. return success;
  9049. }
  9050. #endif
  9051. #if defined(USE_TIMERS)
  9052. #define TIMER_API static
  9053. #include "timer.inl"
  9054. #endif /* USE_TIMERS */
  9055. #if !defined(NO_CGI)
  9056. /* This structure helps to create an environment for the spawned CGI
  9057. * program.
  9058. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9059. * last element must be NULL.
  9060. * However, on Windows there is a requirement that all these
  9061. * VARIABLE=VALUE\0
  9062. * strings must reside in a contiguous buffer. The end of the buffer is
  9063. * marked by two '\0' characters.
  9064. * We satisfy both worlds: we create an envp array (which is vars), all
  9065. * entries are actually pointers inside buf. */
  9066. struct cgi_environment {
  9067. struct mg_connection *conn;
  9068. /* Data block */
  9069. char *buf; /* Environment buffer */
  9070. size_t buflen; /* Space available in buf */
  9071. size_t bufused; /* Space taken in buf */
  9072. /* Index block */
  9073. char **var; /* char **envp */
  9074. size_t varlen; /* Number of variables available in var */
  9075. size_t varused; /* Number of variables stored in var */
  9076. };
  9077. static void addenv(struct cgi_environment *env,
  9078. PRINTF_FORMAT_STRING(const char *fmt),
  9079. ...) PRINTF_ARGS(2, 3);
  9080. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9081. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9082. static void
  9083. addenv(struct cgi_environment *env, const char *fmt, ...)
  9084. {
  9085. size_t n, space;
  9086. int truncated = 0;
  9087. char *added;
  9088. va_list ap;
  9089. /* Calculate how much space is left in the buffer */
  9090. space = (env->buflen - env->bufused);
  9091. /* Calculate an estimate for the required space */
  9092. n = strlen(fmt) + 2 + 128;
  9093. do {
  9094. if (space <= n) {
  9095. /* Allocate new buffer */
  9096. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9097. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9098. if (!added) {
  9099. /* Out of memory */
  9100. mg_cry_internal(
  9101. env->conn,
  9102. "%s: Cannot allocate memory for CGI variable [%s]",
  9103. __func__,
  9104. fmt);
  9105. return;
  9106. }
  9107. env->buf = added;
  9108. env->buflen = n;
  9109. space = (env->buflen - env->bufused);
  9110. }
  9111. /* Make a pointer to the free space int the buffer */
  9112. added = env->buf + env->bufused;
  9113. /* Copy VARIABLE=VALUE\0 string into the free space */
  9114. va_start(ap, fmt);
  9115. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  9116. va_end(ap);
  9117. /* Do not add truncated strings to the environment */
  9118. if (truncated) {
  9119. /* Reallocate the buffer */
  9120. space = 0;
  9121. n = 1;
  9122. }
  9123. } while (truncated);
  9124. /* Calculate number of bytes added to the environment */
  9125. n = strlen(added) + 1;
  9126. env->bufused += n;
  9127. /* Now update the variable index */
  9128. space = (env->varlen - env->varused);
  9129. if (space < 2) {
  9130. mg_cry_internal(env->conn,
  9131. "%s: Cannot register CGI variable [%s]",
  9132. __func__,
  9133. fmt);
  9134. return;
  9135. }
  9136. /* Append a pointer to the added string into the envp array */
  9137. env->var[env->varused] = added;
  9138. env->varused++;
  9139. }
  9140. /* Return 0 on success, non-zero if an error occurs. */
  9141. static int
  9142. prepare_cgi_environment(struct mg_connection *conn,
  9143. const char *prog,
  9144. struct cgi_environment *env)
  9145. {
  9146. const char *s;
  9147. struct vec var_vec;
  9148. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9149. int i, truncated, uri_len;
  9150. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9151. return -1;
  9152. }
  9153. env->conn = conn;
  9154. env->buflen = CGI_ENVIRONMENT_SIZE;
  9155. env->bufused = 0;
  9156. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9157. if (env->buf == NULL) {
  9158. mg_cry_internal(conn,
  9159. "%s: Not enough memory for environmental buffer",
  9160. __func__);
  9161. return -1;
  9162. }
  9163. env->varlen = MAX_CGI_ENVIR_VARS;
  9164. env->varused = 0;
  9165. env->var =
  9166. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  9167. if (env->var == NULL) {
  9168. mg_cry_internal(conn,
  9169. "%s: Not enough memory for environmental variables",
  9170. __func__);
  9171. mg_free(env->buf);
  9172. return -1;
  9173. }
  9174. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9175. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9176. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9177. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9178. /* Prepare the environment block */
  9179. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9180. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9181. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9182. #if defined(USE_IPV6)
  9183. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9184. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9185. } else
  9186. #endif
  9187. {
  9188. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9189. }
  9190. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9191. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9192. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9193. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9194. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9195. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9196. /* SCRIPT_NAME */
  9197. uri_len = (int)strlen(conn->request_info.local_uri);
  9198. if (conn->path_info == NULL) {
  9199. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9200. /* URI: /path_to_script/script.cgi */
  9201. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9202. } else {
  9203. /* URI: /path_to_script/ ... using index.cgi */
  9204. const char *index_file = strrchr(prog, '/');
  9205. if (index_file) {
  9206. addenv(env,
  9207. "SCRIPT_NAME=%s%s",
  9208. conn->request_info.local_uri,
  9209. index_file + 1);
  9210. }
  9211. }
  9212. } else {
  9213. /* URI: /path_to_script/script.cgi/path_info */
  9214. addenv(env,
  9215. "SCRIPT_NAME=%.*s",
  9216. uri_len - (int)strlen(conn->path_info),
  9217. conn->request_info.local_uri);
  9218. }
  9219. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9220. if (conn->path_info == NULL) {
  9221. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9222. } else {
  9223. addenv(env,
  9224. "PATH_TRANSLATED=%s%s",
  9225. conn->dom_ctx->config[DOCUMENT_ROOT],
  9226. conn->path_info);
  9227. }
  9228. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9229. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9230. addenv(env, "CONTENT_TYPE=%s", s);
  9231. }
  9232. if (conn->request_info.query_string != NULL) {
  9233. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9234. }
  9235. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9236. addenv(env, "CONTENT_LENGTH=%s", s);
  9237. }
  9238. if ((s = getenv("PATH")) != NULL) {
  9239. addenv(env, "PATH=%s", s);
  9240. }
  9241. if (conn->path_info != NULL) {
  9242. addenv(env, "PATH_INFO=%s", conn->path_info);
  9243. }
  9244. if (conn->status_code > 0) {
  9245. /* CGI error handler should show the status code */
  9246. addenv(env, "STATUS=%d", conn->status_code);
  9247. }
  9248. #if defined(_WIN32)
  9249. if ((s = getenv("COMSPEC")) != NULL) {
  9250. addenv(env, "COMSPEC=%s", s);
  9251. }
  9252. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9253. addenv(env, "SYSTEMROOT=%s", s);
  9254. }
  9255. if ((s = getenv("SystemDrive")) != NULL) {
  9256. addenv(env, "SystemDrive=%s", s);
  9257. }
  9258. if ((s = getenv("ProgramFiles")) != NULL) {
  9259. addenv(env, "ProgramFiles=%s", s);
  9260. }
  9261. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9262. addenv(env, "ProgramFiles(x86)=%s", s);
  9263. }
  9264. #else
  9265. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9266. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9267. }
  9268. #endif /* _WIN32 */
  9269. if ((s = getenv("PERLLIB")) != NULL) {
  9270. addenv(env, "PERLLIB=%s", s);
  9271. }
  9272. if (conn->request_info.remote_user != NULL) {
  9273. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9274. addenv(env, "%s", "AUTH_TYPE=Digest");
  9275. }
  9276. /* Add all headers as HTTP_* variables */
  9277. for (i = 0; i < conn->request_info.num_headers; i++) {
  9278. (void)mg_snprintf(conn,
  9279. &truncated,
  9280. http_var_name,
  9281. sizeof(http_var_name),
  9282. "HTTP_%s",
  9283. conn->request_info.http_headers[i].name);
  9284. if (truncated) {
  9285. mg_cry_internal(conn,
  9286. "%s: HTTP header variable too long [%s]",
  9287. __func__,
  9288. conn->request_info.http_headers[i].name);
  9289. continue;
  9290. }
  9291. /* Convert variable name into uppercase, and change - to _ */
  9292. for (p = http_var_name; *p != '\0'; p++) {
  9293. if (*p == '-') {
  9294. *p = '_';
  9295. }
  9296. *p = (char)toupper((unsigned char)*p);
  9297. }
  9298. addenv(env,
  9299. "%s=%s",
  9300. http_var_name,
  9301. conn->request_info.http_headers[i].value);
  9302. }
  9303. /* Add user-specified variables */
  9304. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9305. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9306. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9307. }
  9308. env->var[env->varused] = NULL;
  9309. env->buf[env->bufused] = '\0';
  9310. return 0;
  9311. }
  9312. /* Data for CGI process control: PID and number of references */
  9313. struct process_control_data {
  9314. pid_t pid;
  9315. int references;
  9316. };
  9317. static int
  9318. abort_process(void *data)
  9319. {
  9320. /* Waitpid checks for child status and won't work for a pid that does not
  9321. * identify a child of the current process. Thus, if the pid is reused,
  9322. * we will not affect a different process. */
  9323. struct process_control_data *proc = (struct process_control_data *)data;
  9324. int status = 0;
  9325. int refs;
  9326. pid_t ret_pid;
  9327. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9328. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9329. /* Stop child process */
  9330. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9331. kill(proc->pid, SIGABRT);
  9332. /* Wait until process is terminated (don't leave zombies) */
  9333. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9334. ;
  9335. } else {
  9336. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9337. }
  9338. /* Dec reference counter */
  9339. refs = mg_atomic_dec(&proc->references);
  9340. if (refs == 0) {
  9341. /* no more references - free data */
  9342. mg_free(data);
  9343. }
  9344. return 0;
  9345. }
  9346. static void
  9347. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9348. {
  9349. char *buf;
  9350. size_t buflen;
  9351. int headers_len, data_len, i, truncated;
  9352. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9353. const char *status, *status_text, *connection_state;
  9354. char *pbuf, dir[PATH_MAX], *p;
  9355. struct mg_request_info ri;
  9356. struct cgi_environment blk;
  9357. FILE *in = NULL, *out = NULL, *err = NULL;
  9358. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9359. pid_t pid = (pid_t)-1;
  9360. struct process_control_data *proc = NULL;
  9361. #if defined(USE_TIMERS)
  9362. double cgi_timeout = -1.0;
  9363. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9364. /* Get timeout in seconds */
  9365. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9366. }
  9367. #endif
  9368. if (conn == NULL) {
  9369. return;
  9370. }
  9371. buf = NULL;
  9372. buflen = conn->phys_ctx->max_request_size;
  9373. i = prepare_cgi_environment(conn, prog, &blk);
  9374. if (i != 0) {
  9375. blk.buf = NULL;
  9376. blk.var = NULL;
  9377. goto done;
  9378. }
  9379. /* CGI must be executed in its own directory. 'dir' must point to the
  9380. * directory containing executable program, 'p' must point to the
  9381. * executable program name relative to 'dir'. */
  9382. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9383. if (truncated) {
  9384. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9385. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9386. goto done;
  9387. }
  9388. if ((p = strrchr(dir, '/')) != NULL) {
  9389. *p++ = '\0';
  9390. } else {
  9391. dir[0] = '.';
  9392. dir[1] = '\0';
  9393. p = (char *)prog;
  9394. }
  9395. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9396. status = strerror(ERRNO);
  9397. mg_cry_internal(
  9398. conn,
  9399. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9400. prog,
  9401. status);
  9402. mg_send_http_error(conn,
  9403. 500,
  9404. "Error: Cannot create CGI pipe: %s",
  9405. status);
  9406. goto done;
  9407. }
  9408. proc = (struct process_control_data *)
  9409. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9410. if (proc == NULL) {
  9411. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9412. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9413. goto done;
  9414. }
  9415. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9416. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9417. if (pid == (pid_t)-1) {
  9418. status = strerror(ERRNO);
  9419. mg_cry_internal(
  9420. conn,
  9421. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9422. prog,
  9423. status);
  9424. mg_send_http_error(conn,
  9425. 500,
  9426. "Error: Cannot spawn CGI process [%s]: %s",
  9427. prog,
  9428. status);
  9429. mg_free(proc);
  9430. proc = NULL;
  9431. goto done;
  9432. }
  9433. /* Store data in shared process_control_data */
  9434. proc->pid = pid;
  9435. proc->references = 1;
  9436. #if defined(USE_TIMERS)
  9437. if (cgi_timeout > 0.0) {
  9438. proc->references = 2;
  9439. // Start a timer for CGI
  9440. timer_add(conn->phys_ctx,
  9441. cgi_timeout /* in seconds */,
  9442. 0.0,
  9443. 1,
  9444. abort_process,
  9445. (void *)proc);
  9446. }
  9447. #endif
  9448. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  9449. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9450. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9451. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9452. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9453. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9454. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9455. /* Parent closes only one side of the pipes.
  9456. * If we don't mark them as closed, close() attempt before
  9457. * return from this function throws an exception on Windows.
  9458. * Windows does not like when closed descriptor is closed again. */
  9459. (void)close(fdin[0]);
  9460. (void)close(fdout[1]);
  9461. (void)close(fderr[1]);
  9462. fdin[0] = fdout[1] = fderr[1] = -1;
  9463. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9464. status = strerror(ERRNO);
  9465. mg_cry_internal(conn,
  9466. "Error: CGI program \"%s\": Can not open stdin: %s",
  9467. prog,
  9468. status);
  9469. mg_send_http_error(conn,
  9470. 500,
  9471. "Error: CGI can not open fdin\nfopen: %s",
  9472. status);
  9473. goto done;
  9474. }
  9475. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9476. status = strerror(ERRNO);
  9477. mg_cry_internal(conn,
  9478. "Error: CGI program \"%s\": Can not open stdout: %s",
  9479. prog,
  9480. status);
  9481. mg_send_http_error(conn,
  9482. 500,
  9483. "Error: CGI can not open fdout\nfopen: %s",
  9484. status);
  9485. goto done;
  9486. }
  9487. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9488. status = strerror(ERRNO);
  9489. mg_cry_internal(conn,
  9490. "Error: CGI program \"%s\": Can not open stderr: %s",
  9491. prog,
  9492. status);
  9493. mg_send_http_error(conn,
  9494. 500,
  9495. "Error: CGI can not open fderr\nfopen: %s",
  9496. status);
  9497. goto done;
  9498. }
  9499. setbuf(in, NULL);
  9500. setbuf(out, NULL);
  9501. setbuf(err, NULL);
  9502. fout.access.fp = out;
  9503. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9504. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9505. (signed long long)conn->request_info.content_length);
  9506. /* This is a POST/PUT request, or another request with body data. */
  9507. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9508. /* Error sending the body data */
  9509. mg_cry_internal(
  9510. conn,
  9511. "Error: CGI program \"%s\": Forward body data failed",
  9512. prog);
  9513. goto done;
  9514. }
  9515. }
  9516. /* Close so child gets an EOF. */
  9517. fclose(in);
  9518. in = NULL;
  9519. fdin[1] = -1;
  9520. /* Now read CGI reply into a buffer. We need to set correct
  9521. * status code, thus we need to see all HTTP headers first.
  9522. * Do not send anything back to client, until we buffer in all
  9523. * HTTP headers. */
  9524. data_len = 0;
  9525. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9526. if (buf == NULL) {
  9527. mg_send_http_error(conn,
  9528. 500,
  9529. "Error: Not enough memory for CGI buffer (%u bytes)",
  9530. (unsigned int)buflen);
  9531. mg_cry_internal(
  9532. conn,
  9533. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9534. "bytes)",
  9535. prog,
  9536. (unsigned int)buflen);
  9537. goto done;
  9538. }
  9539. DEBUG_TRACE("CGI: %s", "wait for response");
  9540. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9541. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9542. if (headers_len <= 0) {
  9543. /* Could not parse the CGI response. Check if some error message on
  9544. * stderr. */
  9545. i = pull_all(err, conn, buf, (int)buflen);
  9546. if (i > 0) {
  9547. /* CGI program explicitly sent an error */
  9548. /* Write the error message to the internal log */
  9549. mg_cry_internal(conn,
  9550. "Error: CGI program \"%s\" sent error "
  9551. "message: [%.*s]",
  9552. prog,
  9553. i,
  9554. buf);
  9555. /* Don't send the error message back to the client */
  9556. mg_send_http_error(conn,
  9557. 500,
  9558. "Error: CGI program \"%s\" failed.",
  9559. prog);
  9560. } else {
  9561. /* CGI program did not explicitly send an error, but a broken
  9562. * respon header */
  9563. mg_cry_internal(conn,
  9564. "Error: CGI program sent malformed or too big "
  9565. "(>%u bytes) HTTP headers: [%.*s]",
  9566. (unsigned)buflen,
  9567. data_len,
  9568. buf);
  9569. mg_send_http_error(conn,
  9570. 500,
  9571. "Error: CGI program sent malformed or too big "
  9572. "(>%u bytes) HTTP headers: [%.*s]",
  9573. (unsigned)buflen,
  9574. data_len,
  9575. buf);
  9576. }
  9577. /* in both cases, abort processing CGI */
  9578. goto done;
  9579. }
  9580. pbuf = buf;
  9581. buf[headers_len - 1] = '\0';
  9582. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9583. /* Make up and send the status line */
  9584. status_text = "OK";
  9585. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9586. != NULL) {
  9587. conn->status_code = atoi(status);
  9588. status_text = status;
  9589. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9590. status_text++;
  9591. }
  9592. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9593. != NULL) {
  9594. conn->status_code = 307;
  9595. } else {
  9596. conn->status_code = 200;
  9597. }
  9598. connection_state =
  9599. get_header(ri.http_headers, ri.num_headers, "Connection");
  9600. if (!header_has_option(connection_state, "keep-alive")) {
  9601. conn->must_close = 1;
  9602. }
  9603. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9604. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9605. /* Send headers */
  9606. for (i = 0; i < ri.num_headers; i++) {
  9607. mg_printf(conn,
  9608. "%s: %s\r\n",
  9609. ri.http_headers[i].name,
  9610. ri.http_headers[i].value);
  9611. }
  9612. mg_write(conn, "\r\n", 2);
  9613. /* Send chunk of data that may have been read after the headers */
  9614. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9615. /* Read the rest of CGI output and send to the client */
  9616. DEBUG_TRACE("CGI: %s", "forward all data");
  9617. send_file_data(conn, &fout, 0, INT64_MAX);
  9618. DEBUG_TRACE("CGI: %s", "all data sent");
  9619. done:
  9620. mg_free(blk.var);
  9621. mg_free(blk.buf);
  9622. if (pid != (pid_t)-1) {
  9623. abort_process((void *)proc);
  9624. }
  9625. if (fdin[0] != -1) {
  9626. close(fdin[0]);
  9627. }
  9628. if (fdout[1] != -1) {
  9629. close(fdout[1]);
  9630. }
  9631. if (in != NULL) {
  9632. fclose(in);
  9633. } else if (fdin[1] != -1) {
  9634. close(fdin[1]);
  9635. }
  9636. if (out != NULL) {
  9637. fclose(out);
  9638. } else if (fdout[0] != -1) {
  9639. close(fdout[0]);
  9640. }
  9641. if (err != NULL) {
  9642. fclose(err);
  9643. } else if (fderr[0] != -1) {
  9644. close(fderr[0]);
  9645. }
  9646. if (buf != NULL) {
  9647. mg_free(buf);
  9648. }
  9649. }
  9650. #endif /* !NO_CGI */
  9651. #if !defined(NO_FILES)
  9652. static void
  9653. mkcol(struct mg_connection *conn, const char *path)
  9654. {
  9655. int rc, body_len;
  9656. struct de de;
  9657. char date[64];
  9658. time_t curtime = time(NULL);
  9659. if (conn == NULL) {
  9660. return;
  9661. }
  9662. /* TODO (mid): Check the mg_send_http_error situations in this function
  9663. */
  9664. memset(&de.file, 0, sizeof(de.file));
  9665. if (!mg_stat(conn, path, &de.file)) {
  9666. mg_cry_internal(conn,
  9667. "%s: mg_stat(%s) failed: %s",
  9668. __func__,
  9669. path,
  9670. strerror(ERRNO));
  9671. }
  9672. if (de.file.last_modified) {
  9673. /* TODO (mid): This check does not seem to make any sense ! */
  9674. /* TODO (mid): Add a webdav unit test first, before changing
  9675. * anything here. */
  9676. mg_send_http_error(
  9677. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9678. return;
  9679. }
  9680. body_len = conn->data_len - conn->request_len;
  9681. if (body_len > 0) {
  9682. mg_send_http_error(
  9683. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9684. return;
  9685. }
  9686. rc = mg_mkdir(conn, path, 0755);
  9687. if (rc == 0) {
  9688. conn->status_code = 201;
  9689. gmt_time_string(date, sizeof(date), &curtime);
  9690. mg_printf(conn,
  9691. "HTTP/1.1 %d Created\r\n"
  9692. "Date: %s\r\n",
  9693. conn->status_code,
  9694. date);
  9695. send_static_cache_header(conn);
  9696. send_additional_header(conn);
  9697. mg_printf(conn,
  9698. "Content-Length: 0\r\n"
  9699. "Connection: %s\r\n\r\n",
  9700. suggest_connection_header(conn));
  9701. } else {
  9702. if (errno == EEXIST) {
  9703. mg_send_http_error(
  9704. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9705. } else if (errno == EACCES) {
  9706. mg_send_http_error(
  9707. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9708. } else if (errno == ENOENT) {
  9709. mg_send_http_error(
  9710. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9711. } else {
  9712. mg_send_http_error(
  9713. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9714. }
  9715. }
  9716. }
  9717. static void
  9718. put_file(struct mg_connection *conn, const char *path)
  9719. {
  9720. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9721. const char *range;
  9722. int64_t r1, r2;
  9723. int rc;
  9724. char date[64];
  9725. time_t curtime = time(NULL);
  9726. if (conn == NULL) {
  9727. return;
  9728. }
  9729. if (mg_stat(conn, path, &file.stat)) {
  9730. /* File already exists */
  9731. conn->status_code = 200;
  9732. if (file.stat.is_directory) {
  9733. /* This is an already existing directory,
  9734. * so there is nothing to do for the server. */
  9735. rc = 0;
  9736. } else {
  9737. /* File exists and is not a directory. */
  9738. /* Can it be replaced? */
  9739. #if defined(MG_USE_OPEN_FILE)
  9740. if (file.access.membuf != NULL) {
  9741. /* This is an "in-memory" file, that can not be replaced */
  9742. mg_send_http_error(conn,
  9743. 405,
  9744. "Error: Put not possible\nReplacing %s "
  9745. "is not supported",
  9746. path);
  9747. return;
  9748. }
  9749. #endif
  9750. /* Check if the server may write this file */
  9751. if (access(path, W_OK) == 0) {
  9752. /* Access granted */
  9753. conn->status_code = 200;
  9754. rc = 1;
  9755. } else {
  9756. mg_send_http_error(
  9757. conn,
  9758. 403,
  9759. "Error: Put not possible\nReplacing %s is not allowed",
  9760. path);
  9761. return;
  9762. }
  9763. }
  9764. } else {
  9765. /* File should be created */
  9766. conn->status_code = 201;
  9767. rc = put_dir(conn, path);
  9768. }
  9769. if (rc == 0) {
  9770. /* put_dir returns 0 if path is a directory */
  9771. gmt_time_string(date, sizeof(date), &curtime);
  9772. mg_printf(conn,
  9773. "HTTP/1.1 %d %s\r\n",
  9774. conn->status_code,
  9775. mg_get_response_code_text(NULL, conn->status_code));
  9776. send_no_cache_header(conn);
  9777. send_additional_header(conn);
  9778. mg_printf(conn,
  9779. "Date: %s\r\n"
  9780. "Content-Length: 0\r\n"
  9781. "Connection: %s\r\n\r\n",
  9782. date,
  9783. suggest_connection_header(conn));
  9784. /* Request to create a directory has been fulfilled successfully.
  9785. * No need to put a file. */
  9786. return;
  9787. }
  9788. if (rc == -1) {
  9789. /* put_dir returns -1 if the path is too long */
  9790. mg_send_http_error(conn,
  9791. 414,
  9792. "Error: Path too long\nput_dir(%s): %s",
  9793. path,
  9794. strerror(ERRNO));
  9795. return;
  9796. }
  9797. if (rc == -2) {
  9798. /* put_dir returns -2 if the directory can not be created */
  9799. mg_send_http_error(conn,
  9800. 500,
  9801. "Error: Can not create directory\nput_dir(%s): %s",
  9802. path,
  9803. strerror(ERRNO));
  9804. return;
  9805. }
  9806. /* A file should be created or overwritten. */
  9807. /* Currently CivetWeb does not nead read+write access. */
  9808. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9809. || file.access.fp == NULL) {
  9810. (void)mg_fclose(&file.access);
  9811. mg_send_http_error(conn,
  9812. 500,
  9813. "Error: Can not create file\nfopen(%s): %s",
  9814. path,
  9815. strerror(ERRNO));
  9816. return;
  9817. }
  9818. fclose_on_exec(&file.access, conn);
  9819. range = mg_get_header(conn, "Content-Range");
  9820. r1 = r2 = 0;
  9821. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9822. conn->status_code = 206; /* Partial content */
  9823. fseeko(file.access.fp, r1, SEEK_SET);
  9824. }
  9825. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9826. /* forward_body_data failed.
  9827. * The error code has already been sent to the client,
  9828. * and conn->status_code is already set. */
  9829. (void)mg_fclose(&file.access);
  9830. return;
  9831. }
  9832. if (mg_fclose(&file.access) != 0) {
  9833. /* fclose failed. This might have different reasons, but a likely
  9834. * one is "no space on disk", http 507. */
  9835. conn->status_code = 507;
  9836. }
  9837. gmt_time_string(date, sizeof(date), &curtime);
  9838. mg_printf(conn,
  9839. "HTTP/1.1 %d %s\r\n",
  9840. conn->status_code,
  9841. mg_get_response_code_text(NULL, conn->status_code));
  9842. send_no_cache_header(conn);
  9843. send_additional_header(conn);
  9844. mg_printf(conn,
  9845. "Date: %s\r\n"
  9846. "Content-Length: 0\r\n"
  9847. "Connection: %s\r\n\r\n",
  9848. date,
  9849. suggest_connection_header(conn));
  9850. }
  9851. static void
  9852. delete_file(struct mg_connection *conn, const char *path)
  9853. {
  9854. struct de de;
  9855. memset(&de.file, 0, sizeof(de.file));
  9856. if (!mg_stat(conn, path, &de.file)) {
  9857. /* mg_stat returns 0 if the file does not exist */
  9858. mg_send_http_error(conn,
  9859. 404,
  9860. "Error: Cannot delete file\nFile %s not found",
  9861. path);
  9862. return;
  9863. }
  9864. #if 0 /* Ignore if a file in memory is inside a folder */
  9865. if (de.access.membuf != NULL) {
  9866. /* the file is cached in memory */
  9867. mg_send_http_error(
  9868. conn,
  9869. 405,
  9870. "Error: Delete not possible\nDeleting %s is not supported",
  9871. path);
  9872. return;
  9873. }
  9874. #endif
  9875. if (de.file.is_directory) {
  9876. if (remove_directory(conn, path)) {
  9877. /* Delete is successful: Return 204 without content. */
  9878. mg_send_http_error(conn, 204, "%s", "");
  9879. } else {
  9880. /* Delete is not successful: Return 500 (Server error). */
  9881. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9882. }
  9883. return;
  9884. }
  9885. /* This is an existing file (not a directory).
  9886. * Check if write permission is granted. */
  9887. if (access(path, W_OK) != 0) {
  9888. /* File is read only */
  9889. mg_send_http_error(
  9890. conn,
  9891. 403,
  9892. "Error: Delete not possible\nDeleting %s is not allowed",
  9893. path);
  9894. return;
  9895. }
  9896. /* Try to delete it. */
  9897. if (mg_remove(conn, path) == 0) {
  9898. /* Delete was successful: Return 204 without content. */
  9899. mg_send_http_error(conn, 204, "%s", "");
  9900. } else {
  9901. /* Delete not successful (file locked). */
  9902. mg_send_http_error(conn,
  9903. 423,
  9904. "Error: Cannot delete file\nremove(%s): %s",
  9905. path,
  9906. strerror(ERRNO));
  9907. }
  9908. }
  9909. #endif /* !NO_FILES */
  9910. static void
  9911. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9912. static void
  9913. do_ssi_include(struct mg_connection *conn,
  9914. const char *ssi,
  9915. char *tag,
  9916. int include_level)
  9917. {
  9918. char file_name[MG_BUF_LEN], path[512], *p;
  9919. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9920. size_t len;
  9921. int truncated = 0;
  9922. if (conn == NULL) {
  9923. return;
  9924. }
  9925. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9926. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9927. * always < MG_BUF_LEN. */
  9928. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9929. /* File name is relative to the webserver root */
  9930. file_name[511] = 0;
  9931. (void)mg_snprintf(conn,
  9932. &truncated,
  9933. path,
  9934. sizeof(path),
  9935. "%s/%s",
  9936. conn->dom_ctx->config[DOCUMENT_ROOT],
  9937. file_name);
  9938. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9939. /* File name is relative to the webserver working directory
  9940. * or it is absolute system path */
  9941. file_name[511] = 0;
  9942. (void)
  9943. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9944. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9945. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9946. /* File name is relative to the currect document */
  9947. file_name[511] = 0;
  9948. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9949. if (!truncated) {
  9950. if ((p = strrchr(path, '/')) != NULL) {
  9951. p[1] = '\0';
  9952. }
  9953. len = strlen(path);
  9954. (void)mg_snprintf(conn,
  9955. &truncated,
  9956. path + len,
  9957. sizeof(path) - len,
  9958. "%s",
  9959. file_name);
  9960. }
  9961. } else {
  9962. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9963. return;
  9964. }
  9965. if (truncated) {
  9966. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9967. return;
  9968. }
  9969. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9970. mg_cry_internal(conn,
  9971. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9972. tag,
  9973. path,
  9974. strerror(ERRNO));
  9975. } else {
  9976. fclose_on_exec(&file.access, conn);
  9977. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9978. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9979. path)
  9980. > 0) {
  9981. send_ssi_file(conn, path, &file, include_level + 1);
  9982. } else {
  9983. send_file_data(conn, &file, 0, INT64_MAX);
  9984. }
  9985. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9986. }
  9987. }
  9988. #if !defined(NO_POPEN)
  9989. static void
  9990. do_ssi_exec(struct mg_connection *conn, char *tag)
  9991. {
  9992. char cmd[1024] = "";
  9993. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9994. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9995. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9996. } else {
  9997. cmd[1023] = 0;
  9998. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9999. mg_cry_internal(conn,
  10000. "Cannot SSI #exec: [%s]: %s",
  10001. cmd,
  10002. strerror(ERRNO));
  10003. } else {
  10004. send_file_data(conn, &file, 0, INT64_MAX);
  10005. pclose(file.access.fp);
  10006. }
  10007. }
  10008. }
  10009. #endif /* !NO_POPEN */
  10010. static int
  10011. mg_fgetc(struct mg_file *filep, int offset)
  10012. {
  10013. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10014. if (filep == NULL) {
  10015. return EOF;
  10016. }
  10017. #if defined(MG_USE_OPEN_FILE)
  10018. if ((filep->access.membuf != NULL) && (offset >= 0)
  10019. && (((unsigned int)(offset)) < filep->stat.size)) {
  10020. return ((const unsigned char *)filep->access.membuf)[offset];
  10021. } else /* else block below */
  10022. #endif
  10023. if (filep->access.fp != NULL) {
  10024. return fgetc(filep->access.fp);
  10025. } else {
  10026. return EOF;
  10027. }
  10028. }
  10029. static void
  10030. send_ssi_file(struct mg_connection *conn,
  10031. const char *path,
  10032. struct mg_file *filep,
  10033. int include_level)
  10034. {
  10035. char buf[MG_BUF_LEN];
  10036. int ch, offset, len, in_tag, in_ssi_tag;
  10037. if (include_level > 10) {
  10038. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10039. return;
  10040. }
  10041. in_tag = in_ssi_tag = len = offset = 0;
  10042. /* Read file, byte by byte, and look for SSI include tags */
  10043. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10044. if (in_tag) {
  10045. /* We are in a tag, either SSI tag or html tag */
  10046. if (ch == '>') {
  10047. /* Tag is closing */
  10048. buf[len++] = '>';
  10049. if (in_ssi_tag) {
  10050. /* Handle SSI tag */
  10051. buf[len] = 0;
  10052. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10053. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10054. #if !defined(NO_POPEN)
  10055. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10056. do_ssi_exec(conn, buf + 9);
  10057. #endif /* !NO_POPEN */
  10058. } else {
  10059. mg_cry_internal(conn,
  10060. "%s: unknown SSI "
  10061. "command: \"%s\"",
  10062. path,
  10063. buf);
  10064. }
  10065. len = 0;
  10066. in_ssi_tag = in_tag = 0;
  10067. } else {
  10068. /* Not an SSI tag */
  10069. /* Flush buffer */
  10070. (void)mg_write(conn, buf, (size_t)len);
  10071. len = 0;
  10072. in_tag = 0;
  10073. }
  10074. } else {
  10075. /* Tag is still open */
  10076. buf[len++] = (char)(ch & 0xff);
  10077. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10078. /* All SSI tags start with <!--# */
  10079. in_ssi_tag = 1;
  10080. }
  10081. if ((len + 2) > (int)sizeof(buf)) {
  10082. /* Tag to long for buffer */
  10083. mg_cry_internal(conn, "%s: tag is too large", path);
  10084. return;
  10085. }
  10086. }
  10087. } else {
  10088. /* We are not in a tag yet. */
  10089. if (ch == '<') {
  10090. /* Tag is opening */
  10091. in_tag = 1;
  10092. if (len > 0) {
  10093. /* Flush current buffer.
  10094. * Buffer is filled with "len" bytes. */
  10095. (void)mg_write(conn, buf, (size_t)len);
  10096. }
  10097. /* Store the < */
  10098. len = 1;
  10099. buf[0] = '<';
  10100. } else {
  10101. /* No Tag */
  10102. /* Add data to buffer */
  10103. buf[len++] = (char)(ch & 0xff);
  10104. /* Flush if buffer is full */
  10105. if (len == (int)sizeof(buf)) {
  10106. mg_write(conn, buf, (size_t)len);
  10107. len = 0;
  10108. }
  10109. }
  10110. }
  10111. }
  10112. /* Send the rest of buffered data */
  10113. if (len > 0) {
  10114. mg_write(conn, buf, (size_t)len);
  10115. }
  10116. }
  10117. static void
  10118. handle_ssi_file_request(struct mg_connection *conn,
  10119. const char *path,
  10120. struct mg_file *filep)
  10121. {
  10122. char date[64];
  10123. time_t curtime = time(NULL);
  10124. const char *cors_orig_cfg;
  10125. const char *cors1, *cors2, *cors3;
  10126. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10127. return;
  10128. }
  10129. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10130. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10131. /* Cross-origin resource sharing (CORS). */
  10132. cors1 = "Access-Control-Allow-Origin: ";
  10133. cors2 = cors_orig_cfg;
  10134. cors3 = "\r\n";
  10135. } else {
  10136. cors1 = cors2 = cors3 = "";
  10137. }
  10138. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10139. /* File exists (precondition for calling this function),
  10140. * but can not be opened by the server. */
  10141. mg_send_http_error(conn,
  10142. 500,
  10143. "Error: Cannot read file\nfopen(%s): %s",
  10144. path,
  10145. strerror(ERRNO));
  10146. } else {
  10147. conn->must_close = 1;
  10148. gmt_time_string(date, sizeof(date), &curtime);
  10149. fclose_on_exec(&filep->access, conn);
  10150. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10151. send_no_cache_header(conn);
  10152. send_additional_header(conn);
  10153. mg_printf(conn,
  10154. "%s%s%s"
  10155. "Date: %s\r\n"
  10156. "Content-Type: text/html\r\n"
  10157. "Connection: %s\r\n\r\n",
  10158. cors1,
  10159. cors2,
  10160. cors3,
  10161. date,
  10162. suggest_connection_header(conn));
  10163. send_ssi_file(conn, path, filep, 0);
  10164. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10165. }
  10166. }
  10167. #if !defined(NO_FILES)
  10168. static void
  10169. send_options(struct mg_connection *conn)
  10170. {
  10171. char date[64];
  10172. time_t curtime = time(NULL);
  10173. if (!conn) {
  10174. return;
  10175. }
  10176. conn->status_code = 200;
  10177. conn->must_close = 1;
  10178. gmt_time_string(date, sizeof(date), &curtime);
  10179. /* We do not set a "Cache-Control" header here, but leave the default.
  10180. * Since browsers do not send an OPTIONS request, we can not test the
  10181. * effect anyway. */
  10182. mg_printf(conn,
  10183. "HTTP/1.1 200 OK\r\n"
  10184. "Date: %s\r\n"
  10185. "Connection: %s\r\n"
  10186. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10187. "PROPFIND, MKCOL\r\n"
  10188. "DAV: 1\r\n",
  10189. date,
  10190. suggest_connection_header(conn));
  10191. send_additional_header(conn);
  10192. mg_printf(conn, "\r\n");
  10193. }
  10194. /* Writes PROPFIND properties for a collection element */
  10195. static void
  10196. print_props(struct mg_connection *conn,
  10197. const char *uri,
  10198. struct mg_file_stat *filep)
  10199. {
  10200. char mtime[64];
  10201. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  10202. return;
  10203. }
  10204. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10205. mg_printf(conn,
  10206. "<d:response>"
  10207. "<d:href>%s</d:href>"
  10208. "<d:propstat>"
  10209. "<d:prop>"
  10210. "<d:resourcetype>%s</d:resourcetype>"
  10211. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10212. "<d:getlastmodified>%s</d:getlastmodified>"
  10213. "</d:prop>"
  10214. "<d:status>HTTP/1.1 200 OK</d:status>"
  10215. "</d:propstat>"
  10216. "</d:response>\n",
  10217. uri,
  10218. filep->is_directory ? "<d:collection/>" : "",
  10219. filep->size,
  10220. mtime);
  10221. }
  10222. static int
  10223. print_dav_dir_entry(struct de *de, void *data)
  10224. {
  10225. char href[PATH_MAX];
  10226. int truncated;
  10227. struct mg_connection *conn = (struct mg_connection *)data;
  10228. if (!de || !conn) {
  10229. return -1;
  10230. }
  10231. mg_snprintf(conn,
  10232. &truncated,
  10233. href,
  10234. sizeof(href),
  10235. "%s%s",
  10236. conn->request_info.local_uri,
  10237. de->file_name);
  10238. if (!truncated) {
  10239. size_t href_encoded_size;
  10240. char *href_encoded;
  10241. href_encoded_size = PATH_MAX * 3; /* worst case */
  10242. href_encoded = (char *)mg_malloc(href_encoded_size);
  10243. if (href_encoded == NULL) {
  10244. return -1;
  10245. }
  10246. mg_url_encode(href, href_encoded, href_encoded_size);
  10247. print_props(conn, href_encoded, &de->file);
  10248. mg_free(href_encoded);
  10249. }
  10250. return 0;
  10251. }
  10252. static void
  10253. handle_propfind(struct mg_connection *conn,
  10254. const char *path,
  10255. struct mg_file_stat *filep)
  10256. {
  10257. const char *depth = mg_get_header(conn, "Depth");
  10258. char date[64];
  10259. time_t curtime = time(NULL);
  10260. gmt_time_string(date, sizeof(date), &curtime);
  10261. if (!conn || !path || !filep || !conn->dom_ctx) {
  10262. return;
  10263. }
  10264. conn->must_close = 1;
  10265. conn->status_code = 207;
  10266. mg_printf(conn,
  10267. "HTTP/1.1 207 Multi-Status\r\n"
  10268. "Date: %s\r\n",
  10269. date);
  10270. send_static_cache_header(conn);
  10271. send_additional_header(conn);
  10272. mg_printf(conn,
  10273. "Connection: %s\r\n"
  10274. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10275. suggest_connection_header(conn));
  10276. mg_printf(conn,
  10277. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10278. "<d:multistatus xmlns:d='DAV:'>\n");
  10279. /* Print properties for the requested resource itself */
  10280. print_props(conn, conn->request_info.local_uri, filep);
  10281. /* If it is a directory, print directory entries too if Depth is not 0
  10282. */
  10283. if (filep->is_directory
  10284. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10285. "yes")
  10286. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10287. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10288. }
  10289. mg_printf(conn, "%s\n", "</d:multistatus>");
  10290. }
  10291. #endif
  10292. void
  10293. mg_lock_connection(struct mg_connection *conn)
  10294. {
  10295. if (conn) {
  10296. (void)pthread_mutex_lock(&conn->mutex);
  10297. }
  10298. }
  10299. void
  10300. mg_unlock_connection(struct mg_connection *conn)
  10301. {
  10302. if (conn) {
  10303. (void)pthread_mutex_unlock(&conn->mutex);
  10304. }
  10305. }
  10306. void
  10307. mg_lock_context(struct mg_context *ctx)
  10308. {
  10309. if (ctx) {
  10310. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10311. }
  10312. }
  10313. void
  10314. mg_unlock_context(struct mg_context *ctx)
  10315. {
  10316. if (ctx) {
  10317. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10318. }
  10319. }
  10320. #if defined(USE_LUA)
  10321. #include "mod_lua.inl"
  10322. #endif /* USE_LUA */
  10323. #if defined(USE_DUKTAPE)
  10324. #include "mod_duktape.inl"
  10325. #endif /* USE_DUKTAPE */
  10326. #if defined(USE_WEBSOCKET)
  10327. #if !defined(NO_SSL_DL)
  10328. #define SHA_API static
  10329. #include "sha1.inl"
  10330. #endif
  10331. static int
  10332. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10333. {
  10334. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10335. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10336. SHA_CTX sha_ctx;
  10337. int truncated;
  10338. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10339. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10340. if (truncated) {
  10341. conn->must_close = 1;
  10342. return 0;
  10343. }
  10344. DEBUG_TRACE("%s", "Send websocket handshake");
  10345. SHA1_Init(&sha_ctx);
  10346. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10347. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10348. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10349. mg_printf(conn,
  10350. "HTTP/1.1 101 Switching Protocols\r\n"
  10351. "Upgrade: websocket\r\n"
  10352. "Connection: Upgrade\r\n"
  10353. "Sec-WebSocket-Accept: %s\r\n",
  10354. b64_sha);
  10355. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10356. mg_printf(conn,
  10357. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10358. conn->request_info.acceptedWebSocketSubprotocol);
  10359. } else {
  10360. mg_printf(conn, "%s", "\r\n");
  10361. }
  10362. return 1;
  10363. }
  10364. #if !defined(MG_MAX_UNANSWERED_PING)
  10365. /* Configuration of the maximum number of websocket PINGs that might
  10366. * stay unanswered before the connection is considered broken.
  10367. * Note: The name of this define may still change (until it is
  10368. * defined as a compile parameter in a documentation).
  10369. */
  10370. #define MG_MAX_UNANSWERED_PING (5)
  10371. #endif
  10372. static void
  10373. read_websocket(struct mg_connection *conn,
  10374. mg_websocket_data_handler ws_data_handler,
  10375. void *callback_data)
  10376. {
  10377. /* Pointer to the beginning of the portion of the incoming websocket
  10378. * message queue.
  10379. * The original websocket upgrade request is never removed, so the queue
  10380. * begins after it. */
  10381. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10382. int n, error, exit_by_callback;
  10383. int ret;
  10384. /* body_len is the length of the entire queue in bytes
  10385. * len is the length of the current message
  10386. * data_len is the length of the current message's data payload
  10387. * header_len is the length of the current message's header */
  10388. size_t i, len, mask_len = 0, header_len, body_len;
  10389. uint64_t data_len = 0;
  10390. /* "The masking key is a 32-bit value chosen at random by the client."
  10391. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10392. */
  10393. unsigned char mask[4];
  10394. /* data points to the place where the message is stored when passed to
  10395. * the websocket_data callback. This is either mem on the stack, or a
  10396. * dynamically allocated buffer if it is too large. */
  10397. unsigned char mem[4096];
  10398. unsigned char mop; /* mask flag and opcode */
  10399. /* Variables used for connection monitoring */
  10400. double timeout = -1.0;
  10401. int enable_ping_pong = 0;
  10402. int ping_count = 0;
  10403. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10404. enable_ping_pong =
  10405. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10406. "yes");
  10407. }
  10408. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10409. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10410. }
  10411. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10412. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10413. }
  10414. /* Enter data processing loop */
  10415. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10416. conn->request_info.remote_addr,
  10417. conn->request_info.remote_port);
  10418. conn->in_websocket_handling = 1;
  10419. mg_set_thread_name("wsock");
  10420. /* Loop continuously, reading messages from the socket, invoking the
  10421. * callback, and waiting repeatedly until an error occurs. */
  10422. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10423. header_len = 0;
  10424. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10425. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10426. len = buf[1] & 127;
  10427. mask_len = (buf[1] & 128) ? 4 : 0;
  10428. if ((len < 126) && (body_len >= mask_len)) {
  10429. /* inline 7-bit length field */
  10430. data_len = len;
  10431. header_len = 2 + mask_len;
  10432. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10433. /* 16-bit length field */
  10434. header_len = 4 + mask_len;
  10435. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10436. } else if (body_len >= (10 + mask_len)) {
  10437. /* 64-bit length field */
  10438. uint32_t l1, l2;
  10439. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10440. memcpy(&l2, &buf[6], 4);
  10441. header_len = 10 + mask_len;
  10442. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10443. if (data_len > (uint64_t)0x7FFF0000ul) {
  10444. /* no can do */
  10445. mg_cry_internal(
  10446. conn,
  10447. "%s",
  10448. "websocket out of memory; closing connection");
  10449. break;
  10450. }
  10451. }
  10452. }
  10453. if ((header_len > 0) && (body_len >= header_len)) {
  10454. /* Allocate space to hold websocket payload */
  10455. unsigned char *data = mem;
  10456. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10457. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10458. conn->phys_ctx);
  10459. if (data == NULL) {
  10460. /* Allocation failed, exit the loop and then close the
  10461. * connection */
  10462. mg_cry_internal(
  10463. conn,
  10464. "%s",
  10465. "websocket out of memory; closing connection");
  10466. break;
  10467. }
  10468. }
  10469. /* Copy the mask before we shift the queue and destroy it */
  10470. if (mask_len > 0) {
  10471. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10472. } else {
  10473. memset(mask, 0, sizeof(mask));
  10474. }
  10475. /* Read frame payload from the first message in the queue into
  10476. * data and advance the queue by moving the memory in place. */
  10477. DEBUG_ASSERT(body_len >= header_len);
  10478. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10479. mop = buf[0]; /* current mask and opcode */
  10480. /* Overflow case */
  10481. len = body_len - header_len;
  10482. memcpy(data, buf + header_len, len);
  10483. error = 0;
  10484. while ((uint64_t)len < data_len) {
  10485. n = pull_inner(NULL,
  10486. conn,
  10487. (char *)(data + len),
  10488. (int)(data_len - len),
  10489. timeout);
  10490. if (n <= -2) {
  10491. error = 1;
  10492. break;
  10493. } else if (n > 0) {
  10494. len += (size_t)n;
  10495. } else {
  10496. /* Timeout: should retry */
  10497. /* TODO: retry condition */
  10498. }
  10499. }
  10500. if (error) {
  10501. mg_cry_internal(
  10502. conn,
  10503. "%s",
  10504. "Websocket pull failed; closing connection");
  10505. if (data != mem) {
  10506. mg_free(data);
  10507. }
  10508. break;
  10509. }
  10510. conn->data_len = conn->request_len;
  10511. } else {
  10512. mop = buf[0]; /* current mask and opcode, overwritten by
  10513. * memmove() */
  10514. /* Length of the message being read at the front of the
  10515. * queue. Cast to 31 bit is OK, since we limited
  10516. * data_len before. */
  10517. len = (size_t)data_len + header_len;
  10518. /* Copy the data payload into the data pointer for the
  10519. * callback. Cast to 31 bit is OK, since we
  10520. * limited data_len */
  10521. memcpy(data, buf + header_len, (size_t)data_len);
  10522. /* Move the queue forward len bytes */
  10523. memmove(buf, buf + len, body_len - len);
  10524. /* Mark the queue as advanced */
  10525. conn->data_len -= (int)len;
  10526. }
  10527. /* Apply mask if necessary */
  10528. if (mask_len > 0) {
  10529. for (i = 0; i < (size_t)data_len; i++) {
  10530. data[i] ^= mask[i & 3];
  10531. }
  10532. }
  10533. exit_by_callback = 0;
  10534. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10535. /* filter PONG messages */
  10536. DEBUG_TRACE("PONG from %s:%u",
  10537. conn->request_info.remote_addr,
  10538. conn->request_info.remote_port);
  10539. /* No unanwered PINGs left */
  10540. ping_count = 0;
  10541. } else if (enable_ping_pong
  10542. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10543. /* reply PING messages */
  10544. DEBUG_TRACE("Reply PING from %s:%u",
  10545. conn->request_info.remote_addr,
  10546. conn->request_info.remote_port);
  10547. ret = mg_websocket_write(conn,
  10548. MG_WEBSOCKET_OPCODE_PONG,
  10549. (char *)data,
  10550. (size_t)data_len);
  10551. if (ret <= 0) {
  10552. /* Error: send failed */
  10553. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10554. break;
  10555. }
  10556. } else {
  10557. /* Exit the loop if callback signals to exit (server side),
  10558. * or "connection close" opcode received (client side). */
  10559. if ((ws_data_handler != NULL)
  10560. && !ws_data_handler(conn,
  10561. mop,
  10562. (char *)data,
  10563. (size_t)data_len,
  10564. callback_data)) {
  10565. exit_by_callback = 1;
  10566. }
  10567. }
  10568. /* It a buffer has been allocated, free it again */
  10569. if (data != mem) {
  10570. mg_free(data);
  10571. }
  10572. if (exit_by_callback) {
  10573. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10574. conn->request_info.remote_addr,
  10575. conn->request_info.remote_port);
  10576. break;
  10577. }
  10578. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10579. /* Opcode == 8, connection close */
  10580. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10581. conn->request_info.remote_addr,
  10582. conn->request_info.remote_port);
  10583. break;
  10584. }
  10585. /* Not breaking the loop, process next websocket frame. */
  10586. } else {
  10587. /* Read from the socket into the next available location in the
  10588. * message queue. */
  10589. n = pull_inner(NULL,
  10590. conn,
  10591. conn->buf + conn->data_len,
  10592. conn->buf_size - conn->data_len,
  10593. timeout);
  10594. if (n <= -2) {
  10595. /* Error, no bytes read */
  10596. DEBUG_TRACE("PULL from %s:%u failed",
  10597. conn->request_info.remote_addr,
  10598. conn->request_info.remote_port);
  10599. break;
  10600. }
  10601. if (n > 0) {
  10602. conn->data_len += n;
  10603. /* Reset open PING count */
  10604. ping_count = 0;
  10605. } else {
  10606. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10607. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10608. /* Stop sending PING */
  10609. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10610. "- closing connection",
  10611. ping_count,
  10612. conn->request_info.remote_addr,
  10613. conn->request_info.remote_port);
  10614. break;
  10615. }
  10616. if (enable_ping_pong) {
  10617. /* Send Websocket PING message */
  10618. DEBUG_TRACE("PING to %s:%u",
  10619. conn->request_info.remote_addr,
  10620. conn->request_info.remote_port);
  10621. ret = mg_websocket_write(conn,
  10622. MG_WEBSOCKET_OPCODE_PING,
  10623. NULL,
  10624. 0);
  10625. if (ret <= 0) {
  10626. /* Error: send failed */
  10627. DEBUG_TRACE("Send PING failed (%i)", ret);
  10628. break;
  10629. }
  10630. ping_count++;
  10631. }
  10632. }
  10633. /* Timeout: should retry */
  10634. /* TODO: get timeout def */
  10635. }
  10636. }
  10637. }
  10638. /* Leave data processing loop */
  10639. mg_set_thread_name("worker");
  10640. conn->in_websocket_handling = 0;
  10641. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10642. conn->request_info.remote_addr,
  10643. conn->request_info.remote_port);
  10644. }
  10645. static int
  10646. mg_websocket_write_exec(struct mg_connection *conn,
  10647. int opcode,
  10648. const char *data,
  10649. size_t dataLen,
  10650. uint32_t masking_key)
  10651. {
  10652. unsigned char header[14];
  10653. size_t headerLen;
  10654. int retval;
  10655. #if defined(GCC_DIAGNOSTIC)
  10656. /* Disable spurious conversion warning for GCC */
  10657. #pragma GCC diagnostic push
  10658. #pragma GCC diagnostic ignored "-Wconversion"
  10659. #endif
  10660. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10661. #if defined(GCC_DIAGNOSTIC)
  10662. #pragma GCC diagnostic pop
  10663. #endif
  10664. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10665. if (dataLen < 126) {
  10666. /* inline 7-bit length field */
  10667. header[1] = (unsigned char)dataLen;
  10668. headerLen = 2;
  10669. } else if (dataLen <= 0xFFFF) {
  10670. /* 16-bit length field */
  10671. uint16_t len = htons((uint16_t)dataLen);
  10672. header[1] = 126;
  10673. memcpy(header + 2, &len, 2);
  10674. headerLen = 4;
  10675. } else {
  10676. /* 64-bit length field */
  10677. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10678. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10679. header[1] = 127;
  10680. memcpy(header + 2, &len1, 4);
  10681. memcpy(header + 6, &len2, 4);
  10682. headerLen = 10;
  10683. }
  10684. if (masking_key) {
  10685. /* add mask */
  10686. header[1] |= 0x80;
  10687. memcpy(header + headerLen, &masking_key, 4);
  10688. headerLen += 4;
  10689. }
  10690. /* Note that POSIX/Winsock's send() is threadsafe
  10691. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10692. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10693. * push(), although that is only a problem if the packet is large or
  10694. * outgoing buffer is full). */
  10695. /* TODO: Check if this lock should be moved to user land.
  10696. * Currently the server sets this lock for websockets, but
  10697. * not for any other connection. It must be set for every
  10698. * conn read/written by more than one thread, no matter if
  10699. * it is a websocket or regular connection. */
  10700. (void)mg_lock_connection(conn);
  10701. retval = mg_write(conn, header, headerLen);
  10702. if (retval != (int)headerLen) {
  10703. /* Did not send complete header */
  10704. retval = -1;
  10705. } else {
  10706. if (dataLen > 0) {
  10707. retval = mg_write(conn, data, dataLen);
  10708. }
  10709. /* if dataLen == 0, the header length (2) is returned */
  10710. }
  10711. /* TODO: Remove this unlock as well, when lock is removed. */
  10712. mg_unlock_connection(conn);
  10713. return retval;
  10714. }
  10715. int
  10716. mg_websocket_write(struct mg_connection *conn,
  10717. int opcode,
  10718. const char *data,
  10719. size_t dataLen)
  10720. {
  10721. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10722. }
  10723. static void
  10724. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10725. {
  10726. size_t i = 0;
  10727. i = 0;
  10728. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10729. /* Convert in 32 bit words, if data is 4 byte aligned */
  10730. while (i < (in_len - 3)) {
  10731. *(uint32_t *)(void *)(out + i) =
  10732. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10733. i += 4;
  10734. }
  10735. }
  10736. if (i != in_len) {
  10737. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10738. while (i < in_len) {
  10739. *(uint8_t *)(void *)(out + i) =
  10740. *(uint8_t *)(void *)(in + i)
  10741. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10742. i++;
  10743. }
  10744. }
  10745. }
  10746. int
  10747. mg_websocket_client_write(struct mg_connection *conn,
  10748. int opcode,
  10749. const char *data,
  10750. size_t dataLen)
  10751. {
  10752. int retval = -1;
  10753. char *masked_data =
  10754. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10755. uint32_t masking_key = 0;
  10756. if (masked_data == NULL) {
  10757. /* Return -1 in an error case */
  10758. mg_cry_internal(conn,
  10759. "%s",
  10760. "Cannot allocate buffer for masked websocket response: "
  10761. "Out of memory");
  10762. return -1;
  10763. }
  10764. do {
  10765. /* Get a masking key - but not 0 */
  10766. masking_key = (uint32_t)get_random();
  10767. } while (masking_key == 0);
  10768. mask_data(data, dataLen, masking_key, masked_data);
  10769. retval = mg_websocket_write_exec(
  10770. conn, opcode, masked_data, dataLen, masking_key);
  10771. mg_free(masked_data);
  10772. return retval;
  10773. }
  10774. static void
  10775. handle_websocket_request(struct mg_connection *conn,
  10776. const char *path,
  10777. int is_callback_resource,
  10778. struct mg_websocket_subprotocols *subprotocols,
  10779. mg_websocket_connect_handler ws_connect_handler,
  10780. mg_websocket_ready_handler ws_ready_handler,
  10781. mg_websocket_data_handler ws_data_handler,
  10782. mg_websocket_close_handler ws_close_handler,
  10783. void *cbData)
  10784. {
  10785. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10786. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10787. ptrdiff_t lua_websock = 0;
  10788. #if !defined(USE_LUA)
  10789. (void)path;
  10790. #endif
  10791. /* Step 1: Check websocket protocol version. */
  10792. /* Step 1.1: Check Sec-WebSocket-Key. */
  10793. if (!websock_key) {
  10794. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10795. * requires a Sec-WebSocket-Key header.
  10796. */
  10797. /* It could be the hixie draft version
  10798. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10799. */
  10800. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10801. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10802. char key3[8];
  10803. if ((key1 != NULL) && (key2 != NULL)) {
  10804. /* This version uses 8 byte body data in a GET request */
  10805. conn->content_len = 8;
  10806. if (8 == mg_read(conn, key3, 8)) {
  10807. /* This is the hixie version */
  10808. mg_send_http_error(conn,
  10809. 426,
  10810. "%s",
  10811. "Protocol upgrade to RFC 6455 required");
  10812. return;
  10813. }
  10814. }
  10815. /* This is an unknown version */
  10816. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10817. return;
  10818. }
  10819. /* Step 1.2: Check websocket protocol version. */
  10820. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10821. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10822. /* Reject wrong versions */
  10823. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10824. return;
  10825. }
  10826. /* Step 1.3: Could check for "Host", but we do not really nead this
  10827. * value for anything, so just ignore it. */
  10828. /* Step 2: If a callback is responsible, call it. */
  10829. if (is_callback_resource) {
  10830. /* Step 2.1 check and select subprotocol */
  10831. const char *protocols[64]; // max 64 headers
  10832. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10833. "Sec-WebSocket-Protocol",
  10834. protocols,
  10835. 64);
  10836. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10837. int cnt = 0;
  10838. int idx;
  10839. unsigned long len;
  10840. const char *sep, *curSubProtocol,
  10841. *acceptedWebSocketSubprotocol = NULL;
  10842. /* look for matching subprotocol */
  10843. do {
  10844. const char *protocol = protocols[cnt];
  10845. do {
  10846. sep = strchr(protocol, ',');
  10847. curSubProtocol = protocol;
  10848. len = sep ? (unsigned long)(sep - protocol)
  10849. : (unsigned long)strlen(protocol);
  10850. while (sep && isspace((unsigned char)*++sep))
  10851. ; // ignore leading whitespaces
  10852. protocol = sep;
  10853. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10854. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10855. && (strncmp(curSubProtocol,
  10856. subprotocols->subprotocols[idx],
  10857. len)
  10858. == 0)) {
  10859. acceptedWebSocketSubprotocol =
  10860. subprotocols->subprotocols[idx];
  10861. break;
  10862. }
  10863. }
  10864. } while (sep && !acceptedWebSocketSubprotocol);
  10865. } while (++cnt < nbSubprotocolHeader
  10866. && !acceptedWebSocketSubprotocol);
  10867. conn->request_info.acceptedWebSocketSubprotocol =
  10868. acceptedWebSocketSubprotocol;
  10869. } else if (nbSubprotocolHeader > 0) {
  10870. /* keep legacy behavior */
  10871. const char *protocol = protocols[0];
  10872. /* The protocol is a comma separated list of names. */
  10873. /* The server must only return one value from this list. */
  10874. /* First check if it is a list or just a single value. */
  10875. const char *sep = strrchr(protocol, ',');
  10876. if (sep == NULL) {
  10877. /* Just a single protocol -> accept it. */
  10878. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10879. } else {
  10880. /* Multiple protocols -> accept the last one. */
  10881. /* This is just a quick fix if the client offers multiple
  10882. * protocols. The handler should have a list of accepted
  10883. * protocols on his own
  10884. * and use it to select one protocol among those the client
  10885. * has
  10886. * offered.
  10887. */
  10888. while (isspace((unsigned char)*++sep)) {
  10889. ; /* ignore leading whitespaces */
  10890. }
  10891. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10892. }
  10893. }
  10894. if ((ws_connect_handler != NULL)
  10895. && (ws_connect_handler(conn, cbData) != 0)) {
  10896. /* C callback has returned non-zero, do not proceed with
  10897. * handshake.
  10898. */
  10899. /* Note that C callbacks are no longer called when Lua is
  10900. * responsible, so C can no longer filter callbacks for Lua. */
  10901. return;
  10902. }
  10903. }
  10904. #if defined(USE_LUA)
  10905. /* Step 3: No callback. Check if Lua is responsible. */
  10906. else {
  10907. /* Step 3.1: Check if Lua is responsible. */
  10908. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10909. lua_websock = match_prefix(
  10910. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10911. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10912. path);
  10913. }
  10914. if (lua_websock) {
  10915. /* Step 3.2: Lua is responsible: call it. */
  10916. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10917. if (!conn->lua_websocket_state) {
  10918. /* Lua rejected the new client */
  10919. return;
  10920. }
  10921. }
  10922. }
  10923. #endif
  10924. /* Step 4: Check if there is a responsible websocket handler. */
  10925. if (!is_callback_resource && !lua_websock) {
  10926. /* There is no callback, and Lua is not responsible either. */
  10927. /* Reply with a 404 Not Found. We are still at a standard
  10928. * HTTP request here, before the websocket handshake, so
  10929. * we can still send standard HTTP error replies. */
  10930. mg_send_http_error(conn, 404, "%s", "Not found");
  10931. return;
  10932. }
  10933. /* Step 5: The websocket connection has been accepted */
  10934. if (!send_websocket_handshake(conn, websock_key)) {
  10935. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10936. return;
  10937. }
  10938. /* Step 6: Call the ready handler */
  10939. if (is_callback_resource) {
  10940. if (ws_ready_handler != NULL) {
  10941. ws_ready_handler(conn, cbData);
  10942. }
  10943. #if defined(USE_LUA)
  10944. } else if (lua_websock) {
  10945. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10946. /* the ready handler returned false */
  10947. return;
  10948. }
  10949. #endif
  10950. }
  10951. /* Step 7: Enter the read loop */
  10952. if (is_callback_resource) {
  10953. read_websocket(conn, ws_data_handler, cbData);
  10954. #if defined(USE_LUA)
  10955. } else if (lua_websock) {
  10956. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10957. #endif
  10958. }
  10959. /* Step 8: Call the close handler */
  10960. if (ws_close_handler) {
  10961. ws_close_handler(conn, cbData);
  10962. }
  10963. }
  10964. static int
  10965. is_websocket_protocol(const struct mg_connection *conn)
  10966. {
  10967. const char *upgrade, *connection;
  10968. /* A websocket protocoll has the following HTTP headers:
  10969. *
  10970. * Connection: Upgrade
  10971. * Upgrade: Websocket
  10972. */
  10973. upgrade = mg_get_header(conn, "Upgrade");
  10974. if (upgrade == NULL) {
  10975. return 0; /* fail early, don't waste time checking other header
  10976. * fields
  10977. */
  10978. }
  10979. if (!mg_strcasestr(upgrade, "websocket")) {
  10980. return 0;
  10981. }
  10982. connection = mg_get_header(conn, "Connection");
  10983. if (connection == NULL) {
  10984. return 0;
  10985. }
  10986. if (!mg_strcasestr(connection, "upgrade")) {
  10987. return 0;
  10988. }
  10989. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10990. * "Sec-WebSocket-Version" are also required.
  10991. * Don't check them here, since even an unsupported websocket protocol
  10992. * request still IS a websocket request (in contrast to a standard HTTP
  10993. * request). It will fail later in handle_websocket_request.
  10994. */
  10995. return 1;
  10996. }
  10997. #endif /* !USE_WEBSOCKET */
  10998. static int
  10999. isbyte(int n)
  11000. {
  11001. return (n >= 0) && (n <= 255);
  11002. }
  11003. static int
  11004. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11005. {
  11006. int n, a, b, c, d, slash = 32, len = 0;
  11007. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11008. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11009. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11010. && (slash < 33)) {
  11011. len = n;
  11012. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11013. | (uint32_t)d;
  11014. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11015. }
  11016. return len;
  11017. }
  11018. static int
  11019. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11020. {
  11021. int throttle = 0;
  11022. struct vec vec, val;
  11023. uint32_t net, mask;
  11024. char mult;
  11025. double v;
  11026. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11027. mult = ',';
  11028. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11029. || (v < 0)
  11030. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11031. && (mult != ','))) {
  11032. continue;
  11033. }
  11034. v *= (lowercase(&mult) == 'k')
  11035. ? 1024
  11036. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11037. if (vec.len == 1 && vec.ptr[0] == '*') {
  11038. throttle = (int)v;
  11039. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11040. if ((remote_ip & mask) == net) {
  11041. throttle = (int)v;
  11042. }
  11043. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11044. throttle = (int)v;
  11045. }
  11046. }
  11047. return throttle;
  11048. }
  11049. static uint32_t
  11050. get_remote_ip(const struct mg_connection *conn)
  11051. {
  11052. if (!conn) {
  11053. return 0;
  11054. }
  11055. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11056. }
  11057. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11058. #include "handle_form.inl"
  11059. #if defined(MG_LEGACY_INTERFACE)
  11060. /* Implement the deprecated mg_upload function by calling the new
  11061. * mg_handle_form_request function. While mg_upload could only handle
  11062. * HTML forms sent as POST request in multipart/form-data format
  11063. * containing only file input elements, mg_handle_form_request can
  11064. * handle all form input elements and all standard request methods. */
  11065. struct mg_upload_user_data {
  11066. struct mg_connection *conn;
  11067. const char *destination_dir;
  11068. int num_uploaded_files;
  11069. };
  11070. /* Helper function for deprecated mg_upload. */
  11071. static int
  11072. mg_upload_field_found(const char *key,
  11073. const char *filename,
  11074. char *path,
  11075. size_t pathlen,
  11076. void *user_data)
  11077. {
  11078. int truncated = 0;
  11079. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11080. (void)key;
  11081. if (!filename) {
  11082. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11083. return FORM_FIELD_STORAGE_ABORT;
  11084. }
  11085. mg_snprintf(fud->conn,
  11086. &truncated,
  11087. path,
  11088. pathlen - 1,
  11089. "%s/%s",
  11090. fud->destination_dir,
  11091. filename);
  11092. if (truncated) {
  11093. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11094. return FORM_FIELD_STORAGE_ABORT;
  11095. }
  11096. return FORM_FIELD_STORAGE_STORE;
  11097. }
  11098. /* Helper function for deprecated mg_upload. */
  11099. static int
  11100. mg_upload_field_get(const char *key,
  11101. const char *value,
  11102. size_t value_size,
  11103. void *user_data)
  11104. {
  11105. /* Function should never be called */
  11106. (void)key;
  11107. (void)value;
  11108. (void)value_size;
  11109. (void)user_data;
  11110. return 0;
  11111. }
  11112. /* Helper function for deprecated mg_upload. */
  11113. static int
  11114. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11115. {
  11116. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11117. (void)file_size;
  11118. fud->num_uploaded_files++;
  11119. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11120. return 0;
  11121. }
  11122. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11123. int
  11124. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11125. {
  11126. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11127. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11128. mg_upload_field_get,
  11129. mg_upload_field_stored,
  11130. 0};
  11131. int ret;
  11132. fdh.user_data = (void *)&fud;
  11133. ret = mg_handle_form_request(conn, &fdh);
  11134. if (ret < 0) {
  11135. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11136. }
  11137. return fud.num_uploaded_files;
  11138. }
  11139. #endif
  11140. static int
  11141. get_first_ssl_listener_index(const struct mg_context *ctx)
  11142. {
  11143. unsigned int i;
  11144. int idx = -1;
  11145. if (ctx) {
  11146. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11147. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11148. }
  11149. }
  11150. return idx;
  11151. }
  11152. /* Return host (without port) */
  11153. /* Use mg_free to free the result */
  11154. static const char *
  11155. alloc_get_host(struct mg_connection *conn)
  11156. {
  11157. char buf[1025];
  11158. size_t buflen = sizeof(buf);
  11159. const char *host_header = get_header(conn->request_info.http_headers,
  11160. conn->request_info.num_headers,
  11161. "Host");
  11162. char *host;
  11163. if (host_header != NULL) {
  11164. char *pos;
  11165. /* Create a local copy of the "Host" header, since it might be
  11166. * modified here. */
  11167. mg_strlcpy(buf, host_header, buflen);
  11168. buf[buflen - 1] = '\0';
  11169. host = buf;
  11170. while (isspace((unsigned char)*host)) {
  11171. host++;
  11172. }
  11173. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11174. * is found. */
  11175. if (*host == '[') {
  11176. pos = strchr(host, ']');
  11177. if (!pos) {
  11178. /* Malformed hostname starts with '[', but no ']' found */
  11179. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11180. return NULL;
  11181. }
  11182. /* terminate after ']' */
  11183. pos[1] = 0;
  11184. } else {
  11185. /* Otherwise, a ':' separates hostname and port number */
  11186. pos = strchr(host, ':');
  11187. if (pos != NULL) {
  11188. *pos = '\0';
  11189. }
  11190. }
  11191. if (conn->ssl) {
  11192. /* This is a HTTPS connection, maybe we have a hostname
  11193. * from SNI (set in ssl_servername_callback). */
  11194. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11195. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11196. /* We are not using the default domain */
  11197. if (mg_strcasecmp(host, sslhost)) {
  11198. /* Mismatch between SNI domain and HTTP domain */
  11199. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11200. sslhost,
  11201. host);
  11202. return NULL;
  11203. }
  11204. }
  11205. DEBUG_TRACE("HTTPS Host: %s", host);
  11206. } else {
  11207. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11208. while (dom) {
  11209. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11210. /* Found matching domain */
  11211. DEBUG_TRACE("HTTP domain %s found",
  11212. dom->config[AUTHENTICATION_DOMAIN]);
  11213. /* TODO: Check if this is a HTTP or HTTPS domain */
  11214. conn->dom_ctx = dom;
  11215. break;
  11216. }
  11217. dom = dom->next;
  11218. }
  11219. DEBUG_TRACE("HTTP Host: %s", host);
  11220. }
  11221. } else {
  11222. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11223. host = buf;
  11224. DEBUG_TRACE("IP: %s", host);
  11225. }
  11226. return mg_strdup_ctx(host, conn->phys_ctx);
  11227. }
  11228. static void
  11229. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11230. {
  11231. char target_url[MG_BUF_LEN];
  11232. int truncated = 0;
  11233. conn->must_close = 1;
  11234. /* Send host, port, uri and (if it exists) ?query_string */
  11235. if (conn->host) {
  11236. /* Use "308 Permanent Redirect" */
  11237. int redirect_code = 308;
  11238. /* Create target URL */
  11239. mg_snprintf(
  11240. conn,
  11241. &truncated,
  11242. target_url,
  11243. sizeof(target_url),
  11244. "https://%s:%d%s%s%s",
  11245. conn->host,
  11246. #if defined(USE_IPV6)
  11247. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11248. == AF_INET6)
  11249. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11250. .lsa.sin6.sin6_port)
  11251. :
  11252. #endif
  11253. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11254. .lsa.sin.sin_port),
  11255. conn->request_info.local_uri,
  11256. (conn->request_info.query_string == NULL) ? "" : "?",
  11257. (conn->request_info.query_string == NULL)
  11258. ? ""
  11259. : conn->request_info.query_string);
  11260. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11261. * is used as buffer size) */
  11262. if (truncated) {
  11263. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11264. return;
  11265. }
  11266. /* Use redirect helper function */
  11267. mg_send_http_redirect(conn, target_url, redirect_code);
  11268. }
  11269. }
  11270. static void
  11271. handler_info_acquire(struct mg_handler_info *handler_info)
  11272. {
  11273. pthread_mutex_lock(&handler_info->refcount_mutex);
  11274. handler_info->refcount++;
  11275. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11276. }
  11277. static void
  11278. handler_info_release(struct mg_handler_info *handler_info)
  11279. {
  11280. pthread_mutex_lock(&handler_info->refcount_mutex);
  11281. handler_info->refcount--;
  11282. pthread_cond_signal(&handler_info->refcount_cond);
  11283. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11284. }
  11285. static void
  11286. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11287. {
  11288. pthread_mutex_lock(&handler_info->refcount_mutex);
  11289. while (handler_info->refcount) {
  11290. pthread_cond_wait(&handler_info->refcount_cond,
  11291. &handler_info->refcount_mutex);
  11292. }
  11293. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11294. }
  11295. static void
  11296. mg_set_handler_type(struct mg_context *phys_ctx,
  11297. struct mg_domain_context *dom_ctx,
  11298. const char *uri,
  11299. int handler_type,
  11300. int is_delete_request,
  11301. mg_request_handler handler,
  11302. struct mg_websocket_subprotocols *subprotocols,
  11303. mg_websocket_connect_handler connect_handler,
  11304. mg_websocket_ready_handler ready_handler,
  11305. mg_websocket_data_handler data_handler,
  11306. mg_websocket_close_handler close_handler,
  11307. mg_authorization_handler auth_handler,
  11308. void *cbdata)
  11309. {
  11310. struct mg_handler_info *tmp_rh, **lastref;
  11311. size_t urilen = strlen(uri);
  11312. if (handler_type == WEBSOCKET_HANDLER) {
  11313. DEBUG_ASSERT(handler == NULL);
  11314. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11315. || ready_handler != NULL || data_handler != NULL
  11316. || close_handler != NULL);
  11317. DEBUG_ASSERT(auth_handler == NULL);
  11318. if (handler != NULL) {
  11319. return;
  11320. }
  11321. if (!is_delete_request && (connect_handler == NULL)
  11322. && (ready_handler == NULL) && (data_handler == NULL)
  11323. && (close_handler == NULL)) {
  11324. return;
  11325. }
  11326. if (auth_handler != NULL) {
  11327. return;
  11328. }
  11329. } else if (handler_type == REQUEST_HANDLER) {
  11330. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11331. && data_handler == NULL && close_handler == NULL);
  11332. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11333. DEBUG_ASSERT(auth_handler == NULL);
  11334. if ((connect_handler != NULL) || (ready_handler != NULL)
  11335. || (data_handler != NULL) || (close_handler != NULL)) {
  11336. return;
  11337. }
  11338. if (!is_delete_request && (handler == NULL)) {
  11339. return;
  11340. }
  11341. if (auth_handler != NULL) {
  11342. return;
  11343. }
  11344. } else { /* AUTH_HANDLER */
  11345. DEBUG_ASSERT(handler == NULL);
  11346. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11347. && data_handler == NULL && close_handler == NULL);
  11348. DEBUG_ASSERT(auth_handler != NULL);
  11349. if (handler != NULL) {
  11350. return;
  11351. }
  11352. if ((connect_handler != NULL) || (ready_handler != NULL)
  11353. || (data_handler != NULL) || (close_handler != NULL)) {
  11354. return;
  11355. }
  11356. if (!is_delete_request && (auth_handler == NULL)) {
  11357. return;
  11358. }
  11359. }
  11360. if (!phys_ctx || !dom_ctx) {
  11361. return;
  11362. }
  11363. mg_lock_context(phys_ctx);
  11364. /* first try to find an existing handler */
  11365. lastref = &(dom_ctx->handlers);
  11366. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11367. if (tmp_rh->handler_type == handler_type) {
  11368. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11369. if (!is_delete_request) {
  11370. /* update existing handler */
  11371. if (handler_type == REQUEST_HANDLER) {
  11372. /* Wait for end of use before updating */
  11373. handler_info_wait_unused(tmp_rh);
  11374. /* Ok, the handler is no more use -> Update it */
  11375. tmp_rh->handler = handler;
  11376. } else if (handler_type == WEBSOCKET_HANDLER) {
  11377. tmp_rh->subprotocols = subprotocols;
  11378. tmp_rh->connect_handler = connect_handler;
  11379. tmp_rh->ready_handler = ready_handler;
  11380. tmp_rh->data_handler = data_handler;
  11381. tmp_rh->close_handler = close_handler;
  11382. } else { /* AUTH_HANDLER */
  11383. tmp_rh->auth_handler = auth_handler;
  11384. }
  11385. tmp_rh->cbdata = cbdata;
  11386. } else {
  11387. /* remove existing handler */
  11388. if (handler_type == REQUEST_HANDLER) {
  11389. /* Wait for end of use before removing */
  11390. handler_info_wait_unused(tmp_rh);
  11391. /* Ok, the handler is no more used -> Destroy resources
  11392. */
  11393. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11394. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11395. }
  11396. *lastref = tmp_rh->next;
  11397. mg_free(tmp_rh->uri);
  11398. mg_free(tmp_rh);
  11399. }
  11400. mg_unlock_context(phys_ctx);
  11401. return;
  11402. }
  11403. }
  11404. lastref = &(tmp_rh->next);
  11405. }
  11406. if (is_delete_request) {
  11407. /* no handler to set, this was a remove request to a non-existing
  11408. * handler */
  11409. mg_unlock_context(phys_ctx);
  11410. return;
  11411. }
  11412. tmp_rh =
  11413. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11414. 1,
  11415. phys_ctx);
  11416. if (tmp_rh == NULL) {
  11417. mg_unlock_context(phys_ctx);
  11418. mg_cry_internal(fc(phys_ctx),
  11419. "%s",
  11420. "Cannot create new request handler struct, OOM");
  11421. return;
  11422. }
  11423. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11424. if (!tmp_rh->uri) {
  11425. mg_unlock_context(phys_ctx);
  11426. mg_free(tmp_rh);
  11427. mg_cry_internal(fc(phys_ctx),
  11428. "%s",
  11429. "Cannot create new request handler struct, OOM");
  11430. return;
  11431. }
  11432. tmp_rh->uri_len = urilen;
  11433. if (handler_type == REQUEST_HANDLER) {
  11434. /* Init refcount mutex and condition */
  11435. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11436. mg_unlock_context(phys_ctx);
  11437. mg_free(tmp_rh);
  11438. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11439. return;
  11440. }
  11441. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11442. mg_unlock_context(phys_ctx);
  11443. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11444. mg_free(tmp_rh);
  11445. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11446. return;
  11447. }
  11448. tmp_rh->refcount = 0;
  11449. tmp_rh->handler = handler;
  11450. } else if (handler_type == WEBSOCKET_HANDLER) {
  11451. tmp_rh->subprotocols = subprotocols;
  11452. tmp_rh->connect_handler = connect_handler;
  11453. tmp_rh->ready_handler = ready_handler;
  11454. tmp_rh->data_handler = data_handler;
  11455. tmp_rh->close_handler = close_handler;
  11456. } else { /* AUTH_HANDLER */
  11457. tmp_rh->auth_handler = auth_handler;
  11458. }
  11459. tmp_rh->cbdata = cbdata;
  11460. tmp_rh->handler_type = handler_type;
  11461. tmp_rh->next = NULL;
  11462. *lastref = tmp_rh;
  11463. mg_unlock_context(phys_ctx);
  11464. }
  11465. void
  11466. mg_set_request_handler(struct mg_context *ctx,
  11467. const char *uri,
  11468. mg_request_handler handler,
  11469. void *cbdata)
  11470. {
  11471. mg_set_handler_type(ctx,
  11472. &(ctx->dd),
  11473. uri,
  11474. REQUEST_HANDLER,
  11475. handler == NULL,
  11476. handler,
  11477. NULL,
  11478. NULL,
  11479. NULL,
  11480. NULL,
  11481. NULL,
  11482. NULL,
  11483. cbdata);
  11484. }
  11485. void
  11486. mg_set_websocket_handler(struct mg_context *ctx,
  11487. const char *uri,
  11488. mg_websocket_connect_handler connect_handler,
  11489. mg_websocket_ready_handler ready_handler,
  11490. mg_websocket_data_handler data_handler,
  11491. mg_websocket_close_handler close_handler,
  11492. void *cbdata)
  11493. {
  11494. mg_set_websocket_handler_with_subprotocols(ctx,
  11495. uri,
  11496. NULL,
  11497. connect_handler,
  11498. ready_handler,
  11499. data_handler,
  11500. close_handler,
  11501. cbdata);
  11502. }
  11503. void
  11504. mg_set_websocket_handler_with_subprotocols(
  11505. struct mg_context *ctx,
  11506. const char *uri,
  11507. struct mg_websocket_subprotocols *subprotocols,
  11508. mg_websocket_connect_handler connect_handler,
  11509. mg_websocket_ready_handler ready_handler,
  11510. mg_websocket_data_handler data_handler,
  11511. mg_websocket_close_handler close_handler,
  11512. void *cbdata)
  11513. {
  11514. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11515. && (data_handler == NULL)
  11516. && (close_handler == NULL);
  11517. mg_set_handler_type(ctx,
  11518. &(ctx->dd),
  11519. uri,
  11520. WEBSOCKET_HANDLER,
  11521. is_delete_request,
  11522. NULL,
  11523. subprotocols,
  11524. connect_handler,
  11525. ready_handler,
  11526. data_handler,
  11527. close_handler,
  11528. NULL,
  11529. cbdata);
  11530. }
  11531. void
  11532. mg_set_auth_handler(struct mg_context *ctx,
  11533. const char *uri,
  11534. mg_authorization_handler handler,
  11535. void *cbdata)
  11536. {
  11537. mg_set_handler_type(ctx,
  11538. &(ctx->dd),
  11539. uri,
  11540. AUTH_HANDLER,
  11541. handler == NULL,
  11542. NULL,
  11543. NULL,
  11544. NULL,
  11545. NULL,
  11546. NULL,
  11547. NULL,
  11548. handler,
  11549. cbdata);
  11550. }
  11551. static int
  11552. get_request_handler(struct mg_connection *conn,
  11553. int handler_type,
  11554. mg_request_handler *handler,
  11555. struct mg_websocket_subprotocols **subprotocols,
  11556. mg_websocket_connect_handler *connect_handler,
  11557. mg_websocket_ready_handler *ready_handler,
  11558. mg_websocket_data_handler *data_handler,
  11559. mg_websocket_close_handler *close_handler,
  11560. mg_authorization_handler *auth_handler,
  11561. void **cbdata,
  11562. struct mg_handler_info **handler_info)
  11563. {
  11564. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11565. if (request_info) {
  11566. const char *uri = request_info->local_uri;
  11567. size_t urilen = strlen(uri);
  11568. struct mg_handler_info *tmp_rh;
  11569. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11570. return 0;
  11571. }
  11572. mg_lock_context(conn->phys_ctx);
  11573. /* first try for an exact match */
  11574. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11575. tmp_rh = tmp_rh->next) {
  11576. if (tmp_rh->handler_type == handler_type) {
  11577. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11578. if (handler_type == WEBSOCKET_HANDLER) {
  11579. *subprotocols = tmp_rh->subprotocols;
  11580. *connect_handler = tmp_rh->connect_handler;
  11581. *ready_handler = tmp_rh->ready_handler;
  11582. *data_handler = tmp_rh->data_handler;
  11583. *close_handler = tmp_rh->close_handler;
  11584. } else if (handler_type == REQUEST_HANDLER) {
  11585. *handler = tmp_rh->handler;
  11586. /* Acquire handler and give it back */
  11587. handler_info_acquire(tmp_rh);
  11588. *handler_info = tmp_rh;
  11589. } else { /* AUTH_HANDLER */
  11590. *auth_handler = tmp_rh->auth_handler;
  11591. }
  11592. *cbdata = tmp_rh->cbdata;
  11593. mg_unlock_context(conn->phys_ctx);
  11594. return 1;
  11595. }
  11596. }
  11597. }
  11598. /* next try for a partial match, we will accept uri/something */
  11599. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11600. tmp_rh = tmp_rh->next) {
  11601. if (tmp_rh->handler_type == handler_type) {
  11602. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11603. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11604. if (handler_type == WEBSOCKET_HANDLER) {
  11605. *subprotocols = tmp_rh->subprotocols;
  11606. *connect_handler = tmp_rh->connect_handler;
  11607. *ready_handler = tmp_rh->ready_handler;
  11608. *data_handler = tmp_rh->data_handler;
  11609. *close_handler = tmp_rh->close_handler;
  11610. } else if (handler_type == REQUEST_HANDLER) {
  11611. *handler = tmp_rh->handler;
  11612. /* Acquire handler and give it back */
  11613. handler_info_acquire(tmp_rh);
  11614. *handler_info = tmp_rh;
  11615. } else { /* AUTH_HANDLER */
  11616. *auth_handler = tmp_rh->auth_handler;
  11617. }
  11618. *cbdata = tmp_rh->cbdata;
  11619. mg_unlock_context(conn->phys_ctx);
  11620. return 1;
  11621. }
  11622. }
  11623. }
  11624. /* finally try for pattern match */
  11625. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11626. tmp_rh = tmp_rh->next) {
  11627. if (tmp_rh->handler_type == handler_type) {
  11628. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11629. if (handler_type == WEBSOCKET_HANDLER) {
  11630. *subprotocols = tmp_rh->subprotocols;
  11631. *connect_handler = tmp_rh->connect_handler;
  11632. *ready_handler = tmp_rh->ready_handler;
  11633. *data_handler = tmp_rh->data_handler;
  11634. *close_handler = tmp_rh->close_handler;
  11635. } else if (handler_type == REQUEST_HANDLER) {
  11636. *handler = tmp_rh->handler;
  11637. /* Acquire handler and give it back */
  11638. handler_info_acquire(tmp_rh);
  11639. *handler_info = tmp_rh;
  11640. } else { /* AUTH_HANDLER */
  11641. *auth_handler = tmp_rh->auth_handler;
  11642. }
  11643. *cbdata = tmp_rh->cbdata;
  11644. mg_unlock_context(conn->phys_ctx);
  11645. return 1;
  11646. }
  11647. }
  11648. }
  11649. mg_unlock_context(conn->phys_ctx);
  11650. }
  11651. return 0; /* none found */
  11652. }
  11653. /* Check if the script file is in a path, allowed for script files.
  11654. * This can be used if uploading files is possible not only for the server
  11655. * admin, and the upload mechanism does not check the file extension.
  11656. */
  11657. static int
  11658. is_in_script_path(const struct mg_connection *conn, const char *path)
  11659. {
  11660. /* TODO (Feature): Add config value for allowed script path.
  11661. * Default: All allowed. */
  11662. (void)conn;
  11663. (void)path;
  11664. return 1;
  11665. }
  11666. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11667. static int
  11668. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11669. void *cbdata)
  11670. {
  11671. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11672. if (pcallbacks->websocket_connect) {
  11673. return pcallbacks->websocket_connect(conn);
  11674. }
  11675. /* No handler set - assume "OK" */
  11676. return 0;
  11677. }
  11678. static void
  11679. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11680. {
  11681. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11682. if (pcallbacks->websocket_ready) {
  11683. pcallbacks->websocket_ready(conn);
  11684. }
  11685. }
  11686. static int
  11687. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11688. int bits,
  11689. char *data,
  11690. size_t len,
  11691. void *cbdata)
  11692. {
  11693. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11694. if (pcallbacks->websocket_data) {
  11695. return pcallbacks->websocket_data(conn, bits, data, len);
  11696. }
  11697. /* No handler set - assume "OK" */
  11698. return 1;
  11699. }
  11700. #endif
  11701. /* This is the heart of the Civetweb's logic.
  11702. * This function is called when the request is read, parsed and validated,
  11703. * and Civetweb must decide what action to take: serve a file, or
  11704. * a directory, or call embedded function, etcetera. */
  11705. static void
  11706. handle_request(struct mg_connection *conn)
  11707. {
  11708. struct mg_request_info *ri = &conn->request_info;
  11709. char path[PATH_MAX];
  11710. int uri_len, ssl_index;
  11711. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11712. is_put_or_delete_request = 0, is_callback_resource = 0;
  11713. int i;
  11714. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11715. mg_request_handler callback_handler = NULL;
  11716. struct mg_handler_info *handler_info = NULL;
  11717. struct mg_websocket_subprotocols *subprotocols;
  11718. mg_websocket_connect_handler ws_connect_handler = NULL;
  11719. mg_websocket_ready_handler ws_ready_handler = NULL;
  11720. mg_websocket_data_handler ws_data_handler = NULL;
  11721. mg_websocket_close_handler ws_close_handler = NULL;
  11722. void *callback_data = NULL;
  11723. mg_authorization_handler auth_handler = NULL;
  11724. void *auth_callback_data = NULL;
  11725. int handler_type;
  11726. time_t curtime = time(NULL);
  11727. char date[64];
  11728. path[0] = 0;
  11729. /* 1. get the request url */
  11730. /* 1.1. split into url and query string */
  11731. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11732. != NULL) {
  11733. *((char *)conn->request_info.query_string++) = '\0';
  11734. }
  11735. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11736. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11737. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11738. if (ssl_index >= 0) {
  11739. redirect_to_https_port(conn, ssl_index);
  11740. } else {
  11741. /* A http to https forward port has been specified,
  11742. * but no https port to forward to. */
  11743. mg_send_http_error(conn,
  11744. 503,
  11745. "%s",
  11746. "Error: SSL forward not configured properly");
  11747. mg_cry_internal(conn,
  11748. "%s",
  11749. "Can not redirect to SSL, no SSL port available");
  11750. }
  11751. return;
  11752. }
  11753. uri_len = (int)strlen(ri->local_uri);
  11754. /* 1.3. decode url (if config says so) */
  11755. if (should_decode_url(conn)) {
  11756. mg_url_decode(
  11757. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11758. }
  11759. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11760. * not possible */
  11761. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11762. /* step 1. completed, the url is known now */
  11763. uri_len = (int)strlen(ri->local_uri);
  11764. DEBUG_TRACE("URL: %s", ri->local_uri);
  11765. /* 2. if this ip has limited speed, set it for this connection */
  11766. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11767. get_remote_ip(conn),
  11768. ri->local_uri);
  11769. /* 3. call a "handle everything" callback, if registered */
  11770. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11771. /* Note that since V1.7 the "begin_request" function is called
  11772. * before an authorization check. If an authorization check is
  11773. * required, use a request_handler instead. */
  11774. i = conn->phys_ctx->callbacks.begin_request(conn);
  11775. if (i > 0) {
  11776. /* callback already processed the request. Store the
  11777. return value as a status code for the access log. */
  11778. conn->status_code = i;
  11779. discard_unread_request_data(conn);
  11780. return;
  11781. } else if (i == 0) {
  11782. /* civetweb should process the request */
  11783. } else {
  11784. /* unspecified - may change with the next version */
  11785. return;
  11786. }
  11787. }
  11788. /* request not yet handled by a handler or redirect, so the request
  11789. * is processed here */
  11790. /* 4. Check for CORS preflight requests and handle them (if configured).
  11791. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11792. */
  11793. if (!strcmp(ri->request_method, "OPTIONS")) {
  11794. /* Send a response to CORS preflights only if
  11795. * access_control_allow_methods is not NULL and not an empty string.
  11796. * In this case, scripts can still handle CORS. */
  11797. const char *cors_meth_cfg =
  11798. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11799. const char *cors_orig_cfg =
  11800. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11801. const char *cors_origin =
  11802. get_header(ri->http_headers, ri->num_headers, "Origin");
  11803. const char *cors_acrm = get_header(ri->http_headers,
  11804. ri->num_headers,
  11805. "Access-Control-Request-Method");
  11806. /* Todo: check if cors_origin is in cors_orig_cfg.
  11807. * Or, let the client check this. */
  11808. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11809. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11810. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11811. /* This is a valid CORS preflight, and the server is configured
  11812. * to
  11813. * handle it automatically. */
  11814. const char *cors_acrh =
  11815. get_header(ri->http_headers,
  11816. ri->num_headers,
  11817. "Access-Control-Request-Headers");
  11818. gmt_time_string(date, sizeof(date), &curtime);
  11819. mg_printf(conn,
  11820. "HTTP/1.1 200 OK\r\n"
  11821. "Date: %s\r\n"
  11822. "Access-Control-Allow-Origin: %s\r\n"
  11823. "Access-Control-Allow-Methods: %s\r\n"
  11824. "Content-Length: 0\r\n"
  11825. "Connection: %s\r\n",
  11826. date,
  11827. cors_orig_cfg,
  11828. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11829. suggest_connection_header(conn));
  11830. if (cors_acrh != NULL) {
  11831. /* CORS request is asking for additional headers */
  11832. const char *cors_hdr_cfg =
  11833. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11834. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11835. /* Allow only if access_control_allow_headers is
  11836. * not NULL and not an empty string. If this
  11837. * configuration is set to *, allow everything.
  11838. * Otherwise this configuration must be a list
  11839. * of allowed HTTP header names. */
  11840. mg_printf(conn,
  11841. "Access-Control-Allow-Headers: %s\r\n",
  11842. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11843. : cors_hdr_cfg));
  11844. }
  11845. }
  11846. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11847. mg_printf(conn, "\r\n");
  11848. return;
  11849. }
  11850. }
  11851. /* 5. interpret the url to find out how the request must be handled
  11852. */
  11853. /* 5.1. first test, if the request targets the regular http(s)://
  11854. * protocol namespace or the websocket ws(s):// protocol namespace.
  11855. */
  11856. is_websocket_request = is_websocket_protocol(conn);
  11857. #if defined(USE_WEBSOCKET)
  11858. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11859. #else
  11860. handler_type = REQUEST_HANDLER;
  11861. #endif /* defined(USE_WEBSOCKET) */
  11862. /* 5.2. check if the request will be handled by a callback */
  11863. if (get_request_handler(conn,
  11864. handler_type,
  11865. &callback_handler,
  11866. &subprotocols,
  11867. &ws_connect_handler,
  11868. &ws_ready_handler,
  11869. &ws_data_handler,
  11870. &ws_close_handler,
  11871. NULL,
  11872. &callback_data,
  11873. &handler_info)) {
  11874. /* 5.2.1. A callback will handle this request. All requests
  11875. * handled
  11876. * by a callback have to be considered as requests to a script
  11877. * resource. */
  11878. is_callback_resource = 1;
  11879. is_script_resource = 1;
  11880. is_put_or_delete_request = is_put_or_delete_method(conn);
  11881. } else {
  11882. no_callback_resource:
  11883. /* 5.2.2. No callback is responsible for this request. The URI
  11884. * addresses a file based resource (static content or Lua/cgi
  11885. * scripts in the file system). */
  11886. is_callback_resource = 0;
  11887. interpret_uri(conn,
  11888. path,
  11889. sizeof(path),
  11890. &file.stat,
  11891. &is_found,
  11892. &is_script_resource,
  11893. &is_websocket_request,
  11894. &is_put_or_delete_request);
  11895. }
  11896. /* 6. authorization check */
  11897. /* 6.1. a custom authorization handler is installed */
  11898. if (get_request_handler(conn,
  11899. AUTH_HANDLER,
  11900. NULL,
  11901. NULL,
  11902. NULL,
  11903. NULL,
  11904. NULL,
  11905. NULL,
  11906. &auth_handler,
  11907. &auth_callback_data,
  11908. NULL)) {
  11909. if (!auth_handler(conn, auth_callback_data)) {
  11910. return;
  11911. }
  11912. } else if (is_put_or_delete_request && !is_script_resource
  11913. && !is_callback_resource) {
  11914. /* 6.2. this request is a PUT/DELETE to a real file */
  11915. /* 6.2.1. thus, the server must have real files */
  11916. #if defined(NO_FILES)
  11917. if (1) {
  11918. #else
  11919. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11920. #endif
  11921. /* This server does not have any real files, thus the
  11922. * PUT/DELETE methods are not valid. */
  11923. mg_send_http_error(conn,
  11924. 405,
  11925. "%s method not allowed",
  11926. conn->request_info.request_method);
  11927. return;
  11928. }
  11929. #if !defined(NO_FILES)
  11930. /* 6.2.2. Check if put authorization for static files is
  11931. * available.
  11932. */
  11933. if (!is_authorized_for_put(conn)) {
  11934. send_authorization_request(conn, NULL);
  11935. return;
  11936. }
  11937. #endif
  11938. } else {
  11939. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11940. * or it is a PUT or DELETE request to a resource that does not
  11941. * correspond to a file. Check authorization. */
  11942. if (!check_authorization(conn, path)) {
  11943. send_authorization_request(conn, NULL);
  11944. return;
  11945. }
  11946. }
  11947. /* request is authorized or does not need authorization */
  11948. /* 7. check if there are request handlers for this uri */
  11949. if (is_callback_resource) {
  11950. if (!is_websocket_request) {
  11951. i = callback_handler(conn, callback_data);
  11952. /* Callback handler will not be used anymore. Release it */
  11953. handler_info_release(handler_info);
  11954. if (i > 0) {
  11955. /* Do nothing, callback has served the request. Store
  11956. * then return value as status code for the log and discard
  11957. * all data from the client not used by the callback. */
  11958. conn->status_code = i;
  11959. discard_unread_request_data(conn);
  11960. } else {
  11961. /* The handler did NOT handle the request. */
  11962. /* Some proper reactions would be:
  11963. * a) close the connections without sending anything
  11964. * b) send a 404 not found
  11965. * c) try if there is a file matching the URI
  11966. * It would be possible to do a, b or c in the callback
  11967. * implementation, and return 1 - we cannot do anything
  11968. * here, that is not possible in the callback.
  11969. *
  11970. * TODO: What would be the best reaction here?
  11971. * (Note: The reaction may change, if there is a better
  11972. *idea.)
  11973. */
  11974. /* For the moment, use option c: We look for a proper file,
  11975. * but since a file request is not always a script resource,
  11976. * the authorization check might be different. */
  11977. interpret_uri(conn,
  11978. path,
  11979. sizeof(path),
  11980. &file.stat,
  11981. &is_found,
  11982. &is_script_resource,
  11983. &is_websocket_request,
  11984. &is_put_or_delete_request);
  11985. callback_handler = NULL;
  11986. /* Here we are at a dead end:
  11987. * According to URI matching, a callback should be
  11988. * responsible for handling the request,
  11989. * we called it, but the callback declared itself
  11990. * not responsible.
  11991. * We use a goto here, to get out of this dead end,
  11992. * and continue with the default handling.
  11993. * A goto here is simpler and better to understand
  11994. * than some curious loop. */
  11995. goto no_callback_resource;
  11996. }
  11997. } else {
  11998. #if defined(USE_WEBSOCKET)
  11999. handle_websocket_request(conn,
  12000. path,
  12001. is_callback_resource,
  12002. subprotocols,
  12003. ws_connect_handler,
  12004. ws_ready_handler,
  12005. ws_data_handler,
  12006. ws_close_handler,
  12007. callback_data);
  12008. #endif
  12009. }
  12010. return;
  12011. }
  12012. /* 8. handle websocket requests */
  12013. #if defined(USE_WEBSOCKET)
  12014. if (is_websocket_request) {
  12015. if (is_script_resource) {
  12016. if (is_in_script_path(conn, path)) {
  12017. /* Websocket Lua script */
  12018. handle_websocket_request(conn,
  12019. path,
  12020. 0 /* Lua Script */,
  12021. NULL,
  12022. NULL,
  12023. NULL,
  12024. NULL,
  12025. NULL,
  12026. conn->phys_ctx->user_data);
  12027. } else {
  12028. /* Script was in an illegal path */
  12029. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12030. }
  12031. } else {
  12032. #if defined(MG_LEGACY_INTERFACE)
  12033. handle_websocket_request(
  12034. conn,
  12035. path,
  12036. !is_script_resource /* could be deprecated global callback */,
  12037. NULL,
  12038. deprecated_websocket_connect_wrapper,
  12039. deprecated_websocket_ready_wrapper,
  12040. deprecated_websocket_data_wrapper,
  12041. NULL,
  12042. conn->phys_ctx->user_data);
  12043. #else
  12044. mg_send_http_error(conn, 404, "%s", "Not found");
  12045. #endif
  12046. }
  12047. return;
  12048. } else
  12049. #endif
  12050. #if defined(NO_FILES)
  12051. /* 9a. In case the server uses only callbacks, this uri is
  12052. * unknown.
  12053. * Then, all request handling ends here. */
  12054. mg_send_http_error(conn, 404, "%s", "Not Found");
  12055. #else
  12056. /* 9b. This request is either for a static file or resource handled
  12057. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12058. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12059. mg_send_http_error(conn, 404, "%s", "Not Found");
  12060. return;
  12061. }
  12062. /* 10. Request is handled by a script */
  12063. if (is_script_resource) {
  12064. handle_file_based_request(conn, path, &file);
  12065. return;
  12066. }
  12067. /* 11. Handle put/delete/mkcol requests */
  12068. if (is_put_or_delete_request) {
  12069. /* 11.1. PUT method */
  12070. if (!strcmp(ri->request_method, "PUT")) {
  12071. put_file(conn, path);
  12072. return;
  12073. }
  12074. /* 11.2. DELETE method */
  12075. if (!strcmp(ri->request_method, "DELETE")) {
  12076. delete_file(conn, path);
  12077. return;
  12078. }
  12079. /* 11.3. MKCOL method */
  12080. if (!strcmp(ri->request_method, "MKCOL")) {
  12081. mkcol(conn, path);
  12082. return;
  12083. }
  12084. /* 11.4. PATCH method
  12085. * This method is not supported for static resources,
  12086. * only for scripts (Lua, CGI) and callbacks. */
  12087. mg_send_http_error(conn,
  12088. 405,
  12089. "%s method not allowed",
  12090. conn->request_info.request_method);
  12091. return;
  12092. }
  12093. /* 11. File does not exist, or it was configured that it should be
  12094. * hidden */
  12095. if (!is_found || (must_hide_file(conn, path))) {
  12096. mg_send_http_error(conn, 404, "%s", "Not found");
  12097. return;
  12098. }
  12099. /* 12. Directory uris should end with a slash */
  12100. if (file.stat.is_directory && (uri_len > 0)
  12101. && (ri->local_uri[uri_len - 1] != '/')) {
  12102. gmt_time_string(date, sizeof(date), &curtime);
  12103. mg_printf(conn,
  12104. "HTTP/1.1 301 Moved Permanently\r\n"
  12105. "Location: %s/\r\n"
  12106. "Date: %s\r\n"
  12107. /* "Cache-Control: private\r\n" (= default) */
  12108. "Content-Length: 0\r\n"
  12109. "Connection: %s\r\n",
  12110. ri->request_uri,
  12111. date,
  12112. suggest_connection_header(conn));
  12113. send_additional_header(conn);
  12114. mg_printf(conn, "\r\n");
  12115. return;
  12116. }
  12117. /* 13. Handle other methods than GET/HEAD */
  12118. /* 13.1. Handle PROPFIND */
  12119. if (!strcmp(ri->request_method, "PROPFIND")) {
  12120. handle_propfind(conn, path, &file.stat);
  12121. return;
  12122. }
  12123. /* 13.2. Handle OPTIONS for files */
  12124. if (!strcmp(ri->request_method, "OPTIONS")) {
  12125. /* This standard handler is only used for real files.
  12126. * Scripts should support the OPTIONS method themselves, to allow a
  12127. * maximum flexibility.
  12128. * Lua and CGI scripts may fully support CORS this way (including
  12129. * preflights). */
  12130. send_options(conn);
  12131. return;
  12132. }
  12133. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12134. if ((0 != strcmp(ri->request_method, "GET"))
  12135. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12136. mg_send_http_error(conn,
  12137. 405,
  12138. "%s method not allowed",
  12139. conn->request_info.request_method);
  12140. return;
  12141. }
  12142. /* 14. directories */
  12143. if (file.stat.is_directory) {
  12144. /* Substitute files have already been handled above. */
  12145. /* Here we can either generate and send a directory listing,
  12146. * or send an "access denied" error. */
  12147. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12148. "yes")) {
  12149. handle_directory_request(conn, path);
  12150. } else {
  12151. mg_send_http_error(conn,
  12152. 403,
  12153. "%s",
  12154. "Error: Directory listing denied");
  12155. }
  12156. return;
  12157. }
  12158. /* 15. read a normal file with GET or HEAD */
  12159. handle_file_based_request(conn, path, &file);
  12160. #endif /* !defined(NO_FILES) */
  12161. }
  12162. static void
  12163. handle_file_based_request(struct mg_connection *conn,
  12164. const char *path,
  12165. struct mg_file *file)
  12166. {
  12167. if (!conn || !conn->dom_ctx) {
  12168. return;
  12169. }
  12170. if (0) {
  12171. #if defined(USE_LUA)
  12172. } else if (match_prefix(
  12173. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12174. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12175. path)
  12176. > 0) {
  12177. if (is_in_script_path(conn, path)) {
  12178. /* Lua server page: an SSI like page containing mostly plain
  12179. * html
  12180. * code
  12181. * plus some tags with server generated contents. */
  12182. handle_lsp_request(conn, path, file, NULL);
  12183. } else {
  12184. /* Script was in an illegal path */
  12185. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12186. }
  12187. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12188. strlen(
  12189. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12190. path)
  12191. > 0) {
  12192. if (is_in_script_path(conn, path)) {
  12193. /* Lua in-server module script: a CGI like script used to
  12194. * generate
  12195. * the
  12196. * entire reply. */
  12197. mg_exec_lua_script(conn, path, NULL);
  12198. } else {
  12199. /* Script was in an illegal path */
  12200. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12201. }
  12202. #endif
  12203. #if defined(USE_DUKTAPE)
  12204. } else if (match_prefix(
  12205. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12206. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12207. path)
  12208. > 0) {
  12209. if (is_in_script_path(conn, path)) {
  12210. /* Call duktape to generate the page */
  12211. mg_exec_duktape_script(conn, path);
  12212. } else {
  12213. /* Script was in an illegal path */
  12214. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12215. }
  12216. #endif
  12217. #if !defined(NO_CGI)
  12218. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12219. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12220. path)
  12221. > 0) {
  12222. if (is_in_script_path(conn, path)) {
  12223. /* CGI scripts may support all HTTP methods */
  12224. handle_cgi_request(conn, path);
  12225. } else {
  12226. /* Script was in an illegal path */
  12227. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12228. }
  12229. #endif /* !NO_CGI */
  12230. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12231. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12232. path)
  12233. > 0) {
  12234. if (is_in_script_path(conn, path)) {
  12235. handle_ssi_file_request(conn, path, file);
  12236. } else {
  12237. /* Script was in an illegal path */
  12238. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12239. }
  12240. #if !defined(NO_CACHING)
  12241. } else if ((!conn->in_error_handler)
  12242. && is_not_modified(conn, &file->stat)) {
  12243. /* Send 304 "Not Modified" - this must not send any body data */
  12244. handle_not_modified_static_file_request(conn, file);
  12245. #endif /* !NO_CACHING */
  12246. } else {
  12247. handle_static_file_request(conn, path, file, NULL, NULL);
  12248. }
  12249. }
  12250. static void
  12251. close_all_listening_sockets(struct mg_context *ctx)
  12252. {
  12253. unsigned int i;
  12254. if (!ctx) {
  12255. return;
  12256. }
  12257. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12258. closesocket(ctx->listening_sockets[i].sock);
  12259. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12260. }
  12261. mg_free(ctx->listening_sockets);
  12262. ctx->listening_sockets = NULL;
  12263. mg_free(ctx->listening_socket_fds);
  12264. ctx->listening_socket_fds = NULL;
  12265. }
  12266. /* Valid listening port specification is: [ip_address:]port[s]
  12267. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12268. * Examples for IPv6: [::]:80, [::1]:80,
  12269. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12270. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12271. * In order to bind to both, IPv4 and IPv6, you can either add
  12272. * both ports using 8080,[::]:8080, or the short form +8080.
  12273. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12274. * one only accepting IPv4 the other only IPv6. +8080 creates
  12275. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12276. * environment, they might work differently, or might not work
  12277. * at all - it must be tested what options work best in the
  12278. * relevant network environment.
  12279. */
  12280. static int
  12281. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12282. {
  12283. unsigned int a, b, c, d, port;
  12284. int ch, len;
  12285. const char *cb;
  12286. #if defined(USE_IPV6)
  12287. char buf[100] = {0};
  12288. #endif
  12289. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12290. * Also, all-zeroes in the socket address means binding to all addresses
  12291. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12292. memset(so, 0, sizeof(*so));
  12293. so->lsa.sin.sin_family = AF_INET;
  12294. *ip_version = 0;
  12295. /* Initialize port and len as invalid. */
  12296. port = 0;
  12297. len = 0;
  12298. /* Test for different ways to format this string */
  12299. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12300. == 5) {
  12301. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12302. so->lsa.sin.sin_addr.s_addr =
  12303. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12304. so->lsa.sin.sin_port = htons((uint16_t)port);
  12305. *ip_version = 4;
  12306. #if defined(USE_IPV6)
  12307. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12308. && mg_inet_pton(
  12309. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12310. /* IPv6 address, examples: see above */
  12311. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12312. */
  12313. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12314. *ip_version = 6;
  12315. #endif
  12316. } else if ((vec->ptr[0] == '+')
  12317. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12318. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12319. /* Add 1 to len for the + character we skipped before */
  12320. len++;
  12321. #if defined(USE_IPV6)
  12322. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12323. so->lsa.sin6.sin6_family = AF_INET6;
  12324. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12325. *ip_version = 4 + 6;
  12326. #else
  12327. /* Bind to IPv4 only, since IPv6 is not built in. */
  12328. so->lsa.sin.sin_port = htons((uint16_t)port);
  12329. *ip_version = 4;
  12330. #endif
  12331. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12332. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12333. so->lsa.sin.sin_port = htons((uint16_t)port);
  12334. *ip_version = 4;
  12335. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12336. /* String could be a hostname. This check algotithm
  12337. * will only work for RFC 952 compliant hostnames,
  12338. * starting with a letter, containing only letters,
  12339. * digits and hyphen ('-'). Newer specs may allow
  12340. * more, but this is not guaranteed here, since it
  12341. * may interfere with rules for port option lists. */
  12342. /* According to RFC 1035, hostnames are restricted to 255 characters
  12343. * in total (63 between two dots). */
  12344. char hostname[256];
  12345. size_t hostnlen = (size_t)(cb - vec->ptr);
  12346. if (hostnlen >= sizeof(hostname)) {
  12347. /* This would be invalid in any case */
  12348. *ip_version = 0;
  12349. return 0;
  12350. }
  12351. memcpy(hostname, vec->ptr, hostnlen);
  12352. hostname[hostnlen] = 0;
  12353. if (mg_inet_pton(
  12354. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12355. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12356. *ip_version = 4;
  12357. so->lsa.sin.sin_family = AF_INET;
  12358. so->lsa.sin.sin_port = htons((uint16_t)port);
  12359. len += (int)(hostnlen + 1);
  12360. } else {
  12361. port = 0;
  12362. len = 0;
  12363. }
  12364. #if defined(USE_IPV6)
  12365. } else if (mg_inet_pton(AF_INET6,
  12366. vec->ptr,
  12367. &so->lsa.sin6,
  12368. sizeof(so->lsa.sin6))) {
  12369. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12370. *ip_version = 6;
  12371. so->lsa.sin6.sin6_family = AF_INET6;
  12372. so->lsa.sin.sin_port = htons((uint16_t)port);
  12373. len += (int)(hostnlen + 1);
  12374. } else {
  12375. port = 0;
  12376. len = 0;
  12377. }
  12378. #endif
  12379. }
  12380. } else {
  12381. /* Parsing failure. */
  12382. }
  12383. /* sscanf and the option splitting code ensure the following condition
  12384. */
  12385. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12386. *ip_version = 0;
  12387. return 0;
  12388. }
  12389. ch = vec->ptr[len]; /* Next character after the port number */
  12390. so->is_ssl = (ch == 's');
  12391. so->ssl_redir = (ch == 'r');
  12392. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12393. if (is_valid_port(port)
  12394. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12395. return 1;
  12396. }
  12397. /* Reset ip_version to 0 if there is an error */
  12398. *ip_version = 0;
  12399. return 0;
  12400. }
  12401. /* Is there any SSL port in use? */
  12402. static int
  12403. is_ssl_port_used(const char *ports)
  12404. {
  12405. if (ports) {
  12406. /* There are several different allowed syntax variants:
  12407. * - "80" for a single port using every network interface
  12408. * - "localhost:80" for a single port using only localhost
  12409. * - "80,localhost:8080" for two ports, one bound to localhost
  12410. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12411. * to IPv4 localhost, one to IPv6 localhost
  12412. * - "+80" use port 80 for IPv4 and IPv6
  12413. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12414. * for both: IPv4 and IPv4
  12415. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12416. * additionally port 8080 bound to localhost connections
  12417. *
  12418. * If we just look for 's' anywhere in the string, "localhost:80"
  12419. * will be detected as SSL (false positive).
  12420. * Looking for 's' after a digit may cause false positives in
  12421. * "my24service:8080".
  12422. * Looking from 's' backward if there are only ':' and numbers
  12423. * before will not work for "24service:8080" (non SSL, port 8080)
  12424. * or "24s" (SSL, port 24).
  12425. *
  12426. * Remark: Initially hostnames were not allowed to start with a
  12427. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12428. * Section 2.1).
  12429. *
  12430. * To get this correct, the entire string must be parsed as a whole,
  12431. * reading it as a list element for element and parsing with an
  12432. * algorithm equivalent to parse_port_string.
  12433. *
  12434. * In fact, we use local interface names here, not arbitrary hostnames,
  12435. * so in most cases the only name will be "localhost".
  12436. *
  12437. * So, for now, we use this simple algorithm, that may still return
  12438. * a false positive in bizarre cases.
  12439. */
  12440. int i;
  12441. int portslen = (int)strlen(ports);
  12442. char prevIsNumber = 0;
  12443. for (i = 0; i < portslen; i++) {
  12444. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12445. return 1;
  12446. }
  12447. if (ports[i] >= '0' && ports[i] <= '9') {
  12448. prevIsNumber = 1;
  12449. } else {
  12450. prevIsNumber = 0;
  12451. }
  12452. }
  12453. }
  12454. return 0;
  12455. }
  12456. static int
  12457. set_ports_option(struct mg_context *phys_ctx)
  12458. {
  12459. const char *list;
  12460. int on = 1;
  12461. #if defined(USE_IPV6)
  12462. int off = 0;
  12463. #endif
  12464. struct vec vec;
  12465. struct socket so, *ptr;
  12466. struct mg_pollfd *pfd;
  12467. union usa usa;
  12468. socklen_t len;
  12469. int ip_version;
  12470. int portsTotal = 0;
  12471. int portsOk = 0;
  12472. if (!phys_ctx) {
  12473. return 0;
  12474. }
  12475. memset(&so, 0, sizeof(so));
  12476. memset(&usa, 0, sizeof(usa));
  12477. len = sizeof(usa);
  12478. list = phys_ctx->dd.config[LISTENING_PORTS];
  12479. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12480. portsTotal++;
  12481. if (!parse_port_string(&vec, &so, &ip_version)) {
  12482. mg_cry_internal(
  12483. fc(phys_ctx),
  12484. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12485. (int)vec.len,
  12486. vec.ptr,
  12487. portsTotal,
  12488. "[IP_ADDRESS:]PORT[s|r]");
  12489. continue;
  12490. }
  12491. #if !defined(NO_SSL)
  12492. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12493. mg_cry_internal(fc(phys_ctx),
  12494. "Cannot add SSL socket (entry %i)",
  12495. portsTotal);
  12496. continue;
  12497. }
  12498. #endif
  12499. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12500. == INVALID_SOCKET) {
  12501. mg_cry_internal(fc(phys_ctx),
  12502. "cannot create socket (entry %i)",
  12503. portsTotal);
  12504. continue;
  12505. }
  12506. #if defined(_WIN32)
  12507. /* Windows SO_REUSEADDR lets many procs binds to a
  12508. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12509. * if someone already has the socket -- DTL */
  12510. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12511. * Windows might need a few seconds before
  12512. * the same port can be used again in the
  12513. * same process, so a short Sleep may be
  12514. * required between mg_stop and mg_start.
  12515. */
  12516. if (setsockopt(so.sock,
  12517. SOL_SOCKET,
  12518. SO_EXCLUSIVEADDRUSE,
  12519. (SOCK_OPT_TYPE)&on,
  12520. sizeof(on))
  12521. != 0) {
  12522. /* Set reuse option, but don't abort on errors. */
  12523. mg_cry_internal(
  12524. fc(phys_ctx),
  12525. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12526. portsTotal);
  12527. }
  12528. #else
  12529. if (setsockopt(so.sock,
  12530. SOL_SOCKET,
  12531. SO_REUSEADDR,
  12532. (SOCK_OPT_TYPE)&on,
  12533. sizeof(on))
  12534. != 0) {
  12535. /* Set reuse option, but don't abort on errors. */
  12536. mg_cry_internal(fc(phys_ctx),
  12537. "cannot set socket option SO_REUSEADDR (entry %i)",
  12538. portsTotal);
  12539. }
  12540. #endif
  12541. if (ip_version > 4) {
  12542. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12543. #if defined(USE_IPV6)
  12544. if (ip_version > 6) {
  12545. if (so.lsa.sa.sa_family == AF_INET6
  12546. && setsockopt(so.sock,
  12547. IPPROTO_IPV6,
  12548. IPV6_V6ONLY,
  12549. (void *)&off,
  12550. sizeof(off))
  12551. != 0) {
  12552. /* Set IPv6 only option, but don't abort on errors. */
  12553. mg_cry_internal(
  12554. fc(phys_ctx),
  12555. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12556. portsTotal);
  12557. }
  12558. } else {
  12559. if (so.lsa.sa.sa_family == AF_INET6
  12560. && setsockopt(so.sock,
  12561. IPPROTO_IPV6,
  12562. IPV6_V6ONLY,
  12563. (void *)&on,
  12564. sizeof(on))
  12565. != 0) {
  12566. /* Set IPv6 only option, but don't abort on errors. */
  12567. mg_cry_internal(
  12568. fc(phys_ctx),
  12569. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12570. portsTotal);
  12571. }
  12572. }
  12573. #else
  12574. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12575. closesocket(so.sock);
  12576. so.sock = INVALID_SOCKET;
  12577. continue;
  12578. #endif
  12579. }
  12580. if (so.lsa.sa.sa_family == AF_INET) {
  12581. len = sizeof(so.lsa.sin);
  12582. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12583. mg_cry_internal(fc(phys_ctx),
  12584. "cannot bind to %.*s: %d (%s)",
  12585. (int)vec.len,
  12586. vec.ptr,
  12587. (int)ERRNO,
  12588. strerror(errno));
  12589. closesocket(so.sock);
  12590. so.sock = INVALID_SOCKET;
  12591. continue;
  12592. }
  12593. }
  12594. #if defined(USE_IPV6)
  12595. else if (so.lsa.sa.sa_family == AF_INET6) {
  12596. len = sizeof(so.lsa.sin6);
  12597. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12598. mg_cry_internal(fc(phys_ctx),
  12599. "cannot bind to IPv6 %.*s: %d (%s)",
  12600. (int)vec.len,
  12601. vec.ptr,
  12602. (int)ERRNO,
  12603. strerror(errno));
  12604. closesocket(so.sock);
  12605. so.sock = INVALID_SOCKET;
  12606. continue;
  12607. }
  12608. }
  12609. #endif
  12610. else {
  12611. mg_cry_internal(
  12612. fc(phys_ctx),
  12613. "cannot bind: address family not supported (entry %i)",
  12614. portsTotal);
  12615. closesocket(so.sock);
  12616. so.sock = INVALID_SOCKET;
  12617. continue;
  12618. }
  12619. if (listen(so.sock, SOMAXCONN) != 0) {
  12620. mg_cry_internal(fc(phys_ctx),
  12621. "cannot listen to %.*s: %d (%s)",
  12622. (int)vec.len,
  12623. vec.ptr,
  12624. (int)ERRNO,
  12625. strerror(errno));
  12626. closesocket(so.sock);
  12627. so.sock = INVALID_SOCKET;
  12628. continue;
  12629. }
  12630. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12631. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12632. int err = (int)ERRNO;
  12633. mg_cry_internal(fc(phys_ctx),
  12634. "call to getsockname failed %.*s: %d (%s)",
  12635. (int)vec.len,
  12636. vec.ptr,
  12637. err,
  12638. strerror(errno));
  12639. closesocket(so.sock);
  12640. so.sock = INVALID_SOCKET;
  12641. continue;
  12642. }
  12643. /* Update lsa port in case of random free ports */
  12644. #if defined(USE_IPV6)
  12645. if (so.lsa.sa.sa_family == AF_INET6) {
  12646. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12647. } else
  12648. #endif
  12649. {
  12650. so.lsa.sin.sin_port = usa.sin.sin_port;
  12651. }
  12652. if ((ptr = (struct socket *)
  12653. mg_realloc_ctx(phys_ctx->listening_sockets,
  12654. (phys_ctx->num_listening_sockets + 1)
  12655. * sizeof(phys_ctx->listening_sockets[0]),
  12656. phys_ctx))
  12657. == NULL) {
  12658. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12659. closesocket(so.sock);
  12660. so.sock = INVALID_SOCKET;
  12661. continue;
  12662. }
  12663. if ((pfd = (struct mg_pollfd *)
  12664. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12665. (phys_ctx->num_listening_sockets + 1)
  12666. * sizeof(phys_ctx->listening_socket_fds[0]),
  12667. phys_ctx))
  12668. == NULL) {
  12669. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12670. closesocket(so.sock);
  12671. so.sock = INVALID_SOCKET;
  12672. mg_free(ptr);
  12673. continue;
  12674. }
  12675. set_close_on_exec(so.sock, fc(phys_ctx));
  12676. phys_ctx->listening_sockets = ptr;
  12677. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12678. phys_ctx->listening_socket_fds = pfd;
  12679. phys_ctx->num_listening_sockets++;
  12680. portsOk++;
  12681. }
  12682. if (portsOk != portsTotal) {
  12683. close_all_listening_sockets(phys_ctx);
  12684. portsOk = 0;
  12685. }
  12686. return portsOk;
  12687. }
  12688. static const char *
  12689. header_val(const struct mg_connection *conn, const char *header)
  12690. {
  12691. const char *header_value;
  12692. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12693. return "-";
  12694. } else {
  12695. return header_value;
  12696. }
  12697. }
  12698. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12699. static void log_access(const struct mg_connection *conn);
  12700. #include "external_log_access.inl"
  12701. #else
  12702. static void
  12703. log_access(const struct mg_connection *conn)
  12704. {
  12705. const struct mg_request_info *ri;
  12706. struct mg_file fi;
  12707. char date[64], src_addr[IP_ADDR_STR_LEN];
  12708. struct tm *tm;
  12709. const char *referer;
  12710. const char *user_agent;
  12711. char buf[4096];
  12712. if (!conn || !conn->dom_ctx) {
  12713. return;
  12714. }
  12715. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12716. if (mg_fopen(conn,
  12717. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12718. MG_FOPEN_MODE_APPEND,
  12719. &fi)
  12720. == 0) {
  12721. fi.access.fp = NULL;
  12722. }
  12723. } else {
  12724. fi.access.fp = NULL;
  12725. }
  12726. /* Log is written to a file and/or a callback. If both are not set,
  12727. * executing the rest of the function is pointless. */
  12728. if ((fi.access.fp == NULL)
  12729. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12730. return;
  12731. }
  12732. tm = localtime(&conn->conn_birth_time);
  12733. if (tm != NULL) {
  12734. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12735. } else {
  12736. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12737. date[sizeof(date) - 1] = '\0';
  12738. }
  12739. ri = &conn->request_info;
  12740. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12741. referer = header_val(conn, "Referer");
  12742. user_agent = header_val(conn, "User-Agent");
  12743. mg_snprintf(conn,
  12744. NULL, /* Ignore truncation in access log */
  12745. buf,
  12746. sizeof(buf),
  12747. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12748. src_addr,
  12749. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12750. date,
  12751. ri->request_method ? ri->request_method : "-",
  12752. ri->request_uri ? ri->request_uri : "-",
  12753. ri->query_string ? "?" : "",
  12754. ri->query_string ? ri->query_string : "",
  12755. ri->http_version,
  12756. conn->status_code,
  12757. conn->num_bytes_sent,
  12758. referer,
  12759. user_agent);
  12760. if (conn->phys_ctx->callbacks.log_access) {
  12761. conn->phys_ctx->callbacks.log_access(conn, buf);
  12762. }
  12763. if (fi.access.fp) {
  12764. int ok = 1;
  12765. flockfile(fi.access.fp);
  12766. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12767. ok = 0;
  12768. }
  12769. if (fflush(fi.access.fp) != 0) {
  12770. ok = 0;
  12771. }
  12772. funlockfile(fi.access.fp);
  12773. if (mg_fclose(&fi.access) != 0) {
  12774. ok = 0;
  12775. }
  12776. if (!ok) {
  12777. mg_cry_internal(conn,
  12778. "Error writing log file %s",
  12779. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12780. }
  12781. }
  12782. }
  12783. #endif /* Externally provided function */
  12784. /* Verify given socket address against the ACL.
  12785. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12786. */
  12787. static int
  12788. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12789. {
  12790. int allowed, flag;
  12791. uint32_t net, mask;
  12792. struct vec vec;
  12793. if (phys_ctx) {
  12794. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12795. /* If any ACL is set, deny by default */
  12796. allowed = (list == NULL) ? '+' : '-';
  12797. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12798. flag = vec.ptr[0];
  12799. if ((flag != '+' && flag != '-')
  12800. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12801. mg_cry_internal(fc(phys_ctx),
  12802. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12803. __func__);
  12804. return -1;
  12805. }
  12806. if (net == (remote_ip & mask)) {
  12807. allowed = flag;
  12808. }
  12809. }
  12810. return allowed == '+';
  12811. }
  12812. return -1;
  12813. }
  12814. #if !defined(_WIN32)
  12815. static int
  12816. set_uid_option(struct mg_context *phys_ctx)
  12817. {
  12818. int success = 0;
  12819. if (phys_ctx) {
  12820. /* We are currently running as curr_uid. */
  12821. const uid_t curr_uid = getuid();
  12822. /* If set, we want to run as run_as_user. */
  12823. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12824. const struct passwd *to_pw = NULL;
  12825. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12826. /* run_as_user does not exist on the system. We can't proceed
  12827. * further. */
  12828. mg_cry_internal(fc(phys_ctx),
  12829. "%s: unknown user [%s]",
  12830. __func__,
  12831. run_as_user);
  12832. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12833. /* There was either no request to change user, or we're already
  12834. * running as run_as_user. Nothing else to do.
  12835. */
  12836. success = 1;
  12837. } else {
  12838. /* Valid change request. */
  12839. if (setgid(to_pw->pw_gid) == -1) {
  12840. mg_cry_internal(fc(phys_ctx),
  12841. "%s: setgid(%s): %s",
  12842. __func__,
  12843. run_as_user,
  12844. strerror(errno));
  12845. } else if (setgroups(0, NULL) == -1) {
  12846. mg_cry_internal(fc(phys_ctx),
  12847. "%s: setgroups(): %s",
  12848. __func__,
  12849. strerror(errno));
  12850. } else if (setuid(to_pw->pw_uid) == -1) {
  12851. mg_cry_internal(fc(phys_ctx),
  12852. "%s: setuid(%s): %s",
  12853. __func__,
  12854. run_as_user,
  12855. strerror(errno));
  12856. } else {
  12857. success = 1;
  12858. }
  12859. }
  12860. }
  12861. return success;
  12862. }
  12863. #endif /* !_WIN32 */
  12864. static void
  12865. tls_dtor(void *key)
  12866. {
  12867. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12868. /* key == pthread_getspecific(sTlsKey); */
  12869. if (tls) {
  12870. if (tls->is_master == 2) {
  12871. tls->is_master = -3; /* Mark memory as dead */
  12872. mg_free(tls);
  12873. }
  12874. }
  12875. pthread_setspecific(sTlsKey, NULL);
  12876. }
  12877. #if !defined(NO_SSL)
  12878. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12879. struct mg_domain_context *dom_ctx,
  12880. const char *pem,
  12881. const char *chain);
  12882. static const char *ssl_error(void);
  12883. static int
  12884. refresh_trust(struct mg_connection *conn)
  12885. {
  12886. static int reload_lock = 0;
  12887. static long int data_check = 0;
  12888. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12889. struct stat cert_buf;
  12890. long int t;
  12891. const char *pem;
  12892. const char *chain;
  12893. int should_verify_peer;
  12894. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12895. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12896. * refresh_trust still can not work. */
  12897. return 0;
  12898. }
  12899. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12900. if (chain == NULL) {
  12901. /* pem is not NULL here */
  12902. chain = pem;
  12903. }
  12904. if (*chain == 0) {
  12905. chain = NULL;
  12906. }
  12907. t = data_check;
  12908. if (stat(pem, &cert_buf) != -1) {
  12909. t = (long int)cert_buf.st_mtime;
  12910. }
  12911. if (data_check != t) {
  12912. data_check = t;
  12913. should_verify_peer = 0;
  12914. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12915. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12916. == 0) {
  12917. should_verify_peer = 1;
  12918. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12919. "optional")
  12920. == 0) {
  12921. should_verify_peer = 1;
  12922. }
  12923. }
  12924. if (should_verify_peer) {
  12925. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12926. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12927. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12928. ca_file,
  12929. ca_path)
  12930. != 1) {
  12931. mg_cry_internal(
  12932. fc(conn->phys_ctx),
  12933. "SSL_CTX_load_verify_locations error: %s "
  12934. "ssl_verify_peer requires setting "
  12935. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12936. "present in "
  12937. "the .conf file?",
  12938. ssl_error());
  12939. return 0;
  12940. }
  12941. }
  12942. if (1 == mg_atomic_inc(p_reload_lock)) {
  12943. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12944. == 0) {
  12945. return 0;
  12946. }
  12947. *p_reload_lock = 0;
  12948. }
  12949. }
  12950. /* lock while cert is reloading */
  12951. while (*p_reload_lock) {
  12952. sleep(1);
  12953. }
  12954. return 1;
  12955. }
  12956. #if defined(OPENSSL_API_1_1)
  12957. #else
  12958. static pthread_mutex_t *ssl_mutexes;
  12959. #endif /* OPENSSL_API_1_1 */
  12960. static int
  12961. sslize(struct mg_connection *conn,
  12962. SSL_CTX *s,
  12963. int (*func)(SSL *),
  12964. volatile int *stop_server,
  12965. const struct mg_client_options *client_options)
  12966. {
  12967. int ret, err;
  12968. int short_trust;
  12969. unsigned timeout = 1024;
  12970. unsigned i;
  12971. if (!conn) {
  12972. return 0;
  12973. }
  12974. short_trust =
  12975. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12976. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12977. if (short_trust) {
  12978. int trust_ret = refresh_trust(conn);
  12979. if (!trust_ret) {
  12980. return trust_ret;
  12981. }
  12982. }
  12983. conn->ssl = SSL_new(s);
  12984. if (conn->ssl == NULL) {
  12985. return 0;
  12986. }
  12987. SSL_set_app_data(conn->ssl, (char *)conn);
  12988. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12989. if (ret != 1) {
  12990. err = SSL_get_error(conn->ssl, ret);
  12991. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12992. SSL_free(conn->ssl);
  12993. conn->ssl = NULL;
  12994. OPENSSL_REMOVE_THREAD_STATE();
  12995. return 0;
  12996. }
  12997. if (client_options) {
  12998. if (client_options->host_name) {
  12999. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13000. }
  13001. }
  13002. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13003. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13004. /* NOTE: The loop below acts as a back-off, so we can end
  13005. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13006. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13007. }
  13008. /* SSL functions may fail and require to be called again:
  13009. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13010. * Here "func" could be SSL_connect or SSL_accept. */
  13011. for (i = 16; i <= timeout; i *= 2) {
  13012. ret = func(conn->ssl);
  13013. if (ret != 1) {
  13014. err = SSL_get_error(conn->ssl, ret);
  13015. if ((err == SSL_ERROR_WANT_CONNECT)
  13016. || (err == SSL_ERROR_WANT_ACCEPT)
  13017. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13018. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13019. /* Need to retry the function call "later".
  13020. * See https://linux.die.net/man/3/ssl_get_error
  13021. * This is typical for non-blocking sockets. */
  13022. if (*stop_server) {
  13023. /* Don't wait if the server is going to be stopped. */
  13024. break;
  13025. }
  13026. mg_sleep(i);
  13027. } else if (err == SSL_ERROR_SYSCALL) {
  13028. /* This is an IO error. Look at errno. */
  13029. err = errno;
  13030. mg_cry_internal(conn, "SSL syscall error %i", err);
  13031. break;
  13032. } else {
  13033. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13034. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13035. break;
  13036. }
  13037. } else {
  13038. /* success */
  13039. break;
  13040. }
  13041. }
  13042. if (ret != 1) {
  13043. SSL_free(conn->ssl);
  13044. conn->ssl = NULL;
  13045. OPENSSL_REMOVE_THREAD_STATE();
  13046. return 0;
  13047. }
  13048. return 1;
  13049. }
  13050. /* Return OpenSSL error message (from CRYPTO lib) */
  13051. static const char *
  13052. ssl_error(void)
  13053. {
  13054. unsigned long err;
  13055. err = ERR_get_error();
  13056. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13057. }
  13058. static int
  13059. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13060. {
  13061. int i;
  13062. const char hexdigit[] = "0123456789abcdef";
  13063. if ((memlen <= 0) || (buflen <= 0)) {
  13064. return 0;
  13065. }
  13066. if (buflen < (3 * memlen)) {
  13067. return 0;
  13068. }
  13069. for (i = 0; i < memlen; i++) {
  13070. if (i > 0) {
  13071. buf[3 * i - 1] = ' ';
  13072. }
  13073. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13074. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13075. }
  13076. buf[3 * memlen - 1] = 0;
  13077. return 1;
  13078. }
  13079. static void
  13080. ssl_get_client_cert_info(struct mg_connection *conn)
  13081. {
  13082. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13083. if (cert) {
  13084. char str_subject[1024];
  13085. char str_issuer[1024];
  13086. char str_finger[1024];
  13087. unsigned char buf[256];
  13088. char *str_serial = NULL;
  13089. unsigned int ulen;
  13090. int ilen;
  13091. unsigned char *tmp_buf;
  13092. unsigned char *tmp_p;
  13093. /* Handle to algorithm used for fingerprint */
  13094. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13095. /* Get Subject and issuer */
  13096. X509_NAME *subj = X509_get_subject_name(cert);
  13097. X509_NAME *iss = X509_get_issuer_name(cert);
  13098. /* Get serial number */
  13099. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13100. /* Translate serial number to a hex string */
  13101. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13102. str_serial = BN_bn2hex(serial_bn);
  13103. BN_free(serial_bn);
  13104. /* Translate subject and issuer to a string */
  13105. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13106. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13107. /* Calculate SHA1 fingerprint and store as a hex string */
  13108. ulen = 0;
  13109. /* ASN1_digest is deprecated. Do the calculation manually,
  13110. * using EVP_Digest. */
  13111. ilen = i2d_X509(cert, NULL);
  13112. tmp_buf = (ilen > 0)
  13113. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13114. conn->phys_ctx)
  13115. : NULL;
  13116. if (tmp_buf) {
  13117. tmp_p = tmp_buf;
  13118. (void)i2d_X509(cert, &tmp_p);
  13119. if (!EVP_Digest(
  13120. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13121. ulen = 0;
  13122. }
  13123. mg_free(tmp_buf);
  13124. }
  13125. if (!hexdump2string(
  13126. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13127. *str_finger = 0;
  13128. }
  13129. conn->request_info.client_cert = (struct mg_client_cert *)
  13130. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13131. if (conn->request_info.client_cert) {
  13132. conn->request_info.client_cert->peer_cert = (void *)cert;
  13133. conn->request_info.client_cert->subject =
  13134. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13135. conn->request_info.client_cert->issuer =
  13136. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13137. conn->request_info.client_cert->serial =
  13138. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13139. conn->request_info.client_cert->finger =
  13140. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13141. } else {
  13142. mg_cry_internal(conn,
  13143. "%s",
  13144. "Out of memory: Cannot allocate memory for client "
  13145. "certificate");
  13146. }
  13147. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13148. * see https://linux.die.net/man/3/bn_bn2hex */
  13149. OPENSSL_free(str_serial);
  13150. }
  13151. }
  13152. #if defined(OPENSSL_API_1_1)
  13153. #else
  13154. static void
  13155. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13156. {
  13157. (void)line;
  13158. (void)file;
  13159. if (mode & 1) {
  13160. /* 1 is CRYPTO_LOCK */
  13161. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13162. } else {
  13163. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13164. }
  13165. }
  13166. #endif /* OPENSSL_API_1_1 */
  13167. #if !defined(NO_SSL_DL)
  13168. static void *
  13169. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13170. {
  13171. union {
  13172. void *p;
  13173. void (*fp)(void);
  13174. } u;
  13175. void *dll_handle;
  13176. struct ssl_func *fp;
  13177. int ok;
  13178. int truncated = 0;
  13179. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13180. mg_snprintf(NULL,
  13181. NULL, /* No truncation check for ebuf */
  13182. ebuf,
  13183. ebuf_len,
  13184. "%s: cannot load %s",
  13185. __func__,
  13186. dll_name);
  13187. return NULL;
  13188. }
  13189. ok = 1;
  13190. for (fp = sw; fp->name != NULL; fp++) {
  13191. #if defined(_WIN32)
  13192. /* GetProcAddress() returns pointer to function */
  13193. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13194. #else
  13195. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13196. * pointers to function pointers. We need to use a union to make a
  13197. * cast. */
  13198. u.p = dlsym(dll_handle, fp->name);
  13199. #endif /* _WIN32 */
  13200. if (u.fp == NULL) {
  13201. if (ok) {
  13202. mg_snprintf(NULL,
  13203. &truncated,
  13204. ebuf,
  13205. ebuf_len,
  13206. "%s: %s: cannot find %s",
  13207. __func__,
  13208. dll_name,
  13209. fp->name);
  13210. ok = 0;
  13211. } else {
  13212. size_t cur_len = strlen(ebuf);
  13213. if (!truncated) {
  13214. mg_snprintf(NULL,
  13215. &truncated,
  13216. ebuf + cur_len,
  13217. ebuf_len - cur_len - 3,
  13218. ", %s",
  13219. fp->name);
  13220. if (truncated) {
  13221. /* If truncated, add "..." */
  13222. strcat(ebuf, "...");
  13223. }
  13224. }
  13225. }
  13226. /* Debug:
  13227. * printf("Missing function: %s\n", fp->name); */
  13228. } else {
  13229. fp->ptr = u.fp;
  13230. }
  13231. }
  13232. if (!ok) {
  13233. (void)dlclose(dll_handle);
  13234. return NULL;
  13235. }
  13236. return dll_handle;
  13237. }
  13238. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13239. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13240. #endif /* NO_SSL_DL */
  13241. #if defined(SSL_ALREADY_INITIALIZED)
  13242. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13243. #else
  13244. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13245. #endif
  13246. static int
  13247. initialize_ssl(char *ebuf, size_t ebuf_len)
  13248. {
  13249. #if defined(OPENSSL_API_1_1)
  13250. if (ebuf_len > 0) {
  13251. ebuf[0] = 0;
  13252. }
  13253. #if !defined(NO_SSL_DL)
  13254. if (!cryptolib_dll_handle) {
  13255. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13256. if (!cryptolib_dll_handle) {
  13257. mg_snprintf(NULL,
  13258. NULL, /* No truncation check for ebuf */
  13259. ebuf,
  13260. ebuf_len,
  13261. "%s: error loading library %s",
  13262. __func__,
  13263. CRYPTO_LIB);
  13264. DEBUG_TRACE("%s", ebuf);
  13265. return 0;
  13266. }
  13267. }
  13268. #endif /* NO_SSL_DL */
  13269. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13270. return 1;
  13271. }
  13272. #else /* not OPENSSL_API_1_1 */
  13273. int i, num_locks;
  13274. size_t size;
  13275. if (ebuf_len > 0) {
  13276. ebuf[0] = 0;
  13277. }
  13278. #if !defined(NO_SSL_DL)
  13279. if (!cryptolib_dll_handle) {
  13280. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13281. if (!cryptolib_dll_handle) {
  13282. mg_snprintf(NULL,
  13283. NULL, /* No truncation check for ebuf */
  13284. ebuf,
  13285. ebuf_len,
  13286. "%s: error loading library %s",
  13287. __func__,
  13288. CRYPTO_LIB);
  13289. DEBUG_TRACE("%s", ebuf);
  13290. return 0;
  13291. }
  13292. }
  13293. #endif /* NO_SSL_DL */
  13294. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13295. return 1;
  13296. }
  13297. /* Initialize locking callbacks, needed for thread safety.
  13298. * http://www.openssl.org/support/faq.html#PROG1
  13299. */
  13300. num_locks = CRYPTO_num_locks();
  13301. if (num_locks < 0) {
  13302. num_locks = 0;
  13303. }
  13304. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13305. /* allocate mutex array, if required */
  13306. if (num_locks == 0) {
  13307. /* No mutex array required */
  13308. ssl_mutexes = NULL;
  13309. } else {
  13310. /* Mutex array required - allocate it */
  13311. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13312. /* Check OOM */
  13313. if (ssl_mutexes == NULL) {
  13314. mg_snprintf(NULL,
  13315. NULL, /* No truncation check for ebuf */
  13316. ebuf,
  13317. ebuf_len,
  13318. "%s: cannot allocate mutexes: %s",
  13319. __func__,
  13320. ssl_error());
  13321. DEBUG_TRACE("%s", ebuf);
  13322. return 0;
  13323. }
  13324. /* initialize mutex array */
  13325. for (i = 0; i < num_locks; i++) {
  13326. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13327. mg_snprintf(NULL,
  13328. NULL, /* No truncation check for ebuf */
  13329. ebuf,
  13330. ebuf_len,
  13331. "%s: error initializing mutex %i of %i",
  13332. __func__,
  13333. i,
  13334. num_locks);
  13335. DEBUG_TRACE("%s", ebuf);
  13336. mg_free(ssl_mutexes);
  13337. return 0;
  13338. }
  13339. }
  13340. }
  13341. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13342. CRYPTO_set_id_callback(&mg_current_thread_id);
  13343. #endif /* OPENSSL_API_1_1 */
  13344. #if !defined(NO_SSL_DL)
  13345. if (!ssllib_dll_handle) {
  13346. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13347. if (!ssllib_dll_handle) {
  13348. #if !defined(OPENSSL_API_1_1)
  13349. mg_free(ssl_mutexes);
  13350. #endif
  13351. DEBUG_TRACE("%s", ebuf);
  13352. return 0;
  13353. }
  13354. }
  13355. #endif /* NO_SSL_DL */
  13356. #if defined(OPENSSL_API_1_1)
  13357. /* Initialize SSL library */
  13358. OPENSSL_init_ssl(0, NULL);
  13359. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13360. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13361. NULL);
  13362. #else
  13363. /* Initialize SSL library */
  13364. SSL_library_init();
  13365. SSL_load_error_strings();
  13366. #endif
  13367. return 1;
  13368. }
  13369. static int
  13370. ssl_use_pem_file(struct mg_context *phys_ctx,
  13371. struct mg_domain_context *dom_ctx,
  13372. const char *pem,
  13373. const char *chain)
  13374. {
  13375. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13376. mg_cry_internal(fc(phys_ctx),
  13377. "%s: cannot open certificate file %s: %s",
  13378. __func__,
  13379. pem,
  13380. ssl_error());
  13381. return 0;
  13382. }
  13383. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13384. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13385. mg_cry_internal(fc(phys_ctx),
  13386. "%s: cannot open private key file %s: %s",
  13387. __func__,
  13388. pem,
  13389. ssl_error());
  13390. return 0;
  13391. }
  13392. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13393. mg_cry_internal(fc(phys_ctx),
  13394. "%s: certificate and private key do not match: %s",
  13395. __func__,
  13396. pem);
  13397. return 0;
  13398. }
  13399. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13400. * chain files that contain private keys and certificates in
  13401. * SSL_CTX_use_certificate_chain_file.
  13402. * The CivetWeb-Server used pem-Files that contained both information.
  13403. * In order to make wolfSSL work, it is split in two files.
  13404. * One file that contains key and certificate used by the server and
  13405. * an optional chain file for the ssl stack.
  13406. */
  13407. if (chain) {
  13408. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13409. mg_cry_internal(fc(phys_ctx),
  13410. "%s: cannot use certificate chain file %s: %s",
  13411. __func__,
  13412. pem,
  13413. ssl_error());
  13414. return 0;
  13415. }
  13416. }
  13417. return 1;
  13418. }
  13419. #if defined(OPENSSL_API_1_1)
  13420. static unsigned long
  13421. ssl_get_protocol(int version_id)
  13422. {
  13423. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13424. if (version_id > 0)
  13425. ret |= SSL_OP_NO_SSLv2;
  13426. if (version_id > 1)
  13427. ret |= SSL_OP_NO_SSLv3;
  13428. if (version_id > 2)
  13429. ret |= SSL_OP_NO_TLSv1;
  13430. if (version_id > 3)
  13431. ret |= SSL_OP_NO_TLSv1_1;
  13432. return ret;
  13433. }
  13434. #else
  13435. static long
  13436. ssl_get_protocol(int version_id)
  13437. {
  13438. long ret = (long)SSL_OP_ALL;
  13439. if (version_id > 0)
  13440. ret |= SSL_OP_NO_SSLv2;
  13441. if (version_id > 1)
  13442. ret |= SSL_OP_NO_SSLv3;
  13443. if (version_id > 2)
  13444. ret |= SSL_OP_NO_TLSv1;
  13445. if (version_id > 3)
  13446. ret |= SSL_OP_NO_TLSv1_1;
  13447. return ret;
  13448. }
  13449. #endif /* OPENSSL_API_1_1 */
  13450. /* SSL callback documentation:
  13451. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13452. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13453. * https://linux.die.net/man/3/ssl_set_info_callback */
  13454. /* Note: There is no "const" for the first argument in the documentation
  13455. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13456. * / OpenSSL compatibility layers have it. Having a different definition will
  13457. * cause a warning in C and an error in C++. Use "const SSL *", while
  13458. * automatical conversion from "SSL *" works for all compilers, but not other
  13459. * way around */
  13460. static void
  13461. ssl_info_callback(const SSL *ssl, int what, int ret)
  13462. {
  13463. (void)ret;
  13464. if (what & SSL_CB_HANDSHAKE_START) {
  13465. SSL_get_app_data(ssl);
  13466. }
  13467. if (what & SSL_CB_HANDSHAKE_DONE) {
  13468. /* TODO: check for openSSL 1.1 */
  13469. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13470. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13471. }
  13472. }
  13473. static int
  13474. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13475. {
  13476. struct mg_context *ctx = (struct mg_context *)arg;
  13477. struct mg_domain_context *dom =
  13478. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13479. #if defined(GCC_DIAGNOSTIC)
  13480. #pragma GCC diagnostic push
  13481. #pragma GCC diagnostic ignored "-Wcast-align"
  13482. #endif /* defined(GCC_DIAGNOSTIC) */
  13483. /* We used an aligned pointer in SSL_set_app_data */
  13484. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13485. #if defined(GCC_DIAGNOSTIC)
  13486. #pragma GCC diagnostic pop
  13487. #endif /* defined(GCC_DIAGNOSTIC) */
  13488. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13489. (void)ad;
  13490. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13491. DEBUG_TRACE("%s", "internal error - assertion failed");
  13492. return SSL_TLSEXT_ERR_NOACK;
  13493. }
  13494. /* Old clients (Win XP) will not support SNI. Then, there
  13495. * is no server name available in the request - we can
  13496. * only work with the default certificate.
  13497. * Multiple HTTPS hosts on one IP+port are only possible
  13498. * with a certificate containing all alternative names.
  13499. */
  13500. if ((servername == NULL) || (*servername == 0)) {
  13501. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13502. conn->dom_ctx = &(ctx->dd);
  13503. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13504. return SSL_TLSEXT_ERR_NOACK;
  13505. }
  13506. DEBUG_TRACE("TLS connection to host %s", servername);
  13507. while (dom) {
  13508. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13509. /* Found matching domain */
  13510. DEBUG_TRACE("TLS domain %s found",
  13511. dom->config[AUTHENTICATION_DOMAIN]);
  13512. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13513. conn->dom_ctx = dom;
  13514. return SSL_TLSEXT_ERR_OK;
  13515. }
  13516. dom = dom->next;
  13517. }
  13518. /* Default domain */
  13519. DEBUG_TRACE("TLS default domain %s used",
  13520. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13521. conn->dom_ctx = &(ctx->dd);
  13522. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13523. return SSL_TLSEXT_ERR_OK;
  13524. }
  13525. /* Setup SSL CTX as required by CivetWeb */
  13526. static int
  13527. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13528. struct mg_domain_context *dom_ctx,
  13529. const char *pem,
  13530. const char *chain)
  13531. {
  13532. int callback_ret;
  13533. int should_verify_peer;
  13534. int peer_certificate_optional;
  13535. const char *ca_path;
  13536. const char *ca_file;
  13537. int use_default_verify_paths;
  13538. int verify_depth;
  13539. struct timespec now_mt;
  13540. md5_byte_t ssl_context_id[16];
  13541. md5_state_t md5state;
  13542. int protocol_ver;
  13543. #if defined(OPENSSL_API_1_1)
  13544. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13545. mg_cry_internal(fc(phys_ctx),
  13546. "SSL_CTX_new (server) error: %s",
  13547. ssl_error());
  13548. return 0;
  13549. }
  13550. #else
  13551. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13552. mg_cry_internal(fc(phys_ctx),
  13553. "SSL_CTX_new (server) error: %s",
  13554. ssl_error());
  13555. return 0;
  13556. }
  13557. #endif /* OPENSSL_API_1_1 */
  13558. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13559. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13560. | SSL_OP_NO_TLSv1_1);
  13561. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13562. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13563. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13564. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13565. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13566. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13567. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13568. #if !defined(NO_SSL_DL)
  13569. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13570. #endif /* NO_SSL_DL */
  13571. /* In SSL documentation examples callback defined without const specifier
  13572. * 'void (*)(SSL *, int, int)' See:
  13573. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13574. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13575. * But in the source code const SSL is used:
  13576. * 'void (*)(const SSL *, int, int)' See:
  13577. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13578. * Problem about wrong documentation described, but not resolved:
  13579. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13580. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13581. * But when compiled with modern C++ compiler, correct const should be
  13582. * provided
  13583. */
  13584. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13585. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13586. ssl_servername_callback);
  13587. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13588. /* If a callback has been specified, call it. */
  13589. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13590. ? 0
  13591. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13592. phys_ctx->user_data));
  13593. /* If callback returns 0, civetweb sets up the SSL certificate.
  13594. * If it returns 1, civetweb assumes the calback already did this.
  13595. * If it returns -1, initializing ssl fails. */
  13596. if (callback_ret < 0) {
  13597. mg_cry_internal(fc(phys_ctx),
  13598. "SSL callback returned error: %i",
  13599. callback_ret);
  13600. return 0;
  13601. }
  13602. if (callback_ret > 0) {
  13603. /* Callback did everything. */
  13604. return 1;
  13605. }
  13606. /* Use some combination of start time, domain and port as a SSL
  13607. * context ID. This should be unique on the current machine. */
  13608. md5_init(&md5state);
  13609. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13610. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13611. md5_append(&md5state,
  13612. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13613. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13614. md5_append(&md5state,
  13615. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13616. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13617. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13618. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13619. md5_finish(&md5state, ssl_context_id);
  13620. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13621. (unsigned char *)ssl_context_id,
  13622. sizeof(ssl_context_id));
  13623. if (pem != NULL) {
  13624. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13625. return 0;
  13626. }
  13627. }
  13628. /* Should we support client certificates? */
  13629. /* Default is "no". */
  13630. should_verify_peer = 0;
  13631. peer_certificate_optional = 0;
  13632. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13633. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13634. /* Yes, they are mandatory */
  13635. should_verify_peer = 1;
  13636. peer_certificate_optional = 0;
  13637. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13638. "optional")
  13639. == 0) {
  13640. /* Yes, they are optional */
  13641. should_verify_peer = 1;
  13642. peer_certificate_optional = 1;
  13643. }
  13644. }
  13645. use_default_verify_paths =
  13646. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13647. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13648. == 0);
  13649. if (should_verify_peer) {
  13650. ca_path = dom_ctx->config[SSL_CA_PATH];
  13651. ca_file = dom_ctx->config[SSL_CA_FILE];
  13652. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13653. != 1) {
  13654. mg_cry_internal(fc(phys_ctx),
  13655. "SSL_CTX_load_verify_locations error: %s "
  13656. "ssl_verify_peer requires setting "
  13657. "either ssl_ca_path or ssl_ca_file. "
  13658. "Is any of them present in the "
  13659. ".conf file?",
  13660. ssl_error());
  13661. return 0;
  13662. }
  13663. if (peer_certificate_optional) {
  13664. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13665. } else {
  13666. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13667. SSL_VERIFY_PEER
  13668. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13669. NULL);
  13670. }
  13671. if (use_default_verify_paths
  13672. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13673. mg_cry_internal(fc(phys_ctx),
  13674. "SSL_CTX_set_default_verify_paths error: %s",
  13675. ssl_error());
  13676. return 0;
  13677. }
  13678. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13679. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13680. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13681. }
  13682. }
  13683. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13684. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13685. dom_ctx->config[SSL_CIPHER_LIST])
  13686. != 1) {
  13687. mg_cry_internal(fc(phys_ctx),
  13688. "SSL_CTX_set_cipher_list error: %s",
  13689. ssl_error());
  13690. }
  13691. }
  13692. return 1;
  13693. }
  13694. /* Check if SSL is required.
  13695. * If so, dynamically load SSL library
  13696. * and set up ctx->ssl_ctx pointer. */
  13697. static int
  13698. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13699. {
  13700. void *ssl_ctx = 0;
  13701. int callback_ret;
  13702. const char *pem;
  13703. const char *chain;
  13704. char ebuf[128];
  13705. if (!phys_ctx) {
  13706. return 0;
  13707. }
  13708. if (!dom_ctx) {
  13709. dom_ctx = &(phys_ctx->dd);
  13710. }
  13711. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13712. /* No SSL port is set. No need to setup SSL. */
  13713. return 1;
  13714. }
  13715. /* Check for external SSL_CTX */
  13716. callback_ret =
  13717. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13718. ? 0
  13719. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13720. phys_ctx->user_data));
  13721. if (callback_ret < 0) {
  13722. mg_cry_internal(fc(phys_ctx),
  13723. "external_ssl_ctx callback returned error: %i",
  13724. callback_ret);
  13725. return 0;
  13726. } else if (callback_ret > 0) {
  13727. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13728. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13729. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13730. return 0;
  13731. }
  13732. return 1;
  13733. }
  13734. /* else: external_ssl_ctx does not exist or returns 0,
  13735. * CivetWeb should continue initializing SSL */
  13736. /* If PEM file is not specified and the init_ssl callback
  13737. * is not specified, setup will fail. */
  13738. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13739. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13740. /* No certificate and no callback:
  13741. * Essential data to set up TLS is missing.
  13742. */
  13743. mg_cry_internal(fc(phys_ctx),
  13744. "Initializing SSL failed: -%s is not set",
  13745. config_options[SSL_CERTIFICATE].name);
  13746. return 0;
  13747. }
  13748. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13749. if (chain == NULL) {
  13750. chain = pem;
  13751. }
  13752. if ((chain != NULL) && (*chain == 0)) {
  13753. chain = NULL;
  13754. }
  13755. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13756. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13757. return 0;
  13758. }
  13759. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13760. }
  13761. static void
  13762. uninitialize_ssl(void)
  13763. {
  13764. #if defined(OPENSSL_API_1_1)
  13765. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13766. /* Shutdown according to
  13767. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13768. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13769. */
  13770. CONF_modules_unload(1);
  13771. #else
  13772. int i;
  13773. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13774. /* Shutdown according to
  13775. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13776. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13777. */
  13778. CRYPTO_set_locking_callback(NULL);
  13779. CRYPTO_set_id_callback(NULL);
  13780. ENGINE_cleanup();
  13781. CONF_modules_unload(1);
  13782. ERR_free_strings();
  13783. EVP_cleanup();
  13784. CRYPTO_cleanup_all_ex_data();
  13785. OPENSSL_REMOVE_THREAD_STATE();
  13786. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13787. pthread_mutex_destroy(&ssl_mutexes[i]);
  13788. }
  13789. mg_free(ssl_mutexes);
  13790. ssl_mutexes = NULL;
  13791. #endif /* OPENSSL_API_1_1 */
  13792. }
  13793. }
  13794. #endif /* !NO_SSL */
  13795. static int
  13796. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13797. {
  13798. if (phys_ctx) {
  13799. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13800. const char *path;
  13801. if (!dom_ctx) {
  13802. dom_ctx = &(phys_ctx->dd);
  13803. }
  13804. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13805. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13806. mg_cry_internal(fc(phys_ctx),
  13807. "Cannot open %s: %s",
  13808. path,
  13809. strerror(ERRNO));
  13810. return 0;
  13811. }
  13812. return 1;
  13813. }
  13814. return 0;
  13815. }
  13816. static int
  13817. set_acl_option(struct mg_context *phys_ctx)
  13818. {
  13819. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13820. }
  13821. static void
  13822. reset_per_request_attributes(struct mg_connection *conn)
  13823. {
  13824. if (!conn) {
  13825. return;
  13826. }
  13827. conn->connection_type =
  13828. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13829. conn->num_bytes_sent = conn->consumed_content = 0;
  13830. conn->path_info = NULL;
  13831. conn->status_code = -1;
  13832. conn->content_len = -1;
  13833. conn->is_chunked = 0;
  13834. conn->must_close = 0;
  13835. conn->request_len = 0;
  13836. conn->throttle = 0;
  13837. conn->data_len = 0;
  13838. conn->chunk_remainder = 0;
  13839. conn->accept_gzip = 0;
  13840. conn->response_info.content_length = conn->request_info.content_length = -1;
  13841. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13842. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13843. conn->response_info.status_text = NULL;
  13844. conn->response_info.status_code = 0;
  13845. conn->request_info.remote_user = NULL;
  13846. conn->request_info.request_method = NULL;
  13847. conn->request_info.request_uri = NULL;
  13848. conn->request_info.local_uri = NULL;
  13849. #if defined(MG_LEGACY_INTERFACE)
  13850. /* Legacy before split into local_uri and request_uri */
  13851. conn->request_info.uri = NULL;
  13852. #endif
  13853. }
  13854. #if 0
  13855. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13856. * Leave this function here (commented out) for reference until
  13857. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13858. * no longer required.
  13859. */
  13860. static int
  13861. set_sock_timeout(SOCKET sock, int milliseconds)
  13862. {
  13863. int r0 = 0, r1, r2;
  13864. #if defined(_WIN32)
  13865. /* Windows specific */
  13866. DWORD tv = (DWORD)milliseconds;
  13867. #else
  13868. /* Linux, ... (not Windows) */
  13869. struct timeval tv;
  13870. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13871. * max. time waiting for the acknowledged of TCP data before the connection
  13872. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13873. * If this option is not set, the default timeout of 20-30 minutes is used.
  13874. */
  13875. /* #define TCP_USER_TIMEOUT (18) */
  13876. #if defined(TCP_USER_TIMEOUT)
  13877. unsigned int uto = (unsigned int)milliseconds;
  13878. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13879. #endif
  13880. memset(&tv, 0, sizeof(tv));
  13881. tv.tv_sec = milliseconds / 1000;
  13882. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13883. #endif /* _WIN32 */
  13884. r1 = setsockopt(
  13885. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13886. r2 = setsockopt(
  13887. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13888. return r0 || r1 || r2;
  13889. }
  13890. #endif
  13891. static int
  13892. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13893. {
  13894. if (setsockopt(sock,
  13895. IPPROTO_TCP,
  13896. TCP_NODELAY,
  13897. (SOCK_OPT_TYPE)&nodelay_on,
  13898. sizeof(nodelay_on))
  13899. != 0) {
  13900. /* Error */
  13901. return 1;
  13902. }
  13903. /* OK */
  13904. return 0;
  13905. }
  13906. static void
  13907. close_socket_gracefully(struct mg_connection *conn)
  13908. {
  13909. #if defined(_WIN32)
  13910. char buf[MG_BUF_LEN];
  13911. int n;
  13912. #endif
  13913. struct linger linger;
  13914. int error_code = 0;
  13915. int linger_timeout = -2;
  13916. socklen_t opt_len = sizeof(error_code);
  13917. if (!conn) {
  13918. return;
  13919. }
  13920. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13921. * "Note that enabling a nonzero timeout on a nonblocking socket
  13922. * is not recommended.", so set it to blocking now */
  13923. set_blocking_mode(conn->client.sock);
  13924. /* Send FIN to the client */
  13925. shutdown(conn->client.sock, SHUTDOWN_WR);
  13926. #if defined(_WIN32)
  13927. /* Read and discard pending incoming data. If we do not do that and
  13928. * close
  13929. * the socket, the data in the send buffer may be discarded. This
  13930. * behaviour is seen on Windows, when client keeps sending data
  13931. * when server decides to close the connection; then when client
  13932. * does recv() it gets no data back. */
  13933. do {
  13934. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13935. } while (n > 0);
  13936. #endif
  13937. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13938. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13939. }
  13940. /* Set linger option according to configuration */
  13941. if (linger_timeout >= 0) {
  13942. /* Set linger option to avoid socket hanging out after close. This
  13943. * prevent ephemeral port exhaust problem under high QPS. */
  13944. linger.l_onoff = 1;
  13945. #if defined(_MSC_VER)
  13946. #pragma warning(push)
  13947. #pragma warning(disable : 4244)
  13948. #endif
  13949. #if defined(GCC_DIAGNOSTIC)
  13950. #pragma GCC diagnostic push
  13951. #pragma GCC diagnostic ignored "-Wconversion"
  13952. #endif
  13953. /* Data type of linger structure elements may differ,
  13954. * so we don't know what cast we need here.
  13955. * Disable type conversion warnings. */
  13956. linger.l_linger = (linger_timeout + 999) / 1000;
  13957. #if defined(GCC_DIAGNOSTIC)
  13958. #pragma GCC diagnostic pop
  13959. #endif
  13960. #if defined(_MSC_VER)
  13961. #pragma warning(pop)
  13962. #endif
  13963. } else {
  13964. linger.l_onoff = 0;
  13965. linger.l_linger = 0;
  13966. }
  13967. if (linger_timeout < -1) {
  13968. /* Default: don't configure any linger */
  13969. } else if (getsockopt(conn->client.sock,
  13970. SOL_SOCKET,
  13971. SO_ERROR,
  13972. #if defined(_WIN32) /* WinSock uses different data type here */
  13973. (char *)&error_code,
  13974. #else
  13975. &error_code,
  13976. #endif
  13977. &opt_len)
  13978. != 0) {
  13979. /* Cannot determine if socket is already closed. This should
  13980. * not occur and never did in a test. Log an error message
  13981. * and continue. */
  13982. mg_cry_internal(conn,
  13983. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13984. __func__,
  13985. strerror(ERRNO));
  13986. } else if (error_code == ECONNRESET) {
  13987. /* Socket already closed by client/peer, close socket without linger
  13988. */
  13989. } else {
  13990. /* Set linger timeout */
  13991. if (setsockopt(conn->client.sock,
  13992. SOL_SOCKET,
  13993. SO_LINGER,
  13994. (char *)&linger,
  13995. sizeof(linger))
  13996. != 0) {
  13997. mg_cry_internal(
  13998. conn,
  13999. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14000. __func__,
  14001. linger.l_onoff,
  14002. linger.l_linger,
  14003. strerror(ERRNO));
  14004. }
  14005. }
  14006. /* Now we know that our FIN is ACK-ed, safe to close */
  14007. closesocket(conn->client.sock);
  14008. conn->client.sock = INVALID_SOCKET;
  14009. }
  14010. static void
  14011. close_connection(struct mg_connection *conn)
  14012. {
  14013. #if defined(USE_SERVER_STATS)
  14014. conn->conn_state = 6; /* to close */
  14015. #endif
  14016. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14017. if (conn->lua_websocket_state) {
  14018. lua_websocket_close(conn, conn->lua_websocket_state);
  14019. conn->lua_websocket_state = NULL;
  14020. }
  14021. #endif
  14022. mg_lock_connection(conn);
  14023. /* Set close flag, so keep-alive loops will stop */
  14024. conn->must_close = 1;
  14025. /* call the connection_close callback if assigned */
  14026. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14027. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14028. conn->phys_ctx->callbacks.connection_close(conn);
  14029. }
  14030. }
  14031. /* Reset user data, after close callback is called.
  14032. * Do not reuse it. If the user needs a destructor,
  14033. * it must be done in the connection_close callback. */
  14034. mg_set_user_connection_data(conn, NULL);
  14035. #if defined(USE_SERVER_STATS)
  14036. conn->conn_state = 7; /* closing */
  14037. #endif
  14038. #if !defined(NO_SSL)
  14039. if (conn->ssl != NULL) {
  14040. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14041. */
  14042. SSL_shutdown(conn->ssl);
  14043. SSL_free(conn->ssl);
  14044. OPENSSL_REMOVE_THREAD_STATE();
  14045. conn->ssl = NULL;
  14046. }
  14047. #endif
  14048. if (conn->client.sock != INVALID_SOCKET) {
  14049. close_socket_gracefully(conn);
  14050. conn->client.sock = INVALID_SOCKET;
  14051. }
  14052. if (conn->host) {
  14053. mg_free((void *)conn->host);
  14054. conn->host = NULL;
  14055. }
  14056. mg_unlock_connection(conn);
  14057. #if defined(USE_SERVER_STATS)
  14058. conn->conn_state = 8; /* closed */
  14059. #endif
  14060. }
  14061. void
  14062. mg_close_connection(struct mg_connection *conn)
  14063. {
  14064. #if defined(USE_WEBSOCKET)
  14065. struct mg_context *client_ctx = NULL;
  14066. #endif /* defined(USE_WEBSOCKET) */
  14067. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14068. return;
  14069. }
  14070. #if defined(USE_WEBSOCKET)
  14071. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14072. if (conn->in_websocket_handling) {
  14073. /* Set close flag, so the server thread can exit. */
  14074. conn->must_close = 1;
  14075. return;
  14076. }
  14077. }
  14078. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14079. unsigned int i;
  14080. /* ws/wss client */
  14081. client_ctx = conn->phys_ctx;
  14082. /* client context: loops must end */
  14083. client_ctx->stop_flag = 1;
  14084. conn->must_close = 1;
  14085. /* We need to get the client thread out of the select/recv call
  14086. * here. */
  14087. /* Since we use a sleep quantum of some seconds to check for recv
  14088. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14089. /* join worker thread */
  14090. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  14091. if (client_ctx->worker_threadids[i] != 0) {
  14092. mg_join_thread(client_ctx->worker_threadids[i]);
  14093. }
  14094. }
  14095. }
  14096. #endif /* defined(USE_WEBSOCKET) */
  14097. close_connection(conn);
  14098. #if !defined(NO_SSL)
  14099. if (conn->client_ssl_ctx != NULL) {
  14100. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  14101. }
  14102. #endif
  14103. #if defined(USE_WEBSOCKET)
  14104. if (client_ctx != NULL) {
  14105. /* free context */
  14106. mg_free(client_ctx->worker_threadids);
  14107. mg_free(client_ctx);
  14108. (void)pthread_mutex_destroy(&conn->mutex);
  14109. mg_free(conn);
  14110. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14111. mg_free(conn);
  14112. }
  14113. #else
  14114. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14115. mg_free(conn);
  14116. }
  14117. #endif /* defined(USE_WEBSOCKET) */
  14118. }
  14119. /* Only for memory statistics */
  14120. static struct mg_context common_client_context;
  14121. static struct mg_connection *
  14122. mg_connect_client_impl(const struct mg_client_options *client_options,
  14123. int use_ssl,
  14124. char *ebuf,
  14125. size_t ebuf_len)
  14126. {
  14127. struct mg_connection *conn = NULL;
  14128. SOCKET sock;
  14129. union usa sa;
  14130. struct sockaddr *psa;
  14131. socklen_t len;
  14132. unsigned max_req_size =
  14133. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14134. /* Size of structures, aligned to 8 bytes */
  14135. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14136. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14137. conn = (struct mg_connection *)mg_calloc_ctx(
  14138. 1, conn_size + ctx_size + max_req_size, &common_client_context);
  14139. if (conn == NULL) {
  14140. mg_snprintf(NULL,
  14141. NULL, /* No truncation check for ebuf */
  14142. ebuf,
  14143. ebuf_len,
  14144. "calloc(): %s",
  14145. strerror(ERRNO));
  14146. return NULL;
  14147. }
  14148. #if defined(GCC_DIAGNOSTIC)
  14149. #pragma GCC diagnostic push
  14150. #pragma GCC diagnostic ignored "-Wcast-align"
  14151. #endif /* defined(GCC_DIAGNOSTIC) */
  14152. /* conn_size is aligned to 8 bytes */
  14153. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14154. #if defined(GCC_DIAGNOSTIC)
  14155. #pragma GCC diagnostic pop
  14156. #endif /* defined(GCC_DIAGNOSTIC) */
  14157. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14158. conn->buf_size = (int)max_req_size;
  14159. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14160. conn->dom_ctx = &(conn->phys_ctx->dd);
  14161. if (!connect_socket(&common_client_context,
  14162. client_options->host,
  14163. client_options->port,
  14164. use_ssl,
  14165. ebuf,
  14166. ebuf_len,
  14167. &sock,
  14168. &sa)) {
  14169. /* ebuf is set by connect_socket,
  14170. * free all memory and return NULL; */
  14171. mg_free(conn);
  14172. return NULL;
  14173. }
  14174. #if !defined(NO_SSL)
  14175. #if defined(OPENSSL_API_1_1)
  14176. if (use_ssl
  14177. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14178. mg_snprintf(NULL,
  14179. NULL, /* No truncation check for ebuf */
  14180. ebuf,
  14181. ebuf_len,
  14182. "SSL_CTX_new error");
  14183. closesocket(sock);
  14184. mg_free(conn);
  14185. return NULL;
  14186. }
  14187. #else
  14188. if (use_ssl
  14189. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14190. == NULL) {
  14191. mg_snprintf(NULL,
  14192. NULL, /* No truncation check for ebuf */
  14193. ebuf,
  14194. ebuf_len,
  14195. "SSL_CTX_new error");
  14196. closesocket(sock);
  14197. mg_free(conn);
  14198. return NULL;
  14199. }
  14200. #endif /* OPENSSL_API_1_1 */
  14201. #endif /* NO_SSL */
  14202. #if defined(USE_IPV6)
  14203. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14204. : sizeof(conn->client.rsa.sin6);
  14205. psa = (sa.sa.sa_family == AF_INET)
  14206. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14207. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14208. #else
  14209. len = sizeof(conn->client.rsa.sin);
  14210. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14211. #endif
  14212. conn->client.sock = sock;
  14213. conn->client.lsa = sa;
  14214. if (getsockname(sock, psa, &len) != 0) {
  14215. mg_cry_internal(conn,
  14216. "%s: getsockname() failed: %s",
  14217. __func__,
  14218. strerror(ERRNO));
  14219. }
  14220. conn->client.is_ssl = use_ssl ? 1 : 0;
  14221. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14222. mg_snprintf(NULL,
  14223. NULL, /* No truncation check for ebuf */
  14224. ebuf,
  14225. ebuf_len,
  14226. "Can not create mutex");
  14227. #if !defined(NO_SSL)
  14228. SSL_CTX_free(conn->client_ssl_ctx);
  14229. #endif
  14230. closesocket(sock);
  14231. mg_free(conn);
  14232. return NULL;
  14233. }
  14234. #if !defined(NO_SSL)
  14235. if (use_ssl) {
  14236. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14237. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14238. * SSL_CTX_set_verify call is needed to switch off server
  14239. * certificate checking, which is off by default in OpenSSL and
  14240. * on in yaSSL. */
  14241. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14242. * SSL_VERIFY_PEER, verify_ssl_server); */
  14243. if (client_options->client_cert) {
  14244. if (!ssl_use_pem_file(&common_client_context,
  14245. &(common_client_context.dd),
  14246. client_options->client_cert,
  14247. NULL)) {
  14248. mg_snprintf(NULL,
  14249. NULL, /* No truncation check for ebuf */
  14250. ebuf,
  14251. ebuf_len,
  14252. "Can not use SSL client certificate");
  14253. SSL_CTX_free(conn->client_ssl_ctx);
  14254. closesocket(sock);
  14255. mg_free(conn);
  14256. return NULL;
  14257. }
  14258. }
  14259. if (client_options->server_cert) {
  14260. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14261. client_options->server_cert,
  14262. NULL);
  14263. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14264. } else {
  14265. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14266. }
  14267. if (!sslize(conn,
  14268. conn->client_ssl_ctx,
  14269. SSL_connect,
  14270. &(conn->phys_ctx->stop_flag),
  14271. client_options)) {
  14272. mg_snprintf(NULL,
  14273. NULL, /* No truncation check for ebuf */
  14274. ebuf,
  14275. ebuf_len,
  14276. "SSL connection error");
  14277. SSL_CTX_free(conn->client_ssl_ctx);
  14278. closesocket(sock);
  14279. mg_free(conn);
  14280. return NULL;
  14281. }
  14282. }
  14283. #endif
  14284. if (0 != set_non_blocking_mode(sock)) {
  14285. mg_cry_internal(conn,
  14286. "Cannot set non-blocking mode for client %s:%i",
  14287. client_options->host,
  14288. client_options->port);
  14289. }
  14290. return conn;
  14291. }
  14292. CIVETWEB_API struct mg_connection *
  14293. mg_connect_client_secure(const struct mg_client_options *client_options,
  14294. char *error_buffer,
  14295. size_t error_buffer_size)
  14296. {
  14297. return mg_connect_client_impl(client_options,
  14298. 1,
  14299. error_buffer,
  14300. error_buffer_size);
  14301. }
  14302. struct mg_connection *
  14303. mg_connect_client(const char *host,
  14304. int port,
  14305. int use_ssl,
  14306. char *error_buffer,
  14307. size_t error_buffer_size)
  14308. {
  14309. struct mg_client_options opts;
  14310. memset(&opts, 0, sizeof(opts));
  14311. opts.host = host;
  14312. opts.port = port;
  14313. return mg_connect_client_impl(&opts,
  14314. use_ssl,
  14315. error_buffer,
  14316. error_buffer_size);
  14317. }
  14318. static const struct {
  14319. const char *proto;
  14320. size_t proto_len;
  14321. unsigned default_port;
  14322. } abs_uri_protocols[] = {{"http://", 7, 80},
  14323. {"https://", 8, 443},
  14324. {"ws://", 5, 80},
  14325. {"wss://", 6, 443},
  14326. {NULL, 0, 0}};
  14327. /* Check if the uri is valid.
  14328. * return 0 for invalid uri,
  14329. * return 1 for *,
  14330. * return 2 for relative uri,
  14331. * return 3 for absolute uri without port,
  14332. * return 4 for absolute uri with port */
  14333. static int
  14334. get_uri_type(const char *uri)
  14335. {
  14336. int i;
  14337. const char *hostend, *portbegin;
  14338. char *portend;
  14339. unsigned long port;
  14340. /* According to the HTTP standard
  14341. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14342. * URI can be an asterisk (*) or should start with slash (relative uri),
  14343. * or it should start with the protocol (absolute uri). */
  14344. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14345. /* asterisk */
  14346. return 1;
  14347. }
  14348. /* Valid URIs according to RFC 3986
  14349. * (https://www.ietf.org/rfc/rfc3986.txt)
  14350. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14351. * and unreserved characters A-Z a-z 0-9 and -._~
  14352. * and % encoded symbols.
  14353. */
  14354. for (i = 0; uri[i] != 0; i++) {
  14355. if (uri[i] < 33) {
  14356. /* control characters and spaces are invalid */
  14357. return 0;
  14358. }
  14359. if (uri[i] > 126) {
  14360. /* non-ascii characters must be % encoded */
  14361. return 0;
  14362. } else {
  14363. switch (uri[i]) {
  14364. case '"': /* 34 */
  14365. case '<': /* 60 */
  14366. case '>': /* 62 */
  14367. case '\\': /* 92 */
  14368. case '^': /* 94 */
  14369. case '`': /* 96 */
  14370. case '{': /* 123 */
  14371. case '|': /* 124 */
  14372. case '}': /* 125 */
  14373. return 0;
  14374. default:
  14375. /* character is ok */
  14376. break;
  14377. }
  14378. }
  14379. }
  14380. /* A relative uri starts with a / character */
  14381. if (uri[0] == '/') {
  14382. /* relative uri */
  14383. return 2;
  14384. }
  14385. /* It could be an absolute uri: */
  14386. /* This function only checks if the uri is valid, not if it is
  14387. * addressing the current server. So civetweb can also be used
  14388. * as a proxy server. */
  14389. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14390. if (mg_strncasecmp(uri,
  14391. abs_uri_protocols[i].proto,
  14392. abs_uri_protocols[i].proto_len)
  14393. == 0) {
  14394. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14395. if (!hostend) {
  14396. return 0;
  14397. }
  14398. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14399. if (!portbegin) {
  14400. return 3;
  14401. }
  14402. port = strtoul(portbegin + 1, &portend, 10);
  14403. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14404. return 0;
  14405. }
  14406. return 4;
  14407. }
  14408. }
  14409. return 0;
  14410. }
  14411. /* Return NULL or the relative uri at the current server */
  14412. static const char *
  14413. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14414. {
  14415. const char *server_domain;
  14416. size_t server_domain_len;
  14417. size_t request_domain_len = 0;
  14418. unsigned long port = 0;
  14419. int i, auth_domain_check_enabled;
  14420. const char *hostbegin = NULL;
  14421. const char *hostend = NULL;
  14422. const char *portbegin;
  14423. char *portend;
  14424. auth_domain_check_enabled =
  14425. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14426. /* DNS is case insensitive, so use case insensitive string compare here
  14427. */
  14428. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14429. if (mg_strncasecmp(uri,
  14430. abs_uri_protocols[i].proto,
  14431. abs_uri_protocols[i].proto_len)
  14432. == 0) {
  14433. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14434. hostend = strchr(hostbegin, '/');
  14435. if (!hostend) {
  14436. return 0;
  14437. }
  14438. portbegin = strchr(hostbegin, ':');
  14439. if ((!portbegin) || (portbegin > hostend)) {
  14440. port = abs_uri_protocols[i].default_port;
  14441. request_domain_len = (size_t)(hostend - hostbegin);
  14442. } else {
  14443. port = strtoul(portbegin + 1, &portend, 10);
  14444. if ((portend != hostend) || (port <= 0)
  14445. || !is_valid_port(port)) {
  14446. return 0;
  14447. }
  14448. request_domain_len = (size_t)(portbegin - hostbegin);
  14449. }
  14450. /* protocol found, port set */
  14451. break;
  14452. }
  14453. }
  14454. if (!port) {
  14455. /* port remains 0 if the protocol is not found */
  14456. return 0;
  14457. }
  14458. /* Check if the request is directed to a different server. */
  14459. /* First check if the port is the same (IPv4 and IPv6). */
  14460. #if defined(USE_IPV6)
  14461. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14462. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14463. /* Request is directed to a different port */
  14464. return 0;
  14465. }
  14466. } else
  14467. #endif
  14468. {
  14469. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14470. /* Request is directed to a different port */
  14471. return 0;
  14472. }
  14473. }
  14474. /* Finally check if the server corresponds to the authentication
  14475. * domain of the server (the server domain).
  14476. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14477. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14478. * but do not allow substrings (like
  14479. * http://notmydomain.com/path/file.ext
  14480. * or http://mydomain.com.fake/path/file.ext).
  14481. */
  14482. if (auth_domain_check_enabled) {
  14483. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14484. server_domain_len = strlen(server_domain);
  14485. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14486. return 0;
  14487. }
  14488. if ((request_domain_len == server_domain_len)
  14489. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14490. /* Request is directed to this server - full name match. */
  14491. } else {
  14492. if (request_domain_len < (server_domain_len + 2)) {
  14493. /* Request is directed to another server: The server name
  14494. * is longer than the request name.
  14495. * Drop this case here to avoid overflows in the
  14496. * following checks. */
  14497. return 0;
  14498. }
  14499. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14500. /* Request is directed to another server: It could be a
  14501. * substring
  14502. * like notmyserver.com */
  14503. return 0;
  14504. }
  14505. if (0
  14506. != memcmp(server_domain,
  14507. hostbegin + request_domain_len - server_domain_len,
  14508. server_domain_len)) {
  14509. /* Request is directed to another server:
  14510. * The server name is different. */
  14511. return 0;
  14512. }
  14513. }
  14514. }
  14515. return hostend;
  14516. }
  14517. static int
  14518. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14519. {
  14520. if (ebuf_len > 0) {
  14521. ebuf[0] = '\0';
  14522. }
  14523. *err = 0;
  14524. reset_per_request_attributes(conn);
  14525. if (!conn) {
  14526. mg_snprintf(conn,
  14527. NULL, /* No truncation check for ebuf */
  14528. ebuf,
  14529. ebuf_len,
  14530. "%s",
  14531. "Internal error");
  14532. *err = 500;
  14533. return 0;
  14534. }
  14535. /* Set the time the request was received. This value should be used for
  14536. * timeouts. */
  14537. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14538. conn->request_len =
  14539. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14540. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14541. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14542. mg_snprintf(conn,
  14543. NULL, /* No truncation check for ebuf */
  14544. ebuf,
  14545. ebuf_len,
  14546. "%s",
  14547. "Invalid message size");
  14548. *err = 500;
  14549. return 0;
  14550. }
  14551. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14552. mg_snprintf(conn,
  14553. NULL, /* No truncation check for ebuf */
  14554. ebuf,
  14555. ebuf_len,
  14556. "%s",
  14557. "Message too large");
  14558. *err = 413;
  14559. return 0;
  14560. }
  14561. if (conn->request_len <= 0) {
  14562. if (conn->data_len > 0) {
  14563. mg_snprintf(conn,
  14564. NULL, /* No truncation check for ebuf */
  14565. ebuf,
  14566. ebuf_len,
  14567. "%s",
  14568. "Malformed message");
  14569. *err = 400;
  14570. } else {
  14571. /* Server did not recv anything -> just close the connection */
  14572. conn->must_close = 1;
  14573. mg_snprintf(conn,
  14574. NULL, /* No truncation check for ebuf */
  14575. ebuf,
  14576. ebuf_len,
  14577. "%s",
  14578. "No data received");
  14579. *err = 0;
  14580. }
  14581. return 0;
  14582. }
  14583. return 1;
  14584. }
  14585. static int
  14586. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14587. {
  14588. const char *cl;
  14589. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14590. return 0;
  14591. }
  14592. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14593. <= 0) {
  14594. mg_snprintf(conn,
  14595. NULL, /* No truncation check for ebuf */
  14596. ebuf,
  14597. ebuf_len,
  14598. "%s",
  14599. "Bad request");
  14600. *err = 400;
  14601. return 0;
  14602. }
  14603. /* Message is a valid request */
  14604. /* Is there a "host" ? */
  14605. if (conn->host != NULL) {
  14606. mg_free((void *)conn->host);
  14607. }
  14608. conn->host = alloc_get_host(conn);
  14609. if (!conn->host) {
  14610. mg_snprintf(conn,
  14611. NULL, /* No truncation check for ebuf */
  14612. ebuf,
  14613. ebuf_len,
  14614. "%s",
  14615. "Bad request: Host mismatch");
  14616. *err = 400;
  14617. return 0;
  14618. }
  14619. /* Do we know the content length? */
  14620. if ((cl = get_header(conn->request_info.http_headers,
  14621. conn->request_info.num_headers,
  14622. "Content-Length"))
  14623. != NULL) {
  14624. /* Request/response has content length set */
  14625. char *endptr = NULL;
  14626. conn->content_len = strtoll(cl, &endptr, 10);
  14627. if (endptr == cl) {
  14628. mg_snprintf(conn,
  14629. NULL, /* No truncation check for ebuf */
  14630. ebuf,
  14631. ebuf_len,
  14632. "%s",
  14633. "Bad request");
  14634. *err = 411;
  14635. return 0;
  14636. }
  14637. /* Publish the content length back to the request info. */
  14638. conn->request_info.content_length = conn->content_len;
  14639. } else if ((cl = get_header(conn->request_info.http_headers,
  14640. conn->request_info.num_headers,
  14641. "Transfer-Encoding"))
  14642. != NULL
  14643. && !mg_strcasecmp(cl, "chunked")) {
  14644. conn->is_chunked = 1;
  14645. conn->content_len = -1; /* unknown content length */
  14646. } else {
  14647. const struct mg_http_method_info *meth =
  14648. get_http_method_info(conn->request_info.request_method);
  14649. if (!meth) {
  14650. /* No valid HTTP method */
  14651. mg_snprintf(conn,
  14652. NULL, /* No truncation check for ebuf */
  14653. ebuf,
  14654. ebuf_len,
  14655. "%s",
  14656. "Bad request");
  14657. *err = 411;
  14658. return 0;
  14659. }
  14660. if (meth->request_has_body) {
  14661. /* POST or PUT request without content length set */
  14662. conn->content_len = -1; /* unknown content length */
  14663. } else {
  14664. /* Other request */
  14665. conn->content_len = 0; /* No content */
  14666. }
  14667. }
  14668. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14669. return 1;
  14670. }
  14671. /* conn is assumed to be valid in this internal function */
  14672. static int
  14673. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14674. {
  14675. const char *cl;
  14676. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14677. return 0;
  14678. }
  14679. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14680. <= 0) {
  14681. mg_snprintf(conn,
  14682. NULL, /* No truncation check for ebuf */
  14683. ebuf,
  14684. ebuf_len,
  14685. "%s",
  14686. "Bad response");
  14687. *err = 400;
  14688. return 0;
  14689. }
  14690. /* Message is a valid response */
  14691. /* Do we know the content length? */
  14692. if ((cl = get_header(conn->response_info.http_headers,
  14693. conn->response_info.num_headers,
  14694. "Content-Length"))
  14695. != NULL) {
  14696. /* Request/response has content length set */
  14697. char *endptr = NULL;
  14698. conn->content_len = strtoll(cl, &endptr, 10);
  14699. if (endptr == cl) {
  14700. mg_snprintf(conn,
  14701. NULL, /* No truncation check for ebuf */
  14702. ebuf,
  14703. ebuf_len,
  14704. "%s",
  14705. "Bad request");
  14706. *err = 411;
  14707. return 0;
  14708. }
  14709. /* Publish the content length back to the response info. */
  14710. conn->response_info.content_length = conn->content_len;
  14711. /* TODO: check if it is still used in response_info */
  14712. conn->request_info.content_length = conn->content_len;
  14713. } else if ((cl = get_header(conn->response_info.http_headers,
  14714. conn->response_info.num_headers,
  14715. "Transfer-Encoding"))
  14716. != NULL
  14717. && !mg_strcasecmp(cl, "chunked")) {
  14718. conn->is_chunked = 1;
  14719. conn->content_len = -1; /* unknown content length */
  14720. } else {
  14721. conn->content_len = -1; /* unknown content length */
  14722. }
  14723. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14724. return 1;
  14725. }
  14726. int
  14727. mg_get_response(struct mg_connection *conn,
  14728. char *ebuf,
  14729. size_t ebuf_len,
  14730. int timeout)
  14731. {
  14732. int err, ret;
  14733. char txt[32]; /* will not overflow */
  14734. char *save_timeout;
  14735. char *new_timeout;
  14736. if (ebuf_len > 0) {
  14737. ebuf[0] = '\0';
  14738. }
  14739. if (!conn) {
  14740. mg_snprintf(conn,
  14741. NULL, /* No truncation check for ebuf */
  14742. ebuf,
  14743. ebuf_len,
  14744. "%s",
  14745. "Parameter error");
  14746. return -1;
  14747. }
  14748. /* Implementation of API function for HTTP clients */
  14749. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14750. if (timeout >= 0) {
  14751. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14752. new_timeout = txt;
  14753. /* Not required for non-blocking sockets.
  14754. set_sock_timeout(conn->client.sock, timeout);
  14755. */
  14756. } else {
  14757. new_timeout = NULL;
  14758. }
  14759. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14760. ret = get_response(conn, ebuf, ebuf_len, &err);
  14761. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14762. #if defined(MG_LEGACY_INTERFACE)
  14763. /* TODO: 1) uri is deprecated;
  14764. * 2) here, ri.uri is the http response code */
  14765. conn->request_info.uri = conn->request_info.request_uri;
  14766. #endif
  14767. conn->request_info.local_uri = conn->request_info.request_uri;
  14768. /* TODO (mid): Define proper return values - maybe return length?
  14769. * For the first test use <0 for error and >0 for OK */
  14770. return (ret == 0) ? -1 : +1;
  14771. }
  14772. struct mg_connection *
  14773. mg_download(const char *host,
  14774. int port,
  14775. int use_ssl,
  14776. char *ebuf,
  14777. size_t ebuf_len,
  14778. const char *fmt,
  14779. ...)
  14780. {
  14781. struct mg_connection *conn;
  14782. va_list ap;
  14783. int i;
  14784. int reqerr;
  14785. if (ebuf_len > 0) {
  14786. ebuf[0] = '\0';
  14787. }
  14788. va_start(ap, fmt);
  14789. /* open a connection */
  14790. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14791. if (conn != NULL) {
  14792. i = mg_vprintf(conn, fmt, ap);
  14793. if (i <= 0) {
  14794. mg_snprintf(conn,
  14795. NULL, /* No truncation check for ebuf */
  14796. ebuf,
  14797. ebuf_len,
  14798. "%s",
  14799. "Error sending request");
  14800. } else {
  14801. get_response(conn, ebuf, ebuf_len, &reqerr);
  14802. #if defined(MG_LEGACY_INTERFACE)
  14803. /* TODO: 1) uri is deprecated;
  14804. * 2) here, ri.uri is the http response code */
  14805. conn->request_info.uri = conn->request_info.request_uri;
  14806. #endif
  14807. conn->request_info.local_uri = conn->request_info.request_uri;
  14808. }
  14809. }
  14810. /* if an error occurred, close the connection */
  14811. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14812. mg_close_connection(conn);
  14813. conn = NULL;
  14814. }
  14815. va_end(ap);
  14816. return conn;
  14817. }
  14818. struct websocket_client_thread_data {
  14819. struct mg_connection *conn;
  14820. mg_websocket_data_handler data_handler;
  14821. mg_websocket_close_handler close_handler;
  14822. void *callback_data;
  14823. };
  14824. #if defined(USE_WEBSOCKET)
  14825. #if defined(_WIN32)
  14826. static unsigned __stdcall websocket_client_thread(void *data)
  14827. #else
  14828. static void *
  14829. websocket_client_thread(void *data)
  14830. #endif
  14831. {
  14832. struct websocket_client_thread_data *cdata =
  14833. (struct websocket_client_thread_data *)data;
  14834. #if !defined(_WIN32)
  14835. struct sigaction sa;
  14836. /* Ignore SIGPIPE */
  14837. memset(&sa, 0, sizeof(sa));
  14838. sa.sa_handler = SIG_IGN;
  14839. sigaction(SIGPIPE, &sa, NULL);
  14840. #endif
  14841. mg_set_thread_name("ws-clnt");
  14842. if (cdata->conn->phys_ctx) {
  14843. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14844. /* 3 indicates a websocket client thread */
  14845. /* TODO: check if conn->phys_ctx can be set */
  14846. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14847. 3);
  14848. }
  14849. }
  14850. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14851. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14852. if (cdata->close_handler != NULL) {
  14853. cdata->close_handler(cdata->conn, cdata->callback_data);
  14854. }
  14855. /* The websocket_client context has only this thread. If it runs out,
  14856. set the stop_flag to 2 (= "stopped"). */
  14857. cdata->conn->phys_ctx->stop_flag = 2;
  14858. mg_free((void *)cdata);
  14859. #if defined(_WIN32)
  14860. return 0;
  14861. #else
  14862. return NULL;
  14863. #endif
  14864. }
  14865. #endif
  14866. struct mg_connection *
  14867. mg_connect_websocket_client(const char *host,
  14868. int port,
  14869. int use_ssl,
  14870. char *error_buffer,
  14871. size_t error_buffer_size,
  14872. const char *path,
  14873. const char *origin,
  14874. mg_websocket_data_handler data_func,
  14875. mg_websocket_close_handler close_func,
  14876. void *user_data)
  14877. {
  14878. struct mg_connection *conn = NULL;
  14879. #if defined(USE_WEBSOCKET)
  14880. struct mg_context *newctx = NULL;
  14881. struct websocket_client_thread_data *thread_data;
  14882. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14883. static const char *handshake_req;
  14884. if (origin != NULL) {
  14885. handshake_req = "GET %s HTTP/1.1\r\n"
  14886. "Host: %s\r\n"
  14887. "Upgrade: websocket\r\n"
  14888. "Connection: Upgrade\r\n"
  14889. "Sec-WebSocket-Key: %s\r\n"
  14890. "Sec-WebSocket-Version: 13\r\n"
  14891. "Origin: %s\r\n"
  14892. "\r\n";
  14893. } else {
  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. "\r\n";
  14901. }
  14902. #if defined(__clang__)
  14903. #pragma clang diagnostic push
  14904. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14905. #endif
  14906. /* Establish the client connection and request upgrade */
  14907. conn = mg_download(host,
  14908. port,
  14909. use_ssl,
  14910. error_buffer,
  14911. error_buffer_size,
  14912. handshake_req,
  14913. path,
  14914. host,
  14915. magic,
  14916. origin);
  14917. #if defined(__clang__)
  14918. #pragma clang diagnostic pop
  14919. #endif
  14920. /* Connection object will be null if something goes wrong */
  14921. if (conn == NULL) {
  14922. if (!*error_buffer) {
  14923. /* There should be already an error message */
  14924. mg_snprintf(conn,
  14925. NULL, /* No truncation check for ebuf */
  14926. error_buffer,
  14927. error_buffer_size,
  14928. "Unexpected error");
  14929. }
  14930. return NULL;
  14931. }
  14932. if (conn->response_info.status_code != 101) {
  14933. /* We sent an "upgrade" request. For a correct websocket
  14934. * protocol handshake, we expect a "101 Continue" response.
  14935. * Otherwise it is a protocol violation. Maybe the HTTP
  14936. * Server does not know websockets. */
  14937. if (!*error_buffer) {
  14938. /* set an error, if not yet set */
  14939. mg_snprintf(conn,
  14940. NULL, /* No truncation check for ebuf */
  14941. error_buffer,
  14942. error_buffer_size,
  14943. "Unexpected server reply");
  14944. }
  14945. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14946. mg_free(conn);
  14947. return NULL;
  14948. }
  14949. /* For client connections, mg_context is fake. Since we need to set a
  14950. * callback function, we need to create a copy and modify it. */
  14951. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14952. if (!newctx) {
  14953. DEBUG_TRACE("%s\r\n", "Out of memory");
  14954. mg_free(conn);
  14955. return NULL;
  14956. }
  14957. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14958. newctx->user_data = user_data;
  14959. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14960. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14961. newctx->worker_threadids =
  14962. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14963. sizeof(pthread_t),
  14964. newctx);
  14965. conn->phys_ctx = newctx;
  14966. conn->dom_ctx = &(newctx->dd);
  14967. thread_data = (struct websocket_client_thread_data *)
  14968. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14969. if (!thread_data) {
  14970. DEBUG_TRACE("%s\r\n", "Out of memory");
  14971. mg_free(newctx);
  14972. mg_free(conn);
  14973. return NULL;
  14974. }
  14975. thread_data->conn = conn;
  14976. thread_data->data_handler = data_func;
  14977. thread_data->close_handler = close_func;
  14978. thread_data->callback_data = user_data;
  14979. /* Start a thread to read the websocket client connection
  14980. * This thread will automatically stop when mg_disconnect is
  14981. * called on the client connection */
  14982. if (mg_start_thread_with_id(websocket_client_thread,
  14983. (void *)thread_data,
  14984. newctx->worker_threadids)
  14985. != 0) {
  14986. mg_free((void *)thread_data);
  14987. mg_free((void *)newctx->worker_threadids);
  14988. mg_free((void *)newctx);
  14989. mg_free((void *)conn);
  14990. conn = NULL;
  14991. DEBUG_TRACE("%s",
  14992. "Websocket client connect thread could not be started\r\n");
  14993. }
  14994. #else
  14995. /* Appease "unused parameter" warnings */
  14996. (void)host;
  14997. (void)port;
  14998. (void)use_ssl;
  14999. (void)error_buffer;
  15000. (void)error_buffer_size;
  15001. (void)path;
  15002. (void)origin;
  15003. (void)user_data;
  15004. (void)data_func;
  15005. (void)close_func;
  15006. #endif
  15007. return conn;
  15008. }
  15009. /* Prepare connection data structure */
  15010. static void
  15011. init_connection(struct mg_connection *conn)
  15012. {
  15013. /* Is keep alive allowed by the server */
  15014. int keep_alive_enabled =
  15015. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15016. if (!keep_alive_enabled) {
  15017. conn->must_close = 1;
  15018. }
  15019. /* Important: on new connection, reset the receiving buffer. Credit
  15020. * goes to crule42. */
  15021. conn->data_len = 0;
  15022. conn->handled_requests = 0;
  15023. mg_set_user_connection_data(conn, NULL);
  15024. #if defined(USE_SERVER_STATS)
  15025. conn->conn_state = 2; /* init */
  15026. #endif
  15027. /* call the init_connection callback if assigned */
  15028. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15029. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15030. void *conn_data = NULL;
  15031. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15032. mg_set_user_connection_data(conn, conn_data);
  15033. }
  15034. }
  15035. }
  15036. /* Process a connection - may handle multiple requests
  15037. * using the same connection.
  15038. * Must be called with a valid connection (conn and
  15039. * conn->phys_ctx must be valid).
  15040. */
  15041. static void
  15042. process_new_connection(struct mg_connection *conn)
  15043. {
  15044. struct mg_request_info *ri = &conn->request_info;
  15045. int keep_alive, discard_len;
  15046. char ebuf[100];
  15047. const char *hostend;
  15048. int reqerr, uri_type;
  15049. #if defined(USE_SERVER_STATS)
  15050. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15051. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15052. if (mcon > (conn->phys_ctx->max_connections)) {
  15053. /* could use atomic compare exchange, but this
  15054. * seems overkill for statistics data */
  15055. conn->phys_ctx->max_connections = mcon;
  15056. }
  15057. #endif
  15058. init_connection(conn);
  15059. DEBUG_TRACE("Start processing connection from %s",
  15060. conn->request_info.remote_addr);
  15061. /* Loop over multiple requests sent using the same connection
  15062. * (while "keep alive"). */
  15063. do {
  15064. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15065. conn->handled_requests + 1);
  15066. #if defined(USE_SERVER_STATS)
  15067. conn->conn_state = 3; /* ready */
  15068. #endif
  15069. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15070. /* The request sent by the client could not be understood by
  15071. * the server, or it was incomplete or a timeout. Send an
  15072. * error message and close the connection. */
  15073. if (reqerr > 0) {
  15074. DEBUG_ASSERT(ebuf[0] != '\0');
  15075. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15076. }
  15077. } else if (strcmp(ri->http_version, "1.0")
  15078. && strcmp(ri->http_version, "1.1")) {
  15079. mg_snprintf(conn,
  15080. NULL, /* No truncation check for ebuf */
  15081. ebuf,
  15082. sizeof(ebuf),
  15083. "Bad HTTP version: [%s]",
  15084. ri->http_version);
  15085. mg_send_http_error(conn, 505, "%s", ebuf);
  15086. }
  15087. if (ebuf[0] == '\0') {
  15088. uri_type = get_uri_type(conn->request_info.request_uri);
  15089. switch (uri_type) {
  15090. case 1:
  15091. /* Asterisk */
  15092. conn->request_info.local_uri = NULL;
  15093. break;
  15094. case 2:
  15095. /* relative uri */
  15096. conn->request_info.local_uri = conn->request_info.request_uri;
  15097. break;
  15098. case 3:
  15099. case 4:
  15100. /* absolute uri (with/without port) */
  15101. hostend = get_rel_url_at_current_server(
  15102. conn->request_info.request_uri, conn);
  15103. if (hostend) {
  15104. conn->request_info.local_uri = hostend;
  15105. } else {
  15106. conn->request_info.local_uri = NULL;
  15107. }
  15108. break;
  15109. default:
  15110. mg_snprintf(conn,
  15111. NULL, /* No truncation check for ebuf */
  15112. ebuf,
  15113. sizeof(ebuf),
  15114. "Invalid URI");
  15115. mg_send_http_error(conn, 400, "%s", ebuf);
  15116. conn->request_info.local_uri = NULL;
  15117. break;
  15118. }
  15119. #if defined(MG_LEGACY_INTERFACE)
  15120. /* Legacy before split into local_uri and request_uri */
  15121. conn->request_info.uri = conn->request_info.local_uri;
  15122. #endif
  15123. }
  15124. DEBUG_TRACE("http: %s, error: %s",
  15125. (ri->http_version ? ri->http_version : "none"),
  15126. (ebuf[0] ? ebuf : "none"));
  15127. if (ebuf[0] == '\0') {
  15128. if (conn->request_info.local_uri) {
  15129. /* handle request to local server */
  15130. #if defined(USE_SERVER_STATS)
  15131. conn->conn_state = 4; /* processing */
  15132. #endif
  15133. handle_request(conn);
  15134. #if defined(USE_SERVER_STATS)
  15135. conn->conn_state = 5; /* processed */
  15136. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15137. conn->consumed_content);
  15138. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15139. conn->num_bytes_sent);
  15140. #endif
  15141. DEBUG_TRACE("%s", "handle_request done");
  15142. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15143. conn->phys_ctx->callbacks.end_request(conn,
  15144. conn->status_code);
  15145. DEBUG_TRACE("%s", "end_request callback done");
  15146. }
  15147. log_access(conn);
  15148. } else {
  15149. /* TODO: handle non-local request (PROXY) */
  15150. conn->must_close = 1;
  15151. }
  15152. } else {
  15153. conn->must_close = 1;
  15154. }
  15155. if (ri->remote_user != NULL) {
  15156. mg_free((void *)ri->remote_user);
  15157. /* Important! When having connections with and without auth
  15158. * would cause double free and then crash */
  15159. ri->remote_user = NULL;
  15160. }
  15161. /* NOTE(lsm): order is important here. should_keep_alive() call
  15162. * is using parsed request, which will be invalid after
  15163. * memmove's below.
  15164. * Therefore, memorize should_keep_alive() result now for later
  15165. * use in loop exit condition. */
  15166. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15167. && (conn->content_len >= 0);
  15168. /* Discard all buffered data for this request */
  15169. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15170. && ((conn->request_len + conn->content_len)
  15171. < (int64_t)conn->data_len))
  15172. ? (int)(conn->request_len + conn->content_len)
  15173. : conn->data_len;
  15174. DEBUG_ASSERT(discard_len >= 0);
  15175. if (discard_len < 0) {
  15176. DEBUG_TRACE("internal error: discard_len = %li",
  15177. (long int)discard_len);
  15178. break;
  15179. }
  15180. conn->data_len -= discard_len;
  15181. if (conn->data_len > 0) {
  15182. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15183. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15184. }
  15185. DEBUG_ASSERT(conn->data_len >= 0);
  15186. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15187. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15188. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15189. (long int)conn->data_len,
  15190. (long int)conn->buf_size);
  15191. break;
  15192. }
  15193. conn->handled_requests++;
  15194. } while (keep_alive);
  15195. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15196. conn->request_info.remote_addr,
  15197. difftime(time(NULL), conn->conn_birth_time));
  15198. close_connection(conn);
  15199. #if defined(USE_SERVER_STATS)
  15200. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15201. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15202. #endif
  15203. }
  15204. #if defined(ALTERNATIVE_QUEUE)
  15205. static void
  15206. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15207. {
  15208. unsigned int i;
  15209. while (!ctx->stop_flag) {
  15210. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15211. /* find a free worker slot and signal it */
  15212. if (ctx->client_socks[i].in_use == 2) {
  15213. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15214. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15215. ctx->client_socks[i] = *sp;
  15216. ctx->client_socks[i].in_use = 1;
  15217. /* socket has been moved to the consumer */
  15218. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15219. (void)event_signal(ctx->client_wait_events[i]);
  15220. return;
  15221. }
  15222. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15223. }
  15224. }
  15225. /* queue is full */
  15226. mg_sleep(1);
  15227. }
  15228. /* must consume */
  15229. set_blocking_mode(sp->sock);
  15230. closesocket(sp->sock);
  15231. }
  15232. static int
  15233. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15234. {
  15235. DEBUG_TRACE("%s", "going idle");
  15236. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15237. ctx->client_socks[thread_index].in_use = 2;
  15238. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15239. event_wait(ctx->client_wait_events[thread_index]);
  15240. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15241. *sp = ctx->client_socks[thread_index];
  15242. if (ctx->stop_flag) {
  15243. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15244. if (sp->in_use == 1) {
  15245. /* must consume */
  15246. set_blocking_mode(sp->sock);
  15247. closesocket(sp->sock);
  15248. }
  15249. return 0;
  15250. }
  15251. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15252. if (sp->in_use == 1) {
  15253. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15254. return 1;
  15255. }
  15256. /* must not reach here */
  15257. DEBUG_ASSERT(0);
  15258. return 0;
  15259. }
  15260. #else /* ALTERNATIVE_QUEUE */
  15261. /* Worker threads take accepted socket from the queue */
  15262. static int
  15263. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15264. {
  15265. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15266. (void)thread_index;
  15267. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15268. DEBUG_TRACE("%s", "going idle");
  15269. /* If the queue is empty, wait. We're idle at this point. */
  15270. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15271. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15272. }
  15273. /* If we're stopping, sq_head may be equal to sq_tail. */
  15274. if (ctx->sq_head > ctx->sq_tail) {
  15275. /* Copy socket from the queue and increment tail */
  15276. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15277. ctx->sq_tail++;
  15278. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15279. /* Wrap pointers if needed */
  15280. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15281. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15282. ctx->sq_head -= QUEUE_SIZE(ctx);
  15283. }
  15284. }
  15285. (void)pthread_cond_signal(&ctx->sq_empty);
  15286. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15287. return !ctx->stop_flag;
  15288. #undef QUEUE_SIZE
  15289. }
  15290. /* Master thread adds accepted socket to a queue */
  15291. static void
  15292. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15293. {
  15294. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15295. if (!ctx) {
  15296. return;
  15297. }
  15298. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15299. /* If the queue is full, wait */
  15300. while ((ctx->stop_flag == 0)
  15301. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15302. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15303. }
  15304. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15305. /* Copy socket to the queue and increment head */
  15306. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15307. ctx->sq_head++;
  15308. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15309. }
  15310. (void)pthread_cond_signal(&ctx->sq_full);
  15311. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15312. #undef QUEUE_SIZE
  15313. }
  15314. #endif /* ALTERNATIVE_QUEUE */
  15315. struct worker_thread_args {
  15316. struct mg_context *ctx;
  15317. int index;
  15318. };
  15319. static void *
  15320. worker_thread_run(struct worker_thread_args *thread_args)
  15321. {
  15322. struct mg_context *ctx = thread_args->ctx;
  15323. struct mg_connection *conn;
  15324. struct mg_workerTLS tls;
  15325. #if defined(MG_LEGACY_INTERFACE)
  15326. uint32_t addr;
  15327. #endif
  15328. mg_set_thread_name("worker");
  15329. tls.is_master = 0;
  15330. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15331. #if defined(_WIN32)
  15332. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15333. #endif
  15334. /* Initialize thread local storage before calling any callback */
  15335. pthread_setspecific(sTlsKey, &tls);
  15336. if (ctx->callbacks.init_thread) {
  15337. /* call init_thread for a worker thread (type 1) */
  15338. ctx->callbacks.init_thread(ctx, 1);
  15339. }
  15340. /* Connection structure has been pre-allocated */
  15341. if (((int)thread_args->index < 0)
  15342. || ((unsigned)thread_args->index
  15343. >= (unsigned)ctx->cfg_worker_threads)) {
  15344. mg_cry_internal(fc(ctx),
  15345. "Internal error: Invalid worker index %i",
  15346. (int)thread_args->index);
  15347. return NULL;
  15348. }
  15349. conn = ctx->worker_connections + thread_args->index;
  15350. /* Request buffers are not pre-allocated. They are private to the
  15351. * request and do not contain any state information that might be
  15352. * of interest to anyone observing a server status. */
  15353. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15354. if (conn->buf == NULL) {
  15355. mg_cry_internal(fc(ctx),
  15356. "Out of memory: Cannot allocate buffer for worker %i",
  15357. (int)thread_args->index);
  15358. return NULL;
  15359. }
  15360. conn->buf_size = (int)ctx->max_request_size;
  15361. conn->phys_ctx = ctx;
  15362. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15363. conn->host = NULL; /* until we have more information. */
  15364. conn->thread_index = thread_args->index;
  15365. conn->request_info.user_data = ctx->user_data;
  15366. /* Allocate a mutex for this connection to allow communication both
  15367. * within the request handler and from elsewhere in the application
  15368. */
  15369. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15370. mg_free(conn->buf);
  15371. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15372. return NULL;
  15373. }
  15374. #if defined(USE_SERVER_STATS)
  15375. conn->conn_state = 1; /* not consumed */
  15376. #endif
  15377. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15378. * signal sq_empty condvar to wake up the master waiting in
  15379. * produce_socket() */
  15380. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  15381. conn->conn_birth_time = time(NULL);
  15382. /* Fill in IP, port info early so even if SSL setup below fails,
  15383. * error handler would have the corresponding info.
  15384. * Thanks to Johannes Winkelmann for the patch.
  15385. */
  15386. #if defined(USE_IPV6)
  15387. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15388. conn->request_info.remote_port =
  15389. ntohs(conn->client.rsa.sin6.sin6_port);
  15390. } else
  15391. #endif
  15392. {
  15393. conn->request_info.remote_port =
  15394. ntohs(conn->client.rsa.sin.sin_port);
  15395. }
  15396. sockaddr_to_string(conn->request_info.remote_addr,
  15397. sizeof(conn->request_info.remote_addr),
  15398. &conn->client.rsa);
  15399. DEBUG_TRACE("Start processing connection from %s",
  15400. conn->request_info.remote_addr);
  15401. conn->request_info.is_ssl = conn->client.is_ssl;
  15402. if (conn->client.is_ssl) {
  15403. #if !defined(NO_SSL)
  15404. /* HTTPS connection */
  15405. if (sslize(conn,
  15406. conn->dom_ctx->ssl_ctx,
  15407. SSL_accept,
  15408. &(conn->phys_ctx->stop_flag),
  15409. NULL)) {
  15410. /* conn->dom_ctx is set in get_request */
  15411. /* Get SSL client certificate information (if set) */
  15412. ssl_get_client_cert_info(conn);
  15413. /* process HTTPS connection */
  15414. process_new_connection(conn);
  15415. /* Free client certificate info */
  15416. if (conn->request_info.client_cert) {
  15417. mg_free((void *)(conn->request_info.client_cert->subject));
  15418. mg_free((void *)(conn->request_info.client_cert->issuer));
  15419. mg_free((void *)(conn->request_info.client_cert->serial));
  15420. mg_free((void *)(conn->request_info.client_cert->finger));
  15421. /* Free certificate memory */
  15422. X509_free(
  15423. (X509 *)conn->request_info.client_cert->peer_cert);
  15424. conn->request_info.client_cert->peer_cert = 0;
  15425. conn->request_info.client_cert->subject = 0;
  15426. conn->request_info.client_cert->issuer = 0;
  15427. conn->request_info.client_cert->serial = 0;
  15428. conn->request_info.client_cert->finger = 0;
  15429. mg_free(conn->request_info.client_cert);
  15430. conn->request_info.client_cert = 0;
  15431. }
  15432. } else {
  15433. /* make sure the connection is cleaned up on SSL failure */
  15434. close_connection(conn);
  15435. }
  15436. #endif
  15437. } else {
  15438. /* process HTTP connection */
  15439. process_new_connection(conn);
  15440. }
  15441. DEBUG_TRACE("%s", "Connection closed");
  15442. }
  15443. pthread_setspecific(sTlsKey, NULL);
  15444. #if defined(_WIN32)
  15445. CloseHandle(tls.pthread_cond_helper_mutex);
  15446. #endif
  15447. pthread_mutex_destroy(&conn->mutex);
  15448. /* Free the request buffer. */
  15449. conn->buf_size = 0;
  15450. mg_free(conn->buf);
  15451. conn->buf = NULL;
  15452. #if defined(USE_SERVER_STATS)
  15453. conn->conn_state = 9; /* done */
  15454. #endif
  15455. DEBUG_TRACE("%s", "exiting");
  15456. return NULL;
  15457. }
  15458. /* Threads have different return types on Windows and Unix. */
  15459. #if defined(_WIN32)
  15460. static unsigned __stdcall worker_thread(void *thread_func_param)
  15461. {
  15462. struct worker_thread_args *pwta =
  15463. (struct worker_thread_args *)thread_func_param;
  15464. worker_thread_run(pwta);
  15465. mg_free(thread_func_param);
  15466. return 0;
  15467. }
  15468. #else
  15469. static void *
  15470. worker_thread(void *thread_func_param)
  15471. {
  15472. struct worker_thread_args *pwta =
  15473. (struct worker_thread_args *)thread_func_param;
  15474. struct sigaction sa;
  15475. /* Ignore SIGPIPE */
  15476. memset(&sa, 0, sizeof(sa));
  15477. sa.sa_handler = SIG_IGN;
  15478. sigaction(SIGPIPE, &sa, NULL);
  15479. worker_thread_run(pwta);
  15480. mg_free(thread_func_param);
  15481. return NULL;
  15482. }
  15483. #endif /* _WIN32 */
  15484. /* This is an internal function, thus all arguments are expected to be
  15485. * valid - a NULL check is not required. */
  15486. static void
  15487. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15488. {
  15489. struct socket so;
  15490. char src_addr[IP_ADDR_STR_LEN];
  15491. socklen_t len = sizeof(so.rsa);
  15492. int on = 1;
  15493. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15494. == INVALID_SOCKET) {
  15495. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15496. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15497. mg_cry_internal(fc(ctx),
  15498. "%s: %s is not allowed to connect",
  15499. __func__,
  15500. src_addr);
  15501. closesocket(so.sock);
  15502. } else {
  15503. /* Put so socket structure into the queue */
  15504. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15505. set_close_on_exec(so.sock, fc(ctx));
  15506. so.is_ssl = listener->is_ssl;
  15507. so.ssl_redir = listener->ssl_redir;
  15508. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15509. mg_cry_internal(fc(ctx),
  15510. "%s: getsockname() failed: %s",
  15511. __func__,
  15512. strerror(ERRNO));
  15513. }
  15514. /* Set TCP keep-alive. This is needed because if HTTP-level
  15515. * keep-alive
  15516. * is enabled, and client resets the connection, server won't get
  15517. * TCP FIN or RST and will keep the connection open forever. With
  15518. * TCP keep-alive, next keep-alive handshake will figure out that
  15519. * the client is down and will close the server end.
  15520. * Thanks to Igor Klopov who suggested the patch. */
  15521. if (setsockopt(so.sock,
  15522. SOL_SOCKET,
  15523. SO_KEEPALIVE,
  15524. (SOCK_OPT_TYPE)&on,
  15525. sizeof(on))
  15526. != 0) {
  15527. mg_cry_internal(
  15528. fc(ctx),
  15529. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15530. __func__,
  15531. strerror(ERRNO));
  15532. }
  15533. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15534. * to effectively fill up the underlying IP packet payload and
  15535. * reduce the overhead of sending lots of small buffers. However
  15536. * this hurts the server's throughput (ie. operations per second)
  15537. * when HTTP 1.1 persistent connections are used and the responses
  15538. * are relatively small (eg. less than 1400 bytes).
  15539. */
  15540. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15541. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15542. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15543. mg_cry_internal(
  15544. fc(ctx),
  15545. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15546. __func__,
  15547. strerror(ERRNO));
  15548. }
  15549. }
  15550. /* We are using non-blocking sockets. Thus, the
  15551. * set_sock_timeout(so.sock, timeout);
  15552. * call is no longer required. */
  15553. /* The "non blocking" property should already be
  15554. * inherited from the parent socket. Set it for
  15555. * non-compliant socket implementations. */
  15556. set_non_blocking_mode(so.sock);
  15557. so.in_use = 0;
  15558. produce_socket(ctx, &so);
  15559. }
  15560. }
  15561. static void
  15562. master_thread_run(void *thread_func_param)
  15563. {
  15564. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15565. struct mg_workerTLS tls;
  15566. struct mg_pollfd *pfd;
  15567. unsigned int i;
  15568. unsigned int workerthreadcount;
  15569. if (!ctx) {
  15570. return;
  15571. }
  15572. mg_set_thread_name("master");
  15573. /* Increase priority of the master thread */
  15574. #if defined(_WIN32)
  15575. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15576. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15577. int min_prio = sched_get_priority_min(SCHED_RR);
  15578. int max_prio = sched_get_priority_max(SCHED_RR);
  15579. if ((min_prio >= 0) && (max_prio >= 0)
  15580. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15581. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15582. struct sched_param sched_param = {0};
  15583. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15584. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15585. }
  15586. #endif
  15587. /* Initialize thread local storage */
  15588. #if defined(_WIN32)
  15589. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15590. #endif
  15591. tls.is_master = 1;
  15592. pthread_setspecific(sTlsKey, &tls);
  15593. if (ctx->callbacks.init_thread) {
  15594. /* Callback for the master thread (type 0) */
  15595. ctx->callbacks.init_thread(ctx, 0);
  15596. }
  15597. /* Server starts *now* */
  15598. ctx->start_time = time(NULL);
  15599. /* Start the server */
  15600. pfd = ctx->listening_socket_fds;
  15601. while (ctx->stop_flag == 0) {
  15602. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15603. pfd[i].fd = ctx->listening_sockets[i].sock;
  15604. pfd[i].events = POLLIN;
  15605. }
  15606. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15607. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15608. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15609. * successful poll, and POLLIN is defined as
  15610. * (POLLRDNORM | POLLRDBAND)
  15611. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15612. * pfd[i].revents == POLLIN. */
  15613. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15614. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15615. }
  15616. }
  15617. }
  15618. }
  15619. /* Here stop_flag is 1 - Initiate shutdown. */
  15620. DEBUG_TRACE("%s", "stopping workers");
  15621. /* Stop signal received: somebody called mg_stop. Quit. */
  15622. close_all_listening_sockets(ctx);
  15623. /* Wakeup workers that are waiting for connections to handle. */
  15624. #if defined(ALTERNATIVE_QUEUE)
  15625. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15626. event_signal(ctx->client_wait_events[i]);
  15627. }
  15628. #else
  15629. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15630. pthread_cond_broadcast(&ctx->sq_full);
  15631. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15632. #endif
  15633. /* Join all worker threads to avoid leaking threads. */
  15634. workerthreadcount = ctx->cfg_worker_threads;
  15635. for (i = 0; i < workerthreadcount; i++) {
  15636. if (ctx->worker_threadids[i] != 0) {
  15637. mg_join_thread(ctx->worker_threadids[i]);
  15638. }
  15639. }
  15640. #if defined(USE_LUA)
  15641. /* Free Lua state of lua background task */
  15642. if (ctx->lua_background_state) {
  15643. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15644. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15645. if (lua_istable(lstate, -1)) {
  15646. reg_boolean(lstate, "shutdown", 1);
  15647. lua_pop(lstate, 1);
  15648. mg_sleep(2);
  15649. }
  15650. lua_close(lstate);
  15651. ctx->lua_background_state = 0;
  15652. }
  15653. #endif
  15654. DEBUG_TRACE("%s", "exiting");
  15655. #if defined(_WIN32)
  15656. CloseHandle(tls.pthread_cond_helper_mutex);
  15657. #endif
  15658. pthread_setspecific(sTlsKey, NULL);
  15659. /* Signal mg_stop() that we're done.
  15660. * WARNING: This must be the very last thing this
  15661. * thread does, as ctx becomes invalid after this line. */
  15662. ctx->stop_flag = 2;
  15663. }
  15664. /* Threads have different return types on Windows and Unix. */
  15665. #if defined(_WIN32)
  15666. static unsigned __stdcall master_thread(void *thread_func_param)
  15667. {
  15668. master_thread_run(thread_func_param);
  15669. return 0;
  15670. }
  15671. #else
  15672. static void *
  15673. master_thread(void *thread_func_param)
  15674. {
  15675. struct sigaction sa;
  15676. /* Ignore SIGPIPE */
  15677. memset(&sa, 0, sizeof(sa));
  15678. sa.sa_handler = SIG_IGN;
  15679. sigaction(SIGPIPE, &sa, NULL);
  15680. master_thread_run(thread_func_param);
  15681. return NULL;
  15682. }
  15683. #endif /* _WIN32 */
  15684. static void
  15685. free_context(struct mg_context *ctx)
  15686. {
  15687. int i;
  15688. struct mg_handler_info *tmp_rh;
  15689. if (ctx == NULL) {
  15690. return;
  15691. }
  15692. if (ctx->callbacks.exit_context) {
  15693. ctx->callbacks.exit_context(ctx);
  15694. }
  15695. /* All threads exited, no sync is needed. Destroy thread mutex and
  15696. * condvars
  15697. */
  15698. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15699. #if defined(ALTERNATIVE_QUEUE)
  15700. mg_free(ctx->client_socks);
  15701. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15702. event_destroy(ctx->client_wait_events[i]);
  15703. }
  15704. mg_free(ctx->client_wait_events);
  15705. #else
  15706. (void)pthread_cond_destroy(&ctx->sq_empty);
  15707. (void)pthread_cond_destroy(&ctx->sq_full);
  15708. #endif
  15709. /* Destroy other context global data structures mutex */
  15710. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15711. #if defined(USE_TIMERS)
  15712. timers_exit(ctx);
  15713. #endif
  15714. /* Deallocate config parameters */
  15715. for (i = 0; i < NUM_OPTIONS; i++) {
  15716. if (ctx->dd.config[i] != NULL) {
  15717. #if defined(_MSC_VER)
  15718. #pragma warning(suppress : 6001)
  15719. #endif
  15720. mg_free(ctx->dd.config[i]);
  15721. }
  15722. }
  15723. /* Deallocate request handlers */
  15724. while (ctx->dd.handlers) {
  15725. tmp_rh = ctx->dd.handlers;
  15726. ctx->dd.handlers = tmp_rh->next;
  15727. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15728. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15729. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15730. }
  15731. mg_free(tmp_rh->uri);
  15732. mg_free(tmp_rh);
  15733. }
  15734. #if !defined(NO_SSL)
  15735. /* Deallocate SSL context */
  15736. if (ctx->dd.ssl_ctx != NULL) {
  15737. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15738. int callback_ret =
  15739. (ctx->callbacks.external_ssl_ctx == NULL)
  15740. ? 0
  15741. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15742. if (callback_ret == 0) {
  15743. SSL_CTX_free(ctx->dd.ssl_ctx);
  15744. }
  15745. /* else: ignore error and ommit SSL_CTX_free in case
  15746. * callback_ret is 1 */
  15747. }
  15748. #endif /* !NO_SSL */
  15749. /* Deallocate worker thread ID array */
  15750. if (ctx->worker_threadids != NULL) {
  15751. mg_free(ctx->worker_threadids);
  15752. }
  15753. /* Deallocate worker thread ID array */
  15754. if (ctx->worker_connections != NULL) {
  15755. mg_free(ctx->worker_connections);
  15756. }
  15757. /* deallocate system name string */
  15758. mg_free(ctx->systemName);
  15759. /* Deallocate context itself */
  15760. mg_free(ctx);
  15761. }
  15762. void
  15763. mg_stop(struct mg_context *ctx)
  15764. {
  15765. pthread_t mt;
  15766. if (!ctx) {
  15767. return;
  15768. }
  15769. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15770. * two threads is not allowed. */
  15771. mt = ctx->masterthreadid;
  15772. if (mt == 0) {
  15773. return;
  15774. }
  15775. ctx->masterthreadid = 0;
  15776. /* Set stop flag, so all threads know they have to exit. */
  15777. ctx->stop_flag = 1;
  15778. /* Wait until everything has stopped. */
  15779. while (ctx->stop_flag != 2) {
  15780. (void)mg_sleep(10);
  15781. }
  15782. mg_join_thread(mt);
  15783. free_context(ctx);
  15784. #if defined(_WIN32)
  15785. (void)WSACleanup();
  15786. #endif /* _WIN32 */
  15787. }
  15788. static void
  15789. get_system_name(char **sysName)
  15790. {
  15791. #if defined(_WIN32)
  15792. #if !defined(__SYMBIAN32__)
  15793. #if defined(_WIN32_WCE)
  15794. *sysName = mg_strdup("WinCE");
  15795. #else
  15796. char name[128];
  15797. DWORD dwVersion = 0;
  15798. DWORD dwMajorVersion = 0;
  15799. DWORD dwMinorVersion = 0;
  15800. DWORD dwBuild = 0;
  15801. BOOL wowRet, isWoW = FALSE;
  15802. #if defined(_MSC_VER)
  15803. #pragma warning(push)
  15804. /* GetVersion was declared deprecated */
  15805. #pragma warning(disable : 4996)
  15806. #endif
  15807. dwVersion = GetVersion();
  15808. #if defined(_MSC_VER)
  15809. #pragma warning(pop)
  15810. #endif
  15811. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15812. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15813. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15814. (void)dwBuild;
  15815. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15816. sprintf(name,
  15817. "Windows %u.%u%s",
  15818. (unsigned)dwMajorVersion,
  15819. (unsigned)dwMinorVersion,
  15820. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15821. *sysName = mg_strdup(name);
  15822. #endif
  15823. #else
  15824. *sysName = mg_strdup("Symbian");
  15825. #endif
  15826. #else
  15827. struct utsname name;
  15828. memset(&name, 0, sizeof(name));
  15829. uname(&name);
  15830. *sysName = mg_strdup(name.sysname);
  15831. #endif
  15832. }
  15833. struct mg_context *
  15834. mg_start(const struct mg_callbacks *callbacks,
  15835. void *user_data,
  15836. const char **options)
  15837. {
  15838. struct mg_context *ctx;
  15839. const char *name, *value, *default_value;
  15840. int idx, ok, workerthreadcount;
  15841. unsigned int i;
  15842. int itmp;
  15843. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15844. struct mg_workerTLS tls;
  15845. #if defined(_WIN32)
  15846. WSADATA data;
  15847. WSAStartup(MAKEWORD(2, 2), &data);
  15848. #endif /* _WIN32 */
  15849. /* Allocate context and initialize reasonable general case defaults. */
  15850. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15851. return NULL;
  15852. }
  15853. /* Random number generator will initialize at the first call */
  15854. ctx->dd.auth_nonce_mask =
  15855. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15856. if (mg_init_library_called == 0) {
  15857. /* Legacy INIT, if mg_start is called without mg_init_library.
  15858. * Note: This may cause a memory leak */
  15859. const char *ports_option =
  15860. config_options[LISTENING_PORTS].default_value;
  15861. if (options) {
  15862. const char **run_options = options;
  15863. const char *optname = config_options[LISTENING_PORTS].name;
  15864. /* Try to find the "listening_ports" option */
  15865. while (*run_options) {
  15866. if (!strcmp(*run_options, optname)) {
  15867. ports_option = run_options[1];
  15868. }
  15869. run_options += 2;
  15870. }
  15871. }
  15872. if (is_ssl_port_used(ports_option)) {
  15873. /* Initialize with SSL support */
  15874. mg_init_library(MG_FEATURES_TLS);
  15875. } else {
  15876. /* Initialize without SSL support */
  15877. mg_init_library(MG_FEATURES_DEFAULT);
  15878. }
  15879. }
  15880. tls.is_master = -1;
  15881. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15882. #if defined(_WIN32)
  15883. tls.pthread_cond_helper_mutex = NULL;
  15884. #endif
  15885. pthread_setspecific(sTlsKey, &tls);
  15886. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15887. #if !defined(ALTERNATIVE_QUEUE)
  15888. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15889. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15890. #endif
  15891. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15892. if (!ok) {
  15893. /* Fatal error - abort start. However, this situation should never
  15894. * occur in practice. */
  15895. mg_cry_internal(fc(ctx),
  15896. "%s",
  15897. "Cannot initialize thread synchronization objects");
  15898. mg_free(ctx);
  15899. pthread_setspecific(sTlsKey, NULL);
  15900. return NULL;
  15901. }
  15902. if (callbacks) {
  15903. ctx->callbacks = *callbacks;
  15904. exit_callback = callbacks->exit_context;
  15905. ctx->callbacks.exit_context = 0;
  15906. }
  15907. ctx->user_data = user_data;
  15908. ctx->dd.handlers = NULL;
  15909. ctx->dd.next = NULL;
  15910. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15911. ctx->dd.shared_lua_websockets = NULL;
  15912. #endif
  15913. /* Store options */
  15914. while (options && (name = *options++) != NULL) {
  15915. if ((idx = get_option_index(name)) == -1) {
  15916. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15917. free_context(ctx);
  15918. pthread_setspecific(sTlsKey, NULL);
  15919. return NULL;
  15920. } else if ((value = *options++) == NULL) {
  15921. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15922. free_context(ctx);
  15923. pthread_setspecific(sTlsKey, NULL);
  15924. return NULL;
  15925. }
  15926. if (ctx->dd.config[idx] != NULL) {
  15927. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15928. mg_free(ctx->dd.config[idx]);
  15929. }
  15930. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15931. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15932. }
  15933. /* Set default value if needed */
  15934. for (i = 0; config_options[i].name != NULL; i++) {
  15935. default_value = config_options[i].default_value;
  15936. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15937. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15938. }
  15939. }
  15940. /* Request size option */
  15941. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15942. if (itmp < 1024) {
  15943. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15944. free_context(ctx);
  15945. pthread_setspecific(sTlsKey, NULL);
  15946. return NULL;
  15947. }
  15948. ctx->max_request_size = (unsigned)itmp;
  15949. /* Worker thread count option */
  15950. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15951. if (workerthreadcount > MAX_WORKER_THREADS) {
  15952. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15953. free_context(ctx);
  15954. pthread_setspecific(sTlsKey, NULL);
  15955. return NULL;
  15956. }
  15957. if (workerthreadcount <= 0) {
  15958. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15959. free_context(ctx);
  15960. pthread_setspecific(sTlsKey, NULL);
  15961. return NULL;
  15962. }
  15963. /* Document root */
  15964. #if defined(NO_FILES)
  15965. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15966. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15967. free_context(ctx);
  15968. pthread_setspecific(sTlsKey, NULL);
  15969. return NULL;
  15970. }
  15971. #endif
  15972. get_system_name(&ctx->systemName);
  15973. #if defined(USE_LUA)
  15974. /* If a Lua background script has been configured, start it. */
  15975. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15976. char ebuf[256];
  15977. struct vec opt_vec;
  15978. struct vec eq_vec;
  15979. const char *sparams;
  15980. lua_State *state = mg_prepare_lua_context_script(
  15981. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15982. if (!state) {
  15983. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15984. free_context(ctx);
  15985. pthread_setspecific(sTlsKey, NULL);
  15986. return NULL;
  15987. }
  15988. ctx->lua_background_state = (void *)state;
  15989. lua_newtable(state);
  15990. reg_boolean(state, "shutdown", 0);
  15991. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15992. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15993. reg_llstring(
  15994. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15995. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15996. break;
  15997. }
  15998. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15999. } else {
  16000. ctx->lua_background_state = 0;
  16001. }
  16002. #endif
  16003. /* NOTE(lsm): order is important here. SSL certificates must
  16004. * be initialized before listening ports. UID must be set last. */
  16005. if (!set_gpass_option(ctx, NULL) ||
  16006. #if !defined(NO_SSL)
  16007. !init_ssl_ctx(ctx, NULL) ||
  16008. #endif
  16009. !set_ports_option(ctx) ||
  16010. #if !defined(_WIN32)
  16011. !set_uid_option(ctx) ||
  16012. #endif
  16013. !set_acl_option(ctx)) {
  16014. free_context(ctx);
  16015. pthread_setspecific(sTlsKey, NULL);
  16016. return NULL;
  16017. }
  16018. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16019. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16020. sizeof(pthread_t),
  16021. ctx);
  16022. if (ctx->worker_threadids == NULL) {
  16023. mg_cry_internal(fc(ctx),
  16024. "%s",
  16025. "Not enough memory for worker thread ID array");
  16026. free_context(ctx);
  16027. pthread_setspecific(sTlsKey, NULL);
  16028. return NULL;
  16029. }
  16030. ctx->worker_connections =
  16031. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16032. sizeof(struct mg_connection),
  16033. ctx);
  16034. if (ctx->worker_connections == NULL) {
  16035. mg_cry_internal(fc(ctx),
  16036. "%s",
  16037. "Not enough memory for worker thread connection array");
  16038. free_context(ctx);
  16039. pthread_setspecific(sTlsKey, NULL);
  16040. return NULL;
  16041. }
  16042. #if defined(ALTERNATIVE_QUEUE)
  16043. ctx->client_wait_events =
  16044. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  16045. ctx->cfg_worker_threads,
  16046. ctx);
  16047. if (ctx->client_wait_events == NULL) {
  16048. mg_cry_internal(fc(ctx),
  16049. "%s",
  16050. "Not enough memory for worker event array");
  16051. mg_free(ctx->worker_threadids);
  16052. free_context(ctx);
  16053. pthread_setspecific(sTlsKey, NULL);
  16054. return NULL;
  16055. }
  16056. ctx->client_socks =
  16057. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16058. ctx->cfg_worker_threads,
  16059. ctx);
  16060. if (ctx->client_socks == NULL) {
  16061. mg_cry_internal(fc(ctx),
  16062. "%s",
  16063. "Not enough memory for worker socket array");
  16064. mg_free(ctx->client_wait_events);
  16065. mg_free(ctx->worker_threadids);
  16066. free_context(ctx);
  16067. pthread_setspecific(sTlsKey, NULL);
  16068. return NULL;
  16069. }
  16070. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16071. ctx->client_wait_events[i] = event_create();
  16072. if (ctx->client_wait_events[i] == 0) {
  16073. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  16074. while (i > 0) {
  16075. i--;
  16076. event_destroy(ctx->client_wait_events[i]);
  16077. }
  16078. mg_free(ctx->client_socks);
  16079. mg_free(ctx->client_wait_events);
  16080. mg_free(ctx->worker_threadids);
  16081. free_context(ctx);
  16082. pthread_setspecific(sTlsKey, NULL);
  16083. return NULL;
  16084. }
  16085. }
  16086. #endif
  16087. #if defined(USE_TIMERS)
  16088. if (timers_init(ctx) != 0) {
  16089. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  16090. free_context(ctx);
  16091. pthread_setspecific(sTlsKey, NULL);
  16092. return NULL;
  16093. }
  16094. #endif
  16095. /* Context has been created - init user libraries */
  16096. if (ctx->callbacks.init_context) {
  16097. ctx->callbacks.init_context(ctx);
  16098. }
  16099. ctx->callbacks.exit_context = exit_callback;
  16100. ctx->context_type = CONTEXT_SERVER; /* server context */
  16101. /* Start master (listening) thread */
  16102. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16103. /* Start worker threads */
  16104. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16105. struct worker_thread_args *wta = (struct worker_thread_args *)
  16106. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  16107. if (wta) {
  16108. wta->ctx = ctx;
  16109. wta->index = (int)i;
  16110. }
  16111. if ((wta == NULL)
  16112. || (mg_start_thread_with_id(worker_thread,
  16113. wta,
  16114. &ctx->worker_threadids[i])
  16115. != 0)) {
  16116. /* thread was not created */
  16117. if (wta != NULL) {
  16118. mg_free(wta);
  16119. }
  16120. if (i > 0) {
  16121. mg_cry_internal(fc(ctx),
  16122. "Cannot start worker thread %i: error %ld",
  16123. i + 1,
  16124. (long)ERRNO);
  16125. } else {
  16126. mg_cry_internal(fc(ctx),
  16127. "Cannot create threads: error %ld",
  16128. (long)ERRNO);
  16129. free_context(ctx);
  16130. pthread_setspecific(sTlsKey, NULL);
  16131. return NULL;
  16132. }
  16133. break;
  16134. }
  16135. }
  16136. pthread_setspecific(sTlsKey, NULL);
  16137. return ctx;
  16138. }
  16139. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16140. /* Add an additional domain to an already running web server. */
  16141. int
  16142. mg_start_domain(struct mg_context *ctx, const char **options)
  16143. {
  16144. const char *name;
  16145. const char *value;
  16146. const char *default_value;
  16147. struct mg_domain_context *new_dom;
  16148. struct mg_domain_context *dom;
  16149. int idx, i;
  16150. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16151. return -1;
  16152. }
  16153. new_dom = (struct mg_domain_context *)
  16154. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16155. if (!new_dom) {
  16156. /* Out of memory */
  16157. return -6;
  16158. }
  16159. /* Store options - TODO: unite duplicate code */
  16160. while (options && (name = *options++) != NULL) {
  16161. if ((idx = get_option_index(name)) == -1) {
  16162. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16163. mg_free(new_dom);
  16164. return -2;
  16165. } else if ((value = *options++) == NULL) {
  16166. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16167. mg_free(new_dom);
  16168. return -2;
  16169. }
  16170. if (new_dom->config[idx] != NULL) {
  16171. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16172. mg_free(new_dom->config[idx]);
  16173. }
  16174. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16175. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16176. }
  16177. /* Authentication domain is mandatory */
  16178. /* TODO: Maybe use a new option hostname? */
  16179. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16180. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16181. mg_free(new_dom);
  16182. return -4;
  16183. }
  16184. /* Set default value if needed. Take the config value from
  16185. * ctx as a default value. */
  16186. for (i = 0; config_options[i].name != NULL; i++) {
  16187. default_value = ctx->dd.config[i];
  16188. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16189. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16190. }
  16191. }
  16192. new_dom->handlers = NULL;
  16193. new_dom->next = NULL;
  16194. new_dom->nonce_count = 0;
  16195. new_dom->auth_nonce_mask =
  16196. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16197. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16198. new_dom->shared_lua_websockets = NULL;
  16199. #endif
  16200. if (!init_ssl_ctx(ctx, new_dom)) {
  16201. /* Init SSL failed */
  16202. mg_free(new_dom);
  16203. return -3;
  16204. }
  16205. /* Add element to linked list. */
  16206. mg_lock_context(ctx);
  16207. idx = 0;
  16208. dom = &(ctx->dd);
  16209. for (;;) {
  16210. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16211. dom->config[AUTHENTICATION_DOMAIN])) {
  16212. /* Domain collision */
  16213. mg_cry_internal(fc(ctx),
  16214. "domain %s already in use",
  16215. new_dom->config[AUTHENTICATION_DOMAIN]);
  16216. mg_free(new_dom);
  16217. return -5;
  16218. }
  16219. /* Count number of domains */
  16220. idx++;
  16221. if (dom->next == NULL) {
  16222. dom->next = new_dom;
  16223. break;
  16224. }
  16225. dom = dom->next;
  16226. }
  16227. mg_unlock_context(ctx);
  16228. /* Return domain number */
  16229. return idx;
  16230. }
  16231. #endif
  16232. /* Feature check API function */
  16233. unsigned
  16234. mg_check_feature(unsigned feature)
  16235. {
  16236. static const unsigned feature_set = 0
  16237. /* Set bits for available features according to API documentation.
  16238. * This bit mask is created at compile time, according to the active
  16239. * preprocessor defines. It is a single const value at runtime. */
  16240. #if !defined(NO_FILES)
  16241. | MG_FEATURES_FILES
  16242. #endif
  16243. #if !defined(NO_SSL)
  16244. | MG_FEATURES_SSL
  16245. #endif
  16246. #if !defined(NO_CGI)
  16247. | MG_FEATURES_CGI
  16248. #endif
  16249. #if defined(USE_IPV6)
  16250. | MG_FEATURES_IPV6
  16251. #endif
  16252. #if defined(USE_WEBSOCKET)
  16253. | MG_FEATURES_WEBSOCKET
  16254. #endif
  16255. #if defined(USE_LUA)
  16256. | MG_FEATURES_LUA
  16257. #endif
  16258. #if defined(USE_DUKTAPE)
  16259. | MG_FEATURES_SSJS
  16260. #endif
  16261. #if !defined(NO_CACHING)
  16262. | MG_FEATURES_CACHE
  16263. #endif
  16264. #if defined(USE_SERVER_STATS)
  16265. | MG_FEATURES_STATS
  16266. #endif
  16267. #if defined(USE_ZLIB)
  16268. | MG_FEATURES_COMPRESSION
  16269. #endif
  16270. /* Set some extra bits not defined in the API documentation.
  16271. * These bits may change without further notice. */
  16272. #if defined(MG_LEGACY_INTERFACE)
  16273. | 0x00008000u
  16274. #endif
  16275. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16276. | 0x00004000u
  16277. #endif
  16278. #if defined(MEMORY_DEBUGGING)
  16279. | 0x00001000u
  16280. #endif
  16281. #if defined(USE_TIMERS)
  16282. | 0x00020000u
  16283. #endif
  16284. #if !defined(NO_NONCE_CHECK)
  16285. | 0x00040000u
  16286. #endif
  16287. #if !defined(NO_POPEN)
  16288. | 0x00080000u
  16289. #endif
  16290. ;
  16291. return (feature & feature_set);
  16292. }
  16293. /* strcat with additional NULL check to avoid clang scan-build warning. */
  16294. #define strcat0(a, b) \
  16295. { \
  16296. if ((a != NULL) && (b != NULL)) { \
  16297. strcat(a, b); \
  16298. } \
  16299. }
  16300. /* Get system information. It can be printed or stored by the caller.
  16301. * Return the size of available information. */
  16302. static int
  16303. mg_get_system_info_impl(char *buffer, int buflen)
  16304. {
  16305. char block[256];
  16306. int system_info_length = 0;
  16307. #if defined(_WIN32)
  16308. const char *eol = "\r\n";
  16309. #else
  16310. const char *eol = "\n";
  16311. #endif
  16312. const char *eoobj = "}";
  16313. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16314. if ((buffer == NULL) || (buflen < 1)) {
  16315. buflen = 0;
  16316. } else {
  16317. *buffer = 0;
  16318. }
  16319. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16320. system_info_length += (int)strlen(block);
  16321. if (system_info_length < buflen) {
  16322. strcat0(buffer, block);
  16323. }
  16324. /* Server version */
  16325. {
  16326. const char *version = mg_version();
  16327. mg_snprintf(NULL,
  16328. NULL,
  16329. block,
  16330. sizeof(block),
  16331. "\"version\" : \"%s\",%s",
  16332. version,
  16333. eol);
  16334. system_info_length += (int)strlen(block);
  16335. if (system_info_length < buflen) {
  16336. strcat0(buffer, block);
  16337. }
  16338. }
  16339. /* System info */
  16340. {
  16341. #if defined(_WIN32)
  16342. DWORD dwVersion = 0;
  16343. DWORD dwMajorVersion = 0;
  16344. DWORD dwMinorVersion = 0;
  16345. SYSTEM_INFO si;
  16346. GetSystemInfo(&si);
  16347. #if defined(_MSC_VER)
  16348. #pragma warning(push)
  16349. /* GetVersion was declared deprecated */
  16350. #pragma warning(disable : 4996)
  16351. #endif
  16352. dwVersion = GetVersion();
  16353. #if defined(_MSC_VER)
  16354. #pragma warning(pop)
  16355. #endif
  16356. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16357. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16358. mg_snprintf(NULL,
  16359. NULL,
  16360. block,
  16361. sizeof(block),
  16362. "\"os\" : \"Windows %u.%u\",%s",
  16363. (unsigned)dwMajorVersion,
  16364. (unsigned)dwMinorVersion,
  16365. eol);
  16366. system_info_length += (int)strlen(block);
  16367. if (system_info_length < buflen) {
  16368. strcat0(buffer, block);
  16369. }
  16370. mg_snprintf(NULL,
  16371. NULL,
  16372. block,
  16373. sizeof(block),
  16374. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  16375. (unsigned)si.wProcessorArchitecture,
  16376. (unsigned)si.dwNumberOfProcessors,
  16377. (unsigned)si.dwActiveProcessorMask,
  16378. eol);
  16379. system_info_length += (int)strlen(block);
  16380. if (system_info_length < buflen) {
  16381. strcat0(buffer, block);
  16382. }
  16383. #else
  16384. struct utsname name;
  16385. memset(&name, 0, sizeof(name));
  16386. uname(&name);
  16387. mg_snprintf(NULL,
  16388. NULL,
  16389. block,
  16390. sizeof(block),
  16391. "\"os\" : \"%s %s (%s) - %s\",%s",
  16392. name.sysname,
  16393. name.version,
  16394. name.release,
  16395. name.machine,
  16396. eol);
  16397. system_info_length += (int)strlen(block);
  16398. if (system_info_length < buflen) {
  16399. strcat0(buffer, block);
  16400. }
  16401. #endif
  16402. }
  16403. /* Features */
  16404. {
  16405. mg_snprintf(NULL,
  16406. NULL,
  16407. block,
  16408. sizeof(block),
  16409. "\"features\" : %lu,%s"
  16410. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  16411. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16412. eol,
  16413. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16414. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16415. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16416. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16417. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16418. : "",
  16419. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16420. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16421. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16422. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  16423. eol);
  16424. system_info_length += (int)strlen(block);
  16425. if (system_info_length < buflen) {
  16426. strcat0(buffer, block);
  16427. }
  16428. #if defined(USE_LUA)
  16429. mg_snprintf(NULL,
  16430. NULL,
  16431. block,
  16432. sizeof(block),
  16433. "\"lua_version\" : \"%u (%s)\",%s",
  16434. (unsigned)LUA_VERSION_NUM,
  16435. LUA_RELEASE,
  16436. eol);
  16437. system_info_length += (int)strlen(block);
  16438. if (system_info_length < buflen) {
  16439. strcat0(buffer, block);
  16440. }
  16441. #endif
  16442. #if defined(USE_DUKTAPE)
  16443. mg_snprintf(NULL,
  16444. NULL,
  16445. block,
  16446. sizeof(block),
  16447. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  16448. (unsigned)DUK_VERSION / 10000,
  16449. ((unsigned)DUK_VERSION / 100) % 100,
  16450. (unsigned)DUK_VERSION % 100,
  16451. eol);
  16452. system_info_length += (int)strlen(block);
  16453. if (system_info_length < buflen) {
  16454. strcat0(buffer, block);
  16455. }
  16456. #endif
  16457. }
  16458. /* Build date */
  16459. {
  16460. #if defined(GCC_DIAGNOSTIC)
  16461. #if GCC_VERSION >= 40900
  16462. #pragma GCC diagnostic push
  16463. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16464. #pragma GCC diagnostic ignored "-Wdate-time"
  16465. #endif
  16466. #endif
  16467. mg_snprintf(NULL,
  16468. NULL,
  16469. block,
  16470. sizeof(block),
  16471. "\"build\" : \"%s\",%s",
  16472. __DATE__,
  16473. eol);
  16474. #if defined(GCC_DIAGNOSTIC)
  16475. #if GCC_VERSION >= 40900
  16476. #pragma GCC diagnostic pop
  16477. #endif
  16478. #endif
  16479. system_info_length += (int)strlen(block);
  16480. if (system_info_length < buflen) {
  16481. strcat0(buffer, block);
  16482. }
  16483. }
  16484. /* Compiler information */
  16485. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16486. {
  16487. #if defined(_MSC_VER)
  16488. mg_snprintf(NULL,
  16489. NULL,
  16490. block,
  16491. sizeof(block),
  16492. "\"compiler\" : \"MSC: %u (%u)\",%s",
  16493. (unsigned)_MSC_VER,
  16494. (unsigned)_MSC_FULL_VER,
  16495. eol);
  16496. system_info_length += (int)strlen(block);
  16497. if (system_info_length < buflen) {
  16498. strcat0(buffer, block);
  16499. }
  16500. #elif defined(__MINGW64__)
  16501. mg_snprintf(NULL,
  16502. NULL,
  16503. block,
  16504. sizeof(block),
  16505. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  16506. (unsigned)__MINGW64_VERSION_MAJOR,
  16507. (unsigned)__MINGW64_VERSION_MINOR,
  16508. eol);
  16509. system_info_length += (int)strlen(block);
  16510. if (system_info_length < buflen) {
  16511. strcat0(buffer, block);
  16512. }
  16513. mg_snprintf(NULL,
  16514. NULL,
  16515. block,
  16516. sizeof(block),
  16517. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16518. (unsigned)__MINGW32_MAJOR_VERSION,
  16519. (unsigned)__MINGW32_MINOR_VERSION,
  16520. eol);
  16521. system_info_length += (int)strlen(block);
  16522. if (system_info_length < buflen) {
  16523. strcat0(buffer, block);
  16524. }
  16525. #elif defined(__MINGW32__)
  16526. mg_snprintf(NULL,
  16527. NULL,
  16528. block,
  16529. sizeof(block),
  16530. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16531. (unsigned)__MINGW32_MAJOR_VERSION,
  16532. (unsigned)__MINGW32_MINOR_VERSION,
  16533. eol);
  16534. system_info_length += (int)strlen(block);
  16535. if (system_info_length < buflen) {
  16536. strcat0(buffer, block);
  16537. }
  16538. #elif defined(__clang__)
  16539. mg_snprintf(NULL,
  16540. NULL,
  16541. block,
  16542. sizeof(block),
  16543. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16544. __clang_major__,
  16545. __clang_minor__,
  16546. __clang_patchlevel__,
  16547. __clang_version__,
  16548. eol);
  16549. system_info_length += (int)strlen(block);
  16550. if (system_info_length < buflen) {
  16551. strcat0(buffer, block);
  16552. }
  16553. #elif defined(__GNUC__)
  16554. mg_snprintf(NULL,
  16555. NULL,
  16556. block,
  16557. sizeof(block),
  16558. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16559. (unsigned)__GNUC__,
  16560. (unsigned)__GNUC_MINOR__,
  16561. (unsigned)__GNUC_PATCHLEVEL__,
  16562. eol);
  16563. system_info_length += (int)strlen(block);
  16564. if (system_info_length < buflen) {
  16565. strcat0(buffer, block);
  16566. }
  16567. #elif defined(__INTEL_COMPILER)
  16568. mg_snprintf(NULL,
  16569. NULL,
  16570. block,
  16571. sizeof(block),
  16572. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16573. (unsigned)__INTEL_COMPILER,
  16574. eol);
  16575. system_info_length += (int)strlen(block);
  16576. if (system_info_length < buflen) {
  16577. strcat0(buffer, block);
  16578. }
  16579. #elif defined(__BORLANDC__)
  16580. mg_snprintf(NULL,
  16581. NULL,
  16582. block,
  16583. sizeof(block),
  16584. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16585. (unsigned)__BORLANDC__,
  16586. eol);
  16587. system_info_length += (int)strlen(block);
  16588. if (system_info_length < buflen) {
  16589. strcat0(buffer, block);
  16590. }
  16591. #elif defined(__SUNPRO_C)
  16592. mg_snprintf(NULL,
  16593. NULL,
  16594. block,
  16595. sizeof(block),
  16596. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16597. (unsigned)__SUNPRO_C,
  16598. eol);
  16599. system_info_length += (int)strlen(block);
  16600. if (system_info_length < buflen) {
  16601. strcat0(buffer, block);
  16602. }
  16603. #else
  16604. mg_snprintf(NULL,
  16605. NULL,
  16606. block,
  16607. sizeof(block),
  16608. "\"compiler\" : \"other\",%s",
  16609. eol);
  16610. system_info_length += (int)strlen(block);
  16611. if (system_info_length < buflen) {
  16612. strcat0(buffer, block);
  16613. }
  16614. #endif
  16615. }
  16616. /* Determine 32/64 bit data mode.
  16617. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16618. {
  16619. mg_snprintf(NULL,
  16620. NULL,
  16621. block,
  16622. sizeof(block),
  16623. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16624. "char:%u/%u, "
  16625. "ptr:%u, size:%u, time:%u\"%s",
  16626. (unsigned)sizeof(short),
  16627. (unsigned)sizeof(int),
  16628. (unsigned)sizeof(long),
  16629. (unsigned)sizeof(long long),
  16630. (unsigned)sizeof(float),
  16631. (unsigned)sizeof(double),
  16632. (unsigned)sizeof(long double),
  16633. (unsigned)sizeof(char),
  16634. (unsigned)sizeof(wchar_t),
  16635. (unsigned)sizeof(void *),
  16636. (unsigned)sizeof(size_t),
  16637. (unsigned)sizeof(time_t),
  16638. eol);
  16639. system_info_length += (int)strlen(block);
  16640. if (system_info_length < buflen) {
  16641. strcat0(buffer, block);
  16642. }
  16643. }
  16644. /* Terminate string */
  16645. if ((buflen > 0) && buffer && buffer[0]) {
  16646. if (system_info_length < buflen) {
  16647. strcat0(buffer, eoobj);
  16648. strcat0(buffer, eol);
  16649. }
  16650. }
  16651. system_info_length += reserved_len;
  16652. return system_info_length;
  16653. }
  16654. #if defined(USE_SERVER_STATS)
  16655. /* Get context information. It can be printed or stored by the caller.
  16656. * Return the size of available information. */
  16657. static int
  16658. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16659. {
  16660. char block[256];
  16661. int context_info_length = 0;
  16662. #if defined(_WIN32)
  16663. const char *eol = "\r\n";
  16664. #else
  16665. const char *eol = "\n";
  16666. #endif
  16667. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16668. const char *eoobj = "}";
  16669. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16670. if ((buffer == NULL) || (buflen < 1)) {
  16671. buflen = 0;
  16672. } else {
  16673. *buffer = 0;
  16674. }
  16675. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16676. context_info_length += (int)strlen(block);
  16677. if (context_info_length < buflen) {
  16678. strcat0(buffer, block);
  16679. }
  16680. if (ms) { /* <-- should be always true */
  16681. /* Memory information */
  16682. mg_snprintf(NULL,
  16683. NULL,
  16684. block,
  16685. sizeof(block),
  16686. "\"memory\" : {%s"
  16687. "\"blocks\" : %i,%s"
  16688. "\"used\" : %" INT64_FMT ",%s"
  16689. "\"maxUsed\" : %" INT64_FMT "%s"
  16690. "}%s%s",
  16691. eol,
  16692. ms->blockCount,
  16693. eol,
  16694. ms->totalMemUsed,
  16695. eol,
  16696. ms->maxMemUsed,
  16697. eol,
  16698. (ctx ? "," : ""),
  16699. eol);
  16700. context_info_length += (int)strlen(block);
  16701. if (context_info_length + reserved_len < buflen) {
  16702. strcat0(buffer, block);
  16703. }
  16704. }
  16705. if (ctx) {
  16706. /* Declare all variables at begin of the block, to comply
  16707. * with old C standards. */
  16708. char start_time_str[64] = {0};
  16709. char now_str[64] = {0};
  16710. time_t start_time = ctx->start_time;
  16711. time_t now = time(NULL);
  16712. /* Connections information */
  16713. mg_snprintf(NULL,
  16714. NULL,
  16715. block,
  16716. sizeof(block),
  16717. "\"connections\" : {%s"
  16718. "\"active\" : %i,%s"
  16719. "\"maxActive\" : %i,%s"
  16720. "\"total\" : %" INT64_FMT "%s"
  16721. "},%s",
  16722. eol,
  16723. ctx->active_connections,
  16724. eol,
  16725. ctx->max_connections,
  16726. eol,
  16727. ctx->total_connections,
  16728. eol,
  16729. eol);
  16730. context_info_length += (int)strlen(block);
  16731. if (context_info_length + reserved_len < buflen) {
  16732. strcat0(buffer, block);
  16733. }
  16734. /* Requests information */
  16735. mg_snprintf(NULL,
  16736. NULL,
  16737. block,
  16738. sizeof(block),
  16739. "\"requests\" : {%s"
  16740. "\"total\" : %" INT64_FMT "%s"
  16741. "},%s",
  16742. eol,
  16743. ctx->total_requests,
  16744. eol,
  16745. eol);
  16746. context_info_length += (int)strlen(block);
  16747. if (context_info_length + reserved_len < buflen) {
  16748. strcat0(buffer, block);
  16749. }
  16750. /* Data information */
  16751. mg_snprintf(NULL,
  16752. NULL,
  16753. block,
  16754. sizeof(block),
  16755. "\"data\" : {%s"
  16756. "\"read\" : %" INT64_FMT "%s,"
  16757. "\"written\" : %" INT64_FMT "%s"
  16758. "},%s",
  16759. eol,
  16760. ctx->total_data_read,
  16761. eol,
  16762. ctx->total_data_written,
  16763. eol,
  16764. eol);
  16765. context_info_length += (int)strlen(block);
  16766. if (context_info_length + reserved_len < buflen) {
  16767. strcat0(buffer, block);
  16768. }
  16769. /* Execution time information */
  16770. gmt_time_string(start_time_str,
  16771. sizeof(start_time_str) - 1,
  16772. &start_time);
  16773. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16774. mg_snprintf(NULL,
  16775. NULL,
  16776. block,
  16777. sizeof(block),
  16778. "\"time\" : {%s"
  16779. "\"uptime\" : %.0f,%s"
  16780. "\"start\" : \"%s\",%s"
  16781. "\"now\" : \"%s\"%s"
  16782. "}%s",
  16783. eol,
  16784. difftime(now, start_time),
  16785. eol,
  16786. start_time_str,
  16787. eol,
  16788. now_str,
  16789. eol,
  16790. eol);
  16791. context_info_length += (int)strlen(block);
  16792. if (context_info_length + reserved_len < buflen) {
  16793. strcat0(buffer, block);
  16794. }
  16795. }
  16796. /* Terminate string */
  16797. if ((buflen > 0) && buffer && buffer[0]) {
  16798. if (context_info_length < buflen) {
  16799. strcat0(buffer, eoobj);
  16800. strcat0(buffer, eol);
  16801. }
  16802. }
  16803. context_info_length += reserved_len;
  16804. return context_info_length;
  16805. }
  16806. #endif
  16807. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16808. /* Get connection information. It can be printed or stored by the caller.
  16809. * Return the size of available information. */
  16810. static int
  16811. mg_get_connection_info_impl(const struct mg_context *ctx,
  16812. int idx,
  16813. char *buffer,
  16814. int buflen)
  16815. {
  16816. const struct mg_connection *conn;
  16817. const struct mg_request_info *ri;
  16818. char block[256];
  16819. int connection_info_length = 0;
  16820. int state = 0;
  16821. const char *state_str = "unknown";
  16822. #if defined(_WIN32)
  16823. const char *eol = "\r\n";
  16824. #else
  16825. const char *eol = "\n";
  16826. #endif
  16827. const char *eoobj = "}";
  16828. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16829. if ((buffer == NULL) || (buflen < 1)) {
  16830. buflen = 0;
  16831. } else {
  16832. *buffer = 0;
  16833. }
  16834. if ((ctx == NULL) || (idx < 0)) {
  16835. /* Parameter error */
  16836. return 0;
  16837. }
  16838. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16839. /* Out of range */
  16840. return 0;
  16841. }
  16842. /* Take connection [idx]. This connection is not locked in
  16843. * any way, so some other thread might use it. */
  16844. conn = (ctx->worker_connections) + idx;
  16845. /* Initialize output string */
  16846. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16847. connection_info_length += (int)strlen(block);
  16848. if (connection_info_length < buflen) {
  16849. strcat0(buffer, block);
  16850. }
  16851. /* Init variables */
  16852. ri = &(conn->request_info);
  16853. #if defined(USE_SERVER_STATS)
  16854. state = conn->conn_state;
  16855. /* State as string */
  16856. switch (state) {
  16857. case 0:
  16858. state_str = "undefined";
  16859. break;
  16860. case 1:
  16861. state_str = "not used";
  16862. break;
  16863. case 2:
  16864. state_str = "init";
  16865. break;
  16866. case 3:
  16867. state_str = "ready";
  16868. break;
  16869. case 4:
  16870. state_str = "processing";
  16871. break;
  16872. case 5:
  16873. state_str = "processed";
  16874. break;
  16875. case 6:
  16876. state_str = "to close";
  16877. break;
  16878. case 7:
  16879. state_str = "closing";
  16880. break;
  16881. case 8:
  16882. state_str = "closed";
  16883. break;
  16884. case 9:
  16885. state_str = "done";
  16886. break;
  16887. }
  16888. #endif
  16889. /* Connection info */
  16890. if ((state >= 3) && (state < 9)) {
  16891. mg_snprintf(NULL,
  16892. NULL,
  16893. block,
  16894. sizeof(block),
  16895. "\"connection\" : {%s"
  16896. "\"remote\" : {%s"
  16897. "\"protocol\" : \"%s\",%s"
  16898. "\"addr\" : \"%s\",%s"
  16899. "\"port\" : %u%s"
  16900. "},%s"
  16901. "\"handled_requests\" : %u%s"
  16902. "},%s",
  16903. eol,
  16904. eol,
  16905. get_proto_name(conn),
  16906. eol,
  16907. ri->remote_addr,
  16908. eol,
  16909. ri->remote_port,
  16910. eol,
  16911. eol,
  16912. conn->handled_requests,
  16913. eol,
  16914. eol);
  16915. connection_info_length += (int)strlen(block);
  16916. if (connection_info_length + reserved_len < buflen) {
  16917. strcat0(buffer, block);
  16918. }
  16919. }
  16920. /* Request info */
  16921. if ((state >= 4) && (state < 6)) {
  16922. mg_snprintf(NULL,
  16923. NULL,
  16924. block,
  16925. sizeof(block),
  16926. "\"request_info\" : {%s"
  16927. "\"method\" : \"%s\",%s"
  16928. "\"uri\" : \"%s\",%s"
  16929. "\"query\" : %s%s%s%s"
  16930. "},%s",
  16931. eol,
  16932. ri->request_method,
  16933. eol,
  16934. ri->request_uri,
  16935. eol,
  16936. ri->query_string ? "\"" : "",
  16937. ri->query_string ? ri->query_string : "null",
  16938. ri->query_string ? "\"" : "",
  16939. eol,
  16940. eol);
  16941. connection_info_length += (int)strlen(block);
  16942. if (connection_info_length + reserved_len < buflen) {
  16943. strcat0(buffer, block);
  16944. }
  16945. }
  16946. /* Execution time information */
  16947. if ((state >= 2) && (state < 9)) {
  16948. char start_time_str[64] = {0};
  16949. char now_str[64] = {0};
  16950. time_t start_time = conn->conn_birth_time;
  16951. time_t now = time(NULL);
  16952. gmt_time_string(start_time_str,
  16953. sizeof(start_time_str) - 1,
  16954. &start_time);
  16955. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16956. mg_snprintf(NULL,
  16957. NULL,
  16958. block,
  16959. sizeof(block),
  16960. "\"time\" : {%s"
  16961. "\"uptime\" : %.0f,%s"
  16962. "\"start\" : \"%s\",%s"
  16963. "\"now\" : \"%s\"%s"
  16964. "},%s",
  16965. eol,
  16966. difftime(now, start_time),
  16967. eol,
  16968. start_time_str,
  16969. eol,
  16970. now_str,
  16971. eol,
  16972. eol);
  16973. connection_info_length += (int)strlen(block);
  16974. if (connection_info_length + reserved_len < buflen) {
  16975. strcat0(buffer, block);
  16976. }
  16977. }
  16978. /* Remote user name */
  16979. if ((ri->remote_user) && (state < 9)) {
  16980. mg_snprintf(NULL,
  16981. NULL,
  16982. block,
  16983. sizeof(block),
  16984. "\"user\" : {%s"
  16985. "\"name\" : \"%s\",%s"
  16986. "},%s",
  16987. eol,
  16988. ri->remote_user,
  16989. eol,
  16990. eol);
  16991. connection_info_length += (int)strlen(block);
  16992. if (connection_info_length + reserved_len < buflen) {
  16993. strcat0(buffer, block);
  16994. }
  16995. }
  16996. /* Data block */
  16997. if (state >= 3) {
  16998. mg_snprintf(NULL,
  16999. NULL,
  17000. block,
  17001. sizeof(block),
  17002. "\"data\" : {%s"
  17003. "\"read\" : %" INT64_FMT ",%s"
  17004. "\"written\" : %" INT64_FMT "%s"
  17005. "},%s",
  17006. eol,
  17007. conn->consumed_content,
  17008. eol,
  17009. conn->num_bytes_sent,
  17010. eol,
  17011. eol);
  17012. connection_info_length += (int)strlen(block);
  17013. if (connection_info_length + reserved_len < buflen) {
  17014. strcat0(buffer, block);
  17015. }
  17016. }
  17017. /* State */
  17018. mg_snprintf(NULL,
  17019. NULL,
  17020. block,
  17021. sizeof(block),
  17022. "\"state\" : \"%s\"%s",
  17023. state_str,
  17024. eol);
  17025. connection_info_length += (int)strlen(block);
  17026. if (connection_info_length + reserved_len < buflen) {
  17027. strcat0(buffer, block);
  17028. }
  17029. /* Terminate string */
  17030. if ((buflen > 0) && buffer && buffer[0]) {
  17031. if (connection_info_length < buflen) {
  17032. strcat0(buffer, eoobj);
  17033. strcat0(buffer, eol);
  17034. }
  17035. }
  17036. connection_info_length += reserved_len;
  17037. return connection_info_length;
  17038. }
  17039. #endif
  17040. /* Get system information. It can be printed or stored by the caller.
  17041. * Return the size of available information. */
  17042. int
  17043. mg_get_system_info(char *buffer, int buflen)
  17044. {
  17045. if ((buffer == NULL) || (buflen < 1)) {
  17046. return mg_get_system_info_impl(NULL, 0);
  17047. } else {
  17048. /* Reset buffer, so we can always use strcat. */
  17049. buffer[0] = 0;
  17050. return mg_get_system_info_impl(buffer, buflen);
  17051. }
  17052. }
  17053. /* Get context information. It can be printed or stored by the caller.
  17054. * Return the size of available information. */
  17055. int
  17056. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17057. {
  17058. #if defined(USE_SERVER_STATS)
  17059. if ((buffer == NULL) || (buflen < 1)) {
  17060. return mg_get_context_info_impl(ctx, NULL, 0);
  17061. } else {
  17062. /* Reset buffer, so we can always use strcat. */
  17063. buffer[0] = 0;
  17064. return mg_get_context_info_impl(ctx, buffer, buflen);
  17065. }
  17066. #else
  17067. (void)ctx;
  17068. if ((buffer != NULL) && (buflen > 0)) {
  17069. buffer[0] = 0;
  17070. }
  17071. return 0;
  17072. #endif
  17073. }
  17074. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17075. int
  17076. mg_get_connection_info(const struct mg_context *ctx,
  17077. int idx,
  17078. char *buffer,
  17079. int buflen)
  17080. {
  17081. if ((buffer == NULL) || (buflen < 1)) {
  17082. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  17083. } else {
  17084. /* Reset buffer, so we can always use strcat. */
  17085. buffer[0] = 0;
  17086. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  17087. }
  17088. }
  17089. #endif
  17090. /* Initialize this library. This function does not need to be thread safe.
  17091. */
  17092. unsigned
  17093. mg_init_library(unsigned features)
  17094. {
  17095. #if !defined(NO_SSL)
  17096. char ebuf[128];
  17097. #endif
  17098. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17099. unsigned features_inited = features_to_init;
  17100. if (mg_init_library_called <= 0) {
  17101. /* Not initialized yet */
  17102. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17103. return 0;
  17104. }
  17105. }
  17106. mg_global_lock();
  17107. if (mg_init_library_called <= 0) {
  17108. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17109. /* Fatal error - abort start. However, this situation should
  17110. * never occur in practice. */
  17111. mg_global_unlock();
  17112. return 0;
  17113. }
  17114. #if defined(_WIN32)
  17115. InitializeCriticalSection(&global_log_file_lock);
  17116. #endif
  17117. #if !defined(_WIN32)
  17118. pthread_mutexattr_init(&pthread_mutex_attr);
  17119. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17120. #endif
  17121. #if defined(USE_LUA)
  17122. lua_init_optional_libraries();
  17123. #endif
  17124. }
  17125. mg_global_unlock();
  17126. #if !defined(NO_SSL)
  17127. if (features_to_init & MG_FEATURES_SSL) {
  17128. if (!mg_ssl_initialized) {
  17129. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17130. mg_ssl_initialized = 1;
  17131. } else {
  17132. (void)ebuf;
  17133. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17134. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17135. }
  17136. } else {
  17137. /* ssl already initialized */
  17138. }
  17139. }
  17140. #endif
  17141. /* Start WinSock for Windows */
  17142. mg_global_lock();
  17143. if (mg_init_library_called <= 0) {
  17144. #if defined(_WIN32)
  17145. WSADATA data;
  17146. WSAStartup(MAKEWORD(2, 2), &data);
  17147. #endif /* _WIN32 */
  17148. mg_init_library_called = 1;
  17149. } else {
  17150. mg_init_library_called++;
  17151. }
  17152. mg_global_unlock();
  17153. return features_inited;
  17154. }
  17155. /* Un-initialize this library. */
  17156. unsigned
  17157. mg_exit_library(void)
  17158. {
  17159. if (mg_init_library_called <= 0) {
  17160. return 0;
  17161. }
  17162. mg_global_lock();
  17163. mg_init_library_called--;
  17164. if (mg_init_library_called == 0) {
  17165. #if defined(_WIN32)
  17166. (void)WSACleanup();
  17167. #endif /* _WIN32 */
  17168. #if !defined(NO_SSL)
  17169. if (mg_ssl_initialized) {
  17170. uninitialize_ssl();
  17171. mg_ssl_initialized = 0;
  17172. }
  17173. #endif
  17174. #if defined(_WIN32)
  17175. (void)DeleteCriticalSection(&global_log_file_lock);
  17176. #endif /* _WIN32 */
  17177. #if !defined(_WIN32)
  17178. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17179. #endif
  17180. (void)pthread_key_delete(sTlsKey);
  17181. #if defined(USE_LUA)
  17182. lua_exit_optional_libraries();
  17183. #endif
  17184. mg_global_unlock();
  17185. (void)pthread_mutex_destroy(&global_lock_mutex);
  17186. return 1;
  17187. }
  17188. mg_global_unlock();
  17189. return 1;
  17190. }
  17191. /* End of civetweb.c */