2
0

civetweb.c 602 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633
  1. /* Copyright (c) 2013-2021 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. #include "civetdefines.h"
  23. #if defined(__GNUC__) || defined(__MINGW32__)
  24. #ifndef GCC_VERSION
  25. #define GCC_VERSION \
  26. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  27. #endif
  28. #if GCC_VERSION >= 40500
  29. /* gcc diagnostic pragmas available */
  30. #define GCC_DIAGNOSTIC
  31. #endif
  32. #endif
  33. #if defined(GCC_DIAGNOSTIC)
  34. /* Disable unused macros warnings - not all defines are required
  35. * for all systems and all compilers. */
  36. #pragma GCC diagnostic ignored "-Wunused-macros"
  37. /* A padding warning is just plain useless */
  38. #pragma GCC diagnostic ignored "-Wpadded"
  39. #endif
  40. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  41. /* We must set some flags for the headers we include. These flags
  42. * are reserved ids according to C99, so we need to disable a
  43. * warning for that. */
  44. #pragma GCC diagnostic push
  45. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  46. #endif
  47. #if defined(_WIN32)
  48. #if !defined(_CRT_SECURE_NO_WARNINGS)
  49. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  50. #endif
  51. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  52. #define _WIN32_WINNT 0x0502
  53. #endif
  54. #else
  55. #if !defined(_GNU_SOURCE)
  56. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  57. #endif
  58. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  59. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  60. #endif
  61. #if defined(__LSB_VERSION__) || defined(__sun)
  62. #define NEED_TIMEGM
  63. #define NO_THREAD_NAME
  64. #endif
  65. #if !defined(_LARGEFILE_SOURCE)
  66. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  67. #endif
  68. #if !defined(_FILE_OFFSET_BITS)
  69. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  70. #endif
  71. #if !defined(__STDC_FORMAT_MACROS)
  72. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  73. #endif
  74. #if !defined(__STDC_LIMIT_MACROS)
  75. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  76. #endif
  77. #if !defined(_DARWIN_UNLIMITED_SELECT)
  78. #define _DARWIN_UNLIMITED_SELECT
  79. #endif
  80. #if defined(__sun)
  81. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  82. #define __inline inline /* not recognized on older compiler versions */
  83. #endif
  84. #endif
  85. #if defined(__clang__)
  86. /* Enable reserved-id-macro warning again. */
  87. #pragma GCC diagnostic pop
  88. #endif
  89. #if defined(USE_LUA)
  90. #define USE_TIMERS
  91. #endif
  92. #if defined(_MSC_VER)
  93. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  94. #pragma warning(disable : 4306)
  95. /* conditional expression is constant: introduced by FD_SET(..) */
  96. #pragma warning(disable : 4127)
  97. /* non-constant aggregate initializer: issued due to missing C99 support */
  98. #pragma warning(disable : 4204)
  99. /* padding added after data member */
  100. #pragma warning(disable : 4820)
  101. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  102. #pragma warning(disable : 4668)
  103. /* no function prototype given: converting '()' to '(void)' */
  104. #pragma warning(disable : 4255)
  105. /* function has been selected for automatic inline expansion */
  106. #pragma warning(disable : 4711)
  107. #endif
  108. /* This code uses static_assert to check some conditions.
  109. * Unfortunately some compilers still do not support it, so we have a
  110. * replacement function here. */
  111. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  112. #define mg_static_assert _Static_assert
  113. #elif defined(__cplusplus) && __cplusplus >= 201103L
  114. #define mg_static_assert static_assert
  115. #else
  116. char static_assert_replacement[1];
  117. #define mg_static_assert(cond, txt) \
  118. extern char static_assert_replacement[(cond) ? 1 : -1]
  119. #endif
  120. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  121. "int data type size check");
  122. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  123. "pointer data type size check");
  124. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  125. /* Select queue implementation. Diagnosis features originally only implemented
  126. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  127. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  128. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  129. * implementation, since the queue length is independent from the number of
  130. * worker threads there, while the new queue is one element per worker thread.
  131. *
  132. */
  133. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  134. /* The queues are exclusive or - only one can be used. */
  135. #error \
  136. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  137. #endif
  138. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  139. /* Use a default implementation */
  140. #define NO_ALTERNATIVE_QUEUE
  141. #endif
  142. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  143. /* File system access:
  144. * NO_FILES = do not serve any files from the file system automatically.
  145. * However, with NO_FILES CivetWeb may still write log files, read access
  146. * control files, default error page files or use API functions like
  147. * mg_send_file in callbacks to send files from the server local
  148. * file system.
  149. * NO_FILES only disables the automatic mapping between URLs and local
  150. * file names.
  151. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  152. * devices without file system. Logging to files in not available
  153. * (use callbacks instead) and API functions like mg_send_file are not
  154. * available.
  155. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  156. */
  157. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  158. #endif
  159. /* DTL -- including winsock2.h works better if lean and mean */
  160. #if !defined(WIN32_LEAN_AND_MEAN)
  161. #define WIN32_LEAN_AND_MEAN
  162. #endif
  163. #if defined(__SYMBIAN32__)
  164. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  165. * Symbian is no longer maintained since 2014-01-01.
  166. * Support for Symbian has been removed from CivetWeb
  167. */
  168. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  169. #endif /* __SYMBIAN32__ */
  170. #if defined(ESP_PLATFORM)
  171. #include <esp_pthread.h>
  172. #include <esp_task.h>
  173. #include <ctype.h>
  174. #include <fcntl.h>
  175. #include <netdb.h>
  176. #include <pthread.h>
  177. #include <stdio.h>
  178. #include <stdlib.h>
  179. #include <string.h>
  180. #include <sys/socket.h>
  181. #include <netdb.h>
  182. #include <time.h>
  183. #include <sys/time.h>
  184. #include "lwip/ip_addr.h"
  185. #include <esp_pthread.h>
  186. #include <esp_task.h>
  187. #include <freertos/FreeRTOS.h>
  188. #include <freertos/timers.h>
  189. #include <freertos/task.h>
  190. #define NEED_TIMEGM
  191. #define NI_NUMERICHOST (1)
  192. #define EAI_OVERFLOW 14
  193. int getnameinfo(const struct sockaddr *sa, socklen_t salen,
  194. char *host, socklen_t hostlen,
  195. char *serv, socklen_t servlen, int flags)
  196. {
  197. if (flags & ~(NI_NUMERICHOST | NI_NUMERICSERV)) {
  198. return EAI_BADFLAGS;
  199. }
  200. const struct sockaddr_in *sinp = (const struct sockaddr_in *) sa;
  201. switch (sa->sa_family) {
  202. case AF_INET:
  203. if (flags & NI_NUMERICHOST) {
  204. if (inet_ntop (AF_INET, &sinp->sin_addr, host, hostlen) == NULL) {
  205. return EAI_OVERFLOW;
  206. }
  207. }
  208. if (flags & NI_NUMERICSERV) {
  209. if (snprintf(serv, servlen, "%d", ntohs (sinp->sin_port)) < 0) {
  210. return EAI_OVERFLOW;
  211. }
  212. }
  213. break;
  214. }
  215. return 0;
  216. }
  217. #define HTTP_ESP_STACK (1024 * 16)
  218. #endif
  219. #if defined(__ZEPHYR__)
  220. #include <ctype.h>
  221. #include <fcntl.h>
  222. #include <netdb.h>
  223. #include <poll.h>
  224. #include <pthread.h>
  225. #include <stdio.h>
  226. #include <stdlib.h>
  227. #include <string.h>
  228. #include <sys/socket.h>
  229. #include <time.h>
  230. #include <zephyr/kernel.h>
  231. /* Max worker threads is the max of pthreads minus the main application thread
  232. * and minus the main civetweb thread, thus -2
  233. */
  234. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  235. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  236. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  237. #else
  238. #define ZEPHYR_STACK_SIZE (1024 * 16)
  239. #endif
  240. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  241. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  242. MAX_WORKER_THREADS,
  243. ZEPHYR_STACK_SIZE);
  244. static int zephyr_worker_stack_index;
  245. #endif
  246. #if !defined(CIVETWEB_HEADER_INCLUDED)
  247. /* Include the header file here, so the CivetWeb interface is defined for the
  248. * entire implementation, including the following forward definitions. */
  249. #include "civetweb.h"
  250. #endif
  251. #if !defined(DEBUG_TRACE)
  252. #if defined(DEBUG)
  253. static void DEBUG_TRACE_FUNC(const char *func,
  254. unsigned line,
  255. PRINTF_FORMAT_STRING(const char *fmt),
  256. ...) PRINTF_ARGS(3, 4);
  257. #define DEBUG_TRACE(fmt, ...) \
  258. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  259. #define NEED_DEBUG_TRACE_FUNC
  260. #if !defined(DEBUG_TRACE_STREAM)
  261. #define DEBUG_TRACE_STREAM stdout
  262. #endif
  263. #else
  264. #define DEBUG_TRACE(fmt, ...) \
  265. do { \
  266. } while (0)
  267. #endif /* DEBUG */
  268. #endif /* DEBUG_TRACE */
  269. #if !defined(DEBUG_ASSERT)
  270. #if defined(DEBUG)
  271. #include <stdlib.h>
  272. #define DEBUG_ASSERT(cond) \
  273. do { \
  274. if (!(cond)) { \
  275. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  276. exit(2); /* Exit with error */ \
  277. } \
  278. } while (0)
  279. #else
  280. #define DEBUG_ASSERT(cond)
  281. #endif /* DEBUG */
  282. #endif
  283. #if defined(ESP_PLATFORM)
  284. typedef struct {
  285. TaskHandle_t task_handle;
  286. StaticTask_t* task_buffer;
  287. StackType_t* x_stack;
  288. size_t stack_size;
  289. mg_thread_func_t entry_func;
  290. void* param;
  291. } cw_freertos_handle;
  292. typedef cw_freertos_handle cw_thread_handle_t;
  293. static void freeRTOSTaskEntryFunc(void* handle) {
  294. cw_thread_handle_t* task_param = (cw_thread_handle_t*) handle;
  295. task_param->entry_func(task_param->param);
  296. // TCB are cleanup in IDLE task, so give it some time
  297. // TODO: IMPLEMENT TCB CLEANUP
  298. vTaskDelete(NULL);
  299. }
  300. static bool cw_is_thread_null(cw_thread_handle_t* handle) {
  301. return handle->task_handle == NULL;
  302. }
  303. static void cw_stop_thread(cw_thread_handle_t* handle) {
  304. handle->task_handle = NULL;
  305. }
  306. #endif
  307. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  308. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  309. __attribute__((no_instrument_function));
  310. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  311. __attribute__((no_instrument_function));
  312. void
  313. __cyg_profile_func_enter(void *this_fn, void *call_site)
  314. {
  315. if ((void *)this_fn != (void *)printf) {
  316. printf("E %p %p\n", this_fn, call_site);
  317. }
  318. }
  319. void
  320. __cyg_profile_func_exit(void *this_fn, void *call_site)
  321. {
  322. if ((void *)this_fn != (void *)printf) {
  323. printf("X %p %p\n", this_fn, call_site);
  324. }
  325. }
  326. #endif
  327. #if !defined(IGNORE_UNUSED_RESULT)
  328. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  329. #endif
  330. #if defined(__GNUC__) || defined(__MINGW32__)
  331. /* GCC unused function attribute seems fundamentally broken.
  332. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  333. * OR UNUSED" for individual functions failed.
  334. * Either the compiler creates an "unused-function" warning if a
  335. * function is not marked with __attribute__((unused)).
  336. * On the other hand, if the function is marked with this attribute,
  337. * but is used, the compiler raises a completely idiotic
  338. * "used-but-marked-unused" warning - and
  339. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  340. * raises error: unknown option after "#pragma GCC diagnostic".
  341. * Disable this warning completely, until the GCC guys sober up
  342. * again.
  343. */
  344. #pragma GCC diagnostic ignored "-Wunused-function"
  345. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  346. #else
  347. #define FUNCTION_MAY_BE_UNUSED
  348. #endif
  349. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  350. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  351. #include <errno.h>
  352. #include <fcntl.h>
  353. #include <signal.h>
  354. #include <stdlib.h>
  355. #include <sys/stat.h>
  356. #include <sys/types.h>
  357. #endif /* !_WIN32_WCE */
  358. #if defined(__clang__)
  359. /* When using -Weverything, clang does not accept it's own headers
  360. * in a release build configuration. Disable what is too much in
  361. * -Weverything. */
  362. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  363. #endif
  364. #if defined(__GNUC__) || defined(__MINGW32__)
  365. /* Who on earth came to the conclusion, using __DATE__ should rise
  366. * an "expansion of date or time macro is not reproducible"
  367. * warning. That's exactly what was intended by using this macro.
  368. * Just disable this nonsense warning. */
  369. /* And disabling them does not work either:
  370. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  371. * #pragma clang diagnostic ignored "-Wdate-time"
  372. * So we just have to disable ALL warnings for some lines
  373. * of code.
  374. * This seems to be a known GCC bug, not resolved since 2012:
  375. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  376. */
  377. #endif
  378. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  379. #if defined(__clang__)
  380. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  381. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  382. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  383. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  384. #endif
  385. #endif
  386. #ifndef CLOCK_MONOTONIC
  387. #define CLOCK_MONOTONIC (1)
  388. #endif
  389. #ifndef CLOCK_REALTIME
  390. #define CLOCK_REALTIME (2)
  391. #endif
  392. #include <mach/clock.h>
  393. #include <mach/mach.h>
  394. #include <mach/mach_time.h>
  395. #include <sys/errno.h>
  396. #include <sys/time.h>
  397. /* clock_gettime is not implemented on OSX prior to 10.12 */
  398. static int
  399. _civet_clock_gettime(int clk_id, struct timespec *t)
  400. {
  401. memset(t, 0, sizeof(*t));
  402. if (clk_id == CLOCK_REALTIME) {
  403. struct timeval now;
  404. int rv = gettimeofday(&now, NULL);
  405. if (rv) {
  406. return rv;
  407. }
  408. t->tv_sec = now.tv_sec;
  409. t->tv_nsec = now.tv_usec * 1000;
  410. return 0;
  411. } else if (clk_id == CLOCK_MONOTONIC) {
  412. static uint64_t clock_start_time = 0;
  413. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  414. uint64_t now = mach_absolute_time();
  415. if (clock_start_time == 0) {
  416. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  417. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  418. /* appease "unused variable" warning for release builds */
  419. (void)mach_status;
  420. clock_start_time = now;
  421. }
  422. now = (uint64_t)((double)(now - clock_start_time)
  423. * (double)timebase_ifo.numer
  424. / (double)timebase_ifo.denom);
  425. t->tv_sec = now / 1000000000;
  426. t->tv_nsec = now % 1000000000;
  427. return 0;
  428. }
  429. return -1; /* EINVAL - Clock ID is unknown */
  430. }
  431. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  432. #if defined(__CLOCK_AVAILABILITY)
  433. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  434. * declared but it may be NULL at runtime. So we need to check before using
  435. * it. */
  436. static int
  437. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  438. {
  439. if (clock_gettime) {
  440. return clock_gettime(clk_id, t);
  441. }
  442. return _civet_clock_gettime(clk_id, t);
  443. }
  444. #define clock_gettime _civet_safe_clock_gettime
  445. #else
  446. #define clock_gettime _civet_clock_gettime
  447. #endif
  448. #endif
  449. #if !defined(_WIN32)
  450. /* Unix might return different error codes indicating to try again.
  451. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  452. * decades ago, but better check both and let the compile optimize it. */
  453. #define ERROR_TRY_AGAIN(err) \
  454. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  455. #endif
  456. #if defined(USE_ZLIB)
  457. #include "zconf.h"
  458. #include "zlib.h"
  459. #endif
  460. /********************************************************************/
  461. /* CivetWeb configuration defines */
  462. /********************************************************************/
  463. /* Maximum number of threads that can be configured.
  464. * The number of threads actually created depends on the "num_threads"
  465. * configuration parameter, but this is the upper limit. */
  466. #if !defined(MAX_WORKER_THREADS)
  467. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  468. #endif
  469. /* Timeout interval for select/poll calls.
  470. * The timeouts depend on "*_timeout_ms" configuration values, but long
  471. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  472. * This reduces the time required to stop the server. */
  473. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  474. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  475. #endif
  476. /* Do not try to compress files smaller than this limit. */
  477. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  478. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  479. #endif
  480. #if !defined(PASSWORDS_FILE_NAME)
  481. #define PASSWORDS_FILE_NAME ".htpasswd"
  482. #endif
  483. /* Initial buffer size for all CGI environment variables. In case there is
  484. * not enough space, another block is allocated. */
  485. #if !defined(CGI_ENVIRONMENT_SIZE)
  486. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  487. #endif
  488. /* Maximum number of environment variables. */
  489. #if !defined(MAX_CGI_ENVIR_VARS)
  490. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  491. #endif
  492. /* General purpose buffer size. */
  493. #if !defined(MG_BUF_LEN) /* in bytes */
  494. #define MG_BUF_LEN (1024 * 4)
  495. #endif
  496. /********************************************************************/
  497. /* Helper makros */
  498. #if !defined(ARRAY_SIZE)
  499. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  500. #endif
  501. #include <stdint.h>
  502. /* Standard defines */
  503. #if !defined(INT64_MAX)
  504. #define INT64_MAX (9223372036854775807)
  505. #endif
  506. #define SHUTDOWN_RD (0)
  507. #define SHUTDOWN_WR (1)
  508. #define SHUTDOWN_BOTH (2)
  509. mg_static_assert(MAX_WORKER_THREADS >= 1,
  510. "worker threads must be a positive number");
  511. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  512. "size_t data type size check");
  513. #if defined(_WIN32) /* WINDOWS include block */
  514. #include <malloc.h> /* *alloc( */
  515. #include <stdlib.h> /* *alloc( */
  516. #include <time.h> /* struct timespec */
  517. #include <windows.h>
  518. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  519. #include <ws2tcpip.h>
  520. #include <stdbool.h>
  521. typedef const char *SOCK_OPT_TYPE;
  522. /* For a detailed description of these *_PATH_MAX defines, see
  523. * https://github.com/civetweb/civetweb/issues/937. */
  524. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  525. * null termination, rounded up to the next 4 bytes boundary */
  526. #define UTF8_PATH_MAX (3 * 260)
  527. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  528. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  529. #define UTF16_PATH_MAX (260)
  530. #if !defined(_IN_PORT_T)
  531. #if !defined(in_port_t)
  532. #define in_port_t u_short
  533. #endif
  534. #endif
  535. #if defined(_WIN32_WCE)
  536. #error "WinCE support has ended"
  537. #endif
  538. #include <direct.h>
  539. #include <io.h>
  540. #include <process.h>
  541. #define MAKEUQUAD(lo, hi) \
  542. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  543. #define RATE_DIFF (10000000) /* 100 nsecs */
  544. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  545. #define SYS2UNIX_TIME(lo, hi) \
  546. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  547. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  548. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  549. * Also use _strtoui64 on modern M$ compilers */
  550. #if defined(_MSC_VER)
  551. #if (_MSC_VER < 1300)
  552. #define STRX(x) #x
  553. #define STR(x) STRX(x)
  554. #define __func__ __FILE__ ":" STR(__LINE__)
  555. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  556. #define strtoll(x, y, z) (_atoi64(x))
  557. #else
  558. #define __func__ __FUNCTION__
  559. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  560. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  561. #endif
  562. #endif /* _MSC_VER */
  563. #define ERRNO ((int)(GetLastError()))
  564. #define NO_SOCKLEN_T
  565. #if defined(_WIN64) || defined(__MINGW64__)
  566. #if !defined(SSL_LIB)
  567. #if defined(OPENSSL_API_3_0)
  568. #define SSL_LIB "libssl-3-x64.dll"
  569. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  570. #endif
  571. #if defined(OPENSSL_API_1_1)
  572. #define SSL_LIB "libssl-1_1-x64.dll"
  573. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  574. #endif /* OPENSSL_API_1_1 */
  575. #if defined(OPENSSL_API_1_0)
  576. #define SSL_LIB "ssleay64.dll"
  577. #define CRYPTO_LIB "libeay64.dll"
  578. #endif /* OPENSSL_API_1_0 */
  579. #endif
  580. #else /* defined(_WIN64) || defined(__MINGW64__) */
  581. #if !defined(SSL_LIB)
  582. #if defined(OPENSSL_API_3_0)
  583. #define SSL_LIB "libssl-3.dll"
  584. #define CRYPTO_LIB "libcrypto-3.dll"
  585. #endif
  586. #if defined(OPENSSL_API_1_1)
  587. #define SSL_LIB "libssl-1_1.dll"
  588. #define CRYPTO_LIB "libcrypto-1_1.dll"
  589. #endif /* OPENSSL_API_1_1 */
  590. #if defined(OPENSSL_API_1_0)
  591. #define SSL_LIB "ssleay32.dll"
  592. #define CRYPTO_LIB "libeay32.dll"
  593. #endif /* OPENSSL_API_1_0 */
  594. #endif /* SSL_LIB */
  595. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  596. #define O_NONBLOCK (0)
  597. #if !defined(W_OK)
  598. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  599. #endif
  600. #define _POSIX_
  601. #define INT64_FMT "I64d"
  602. #define UINT64_FMT "I64u"
  603. #define WINCDECL __cdecl
  604. #define vsnprintf_impl _vsnprintf
  605. #define access _access
  606. #define mg_sleep(x) (Sleep(x))
  607. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  608. #if !defined(popen)
  609. #define popen(x, y) (_popen(x, y))
  610. #endif
  611. #if !defined(pclose)
  612. #define pclose(x) (_pclose(x))
  613. #endif
  614. #define close(x) (_close(x))
  615. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  616. #define RTLD_LAZY (0)
  617. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  618. #define fdopen(x, y) (_fdopen((x), (y)))
  619. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  620. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  621. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  622. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  623. #define sleep(x) (Sleep((x)*1000))
  624. #define rmdir(x) (_rmdir(x))
  625. #if defined(_WIN64) || !defined(__MINGW32__)
  626. /* Only MinGW 32 bit is missing this function */
  627. #define timegm(x) (_mkgmtime(x))
  628. #else
  629. time_t timegm(struct tm *tm);
  630. #define NEED_TIMEGM
  631. #endif
  632. #if !defined(fileno)
  633. #define fileno(x) (_fileno(x))
  634. #endif /* !fileno MINGW #defines fileno */
  635. typedef struct {
  636. CRITICAL_SECTION sec; /* Immovable */
  637. } pthread_mutex_t;
  638. typedef DWORD pthread_key_t;
  639. typedef HANDLE pthread_t;
  640. typedef pthread_t cw_thread_handle_t;
  641. typedef struct {
  642. pthread_mutex_t threadIdSec;
  643. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  644. } pthread_cond_t;
  645. #if !defined(__clockid_t_defined)
  646. typedef DWORD clockid_t;
  647. #endif
  648. #if !defined(CLOCK_MONOTONIC)
  649. #define CLOCK_MONOTONIC (1)
  650. #endif
  651. #if !defined(CLOCK_REALTIME)
  652. #define CLOCK_REALTIME (2)
  653. #endif
  654. #if !defined(CLOCK_THREAD)
  655. #define CLOCK_THREAD (3)
  656. #endif
  657. #if !defined(CLOCK_PROCESS)
  658. #define CLOCK_PROCESS (4)
  659. #endif
  660. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  661. #define _TIMESPEC_DEFINED
  662. #endif
  663. #if !defined(_TIMESPEC_DEFINED)
  664. struct timespec {
  665. time_t tv_sec; /* seconds */
  666. long tv_nsec; /* nanoseconds */
  667. };
  668. #endif
  669. #if !defined(WIN_PTHREADS_TIME_H)
  670. #define MUST_IMPLEMENT_CLOCK_GETTIME
  671. #endif
  672. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  673. #define clock_gettime mg_clock_gettime
  674. static int
  675. clock_gettime(clockid_t clk_id, struct timespec *tp)
  676. {
  677. FILETIME ft;
  678. ULARGE_INTEGER li, li2;
  679. BOOL ok = FALSE;
  680. double d;
  681. static double perfcnt_per_sec = 0.0;
  682. static BOOL initialized = FALSE;
  683. if (!initialized) {
  684. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  685. perfcnt_per_sec = 1.0 / li.QuadPart;
  686. initialized = TRUE;
  687. }
  688. if (tp) {
  689. memset(tp, 0, sizeof(*tp));
  690. if (clk_id == CLOCK_REALTIME) {
  691. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  692. GetSystemTimeAsFileTime(&ft);
  693. li.LowPart = ft.dwLowDateTime;
  694. li.HighPart = ft.dwHighDateTime;
  695. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  696. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  697. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  698. ok = TRUE;
  699. /* END: CLOCK_REALTIME */
  700. } else if (clk_id == CLOCK_MONOTONIC) {
  701. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  702. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  703. d = li.QuadPart * perfcnt_per_sec;
  704. tp->tv_sec = (time_t)d;
  705. d -= (double)tp->tv_sec;
  706. tp->tv_nsec = (long)(d * 1.0E9);
  707. ok = TRUE;
  708. /* END: CLOCK_MONOTONIC */
  709. } else if (clk_id == CLOCK_THREAD) {
  710. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  711. FILETIME t_create, t_exit, t_kernel, t_user;
  712. if (GetThreadTimes(GetCurrentThread(),
  713. &t_create,
  714. &t_exit,
  715. &t_kernel,
  716. &t_user)) {
  717. li.LowPart = t_user.dwLowDateTime;
  718. li.HighPart = t_user.dwHighDateTime;
  719. li2.LowPart = t_kernel.dwLowDateTime;
  720. li2.HighPart = t_kernel.dwHighDateTime;
  721. li.QuadPart += li2.QuadPart;
  722. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  723. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  724. ok = TRUE;
  725. }
  726. /* END: CLOCK_THREAD */
  727. } else if (clk_id == CLOCK_PROCESS) {
  728. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  729. FILETIME t_create, t_exit, t_kernel, t_user;
  730. if (GetProcessTimes(GetCurrentProcess(),
  731. &t_create,
  732. &t_exit,
  733. &t_kernel,
  734. &t_user)) {
  735. li.LowPart = t_user.dwLowDateTime;
  736. li.HighPart = t_user.dwHighDateTime;
  737. li2.LowPart = t_kernel.dwLowDateTime;
  738. li2.HighPart = t_kernel.dwHighDateTime;
  739. li.QuadPart += li2.QuadPart;
  740. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  741. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  742. ok = TRUE;
  743. }
  744. /* END: CLOCK_PROCESS */
  745. } else {
  746. /* BEGIN: unknown clock */
  747. /* ok = FALSE; already set by init */
  748. /* END: unknown clock */
  749. }
  750. }
  751. return ok ? 0 : -1;
  752. }
  753. #endif
  754. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  755. static int pthread_mutex_lock(pthread_mutex_t *);
  756. static int pthread_mutex_unlock(pthread_mutex_t *);
  757. static void path_to_unicode(const struct mg_connection *conn,
  758. const char *path,
  759. wchar_t *wbuf,
  760. size_t wbuf_len);
  761. /* All file operations need to be rewritten to solve #246. */
  762. struct mg_file;
  763. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  764. static bool cw_is_thread_null(cw_thread_handle_t* handle) {
  765. return *handle == 0;
  766. }
  767. static void cw_stop_thread(cw_thread_handle_t* handle) {
  768. *handle = 0;
  769. }
  770. /* POSIX dirent interface */
  771. struct dirent {
  772. char d_name[UTF8_PATH_MAX];
  773. };
  774. typedef struct DIR {
  775. HANDLE handle;
  776. WIN32_FIND_DATAW info;
  777. struct dirent result;
  778. } DIR;
  779. #if defined(HAVE_POLL)
  780. #define mg_pollfd pollfd
  781. #else
  782. struct mg_pollfd {
  783. SOCKET fd;
  784. short events;
  785. short revents;
  786. };
  787. #endif
  788. /* Mark required libraries */
  789. #if defined(_MSC_VER)
  790. #pragma comment(lib, "Ws2_32.lib")
  791. #endif
  792. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  793. #include <inttypes.h>
  794. /* Linux & co. internally use UTF8 */
  795. #define UTF8_PATH_MAX (PATH_MAX)
  796. typedef const void *SOCK_OPT_TYPE;
  797. #if defined(ANDROID)
  798. typedef unsigned short int in_port_t;
  799. #endif
  800. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  801. #include <arpa/inet.h>
  802. #include <ctype.h>
  803. #include <dirent.h>
  804. #include <grp.h>
  805. #include <limits.h>
  806. #include <netdb.h>
  807. #include <netinet/in.h>
  808. #include <netinet/tcp.h>
  809. #include <pthread.h>
  810. #include <pwd.h>
  811. #include <stdarg.h>
  812. #include <stddef.h>
  813. #include <stdio.h>
  814. #include <stdlib.h>
  815. #include <string.h>
  816. #include <sys/poll.h>
  817. #include <sys/socket.h>
  818. #include <sys/time.h>
  819. #include <sys/utsname.h>
  820. #include <sys/wait.h>
  821. #include <time.h>
  822. #include <unistd.h>
  823. #include <stdbool.h>
  824. typedef pthread_t cw_thread_handle_t;
  825. static bool cw_is_thread_null(cw_thread_handle_t* handle) {
  826. return *handle == 0;
  827. }
  828. static void cw_stop_thread(cw_thread_handle_t* handle) {
  829. *handle = 0;
  830. }
  831. #if defined(USE_X_DOM_SOCKET)
  832. #include <sys/un.h>
  833. #endif
  834. #endif
  835. #define vsnprintf_impl vsnprintf
  836. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  837. #include <dlfcn.h>
  838. #endif
  839. #if defined(__MACH__) && defined(__APPLE__)
  840. #define SSL_LIB "libssl.dylib"
  841. #define CRYPTO_LIB "libcrypto.dylib"
  842. #else
  843. #if !defined(SSL_LIB)
  844. #define SSL_LIB "libssl.so"
  845. #endif
  846. #if !defined(CRYPTO_LIB)
  847. #define CRYPTO_LIB "libcrypto.so"
  848. #endif
  849. #endif
  850. #if !defined(O_BINARY)
  851. #define O_BINARY (0)
  852. #endif /* O_BINARY */
  853. #define closesocket(a) (close(a))
  854. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  855. #define mg_remove(conn, x) (remove(x))
  856. #define mg_sleep(x) (usleep((x)*1000))
  857. #define mg_opendir(conn, x) (opendir(x))
  858. #define mg_closedir(x) (closedir(x))
  859. #define mg_readdir(x) (readdir(x))
  860. #define ERRNO (errno)
  861. #define INVALID_SOCKET (-1)
  862. #define INT64_FMT PRId64
  863. #define UINT64_FMT PRIu64
  864. typedef int SOCKET;
  865. #define WINCDECL
  866. #if defined(__hpux)
  867. /* HPUX 11 does not have monotonic, fall back to realtime */
  868. #if !defined(CLOCK_MONOTONIC)
  869. #define CLOCK_MONOTONIC CLOCK_REALTIME
  870. #endif
  871. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  872. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  873. * the prototypes use int* rather than socklen_t* which matches the
  874. * actual library expectation. When called with the wrong size arg
  875. * accept() returns a zero client inet addr and check_acl() always
  876. * fails. Since socklen_t is widely used below, just force replace
  877. * their typedef with int. - DTL
  878. */
  879. #define socklen_t int
  880. #endif /* hpux */
  881. #define mg_pollfd pollfd
  882. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  883. /* In case our C library is missing "timegm", provide an implementation */
  884. #if defined(NEED_TIMEGM)
  885. static inline int
  886. is_leap(int y)
  887. {
  888. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  889. }
  890. static inline int
  891. count_leap(int y)
  892. {
  893. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  894. }
  895. time_t
  896. timegm(struct tm *tm)
  897. {
  898. static const unsigned short ydays[] = {
  899. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  900. int year = tm->tm_year + 1900;
  901. int mon = tm->tm_mon;
  902. int mday = tm->tm_mday - 1;
  903. int hour = tm->tm_hour;
  904. int min = tm->tm_min;
  905. int sec = tm->tm_sec;
  906. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  907. || (mday >= ydays[mon + 1] - ydays[mon]
  908. + (mon == 1 && is_leap(year) ? 1 : 0))
  909. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  910. return -1;
  911. time_t res = year - 1970;
  912. res *= 365;
  913. res += mday;
  914. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  915. res += count_leap(year);
  916. res *= 24;
  917. res += hour;
  918. res *= 60;
  919. res += min;
  920. res *= 60;
  921. res += sec;
  922. return res;
  923. }
  924. #endif /* NEED_TIMEGM */
  925. /* va_copy should always be a macro, C99 and C++11 - DTL */
  926. #if !defined(va_copy)
  927. #define va_copy(x, y) ((x) = (y))
  928. #endif
  929. #if defined(_WIN32)
  930. /* Create substitutes for POSIX functions in Win32. */
  931. #if defined(GCC_DIAGNOSTIC)
  932. /* Show no warning in case system functions are not used. */
  933. #pragma GCC diagnostic push
  934. #pragma GCC diagnostic ignored "-Wunused-function"
  935. #endif
  936. static pthread_mutex_t global_log_file_lock;
  937. FUNCTION_MAY_BE_UNUSED
  938. static DWORD
  939. pthread_self(void)
  940. {
  941. return GetCurrentThreadId();
  942. }
  943. FUNCTION_MAY_BE_UNUSED
  944. static int
  945. pthread_key_create(
  946. pthread_key_t *key,
  947. void (*_ignored)(void *) /* destructor not supported for Windows */
  948. )
  949. {
  950. (void)_ignored;
  951. if ((key != 0)) {
  952. *key = TlsAlloc();
  953. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  954. }
  955. return -2;
  956. }
  957. FUNCTION_MAY_BE_UNUSED
  958. static int
  959. pthread_key_delete(pthread_key_t key)
  960. {
  961. return TlsFree(key) ? 0 : 1;
  962. }
  963. FUNCTION_MAY_BE_UNUSED
  964. static int
  965. pthread_setspecific(pthread_key_t key, void *value)
  966. {
  967. return TlsSetValue(key, value) ? 0 : 1;
  968. }
  969. FUNCTION_MAY_BE_UNUSED
  970. static void *
  971. pthread_getspecific(pthread_key_t key)
  972. {
  973. return TlsGetValue(key);
  974. }
  975. #if defined(GCC_DIAGNOSTIC)
  976. /* Enable unused function warning again */
  977. #pragma GCC diagnostic pop
  978. #endif
  979. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  980. #else
  981. static pthread_mutexattr_t pthread_mutex_attr;
  982. #endif /* _WIN32 */
  983. #if defined(GCC_DIAGNOSTIC)
  984. /* Show no warning in case system functions are not used. */
  985. #pragma GCC diagnostic push
  986. #pragma GCC diagnostic ignored "-Wunused-function"
  987. #endif /* defined(GCC_DIAGNOSTIC) */
  988. #if defined(__clang__)
  989. /* Show no warning in case system functions are not used. */
  990. #pragma clang diagnostic push
  991. #pragma clang diagnostic ignored "-Wunused-function"
  992. #endif
  993. static pthread_mutex_t global_lock_mutex;
  994. FUNCTION_MAY_BE_UNUSED
  995. static void
  996. mg_global_lock(void)
  997. {
  998. (void)pthread_mutex_lock(&global_lock_mutex);
  999. }
  1000. FUNCTION_MAY_BE_UNUSED
  1001. static void
  1002. mg_global_unlock(void)
  1003. {
  1004. (void)pthread_mutex_unlock(&global_lock_mutex);
  1005. }
  1006. #if defined(_WIN64)
  1007. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1008. #elif defined(_WIN32)
  1009. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1010. #endif
  1011. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1012. * Operations: Increment, Decrement, Add, Maximum.
  1013. * Up to size_t, they do not an atomic "load" operation.
  1014. */
  1015. FUNCTION_MAY_BE_UNUSED
  1016. static ptrdiff_t
  1017. mg_atomic_inc(volatile ptrdiff_t *addr)
  1018. {
  1019. ptrdiff_t ret;
  1020. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1021. ret = InterlockedIncrement64(addr);
  1022. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1023. ret = InterlockedIncrement(addr);
  1024. #elif defined(__GNUC__) \
  1025. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1026. && !defined(NO_ATOMICS)
  1027. ret = __sync_add_and_fetch(addr, 1);
  1028. #else
  1029. mg_global_lock();
  1030. ret = (++(*addr));
  1031. mg_global_unlock();
  1032. #endif
  1033. return ret;
  1034. }
  1035. FUNCTION_MAY_BE_UNUSED
  1036. static ptrdiff_t
  1037. mg_atomic_dec(volatile ptrdiff_t *addr)
  1038. {
  1039. ptrdiff_t ret;
  1040. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1041. ret = InterlockedDecrement64(addr);
  1042. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1043. ret = InterlockedDecrement(addr);
  1044. #elif defined(__GNUC__) \
  1045. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1046. && !defined(NO_ATOMICS)
  1047. ret = __sync_sub_and_fetch(addr, 1);
  1048. #else
  1049. mg_global_lock();
  1050. ret = (--(*addr));
  1051. mg_global_unlock();
  1052. #endif
  1053. return ret;
  1054. }
  1055. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  1056. static ptrdiff_t
  1057. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1058. {
  1059. ptrdiff_t ret;
  1060. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1061. ret = InterlockedAdd64(addr, value);
  1062. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1063. ret = InterlockedExchangeAdd(addr, value) + value;
  1064. #elif defined(__GNUC__) \
  1065. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1066. && !defined(NO_ATOMICS)
  1067. ret = __sync_add_and_fetch(addr, value);
  1068. #else
  1069. mg_global_lock();
  1070. *addr += value;
  1071. ret = (*addr);
  1072. mg_global_unlock();
  1073. #endif
  1074. return ret;
  1075. }
  1076. FUNCTION_MAY_BE_UNUSED
  1077. static ptrdiff_t
  1078. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1079. ptrdiff_t oldval,
  1080. ptrdiff_t newval)
  1081. {
  1082. ptrdiff_t ret;
  1083. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1084. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1085. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1086. ret = InterlockedCompareExchange(addr, newval, oldval);
  1087. #elif defined(__GNUC__) \
  1088. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1089. && !defined(NO_ATOMICS)
  1090. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1091. #else
  1092. mg_global_lock();
  1093. ret = *addr;
  1094. if ((ret != newval) && (ret == oldval)) {
  1095. *addr = newval;
  1096. }
  1097. mg_global_unlock();
  1098. #endif
  1099. return ret;
  1100. }
  1101. static void
  1102. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1103. {
  1104. register ptrdiff_t tmp = *addr;
  1105. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1106. while (tmp < value) {
  1107. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1108. }
  1109. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1110. while (tmp < value) {
  1111. tmp = InterlockedCompareExchange(addr, value, tmp);
  1112. }
  1113. #elif defined(__GNUC__) \
  1114. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1115. && !defined(NO_ATOMICS)
  1116. while (tmp < value) {
  1117. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1118. }
  1119. #else
  1120. mg_global_lock();
  1121. if (*addr < value) {
  1122. *addr = value;
  1123. }
  1124. mg_global_unlock();
  1125. #endif
  1126. }
  1127. static int64_t
  1128. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1129. {
  1130. int64_t ret;
  1131. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1132. ret = InterlockedAdd64(addr, value);
  1133. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1134. ret = InterlockedExchangeAdd64(addr, value) + value;
  1135. #elif defined(__GNUC__) \
  1136. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1137. && !defined(NO_ATOMICS)
  1138. ret = __sync_add_and_fetch(addr, value);
  1139. #else
  1140. mg_global_lock();
  1141. *addr += value;
  1142. ret = (*addr);
  1143. mg_global_unlock();
  1144. #endif
  1145. return ret;
  1146. }
  1147. #endif
  1148. #if defined(GCC_DIAGNOSTIC)
  1149. /* Show no warning in case system functions are not used. */
  1150. #pragma GCC diagnostic pop
  1151. #endif /* defined(GCC_DIAGNOSTIC) */
  1152. #if defined(__clang__)
  1153. /* Show no warning in case system functions are not used. */
  1154. #pragma clang diagnostic pop
  1155. #endif
  1156. #if defined(USE_SERVER_STATS)
  1157. struct mg_memory_stat {
  1158. volatile ptrdiff_t totalMemUsed;
  1159. volatile ptrdiff_t maxMemUsed;
  1160. volatile ptrdiff_t blockCount;
  1161. };
  1162. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1163. static void *
  1164. mg_malloc_ex(size_t size,
  1165. struct mg_context *ctx,
  1166. const char *file,
  1167. unsigned line)
  1168. {
  1169. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1170. void *memory = 0;
  1171. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1172. #if defined(MEMORY_DEBUGGING)
  1173. char mallocStr[256];
  1174. #else
  1175. (void)file;
  1176. (void)line;
  1177. #endif
  1178. if (data) {
  1179. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1180. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1181. mg_atomic_inc(&mstat->blockCount);
  1182. ((uintptr_t *)data)[0] = size;
  1183. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1184. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1185. }
  1186. #if defined(MEMORY_DEBUGGING)
  1187. sprintf(mallocStr,
  1188. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1189. memory,
  1190. (unsigned long)size,
  1191. (unsigned long)mstat->totalMemUsed,
  1192. (unsigned long)mstat->blockCount,
  1193. file,
  1194. line);
  1195. DEBUG_TRACE("%s", mallocStr);
  1196. #endif
  1197. return memory;
  1198. }
  1199. static void *
  1200. mg_calloc_ex(size_t count,
  1201. size_t size,
  1202. struct mg_context *ctx,
  1203. const char *file,
  1204. unsigned line)
  1205. {
  1206. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1207. if (data) {
  1208. memset(data, 0, size * count);
  1209. }
  1210. return data;
  1211. }
  1212. static void
  1213. mg_free_ex(void *memory, const char *file, unsigned line)
  1214. {
  1215. #if defined(MEMORY_DEBUGGING)
  1216. char mallocStr[256];
  1217. #else
  1218. (void)file;
  1219. (void)line;
  1220. #endif
  1221. if (memory) {
  1222. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1223. uintptr_t size = ((uintptr_t *)data)[0];
  1224. struct mg_memory_stat *mstat =
  1225. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1226. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1227. mg_atomic_dec(&mstat->blockCount);
  1228. #if defined(MEMORY_DEBUGGING)
  1229. sprintf(mallocStr,
  1230. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1231. memory,
  1232. (unsigned long)size,
  1233. (unsigned long)mstat->totalMemUsed,
  1234. (unsigned long)mstat->blockCount,
  1235. file,
  1236. line);
  1237. DEBUG_TRACE("%s", mallocStr);
  1238. #endif
  1239. free(data);
  1240. }
  1241. }
  1242. static void *
  1243. mg_realloc_ex(void *memory,
  1244. size_t newsize,
  1245. struct mg_context *ctx,
  1246. const char *file,
  1247. unsigned line)
  1248. {
  1249. void *data;
  1250. void *_realloc;
  1251. uintptr_t oldsize;
  1252. #if defined(MEMORY_DEBUGGING)
  1253. char mallocStr[256];
  1254. #else
  1255. (void)file;
  1256. (void)line;
  1257. #endif
  1258. if (newsize) {
  1259. if (memory) {
  1260. /* Reallocate existing block */
  1261. struct mg_memory_stat *mstat;
  1262. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1263. oldsize = ((uintptr_t *)data)[0];
  1264. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1265. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1266. if (_realloc) {
  1267. data = _realloc;
  1268. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1269. #if defined(MEMORY_DEBUGGING)
  1270. sprintf(mallocStr,
  1271. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1272. memory,
  1273. (unsigned long)oldsize,
  1274. (unsigned long)mstat->totalMemUsed,
  1275. (unsigned long)mstat->blockCount,
  1276. file,
  1277. line);
  1278. DEBUG_TRACE("%s", mallocStr);
  1279. #endif
  1280. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1281. #if defined(MEMORY_DEBUGGING)
  1282. sprintf(mallocStr,
  1283. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1284. memory,
  1285. (unsigned long)newsize,
  1286. (unsigned long)mstat->totalMemUsed,
  1287. (unsigned long)mstat->blockCount,
  1288. file,
  1289. line);
  1290. DEBUG_TRACE("%s", mallocStr);
  1291. #endif
  1292. *(uintptr_t *)data = newsize;
  1293. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1294. } else {
  1295. #if defined(MEMORY_DEBUGGING)
  1296. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1297. #endif
  1298. return _realloc;
  1299. }
  1300. } else {
  1301. /* Allocate new block */
  1302. data = mg_malloc_ex(newsize, ctx, file, line);
  1303. }
  1304. } else {
  1305. /* Free existing block */
  1306. data = 0;
  1307. mg_free_ex(memory, file, line);
  1308. }
  1309. return data;
  1310. }
  1311. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1312. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1313. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1314. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1315. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1316. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1317. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1318. #else /* USE_SERVER_STATS */
  1319. static __inline void *
  1320. mg_malloc(size_t a)
  1321. {
  1322. return malloc(a);
  1323. }
  1324. static __inline void *
  1325. mg_calloc(size_t a, size_t b)
  1326. {
  1327. return calloc(a, b);
  1328. }
  1329. static __inline void *
  1330. mg_realloc(void *a, size_t b)
  1331. {
  1332. return realloc(a, b);
  1333. }
  1334. static __inline void
  1335. mg_free(void *a)
  1336. {
  1337. free(a);
  1338. }
  1339. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1340. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1341. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1342. #define mg_free_ctx(a, c) mg_free(a)
  1343. #endif /* USE_SERVER_STATS */
  1344. static void mg_vsnprintf(const struct mg_connection *conn,
  1345. int *truncated,
  1346. char *buf,
  1347. size_t buflen,
  1348. const char *fmt,
  1349. va_list ap);
  1350. static void mg_snprintf(const struct mg_connection *conn,
  1351. int *truncated,
  1352. char *buf,
  1353. size_t buflen,
  1354. PRINTF_FORMAT_STRING(const char *fmt),
  1355. ...) PRINTF_ARGS(5, 6);
  1356. /* This following lines are just meant as a reminder to use the mg-functions
  1357. * for memory management */
  1358. #if defined(malloc)
  1359. #undef malloc
  1360. #endif
  1361. #if defined(calloc)
  1362. #undef calloc
  1363. #endif
  1364. #if defined(realloc)
  1365. #undef realloc
  1366. #endif
  1367. #if defined(free)
  1368. #undef free
  1369. #endif
  1370. #if defined(snprintf)
  1371. #undef snprintf
  1372. #endif
  1373. #if defined(vsnprintf)
  1374. #undef vsnprintf
  1375. #endif
  1376. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1377. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1378. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1379. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1380. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1381. #if defined(_WIN32)
  1382. /* vsnprintf must not be used in any system,
  1383. * but this define only works well for Windows. */
  1384. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1385. #endif
  1386. /* mg_init_library counter */
  1387. static int mg_init_library_called = 0;
  1388. #if !defined(NO_SSL)
  1389. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1390. || defined(OPENSSL_API_3_0)
  1391. static int mg_openssl_initialized = 0;
  1392. #endif
  1393. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1394. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1395. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS"
  1396. #endif
  1397. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1398. #error "Multiple OPENSSL_API versions defined"
  1399. #endif
  1400. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1401. #error "Multiple OPENSSL_API versions defined"
  1402. #endif
  1403. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1404. #error "Multiple OPENSSL_API versions defined"
  1405. #endif
  1406. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1407. || defined(OPENSSL_API_3_0)) \
  1408. && defined(USE_MBEDTLS)
  1409. #error "Multiple SSL libraries defined"
  1410. #endif
  1411. #endif
  1412. static pthread_key_t sTlsKey; /* Thread local storage index */
  1413. static volatile ptrdiff_t thread_idx_max = 0;
  1414. #if defined(MG_LEGACY_INTERFACE)
  1415. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1416. #endif
  1417. struct mg_workerTLS {
  1418. int is_master;
  1419. unsigned long thread_idx;
  1420. void *user_ptr;
  1421. #if defined(_WIN32)
  1422. HANDLE pthread_cond_helper_mutex;
  1423. struct mg_workerTLS *next_waiting_thread;
  1424. #endif
  1425. const char *alpn_proto;
  1426. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1427. char txtbuf[4];
  1428. #endif
  1429. };
  1430. #if defined(GCC_DIAGNOSTIC)
  1431. /* Show no warning in case system functions are not used. */
  1432. #pragma GCC diagnostic push
  1433. #pragma GCC diagnostic ignored "-Wunused-function"
  1434. #endif /* defined(GCC_DIAGNOSTIC) */
  1435. #if defined(__clang__)
  1436. /* Show no warning in case system functions are not used. */
  1437. #pragma clang diagnostic push
  1438. #pragma clang diagnostic ignored "-Wunused-function"
  1439. #endif
  1440. /* Get a unique thread ID as unsigned long, independent from the data type
  1441. * of thread IDs defined by the operating system API.
  1442. * If two calls to mg_current_thread_id return the same value, they calls
  1443. * are done from the same thread. If they return different values, they are
  1444. * done from different threads. (Provided this function is used in the same
  1445. * process context and threads are not repeatedly created and deleted, but
  1446. * CivetWeb does not do that).
  1447. * This function must match the signature required for SSL id callbacks:
  1448. * CRYPTO_set_id_callback
  1449. */
  1450. FUNCTION_MAY_BE_UNUSED
  1451. static unsigned long
  1452. mg_current_thread_id(void)
  1453. {
  1454. #if defined(_WIN32)
  1455. return GetCurrentThreadId();
  1456. #else
  1457. #if defined(__clang__)
  1458. #pragma clang diagnostic push
  1459. #pragma clang diagnostic ignored "-Wunreachable-code"
  1460. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1461. * or not, so one of the two conditions will be unreachable by construction.
  1462. * Unfortunately the C standard does not define a way to check this at
  1463. * compile time, since the #if preprocessor conditions can not use the
  1464. * sizeof operator as an argument. */
  1465. #endif
  1466. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1467. /* This is the problematic case for CRYPTO_set_id_callback:
  1468. * The OS pthread_t can not be cast to unsigned long. */
  1469. struct mg_workerTLS *tls =
  1470. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1471. if (tls == NULL) {
  1472. /* SSL called from an unknown thread: Create some thread index.
  1473. */
  1474. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1475. tls->is_master = -2; /* -2 means "3rd party thread" */
  1476. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1477. pthread_setspecific(sTlsKey, tls);
  1478. }
  1479. return tls->thread_idx;
  1480. } else {
  1481. /* pthread_t may be any data type, so a simple cast to unsigned long
  1482. * can rise a warning/error, depending on the platform.
  1483. * Here memcpy is used as an anything-to-anything cast. */
  1484. unsigned long ret = 0;
  1485. pthread_t t = pthread_self();
  1486. memcpy(&ret, &t, sizeof(pthread_t));
  1487. return ret;
  1488. }
  1489. #if defined(__clang__)
  1490. #pragma clang diagnostic pop
  1491. #endif
  1492. #endif
  1493. }
  1494. FUNCTION_MAY_BE_UNUSED
  1495. static uint64_t
  1496. mg_get_current_time_ns(void)
  1497. {
  1498. struct timespec tsnow;
  1499. clock_gettime(CLOCK_REALTIME, &tsnow);
  1500. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1501. }
  1502. #if defined(GCC_DIAGNOSTIC)
  1503. /* Show no warning in case system functions are not used. */
  1504. #pragma GCC diagnostic pop
  1505. #endif /* defined(GCC_DIAGNOSTIC) */
  1506. #if defined(__clang__)
  1507. /* Show no warning in case system functions are not used. */
  1508. #pragma clang diagnostic pop
  1509. #endif
  1510. #if defined(NEED_DEBUG_TRACE_FUNC)
  1511. static void
  1512. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1513. {
  1514. va_list args;
  1515. struct timespec tsnow;
  1516. /* Get some operating system independent thread id */
  1517. // unsigned long thread_id = mg_current_thread_id();
  1518. clock_gettime(CLOCK_REALTIME, &tsnow);
  1519. // flockfile(DEBUG_TRACE_STREAM);
  1520. fprintf(DEBUG_TRACE_STREAM,
  1521. "*** %lu.%09lu %s:%u: ",
  1522. (unsigned long)tsnow.tv_sec,
  1523. (unsigned long)tsnow.tv_nsec,
  1524. func,
  1525. line);
  1526. // va_start(args, fmt);
  1527. // vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1528. // va_end(args);
  1529. // putc('\n', DEBUG_TRACE_STREAM);
  1530. // fflush(DEBUG_TRACE_STREAM);
  1531. // funlockfile(DEBUG_TRACE_STREAM);
  1532. }
  1533. #endif /* NEED_DEBUG_TRACE_FUNC */
  1534. #define MD5_STATIC static
  1535. #include "md5.inl"
  1536. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1537. #if defined(NO_SOCKLEN_T)
  1538. typedef int socklen_t;
  1539. #endif /* NO_SOCKLEN_T */
  1540. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1541. #if !defined(MSG_NOSIGNAL)
  1542. #define MSG_NOSIGNAL (0)
  1543. #endif
  1544. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1545. #if defined(USE_MBEDTLS)
  1546. /* mbedTLS */
  1547. #include "mod_mbedtls.inl"
  1548. #elif defined(NO_SSL)
  1549. /* no SSL */
  1550. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1551. typedef struct SSL_CTX SSL_CTX;
  1552. #elif defined(NO_SSL_DL)
  1553. /* OpenSSL without dynamic loading */
  1554. #include <openssl/bn.h>
  1555. #include <openssl/conf.h>
  1556. #include <openssl/crypto.h>
  1557. #include <openssl/dh.h>
  1558. #include <openssl/engine.h>
  1559. #include <openssl/err.h>
  1560. #include <openssl/opensslv.h>
  1561. #include <openssl/pem.h>
  1562. #include <openssl/ssl.h>
  1563. #include <openssl/tls1.h>
  1564. #include <openssl/x509.h>
  1565. #if defined(WOLFSSL_VERSION)
  1566. /* Additional defines for WolfSSL, see
  1567. * https://github.com/civetweb/civetweb/issues/583 */
  1568. #include "wolfssl_extras.inl"
  1569. #endif
  1570. #if defined(OPENSSL_IS_BORINGSSL)
  1571. /* From boringssl/src/include/openssl/mem.h:
  1572. *
  1573. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1574. * However, that was written in a time before Valgrind and ASAN. Since we now
  1575. * have those tools, the OpenSSL allocation functions are simply macros around
  1576. * the standard memory functions.
  1577. *
  1578. * #define OPENSSL_free free */
  1579. #define free free
  1580. // disable for boringssl
  1581. #define CONF_modules_unload(a) ((void)0)
  1582. #define ENGINE_cleanup() ((void)0)
  1583. #endif
  1584. /* If OpenSSL headers are included, automatically select the API version */
  1585. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1586. #if !defined(OPENSSL_API_3_0)
  1587. #define OPENSSL_API_3_0
  1588. #endif
  1589. #define OPENSSL_REMOVE_THREAD_STATE()
  1590. #else
  1591. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1592. #if !defined(OPENSSL_API_1_1)
  1593. #define OPENSSL_API_1_1
  1594. #endif
  1595. #define OPENSSL_REMOVE_THREAD_STATE()
  1596. #else
  1597. #if !defined(OPENSSL_API_1_0)
  1598. #define OPENSSL_API_1_0
  1599. #endif
  1600. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1601. #endif
  1602. #endif
  1603. #else
  1604. /* SSL loaded dynamically from DLL / shared object */
  1605. /* Add all prototypes here, to be independent from OpenSSL source
  1606. * installation. */
  1607. #include "openssl_dl.inl"
  1608. #endif /* Various SSL bindings */
  1609. #if !defined(NO_CACHING)
  1610. static const char month_names[][4] = {"Jan",
  1611. "Feb",
  1612. "Mar",
  1613. "Apr",
  1614. "May",
  1615. "Jun",
  1616. "Jul",
  1617. "Aug",
  1618. "Sep",
  1619. "Oct",
  1620. "Nov",
  1621. "Dec"};
  1622. #endif /* !NO_CACHING */
  1623. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1624. * the union u. */
  1625. union usa {
  1626. struct sockaddr sa;
  1627. struct sockaddr_in sin;
  1628. #if defined(USE_IPV6)
  1629. struct sockaddr_in6 sin6;
  1630. #endif
  1631. #if defined(USE_X_DOM_SOCKET)
  1632. struct sockaddr_un sun;
  1633. #endif
  1634. };
  1635. #if defined(USE_X_DOM_SOCKET)
  1636. static unsigned short
  1637. USA_IN_PORT_UNSAFE(union usa *s)
  1638. {
  1639. if (s->sa.sa_family == AF_INET)
  1640. return s->sin.sin_port;
  1641. #if defined(USE_IPV6)
  1642. if (s->sa.sa_family == AF_INET6)
  1643. return s->sin6.sin6_port;
  1644. #endif
  1645. return 0;
  1646. }
  1647. #endif
  1648. #if defined(USE_IPV6)
  1649. #define USA_IN_PORT_UNSAFE(s) \
  1650. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1651. #else
  1652. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1653. #endif
  1654. /* Describes a string (chunk of memory). */
  1655. struct vec {
  1656. const char *ptr;
  1657. size_t len;
  1658. };
  1659. struct mg_file_stat {
  1660. /* File properties filled by mg_stat: */
  1661. uint64_t size;
  1662. time_t last_modified;
  1663. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1664. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1665. * case we need a "Content-Eencoding: gzip" header */
  1666. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1667. };
  1668. struct mg_file_access {
  1669. /* File properties filled by mg_fopen: */
  1670. FILE *fp;
  1671. };
  1672. struct mg_file {
  1673. struct mg_file_stat stat;
  1674. struct mg_file_access access;
  1675. };
  1676. #define STRUCT_FILE_INITIALIZER \
  1677. { \
  1678. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1679. { \
  1680. (FILE *)NULL \
  1681. } \
  1682. }
  1683. /* Describes listening socket, or socket which was accept()-ed by the master
  1684. * thread and queued for future handling by the worker thread. */
  1685. struct socket {
  1686. SOCKET sock; /* Listening socket */
  1687. union usa lsa; /* Local socket address */
  1688. union usa rsa; /* Remote socket address */
  1689. unsigned char is_ssl; /* Is port SSL-ed */
  1690. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1691. * port */
  1692. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1693. };
  1694. /* Enum const for all options must be in sync with
  1695. * static struct mg_option config_options[]
  1696. * This is tested in the unit test (test/private.c)
  1697. * "Private Config Options"
  1698. */
  1699. enum {
  1700. /* Once for each server */
  1701. LISTENING_PORTS,
  1702. NUM_THREADS,
  1703. RUN_AS_USER,
  1704. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1705. * socket option typedef TCP_NODELAY. */
  1706. MAX_REQUEST_SIZE,
  1707. LINGER_TIMEOUT,
  1708. CONNECTION_QUEUE_SIZE,
  1709. LISTEN_BACKLOG_SIZE,
  1710. #if defined(__linux__)
  1711. ALLOW_SENDFILE_CALL,
  1712. #endif
  1713. #if defined(_WIN32)
  1714. CASE_SENSITIVE_FILES,
  1715. #endif
  1716. THROTTLE,
  1717. ENABLE_KEEP_ALIVE,
  1718. REQUEST_TIMEOUT,
  1719. KEEP_ALIVE_TIMEOUT,
  1720. #if defined(USE_WEBSOCKET)
  1721. WEBSOCKET_TIMEOUT,
  1722. ENABLE_WEBSOCKET_PING_PONG,
  1723. #endif
  1724. DECODE_URL,
  1725. DECODE_QUERY_STRING,
  1726. #if defined(USE_LUA)
  1727. LUA_BACKGROUND_SCRIPT,
  1728. LUA_BACKGROUND_SCRIPT_PARAMS,
  1729. #endif
  1730. #if defined(USE_HTTP2)
  1731. ENABLE_HTTP2,
  1732. #endif
  1733. /* Once for each domain */
  1734. DOCUMENT_ROOT,
  1735. ACCESS_LOG_FILE,
  1736. ERROR_LOG_FILE,
  1737. CGI_EXTENSIONS,
  1738. CGI_ENVIRONMENT,
  1739. CGI_INTERPRETER,
  1740. CGI_INTERPRETER_ARGS,
  1741. #if defined(USE_TIMERS)
  1742. CGI_TIMEOUT,
  1743. #endif
  1744. CGI_BUFFERING,
  1745. CGI2_EXTENSIONS,
  1746. CGI2_ENVIRONMENT,
  1747. CGI2_INTERPRETER,
  1748. CGI2_INTERPRETER_ARGS,
  1749. #if defined(USE_TIMERS)
  1750. CGI2_TIMEOUT,
  1751. #endif
  1752. CGI2_BUFFERING,
  1753. #if defined(USE_4_CGI)
  1754. CGI3_EXTENSIONS,
  1755. CGI3_ENVIRONMENT,
  1756. CGI3_INTERPRETER,
  1757. CGI3_INTERPRETER_ARGS,
  1758. #if defined(USE_TIMERS)
  1759. CGI3_TIMEOUT,
  1760. #endif
  1761. CGI3_BUFFERING,
  1762. CGI4_EXTENSIONS,
  1763. CGI4_ENVIRONMENT,
  1764. CGI4_INTERPRETER,
  1765. CGI4_INTERPRETER_ARGS,
  1766. #if defined(USE_TIMERS)
  1767. CGI4_TIMEOUT,
  1768. #endif
  1769. CGI4_BUFFERING,
  1770. #endif
  1771. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1772. PROTECT_URI,
  1773. AUTHENTICATION_DOMAIN,
  1774. ENABLE_AUTH_DOMAIN_CHECK,
  1775. SSI_EXTENSIONS,
  1776. ENABLE_DIRECTORY_LISTING,
  1777. ENABLE_WEBDAV,
  1778. GLOBAL_PASSWORDS_FILE,
  1779. INDEX_FILES,
  1780. ACCESS_CONTROL_LIST,
  1781. EXTRA_MIME_TYPES,
  1782. SSL_CERTIFICATE,
  1783. SSL_CERTIFICATE_CHAIN,
  1784. URL_REWRITE_PATTERN,
  1785. HIDE_FILES,
  1786. SSL_DO_VERIFY_PEER,
  1787. SSL_CACHE_TIMEOUT,
  1788. SSL_CA_PATH,
  1789. SSL_CA_FILE,
  1790. SSL_VERIFY_DEPTH,
  1791. SSL_DEFAULT_VERIFY_PATHS,
  1792. SSL_CIPHER_LIST,
  1793. SSL_PROTOCOL_VERSION,
  1794. SSL_SHORT_TRUST,
  1795. #if defined(USE_LUA)
  1796. LUA_PRELOAD_FILE,
  1797. LUA_SCRIPT_EXTENSIONS,
  1798. LUA_SERVER_PAGE_EXTENSIONS,
  1799. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1800. LUA_DEBUG_PARAMS,
  1801. #endif
  1802. #endif
  1803. #if defined(USE_DUKTAPE)
  1804. DUKTAPE_SCRIPT_EXTENSIONS,
  1805. #endif
  1806. #if defined(USE_WEBSOCKET)
  1807. WEBSOCKET_ROOT,
  1808. #endif
  1809. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1810. LUA_WEBSOCKET_EXTENSIONS,
  1811. #endif
  1812. ACCESS_CONTROL_ALLOW_ORIGIN,
  1813. ACCESS_CONTROL_ALLOW_METHODS,
  1814. ACCESS_CONTROL_ALLOW_HEADERS,
  1815. ERROR_PAGES,
  1816. #if !defined(NO_CACHING)
  1817. STATIC_FILE_MAX_AGE,
  1818. STATIC_FILE_CACHE_CONTROL,
  1819. #endif
  1820. #if !defined(NO_SSL)
  1821. STRICT_HTTPS_MAX_AGE,
  1822. #endif
  1823. ADDITIONAL_HEADER,
  1824. ALLOW_INDEX_SCRIPT_SUB_RES,
  1825. NUM_OPTIONS
  1826. };
  1827. /* Config option name, config types, default value.
  1828. * Must be in the same order as the enum const above.
  1829. */
  1830. static const struct mg_option config_options[] = {
  1831. /* Once for each server */
  1832. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1833. {"num_threads", MG_CONFIG_TYPE_NUMBER, "4"},
  1834. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1835. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1836. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1837. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1838. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1839. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1840. #if defined(__linux__)
  1841. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1842. #endif
  1843. #if defined(_WIN32)
  1844. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1845. #endif
  1846. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1847. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1848. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1849. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1850. #if defined(USE_WEBSOCKET)
  1851. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1852. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1853. #endif
  1854. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1855. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1856. #if defined(USE_LUA)
  1857. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1858. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1859. #endif
  1860. #if defined(USE_HTTP2)
  1861. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1862. #endif
  1863. /* Once for each domain */
  1864. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1865. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1866. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1867. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1868. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1869. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1870. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1871. #if defined(USE_TIMERS)
  1872. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1873. #endif
  1874. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1875. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1876. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1877. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1878. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1879. #if defined(USE_TIMERS)
  1880. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1881. #endif
  1882. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1883. #if defined(USE_4_CGI)
  1884. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1885. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1886. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1887. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1888. #if defined(USE_TIMERS)
  1889. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1890. #endif
  1891. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1892. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1893. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1894. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1895. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1896. #if defined(USE_TIMERS)
  1897. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1898. #endif
  1899. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1900. #endif
  1901. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1902. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1903. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1904. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1905. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1906. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1907. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1908. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1909. {"index_files",
  1910. MG_CONFIG_TYPE_STRING_LIST,
  1911. #if defined(USE_LUA)
  1912. "index.xhtml,index.html,index.htm,"
  1913. "index.lp,index.lsp,index.lua,index.cgi,"
  1914. "index.shtml,index.php"},
  1915. #else
  1916. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1917. #endif
  1918. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1919. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1920. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1921. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1922. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1923. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1924. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1925. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1926. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1927. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1928. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1929. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1930. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1931. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1932. * as a minimum in 2020 */
  1933. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1934. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1935. #if defined(USE_LUA)
  1936. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1937. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1938. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1939. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1940. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1941. #endif
  1942. #endif
  1943. #if defined(USE_DUKTAPE)
  1944. /* The support for duktape is still in alpha version state.
  1945. * The name of this config option might change. */
  1946. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1947. #endif
  1948. #if defined(USE_WEBSOCKET)
  1949. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1950. #endif
  1951. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1952. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1953. #endif
  1954. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1955. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1956. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1957. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1958. #if !defined(NO_CACHING)
  1959. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1960. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1961. #endif
  1962. #if !defined(NO_SSL)
  1963. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1964. #endif
  1965. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1966. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1967. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1968. /* Check if the config_options and the corresponding enum have compatible
  1969. * sizes. */
  1970. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1971. == (NUM_OPTIONS + 1),
  1972. "config_options and enum not sync");
  1973. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1974. struct mg_handler_info {
  1975. /* Name/Pattern of the URI. */
  1976. char *uri;
  1977. size_t uri_len;
  1978. /* handler type */
  1979. int handler_type;
  1980. /* Handler for http/https or requests. */
  1981. mg_request_handler handler;
  1982. unsigned int refcount;
  1983. int removing;
  1984. /* Handler for ws/wss (websocket) requests. */
  1985. mg_websocket_connect_handler connect_handler;
  1986. mg_websocket_ready_handler ready_handler;
  1987. mg_websocket_data_handler data_handler;
  1988. mg_websocket_close_handler close_handler;
  1989. /* accepted subprotocols for ws/wss requests. */
  1990. struct mg_websocket_subprotocols *subprotocols;
  1991. /* Handler for authorization requests */
  1992. mg_authorization_handler auth_handler;
  1993. /* User supplied argument for the handler function. */
  1994. void *cbdata;
  1995. /* next handler in a linked list */
  1996. struct mg_handler_info *next;
  1997. };
  1998. enum {
  1999. CONTEXT_INVALID,
  2000. CONTEXT_SERVER,
  2001. CONTEXT_HTTP_CLIENT,
  2002. CONTEXT_WS_CLIENT
  2003. };
  2004. struct mg_domain_context {
  2005. SSL_CTX *ssl_ctx; /* SSL context */
  2006. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2007. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2008. int64_t ssl_cert_last_mtime;
  2009. /* Server nonce */
  2010. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2011. unsigned long nonce_count; /* Used nonces, used for authentication */
  2012. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2013. /* linked list of shared lua websockets */
  2014. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2015. #endif
  2016. /* Linked list of domains */
  2017. struct mg_domain_context *next;
  2018. };
  2019. /* Stop flag can be "volatile" or require a lock.
  2020. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2021. * states a read operation for int is always atomic. */
  2022. #if defined(STOP_FLAG_NEEDS_LOCK)
  2023. typedef ptrdiff_t volatile stop_flag_t;
  2024. static int
  2025. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  2026. {
  2027. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  2028. return (sf == 0);
  2029. }
  2030. static int
  2031. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2032. {
  2033. stop_flag_t sf = mg_atomic_add(f, 0);
  2034. return (sf == 2);
  2035. }
  2036. static void
  2037. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2038. {
  2039. stop_flag_t sf;
  2040. do {
  2041. sf = mg_atomic_compare_and_swap(f, *f, v);
  2042. } while (sf != v);
  2043. }
  2044. #else /* STOP_FLAG_NEEDS_LOCK */
  2045. typedef int volatile stop_flag_t;
  2046. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2047. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2048. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2049. #endif /* STOP_FLAG_NEEDS_LOCK */
  2050. #if !defined(NUM_WEBDAV_LOCKS)
  2051. #define NUM_WEBDAV_LOCKS 10
  2052. #endif
  2053. #if !defined(LOCK_DURATION_S)
  2054. #define LOCK_DURATION_S 60
  2055. #endif
  2056. struct twebdav_lock {
  2057. uint64_t locktime;
  2058. char token[33];
  2059. char path[UTF8_PATH_MAX * 2];
  2060. char user[UTF8_PATH_MAX * 2];
  2061. };
  2062. struct mg_context {
  2063. /* Part 1 - Physical context:
  2064. * This holds threads, ports, timeouts, ...
  2065. * set for the entire server, independent from the
  2066. * addressed hostname.
  2067. */
  2068. /* Connection related */
  2069. int context_type; /* See CONTEXT_* above */
  2070. struct socket *listening_sockets;
  2071. struct mg_pollfd *listening_socket_fds;
  2072. unsigned int num_listening_sockets;
  2073. struct mg_connection *worker_connections; /* The connection struct, pre-
  2074. * allocated for each worker */
  2075. #if defined(USE_SERVER_STATS)
  2076. volatile ptrdiff_t active_connections;
  2077. volatile ptrdiff_t max_active_connections;
  2078. volatile ptrdiff_t total_connections;
  2079. volatile ptrdiff_t total_requests;
  2080. volatile int64_t total_data_read;
  2081. volatile int64_t total_data_written;
  2082. #endif
  2083. /* Thread related */
  2084. stop_flag_t stop_flag; /* Should we stop event loop */
  2085. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2086. cw_thread_handle_t masterthreadid; /* The master thread ID */
  2087. unsigned int
  2088. cfg_worker_threads; /* The number of configured worker threads. */
  2089. cw_thread_handle_t *worker_threadids; /* The worker thread IDs */
  2090. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2091. /* Connection to thread dispatching */
  2092. #if defined(ALTERNATIVE_QUEUE)
  2093. struct socket *client_socks;
  2094. void **client_wait_events;
  2095. #else
  2096. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2097. worker thread */
  2098. volatile int sq_head; /* Head of the socket queue */
  2099. volatile int sq_tail; /* Tail of the socket queue */
  2100. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2101. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2102. volatile int sq_blocked; /* Status information: sq is full */
  2103. int sq_size; /* No of elements in socket queue */
  2104. #if defined(USE_SERVER_STATS)
  2105. int sq_max_fill;
  2106. #endif /* USE_SERVER_STATS */
  2107. #endif /* ALTERNATIVE_QUEUE */
  2108. /* Memory related */
  2109. unsigned int max_request_size; /* The max request size */
  2110. #if defined(USE_SERVER_STATS)
  2111. struct mg_memory_stat ctx_memory;
  2112. #endif
  2113. /* WebDAV lock structures */
  2114. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2115. /* Operating system related */
  2116. char *systemName; /* What operating system is running */
  2117. time_t start_time; /* Server start time, used for authentication
  2118. * and for diagnstics. */
  2119. #if defined(USE_TIMERS)
  2120. struct ttimers *timers;
  2121. #endif
  2122. /* Lua specific: Background operations and shared websockets */
  2123. #if defined(USE_LUA)
  2124. void *lua_background_state; /* lua_State (here as void *) */
  2125. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2126. int lua_bg_log_available; /* Use Lua background state for access log */
  2127. #endif
  2128. /* Server nonce */
  2129. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2130. * ssl_cert_last_mtime, nonce_count, and
  2131. * next (linked list) */
  2132. /* Server callbacks */
  2133. struct mg_callbacks callbacks; /* User-defined callback function */
  2134. void *user_data; /* User-defined data */
  2135. /* Part 2 - Logical domain:
  2136. * This holds hostname, TLS certificate, document root, ...
  2137. * set for a domain hosted at the server.
  2138. * There may be multiple domains hosted at one physical server.
  2139. * The default domain "dd" is the first element of a list of
  2140. * domains.
  2141. */
  2142. struct mg_domain_context dd; /* default domain */
  2143. };
  2144. #if defined(USE_SERVER_STATS)
  2145. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2146. static struct mg_memory_stat *
  2147. get_memory_stat(struct mg_context *ctx)
  2148. {
  2149. if (ctx) {
  2150. return &(ctx->ctx_memory);
  2151. }
  2152. return &mg_common_memory;
  2153. }
  2154. #endif
  2155. enum {
  2156. CONNECTION_TYPE_INVALID = 0,
  2157. CONNECTION_TYPE_REQUEST = 1,
  2158. CONNECTION_TYPE_RESPONSE = 2
  2159. };
  2160. enum {
  2161. PROTOCOL_TYPE_HTTP1 = 0,
  2162. PROTOCOL_TYPE_WEBSOCKET = 1,
  2163. PROTOCOL_TYPE_HTTP2 = 2
  2164. };
  2165. #if defined(USE_HTTP2)
  2166. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2167. #define HTTP2_DYN_TABLE_SIZE (256)
  2168. #endif
  2169. struct mg_http2_connection {
  2170. uint32_t stream_id;
  2171. uint32_t dyn_table_size;
  2172. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2173. };
  2174. #endif
  2175. struct mg_connection {
  2176. int connection_type; /* see CONNECTION_TYPE_* above */
  2177. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2178. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2179. fully sent */
  2180. #if defined(USE_HTTP2)
  2181. struct mg_http2_connection http2;
  2182. #endif
  2183. struct mg_request_info request_info;
  2184. struct mg_response_info response_info;
  2185. struct mg_context *phys_ctx;
  2186. struct mg_domain_context *dom_ctx;
  2187. #if defined(USE_SERVER_STATS)
  2188. int conn_state; /* 0 = undef, numerical value may change in different
  2189. * versions. For the current definition, see
  2190. * mg_get_connection_info_impl */
  2191. #endif
  2192. SSL *ssl; /* SSL descriptor */
  2193. struct socket client; /* Connected client */
  2194. time_t conn_birth_time; /* Time (wall clock) when connection was
  2195. * established */
  2196. #if defined(USE_SERVER_STATS)
  2197. time_t conn_close_time; /* Time (wall clock) when connection was
  2198. * closed (or 0 if still open) */
  2199. double processing_time; /* Procesing time for one request. */
  2200. #endif
  2201. struct timespec req_time; /* Time (since system start) when the request
  2202. * was received */
  2203. int64_t num_bytes_sent; /* Total bytes sent to client */
  2204. int64_t content_len; /* How many bytes of content can be read
  2205. * !is_chunked: Content-Length header value
  2206. * or -1 (until connection closed,
  2207. * not allowed for a request)
  2208. * is_chunked: >= 0, appended gradually
  2209. */
  2210. int64_t consumed_content; /* How many bytes of content have been read */
  2211. int is_chunked; /* Transfer-Encoding is chunked:
  2212. * 0 = not chunked,
  2213. * 1 = chunked, not yet, or some data read,
  2214. * 2 = chunked, has error,
  2215. * 3 = chunked, all data read except trailer,
  2216. * 4 = chunked, all data read
  2217. */
  2218. char *buf; /* Buffer for received data */
  2219. char *path_info; /* PATH_INFO part of the URL */
  2220. int must_close; /* 1 if connection must be closed */
  2221. int accept_gzip; /* 1 if gzip encoding is accepted */
  2222. int in_error_handler; /* 1 if in handler for user defined error
  2223. * pages */
  2224. #if defined(USE_WEBSOCKET)
  2225. int in_websocket_handling; /* 1 if in read_websocket */
  2226. #endif
  2227. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2228. && defined(MG_EXPERIMENTAL_INTERFACES)
  2229. /* Parameters for websocket data compression according to rfc7692 */
  2230. int websocket_deflate_server_max_windows_bits;
  2231. int websocket_deflate_client_max_windows_bits;
  2232. int websocket_deflate_server_no_context_takeover;
  2233. int websocket_deflate_client_no_context_takeover;
  2234. int websocket_deflate_initialized;
  2235. int websocket_deflate_flush;
  2236. z_stream websocket_deflate_state;
  2237. z_stream websocket_inflate_state;
  2238. #endif
  2239. int handled_requests; /* Number of requests handled by this connection
  2240. */
  2241. int buf_size; /* Buffer size */
  2242. int request_len; /* Size of the request + headers in a buffer */
  2243. int data_len; /* Total size of data in a buffer */
  2244. int status_code; /* HTTP reply status code, e.g. 200 */
  2245. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2246. * throttle */
  2247. time_t last_throttle_time; /* Last time throttled data was sent */
  2248. int last_throttle_bytes; /* Bytes sent this second */
  2249. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2250. * atomic transmissions for websockets */
  2251. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2252. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2253. #endif
  2254. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2255. * for quick access */
  2256. };
  2257. /* Directory entry */
  2258. struct de {
  2259. char *file_name;
  2260. struct mg_file_stat file;
  2261. };
  2262. #define mg_cry_internal(conn, fmt, ...) \
  2263. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2264. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2265. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2266. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2267. struct mg_context *ctx,
  2268. const char *func,
  2269. unsigned line,
  2270. const char *fmt,
  2271. ...) PRINTF_ARGS(5, 6);
  2272. #if !defined(NO_THREAD_NAME)
  2273. #if defined(_WIN32) && defined(_MSC_VER)
  2274. /* Set the thread name for debugging purposes in Visual Studio
  2275. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2276. */
  2277. #pragma pack(push, 8)
  2278. typedef struct tagTHREADNAME_INFO {
  2279. DWORD dwType; /* Must be 0x1000. */
  2280. LPCSTR szName; /* Pointer to name (in user addr space). */
  2281. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2282. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2283. } THREADNAME_INFO;
  2284. #pragma pack(pop)
  2285. #elif defined(__linux__)
  2286. #include <sys/prctl.h>
  2287. #include <sys/sendfile.h>
  2288. #if defined(ALTERNATIVE_QUEUE)
  2289. #include <sys/eventfd.h>
  2290. #endif /* ALTERNATIVE_QUEUE */
  2291. #if defined(ALTERNATIVE_QUEUE)
  2292. static void *
  2293. event_create(void)
  2294. {
  2295. int evhdl = eventfd(0, EFD_CLOEXEC);
  2296. int *ret;
  2297. if (evhdl == -1) {
  2298. /* Linux uses -1 on error, Windows NULL. */
  2299. /* However, Linux does not return 0 on success either. */
  2300. return 0;
  2301. }
  2302. ret = (int *)mg_malloc(sizeof(int));
  2303. if (ret) {
  2304. *ret = evhdl;
  2305. } else {
  2306. (void)close(evhdl);
  2307. }
  2308. return (void *)ret;
  2309. }
  2310. static int
  2311. event_wait(void *eventhdl)
  2312. {
  2313. uint64_t u;
  2314. int evhdl, s;
  2315. if (!eventhdl) {
  2316. /* error */
  2317. return 0;
  2318. }
  2319. evhdl = *(int *)eventhdl;
  2320. s = (int)read(evhdl, &u, sizeof(u));
  2321. if (s != sizeof(u)) {
  2322. /* error */
  2323. return 0;
  2324. }
  2325. (void)u; /* the value is not required */
  2326. return 1;
  2327. }
  2328. static int
  2329. event_signal(void *eventhdl)
  2330. {
  2331. uint64_t u = 1;
  2332. int evhdl, s;
  2333. if (!eventhdl) {
  2334. /* error */
  2335. return 0;
  2336. }
  2337. evhdl = *(int *)eventhdl;
  2338. s = (int)write(evhdl, &u, sizeof(u));
  2339. if (s != sizeof(u)) {
  2340. /* error */
  2341. return 0;
  2342. }
  2343. return 1;
  2344. }
  2345. static void
  2346. event_destroy(void *eventhdl)
  2347. {
  2348. int evhdl;
  2349. if (!eventhdl) {
  2350. /* error */
  2351. return;
  2352. }
  2353. evhdl = *(int *)eventhdl;
  2354. close(evhdl);
  2355. mg_free(eventhdl);
  2356. }
  2357. #endif
  2358. #endif
  2359. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2360. struct posix_event {
  2361. pthread_mutex_t mutex;
  2362. pthread_cond_t cond;
  2363. int signaled;
  2364. };
  2365. static void *
  2366. event_create(void)
  2367. {
  2368. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2369. if (ret == 0) {
  2370. /* out of memory */
  2371. return 0;
  2372. }
  2373. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2374. /* pthread mutex not available */
  2375. mg_free(ret);
  2376. return 0;
  2377. }
  2378. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2379. /* pthread cond not available */
  2380. pthread_mutex_destroy(&(ret->mutex));
  2381. mg_free(ret);
  2382. return 0;
  2383. }
  2384. ret->signaled = 0;
  2385. return (void *)ret;
  2386. }
  2387. static int
  2388. event_wait(void *eventhdl)
  2389. {
  2390. struct posix_event *ev = (struct posix_event *)eventhdl;
  2391. pthread_mutex_lock(&(ev->mutex));
  2392. while (!ev->signaled) {
  2393. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2394. }
  2395. ev->signaled = 0;
  2396. pthread_mutex_unlock(&(ev->mutex));
  2397. return 1;
  2398. }
  2399. static int
  2400. event_signal(void *eventhdl)
  2401. {
  2402. struct posix_event *ev = (struct posix_event *)eventhdl;
  2403. pthread_mutex_lock(&(ev->mutex));
  2404. pthread_cond_signal(&(ev->cond));
  2405. ev->signaled = 1;
  2406. pthread_mutex_unlock(&(ev->mutex));
  2407. return 1;
  2408. }
  2409. static void
  2410. event_destroy(void *eventhdl)
  2411. {
  2412. struct posix_event *ev = (struct posix_event *)eventhdl;
  2413. pthread_cond_destroy(&(ev->cond));
  2414. pthread_mutex_destroy(&(ev->mutex));
  2415. mg_free(ev);
  2416. }
  2417. #endif
  2418. static void
  2419. mg_set_thread_name(const char *name)
  2420. {
  2421. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2422. mg_snprintf(
  2423. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2424. #if defined(_WIN32)
  2425. #if defined(_MSC_VER)
  2426. /* Windows and Visual Studio Compiler */
  2427. __try {
  2428. THREADNAME_INFO info;
  2429. info.dwType = 0x1000;
  2430. info.szName = threadName;
  2431. info.dwThreadID = ~0U;
  2432. info.dwFlags = 0;
  2433. RaiseException(0x406D1388,
  2434. 0,
  2435. sizeof(info) / sizeof(ULONG_PTR),
  2436. (ULONG_PTR *)&info);
  2437. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2438. }
  2439. #elif defined(__MINGW32__)
  2440. /* No option known to set thread name for MinGW known */
  2441. #endif
  2442. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2443. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2444. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2445. #if defined(__MACH__) && defined(__APPLE__)
  2446. /* OS X only current thread name can be changed */
  2447. (void)pthread_setname_np(threadName);
  2448. #else
  2449. (void)pthread_setname_np(pthread_self(), threadName);
  2450. #endif
  2451. #elif defined(__linux__)
  2452. /* On Linux we can use the prctl function.
  2453. * When building for Linux Standard Base (LSB) use
  2454. * NO_THREAD_NAME. However, thread names are a big
  2455. * help for debugging, so the stadard is to set them.
  2456. */
  2457. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2458. #endif
  2459. }
  2460. #else /* !defined(NO_THREAD_NAME) */
  2461. static void
  2462. mg_set_thread_name(const char *threadName)
  2463. {
  2464. }
  2465. #endif
  2466. CIVETWEB_API const struct mg_option *
  2467. mg_get_valid_options(void)
  2468. {
  2469. return config_options;
  2470. }
  2471. /* Do not open file (unused) */
  2472. #define MG_FOPEN_MODE_NONE (0)
  2473. /* Open file for read only access */
  2474. #define MG_FOPEN_MODE_READ (1)
  2475. /* Open file for writing, create and overwrite */
  2476. #define MG_FOPEN_MODE_WRITE (2)
  2477. /* Open file for writing, create and append */
  2478. #define MG_FOPEN_MODE_APPEND (4)
  2479. static int
  2480. is_file_opened(const struct mg_file_access *fileacc)
  2481. {
  2482. if (!fileacc) {
  2483. return 0;
  2484. }
  2485. return (fileacc->fp != NULL);
  2486. }
  2487. #if !defined(NO_FILESYSTEMS)
  2488. static int mg_stat(const struct mg_connection *conn,
  2489. const char *path,
  2490. struct mg_file_stat *filep);
  2491. /* Reject files with special characters (for Windows) */
  2492. static int
  2493. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2494. {
  2495. const uint8_t *c = (const uint8_t *)path;
  2496. (void)conn; /* not used */
  2497. if ((c == NULL) || (c[0] == 0)) {
  2498. /* Null pointer or empty path --> suspicious */
  2499. return 1;
  2500. }
  2501. #if defined(_WIN32)
  2502. while (*c) {
  2503. if (*c < 32) {
  2504. /* Control character */
  2505. return 1;
  2506. }
  2507. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2508. /* stdin/stdout redirection character */
  2509. return 1;
  2510. }
  2511. if ((*c == '*') || (*c == '?')) {
  2512. /* Wildcard character */
  2513. return 1;
  2514. }
  2515. if (*c == '"') {
  2516. /* Windows quotation */
  2517. return 1;
  2518. }
  2519. c++;
  2520. }
  2521. #endif
  2522. /* Nothing suspicious found */
  2523. return 0;
  2524. }
  2525. /* mg_fopen will open a file either in memory or on the disk.
  2526. * The input parameter path is a string in UTF-8 encoding.
  2527. * The input parameter mode is MG_FOPEN_MODE_*
  2528. * On success, fp will be set in the output struct mg_file.
  2529. * All status members will also be set.
  2530. * The function returns 1 on success, 0 on error. */
  2531. static int
  2532. mg_fopen(const struct mg_connection *conn,
  2533. const char *path,
  2534. int mode,
  2535. struct mg_file *filep)
  2536. {
  2537. int found;
  2538. if (!filep) {
  2539. return 0;
  2540. }
  2541. filep->access.fp = NULL;
  2542. if (mg_path_suspicious(conn, path)) {
  2543. return 0;
  2544. }
  2545. /* filep is initialized in mg_stat: all fields with memset to,
  2546. * some fields like size and modification date with values */
  2547. found = mg_stat(conn, path, &(filep->stat));
  2548. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2549. /* file does not exist and will not be created */
  2550. return 0;
  2551. }
  2552. #if defined(_WIN32)
  2553. {
  2554. wchar_t wbuf[UTF16_PATH_MAX];
  2555. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2556. switch (mode) {
  2557. case MG_FOPEN_MODE_READ:
  2558. filep->access.fp = _wfopen(wbuf, L"rb");
  2559. break;
  2560. case MG_FOPEN_MODE_WRITE:
  2561. filep->access.fp = _wfopen(wbuf, L"wb");
  2562. break;
  2563. case MG_FOPEN_MODE_APPEND:
  2564. filep->access.fp = _wfopen(wbuf, L"ab");
  2565. break;
  2566. }
  2567. }
  2568. #else
  2569. /* Linux et al already use unicode. No need to convert. */
  2570. switch (mode) {
  2571. case MG_FOPEN_MODE_READ:
  2572. filep->access.fp = fopen(path, "r");
  2573. break;
  2574. case MG_FOPEN_MODE_WRITE:
  2575. filep->access.fp = fopen(path, "w");
  2576. break;
  2577. case MG_FOPEN_MODE_APPEND:
  2578. filep->access.fp = fopen(path, "a");
  2579. break;
  2580. }
  2581. #endif
  2582. if (!found) {
  2583. /* File did not exist before fopen was called.
  2584. * Maybe it has been created now. Get stat info
  2585. * like creation time now. */
  2586. found = mg_stat(conn, path, &(filep->stat));
  2587. (void)found;
  2588. }
  2589. /* return OK if file is opened */
  2590. return (filep->access.fp != NULL);
  2591. }
  2592. /* return 0 on success, just like fclose */
  2593. static int
  2594. mg_fclose(struct mg_file_access *fileacc)
  2595. {
  2596. int ret = -1;
  2597. if (fileacc != NULL) {
  2598. if (fileacc->fp != NULL) {
  2599. ret = fclose(fileacc->fp);
  2600. }
  2601. /* reset all members of fileacc */
  2602. memset(fileacc, 0, sizeof(*fileacc));
  2603. }
  2604. return ret;
  2605. }
  2606. #endif /* NO_FILESYSTEMS */
  2607. static void
  2608. mg_strlcpy(char *dst, const char *src, size_t n)
  2609. {
  2610. for (; *src != '\0' && n > 1; n--) {
  2611. *dst++ = *src++;
  2612. }
  2613. *dst = '\0';
  2614. }
  2615. static int
  2616. lowercase(const char *s)
  2617. {
  2618. return tolower((unsigned char)*s);
  2619. }
  2620. CIVETWEB_API int
  2621. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2622. {
  2623. int diff = 0;
  2624. if (len > 0) {
  2625. do {
  2626. diff = lowercase(s1++) - lowercase(s2++);
  2627. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2628. }
  2629. return diff;
  2630. }
  2631. CIVETWEB_API int
  2632. mg_strcasecmp(const char *s1, const char *s2)
  2633. {
  2634. int diff;
  2635. do {
  2636. diff = lowercase(s1++) - lowercase(s2++);
  2637. } while (diff == 0 && s1[-1] != '\0');
  2638. return diff;
  2639. }
  2640. static char *
  2641. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2642. {
  2643. char *p;
  2644. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2645. * defined */
  2646. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2647. mg_strlcpy(p, ptr, len + 1);
  2648. }
  2649. return p;
  2650. }
  2651. static char *
  2652. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2653. {
  2654. return mg_strndup_ctx(str, strlen(str), ctx);
  2655. }
  2656. static char *
  2657. mg_strdup(const char *str)
  2658. {
  2659. return mg_strndup_ctx(str, strlen(str), NULL);
  2660. }
  2661. static const char *
  2662. mg_strcasestr(const char *big_str, const char *small_str)
  2663. {
  2664. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2665. if (big_len >= small_len) {
  2666. for (i = 0; i <= (big_len - small_len); i++) {
  2667. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2668. return big_str + i;
  2669. }
  2670. }
  2671. }
  2672. return NULL;
  2673. }
  2674. /* Return null terminated string of given maximum length.
  2675. * Report errors if length is exceeded. */
  2676. static void
  2677. mg_vsnprintf(const struct mg_connection *conn,
  2678. int *truncated,
  2679. char *buf,
  2680. size_t buflen,
  2681. const char *fmt,
  2682. va_list ap)
  2683. {
  2684. int n, ok;
  2685. if (buflen == 0) {
  2686. if (truncated) {
  2687. *truncated = 1;
  2688. }
  2689. return;
  2690. }
  2691. #if defined(__clang__)
  2692. #pragma clang diagnostic push
  2693. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2694. /* Using fmt as a non-literal is intended here, since it is mostly called
  2695. * indirectly by mg_snprintf */
  2696. #endif
  2697. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2698. ok = (n >= 0) && ((size_t)n < buflen);
  2699. #if defined(__clang__)
  2700. #pragma clang diagnostic pop
  2701. #endif
  2702. if (ok) {
  2703. if (truncated) {
  2704. *truncated = 0;
  2705. }
  2706. } else {
  2707. if (truncated) {
  2708. *truncated = 1;
  2709. }
  2710. mg_cry_internal(conn,
  2711. "truncating vsnprintf buffer: [%.*s]",
  2712. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2713. buf);
  2714. n = (int)buflen - 1;
  2715. }
  2716. buf[n] = '\0';
  2717. }
  2718. static void
  2719. mg_snprintf(const struct mg_connection *conn,
  2720. int *truncated,
  2721. char *buf,
  2722. size_t buflen,
  2723. const char *fmt,
  2724. ...)
  2725. {
  2726. va_list ap;
  2727. va_start(ap, fmt);
  2728. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2729. va_end(ap);
  2730. }
  2731. static int
  2732. get_option_index(const char *name)
  2733. {
  2734. int i;
  2735. for (i = 0; config_options[i].name != NULL; i++) {
  2736. if (strcmp(config_options[i].name, name) == 0) {
  2737. return i;
  2738. }
  2739. }
  2740. return -1;
  2741. }
  2742. CIVETWEB_API const char *
  2743. mg_get_option(const struct mg_context *ctx, const char *name)
  2744. {
  2745. int i;
  2746. if ((i = get_option_index(name)) == -1) {
  2747. return NULL;
  2748. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2749. return "";
  2750. } else {
  2751. return ctx->dd.config[i];
  2752. }
  2753. }
  2754. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2755. CIVETWEB_API struct mg_context *
  2756. mg_get_context(const struct mg_connection *conn)
  2757. {
  2758. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2759. }
  2760. CIVETWEB_API void *
  2761. mg_get_user_data(const struct mg_context *ctx)
  2762. {
  2763. return (ctx == NULL) ? NULL : ctx->user_data;
  2764. }
  2765. CIVETWEB_API void *
  2766. mg_get_user_context_data(const struct mg_connection *conn)
  2767. {
  2768. return mg_get_user_data(mg_get_context(conn));
  2769. }
  2770. CIVETWEB_API void *
  2771. mg_get_thread_pointer(const struct mg_connection *conn)
  2772. {
  2773. /* both methods should return the same pointer */
  2774. if (conn) {
  2775. /* quick access, in case conn is known */
  2776. return conn->tls_user_ptr;
  2777. } else {
  2778. /* otherwise get pointer from thread local storage (TLS) */
  2779. struct mg_workerTLS *tls =
  2780. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2781. return tls->user_ptr;
  2782. }
  2783. }
  2784. CIVETWEB_API void
  2785. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2786. {
  2787. if (const_conn != NULL) {
  2788. /* Const cast, since "const struct mg_connection *" does not mean
  2789. * the connection object is not modified. Here "const" is used,
  2790. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2791. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2792. conn->request_info.conn_data = data;
  2793. }
  2794. }
  2795. CIVETWEB_API void *
  2796. mg_get_user_connection_data(const struct mg_connection *conn)
  2797. {
  2798. if (conn != NULL) {
  2799. return conn->request_info.conn_data;
  2800. }
  2801. return NULL;
  2802. }
  2803. CIVETWEB_API int
  2804. mg_get_server_ports(const struct mg_context *ctx,
  2805. int size,
  2806. struct mg_server_port *ports)
  2807. {
  2808. int i, cnt = 0;
  2809. if (size <= 0) {
  2810. return -1;
  2811. }
  2812. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2813. if (!ctx) {
  2814. return -1;
  2815. }
  2816. if (!ctx->listening_sockets) {
  2817. return -1;
  2818. }
  2819. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2820. ports[cnt].port =
  2821. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2822. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2823. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2824. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2825. /* IPv4 */
  2826. ports[cnt].protocol = 1;
  2827. cnt++;
  2828. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2829. /* IPv6 */
  2830. ports[cnt].protocol = 3;
  2831. cnt++;
  2832. }
  2833. }
  2834. return cnt;
  2835. }
  2836. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2837. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2838. #endif
  2839. static void
  2840. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2841. {
  2842. buf[0] = '\0';
  2843. if (!usa) {
  2844. return;
  2845. }
  2846. if (usa->sa.sa_family == AF_INET) {
  2847. getnameinfo(&usa->sa,
  2848. sizeof(usa->sin),
  2849. buf,
  2850. (unsigned)len,
  2851. NULL,
  2852. 0,
  2853. NI_NUMERICHOST);
  2854. }
  2855. #if defined(USE_IPV6)
  2856. else if (usa->sa.sa_family == AF_INET6) {
  2857. getnameinfo(&usa->sa,
  2858. sizeof(usa->sin6),
  2859. buf,
  2860. (unsigned)len,
  2861. NULL,
  2862. 0,
  2863. NI_NUMERICHOST);
  2864. }
  2865. #endif
  2866. #if defined(USE_X_DOM_SOCKET)
  2867. else if (usa->sa.sa_family == AF_UNIX) {
  2868. /* TODO: Define a remote address for unix domain sockets.
  2869. * This code will always return "localhost", identical to http+tcp:
  2870. getnameinfo(&usa->sa,
  2871. sizeof(usa->sun),
  2872. buf,
  2873. (unsigned)len,
  2874. NULL,
  2875. 0,
  2876. NI_NUMERICHOST);
  2877. */
  2878. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2879. buf[len] = 0;
  2880. }
  2881. #endif
  2882. }
  2883. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2884. * included in all responses other than 100, 101, 5xx. */
  2885. static void
  2886. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2887. {
  2888. #if !defined(REENTRANT_TIME)
  2889. struct tm *tm;
  2890. tm = ((t != NULL) ? gmtime(t) : NULL);
  2891. if (tm != NULL) {
  2892. #else
  2893. struct tm _tm;
  2894. struct tm *tm = &_tm;
  2895. if (t != NULL) {
  2896. gmtime_r(t, tm);
  2897. #endif
  2898. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2899. } else {
  2900. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2901. buf[buf_len - 1] = '\0';
  2902. }
  2903. }
  2904. /* difftime for struct timespec. Return value is in seconds. */
  2905. static double
  2906. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2907. {
  2908. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2909. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2910. }
  2911. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2912. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2913. const char *func,
  2914. unsigned line,
  2915. const char *fmt,
  2916. va_list ap);
  2917. #include "external_mg_cry_internal_impl.inl"
  2918. #elif !defined(NO_FILESYSTEMS)
  2919. /* Print error message to the opened error log stream. */
  2920. static void
  2921. mg_cry_internal_impl(const struct mg_connection *conn,
  2922. const char *func,
  2923. unsigned line,
  2924. const char *fmt,
  2925. va_list ap)
  2926. {
  2927. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2928. struct mg_file fi;
  2929. time_t timestamp;
  2930. /* Unused, in the RELEASE build */
  2931. (void)func;
  2932. (void)line;
  2933. #if defined(GCC_DIAGNOSTIC)
  2934. #pragma GCC diagnostic push
  2935. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2936. #endif
  2937. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2938. #if defined(GCC_DIAGNOSTIC)
  2939. #pragma GCC diagnostic pop
  2940. #endif
  2941. buf[sizeof(buf) - 1] = 0;
  2942. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2943. if (!conn) {
  2944. puts(buf);
  2945. return;
  2946. }
  2947. /* Do not lock when getting the callback value, here and below.
  2948. * I suppose this is fine, since function cannot disappear in the
  2949. * same way string option can. */
  2950. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2951. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2952. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2953. if (mg_fopen(conn,
  2954. conn->dom_ctx->config[ERROR_LOG_FILE],
  2955. MG_FOPEN_MODE_APPEND,
  2956. &fi)
  2957. == 0) {
  2958. fi.access.fp = NULL;
  2959. }
  2960. } else {
  2961. fi.access.fp = NULL;
  2962. }
  2963. if (fi.access.fp != NULL) {
  2964. flockfile(fi.access.fp);
  2965. timestamp = time(NULL);
  2966. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2967. fprintf(fi.access.fp,
  2968. "[%010lu] [error] [client %s] ",
  2969. (unsigned long)timestamp,
  2970. src_addr);
  2971. if (conn->request_info.request_method != NULL) {
  2972. fprintf(fi.access.fp,
  2973. "%s %s: ",
  2974. conn->request_info.request_method,
  2975. conn->request_info.request_uri
  2976. ? conn->request_info.request_uri
  2977. : "");
  2978. }
  2979. fprintf(fi.access.fp, "%s", buf);
  2980. fputc('\n', fi.access.fp);
  2981. fflush(fi.access.fp);
  2982. funlockfile(fi.access.fp);
  2983. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2984. * mg_cry here anyway ;-) */
  2985. }
  2986. }
  2987. }
  2988. #else
  2989. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2990. #endif /* Externally provided function */
  2991. /* Construct fake connection structure. Used for logging, if connection
  2992. * is not applicable at the moment of logging. */
  2993. static struct mg_connection *
  2994. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2995. {
  2996. static const struct mg_connection conn_zero = {0};
  2997. *fc = conn_zero;
  2998. fc->phys_ctx = ctx;
  2999. fc->dom_ctx = &(ctx->dd);
  3000. return fc;
  3001. }
  3002. static void
  3003. mg_cry_internal_wrap(const struct mg_connection *conn,
  3004. struct mg_context *ctx,
  3005. const char *func,
  3006. unsigned line,
  3007. const char *fmt,
  3008. ...)
  3009. {
  3010. va_list ap;
  3011. va_start(ap, fmt);
  3012. if (!conn && ctx) {
  3013. struct mg_connection fc;
  3014. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3015. } else {
  3016. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3017. }
  3018. va_end(ap);
  3019. }
  3020. CIVETWEB_API void
  3021. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3022. {
  3023. va_list ap;
  3024. va_start(ap, fmt);
  3025. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3026. va_end(ap);
  3027. }
  3028. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3029. CIVETWEB_API const char *
  3030. mg_version(void)
  3031. {
  3032. return CIVETWEB_VERSION;
  3033. }
  3034. CIVETWEB_API const struct mg_request_info *
  3035. mg_get_request_info(const struct mg_connection *conn)
  3036. {
  3037. if (!conn) {
  3038. return NULL;
  3039. }
  3040. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3041. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3042. char txt[16];
  3043. struct mg_workerTLS *tls =
  3044. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3045. sprintf(txt, "%03i", conn->response_info.status_code);
  3046. if (strlen(txt) == 3) {
  3047. memcpy(tls->txtbuf, txt, 4);
  3048. } else {
  3049. strcpy(tls->txtbuf, "ERR");
  3050. }
  3051. ((struct mg_connection *)conn)->request_info.local_uri =
  3052. tls->txtbuf; /* use thread safe buffer */
  3053. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3054. tls->txtbuf; /* use the same thread safe buffer */
  3055. ((struct mg_connection *)conn)->request_info.request_uri =
  3056. tls->txtbuf; /* use the same thread safe buffer */
  3057. ((struct mg_connection *)conn)->request_info.num_headers =
  3058. conn->response_info.num_headers;
  3059. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3060. conn->response_info.http_headers,
  3061. sizeof(conn->response_info.http_headers));
  3062. } else
  3063. #endif
  3064. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3065. return NULL;
  3066. }
  3067. return &conn->request_info;
  3068. }
  3069. CIVETWEB_API const struct mg_response_info *
  3070. mg_get_response_info(const struct mg_connection *conn)
  3071. {
  3072. if (!conn) {
  3073. return NULL;
  3074. }
  3075. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3076. return NULL;
  3077. }
  3078. return &conn->response_info;
  3079. }
  3080. static const char *
  3081. get_proto_name(const struct mg_connection *conn)
  3082. {
  3083. #if defined(__clang__)
  3084. #pragma clang diagnostic push
  3085. #pragma clang diagnostic ignored "-Wunreachable-code"
  3086. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3087. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3088. * unreachable, but splitting into four different #ifdef clauses here is
  3089. * more complicated.
  3090. */
  3091. #endif
  3092. const struct mg_request_info *ri = &conn->request_info;
  3093. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3094. ? (ri->is_ssl ? "wss" : "ws")
  3095. : (ri->is_ssl ? "https" : "http"));
  3096. return proto;
  3097. #if defined(__clang__)
  3098. #pragma clang diagnostic pop
  3099. #endif
  3100. }
  3101. static int
  3102. mg_construct_local_link(const struct mg_connection *conn,
  3103. char *buf,
  3104. size_t buflen,
  3105. const char *define_proto,
  3106. int define_port,
  3107. const char *define_uri)
  3108. {
  3109. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3110. return -1;
  3111. } else {
  3112. int i, j;
  3113. int truncated = 0;
  3114. const struct mg_request_info *ri = &conn->request_info;
  3115. const char *proto =
  3116. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3117. const char *uri =
  3118. (define_uri != NULL)
  3119. ? define_uri
  3120. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3121. int port = (define_port > 0) ? define_port : ri->server_port;
  3122. int default_port = 80;
  3123. char *uri_encoded;
  3124. size_t uri_encoded_len;
  3125. if (uri == NULL) {
  3126. return -1;
  3127. }
  3128. uri_encoded_len = strlen(uri) * 3 + 1;
  3129. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3130. if (uri_encoded == NULL) {
  3131. return -1;
  3132. }
  3133. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3134. /* Directory separator should be preserved. */
  3135. for (i = j = 0; uri_encoded[i]; j++) {
  3136. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3137. uri_encoded[j] = '/';
  3138. i += 3;
  3139. } else {
  3140. uri_encoded[j] = uri_encoded[i++];
  3141. }
  3142. }
  3143. uri_encoded[j] = '\0';
  3144. #if defined(USE_X_DOM_SOCKET)
  3145. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3146. /* TODO: Define and document a link for UNIX domain sockets. */
  3147. /* There seems to be no official standard for this.
  3148. * Common uses seem to be "httpunix://", "http.unix://" or
  3149. * "http+unix://" as a protocol definition string, followed by
  3150. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3151. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3152. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3153. * "" (completely skipping the server name part). In any case, the
  3154. * last part is the server local path. */
  3155. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3156. mg_snprintf(conn,
  3157. &truncated,
  3158. buf,
  3159. buflen,
  3160. "%s.unix://%s%s",
  3161. proto,
  3162. server_name,
  3163. ri->local_uri);
  3164. default_port = 0;
  3165. mg_free(uri_encoded);
  3166. return 0;
  3167. }
  3168. #endif
  3169. if (define_proto) {
  3170. /* If we got a protocol name, use the default port accordingly. */
  3171. if ((0 == strcmp(define_proto, "https"))
  3172. || (0 == strcmp(define_proto, "wss"))) {
  3173. default_port = 443;
  3174. }
  3175. } else if (ri->is_ssl) {
  3176. /* If we did not get a protocol name, use TLS as default if it is
  3177. * already used. */
  3178. default_port = 443;
  3179. }
  3180. {
  3181. #if defined(USE_IPV6)
  3182. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3183. #endif
  3184. int auth_domain_check_enabled =
  3185. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3186. && (!mg_strcasecmp(
  3187. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3188. const char *server_domain =
  3189. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3190. char portstr[16];
  3191. char server_ip[48];
  3192. if (port != default_port) {
  3193. sprintf(portstr, ":%u", (unsigned)port);
  3194. } else {
  3195. portstr[0] = 0;
  3196. }
  3197. if (!auth_domain_check_enabled || !server_domain) {
  3198. sockaddr_to_string(server_ip,
  3199. sizeof(server_ip),
  3200. &conn->client.lsa);
  3201. server_domain = server_ip;
  3202. }
  3203. mg_snprintf(conn,
  3204. &truncated,
  3205. buf,
  3206. buflen,
  3207. #if defined(USE_IPV6)
  3208. "%s://%s%s%s%s%s",
  3209. proto,
  3210. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3211. server_domain,
  3212. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3213. #else
  3214. "%s://%s%s%s",
  3215. proto,
  3216. server_domain,
  3217. #endif
  3218. portstr,
  3219. uri_encoded);
  3220. mg_free(uri_encoded);
  3221. if (truncated) {
  3222. return -1;
  3223. }
  3224. return 0;
  3225. }
  3226. }
  3227. }
  3228. CIVETWEB_API int
  3229. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3230. {
  3231. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3232. }
  3233. /* Skip the characters until one of the delimiters characters found.
  3234. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3235. * Advance pointer to buffer to the next word. Return found 0-terminated
  3236. * word.
  3237. * Delimiters can be quoted with quotechar. */
  3238. static char *
  3239. skip_quoted(char **buf,
  3240. const char *delimiters,
  3241. const char *whitespace,
  3242. char quotechar)
  3243. {
  3244. char *p, *begin_word, *end_word, *end_whitespace;
  3245. begin_word = *buf;
  3246. end_word = begin_word + strcspn(begin_word, delimiters);
  3247. /* Check for quotechar */
  3248. if (end_word > begin_word) {
  3249. p = end_word - 1;
  3250. while (*p == quotechar) {
  3251. /* While the delimiter is quoted, look for the next delimiter. */
  3252. /* This happens, e.g., in calls from parse_auth_header,
  3253. * if the user name contains a " character. */
  3254. /* If there is anything beyond end_word, copy it. */
  3255. if (*end_word != '\0') {
  3256. size_t end_off = strcspn(end_word + 1, delimiters);
  3257. memmove(p, end_word, end_off + 1);
  3258. p += end_off; /* p must correspond to end_word - 1 */
  3259. end_word += end_off + 1;
  3260. } else {
  3261. *p = '\0';
  3262. break;
  3263. }
  3264. }
  3265. for (p++; p < end_word; p++) {
  3266. *p = '\0';
  3267. }
  3268. }
  3269. if (*end_word == '\0') {
  3270. *buf = end_word;
  3271. } else {
  3272. #if defined(GCC_DIAGNOSTIC)
  3273. /* Disable spurious conversion warning for GCC */
  3274. #pragma GCC diagnostic push
  3275. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3276. #endif /* defined(GCC_DIAGNOSTIC) */
  3277. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3278. #if defined(GCC_DIAGNOSTIC)
  3279. #pragma GCC diagnostic pop
  3280. #endif /* defined(GCC_DIAGNOSTIC) */
  3281. for (p = end_word; p < end_whitespace; p++) {
  3282. *p = '\0';
  3283. }
  3284. *buf = end_whitespace;
  3285. }
  3286. return begin_word;
  3287. }
  3288. /* Return HTTP header value, or NULL if not found. */
  3289. static const char *
  3290. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3291. {
  3292. int i;
  3293. for (i = 0; i < num_hdr; i++) {
  3294. if (!mg_strcasecmp(name, hdr[i].name)) {
  3295. return hdr[i].value;
  3296. }
  3297. }
  3298. return NULL;
  3299. }
  3300. /* Retrieve requested HTTP header multiple values, and return the number of
  3301. * found occurrences */
  3302. static int
  3303. get_req_headers(const struct mg_request_info *ri,
  3304. const char *name,
  3305. const char **output,
  3306. int output_max_size)
  3307. {
  3308. int i;
  3309. int cnt = 0;
  3310. if (ri) {
  3311. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3312. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3313. output[cnt++] = ri->http_headers[i].value;
  3314. }
  3315. }
  3316. }
  3317. return cnt;
  3318. }
  3319. CIVETWEB_API const char *
  3320. mg_get_header(const struct mg_connection *conn, const char *name)
  3321. {
  3322. if (!conn) {
  3323. return NULL;
  3324. }
  3325. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3326. return get_header(conn->request_info.http_headers,
  3327. conn->request_info.num_headers,
  3328. name);
  3329. }
  3330. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3331. return get_header(conn->response_info.http_headers,
  3332. conn->response_info.num_headers,
  3333. name);
  3334. }
  3335. return NULL;
  3336. }
  3337. static const char *
  3338. get_http_version(const struct mg_connection *conn)
  3339. {
  3340. if (!conn) {
  3341. return NULL;
  3342. }
  3343. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3344. return conn->request_info.http_version;
  3345. }
  3346. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3347. return conn->response_info.http_version;
  3348. }
  3349. return NULL;
  3350. }
  3351. /* A helper function for traversing a comma separated list of values.
  3352. * It returns a list pointer shifted to the next value, or NULL if the end
  3353. * of the list found.
  3354. * Value is stored in val vector. If value has form "x=y", then eq_val
  3355. * vector is initialized to point to the "y" part, and val vector length
  3356. * is adjusted to point only to "x". */
  3357. static const char *
  3358. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3359. {
  3360. int end;
  3361. reparse:
  3362. if (val == NULL || list == NULL || *list == '\0') {
  3363. /* End of the list */
  3364. return NULL;
  3365. }
  3366. /* Skip over leading LWS */
  3367. while (*list == ' ' || *list == '\t')
  3368. list++;
  3369. val->ptr = list;
  3370. if ((list = strchr(val->ptr, ',')) != NULL) {
  3371. /* Comma found. Store length and shift the list ptr */
  3372. val->len = ((size_t)(list - val->ptr));
  3373. list++;
  3374. } else {
  3375. /* This value is the last one */
  3376. list = val->ptr + strlen(val->ptr);
  3377. val->len = ((size_t)(list - val->ptr));
  3378. }
  3379. /* Adjust length for trailing LWS */
  3380. end = (int)val->len - 1;
  3381. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3382. end--;
  3383. val->len = (size_t)(end) + (size_t)(1);
  3384. if (val->len == 0) {
  3385. /* Ignore any empty entries. */
  3386. goto reparse;
  3387. }
  3388. if (eq_val != NULL) {
  3389. /* Value has form "x=y", adjust pointers and lengths
  3390. * so that val points to "x", and eq_val points to "y". */
  3391. eq_val->len = 0;
  3392. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3393. if (eq_val->ptr != NULL) {
  3394. eq_val->ptr++; /* Skip over '=' character */
  3395. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3396. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3397. }
  3398. }
  3399. return list;
  3400. }
  3401. /* A helper function for checking if a comma separated list of values
  3402. * contains
  3403. * the given option (case insensitvely).
  3404. * 'header' can be NULL, in which case false is returned. */
  3405. static int
  3406. header_has_option(const char *header, const char *option)
  3407. {
  3408. struct vec opt_vec;
  3409. struct vec eq_vec;
  3410. DEBUG_ASSERT(option != NULL);
  3411. DEBUG_ASSERT(option[0] != '\0');
  3412. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3413. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3414. return 1;
  3415. }
  3416. return 0;
  3417. }
  3418. /* Sorting function implemented in a separate file */
  3419. #include "sort.inl"
  3420. /* Pattern matching has been reimplemented in a new file */
  3421. #include "match.inl"
  3422. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3423. * This function must tolerate situations when connection info is not
  3424. * set up, for example if request parsing failed. */
  3425. static int
  3426. should_keep_alive(const struct mg_connection *conn)
  3427. {
  3428. const char *http_version;
  3429. const char *header;
  3430. /* First satisfy needs of the server */
  3431. if ((conn == NULL) || conn->must_close) {
  3432. /* Close, if civetweb framework needs to close */
  3433. return 0;
  3434. }
  3435. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3436. /* Close, if keep alive is not enabled */
  3437. return 0;
  3438. }
  3439. /* Check explicit wish of the client */
  3440. header = mg_get_header(conn, "Connection");
  3441. if (header) {
  3442. /* If there is a connection header from the client, obey */
  3443. if (header_has_option(header, "keep-alive")) {
  3444. return 1;
  3445. }
  3446. return 0;
  3447. }
  3448. /* Use default of the standard */
  3449. http_version = get_http_version(conn);
  3450. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3451. /* HTTP 1.1 default is keep alive */
  3452. return 1;
  3453. }
  3454. /* HTTP 1.0 (and earlier) default is to close the connection */
  3455. return 0;
  3456. }
  3457. static int
  3458. should_decode_url(const struct mg_connection *conn)
  3459. {
  3460. if (!conn || !conn->dom_ctx) {
  3461. return 0;
  3462. }
  3463. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3464. }
  3465. static int
  3466. should_decode_query_string(const struct mg_connection *conn)
  3467. {
  3468. if (!conn || !conn->dom_ctx) {
  3469. return 0;
  3470. }
  3471. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3472. == 0);
  3473. }
  3474. static const char *
  3475. suggest_connection_header(const struct mg_connection *conn)
  3476. {
  3477. return should_keep_alive(conn) ? "keep-alive" : "close";
  3478. }
  3479. #include "response.inl"
  3480. static void
  3481. send_no_cache_header(struct mg_connection *conn)
  3482. {
  3483. /* Send all current and obsolete cache opt-out directives. */
  3484. mg_response_header_add(conn,
  3485. "Cache-Control",
  3486. "no-cache, no-store, "
  3487. "must-revalidate, private, max-age=0",
  3488. -1);
  3489. mg_response_header_add(conn, "Expires", "0", -1);
  3490. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3491. /* Obsolete, but still send it for HTTP/1.0 */
  3492. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3493. }
  3494. }
  3495. static void
  3496. send_static_cache_header(struct mg_connection *conn)
  3497. {
  3498. #if !defined(NO_CACHING)
  3499. int max_age;
  3500. char val[64];
  3501. const char *cache_control =
  3502. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3503. /* If there is a full cache-control option configured,0 use it */
  3504. if (cache_control != NULL) {
  3505. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3506. return;
  3507. }
  3508. /* Read the server config to check how long a file may be cached.
  3509. * The configuration is in seconds. */
  3510. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3511. if (max_age <= 0) {
  3512. /* 0 means "do not cache". All values <0 are reserved
  3513. * and may be used differently in the future. */
  3514. /* If a file should not be cached, do not only send
  3515. * max-age=0, but also pragmas and Expires headers. */
  3516. send_no_cache_header(conn);
  3517. return;
  3518. }
  3519. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3520. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3521. /* See also https://www.mnot.net/cache_docs/ */
  3522. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3523. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3524. * leap
  3525. * year to 31622400 seconds. For the moment, we just send whatever has
  3526. * been configured, still the behavior for >1 year should be considered
  3527. * as undefined. */
  3528. mg_snprintf(
  3529. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3530. mg_response_header_add(conn, "Cache-Control", val, -1);
  3531. #else /* NO_CACHING */
  3532. send_no_cache_header(conn);
  3533. #endif /* !NO_CACHING */
  3534. }
  3535. static void
  3536. send_additional_header(struct mg_connection *conn)
  3537. {
  3538. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3539. #if !defined(NO_SSL)
  3540. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3541. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3542. if (max_age >= 0) {
  3543. char val[64];
  3544. mg_snprintf(conn,
  3545. NULL,
  3546. val,
  3547. sizeof(val),
  3548. "max-age=%lu",
  3549. (unsigned long)max_age);
  3550. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3551. }
  3552. }
  3553. #endif
  3554. if (header && header[0]) {
  3555. mg_response_header_add_lines(conn, header);
  3556. }
  3557. }
  3558. static void
  3559. send_cors_header(struct mg_connection *conn)
  3560. {
  3561. const char *origin_hdr = mg_get_header(conn, "Origin");
  3562. const char *cors_orig_cfg =
  3563. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3564. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3565. /* Cross-origin resource sharing (CORS), see
  3566. * http://www.html5rocks.com/en/tutorials/cors/,
  3567. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3568. * CORS preflight is not supported for files. */
  3569. mg_response_header_add(conn,
  3570. "Access-Control-Allow-Origin",
  3571. cors_orig_cfg,
  3572. -1);
  3573. }
  3574. }
  3575. #if !defined(NO_FILESYSTEMS)
  3576. static void handle_file_based_request(struct mg_connection *conn,
  3577. const char *path,
  3578. struct mg_file *filep);
  3579. #endif /* NO_FILESYSTEMS */
  3580. CIVETWEB_API const char *
  3581. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3582. {
  3583. /* See IANA HTTP status code assignment:
  3584. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3585. */
  3586. switch (response_code) {
  3587. /* RFC2616 Section 10.1 - Informational 1xx */
  3588. case 100:
  3589. return "Continue"; /* RFC2616 Section 10.1.1 */
  3590. case 101:
  3591. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3592. case 102:
  3593. return "Processing"; /* RFC2518 Section 10.1 */
  3594. /* RFC2616 Section 10.2 - Successful 2xx */
  3595. case 200:
  3596. return "OK"; /* RFC2616 Section 10.2.1 */
  3597. case 201:
  3598. return "Created"; /* RFC2616 Section 10.2.2 */
  3599. case 202:
  3600. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3601. case 203:
  3602. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3603. case 204:
  3604. return "No Content"; /* RFC2616 Section 10.2.5 */
  3605. case 205:
  3606. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3607. case 206:
  3608. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3609. case 207:
  3610. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3611. */
  3612. case 208:
  3613. return "Already Reported"; /* RFC5842 Section 7.1 */
  3614. case 226:
  3615. return "IM used"; /* RFC3229 Section 10.4.1 */
  3616. /* RFC2616 Section 10.3 - Redirection 3xx */
  3617. case 300:
  3618. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3619. case 301:
  3620. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3621. case 302:
  3622. return "Found"; /* RFC2616 Section 10.3.3 */
  3623. case 303:
  3624. return "See Other"; /* RFC2616 Section 10.3.4 */
  3625. case 304:
  3626. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3627. case 305:
  3628. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3629. case 307:
  3630. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3631. case 308:
  3632. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3633. /* RFC2616 Section 10.4 - Client Error 4xx */
  3634. case 400:
  3635. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3636. case 401:
  3637. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3638. case 402:
  3639. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3640. case 403:
  3641. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3642. case 404:
  3643. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3644. case 405:
  3645. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3646. case 406:
  3647. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3648. case 407:
  3649. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3650. case 408:
  3651. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3652. case 409:
  3653. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3654. case 410:
  3655. return "Gone"; /* RFC2616 Section 10.4.11 */
  3656. case 411:
  3657. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3658. case 412:
  3659. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3660. case 413:
  3661. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3662. case 414:
  3663. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3664. case 415:
  3665. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3666. case 416:
  3667. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3668. */
  3669. case 417:
  3670. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3671. case 421:
  3672. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3673. case 422:
  3674. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3675. * Section 11.2 */
  3676. case 423:
  3677. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3678. case 424:
  3679. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3680. * Section 11.4 */
  3681. case 426:
  3682. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3683. case 428:
  3684. return "Precondition Required"; /* RFC 6585, Section 3 */
  3685. case 429:
  3686. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3687. case 431:
  3688. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3689. case 451:
  3690. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3691. * Section 3 */
  3692. /* RFC2616 Section 10.5 - Server Error 5xx */
  3693. case 500:
  3694. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3695. case 501:
  3696. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3697. case 502:
  3698. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3699. case 503:
  3700. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3701. case 504:
  3702. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3703. case 505:
  3704. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3705. case 506:
  3706. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3707. case 507:
  3708. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3709. * Section 11.5 */
  3710. case 508:
  3711. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3712. case 510:
  3713. return "Not Extended"; /* RFC 2774, Section 7 */
  3714. case 511:
  3715. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3716. /* Other status codes, not shown in the IANA HTTP status code
  3717. * assignment.
  3718. * E.g., "de facto" standards due to common use, ... */
  3719. case 418:
  3720. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3721. case 419:
  3722. return "Authentication Timeout"; /* common use */
  3723. case 420:
  3724. return "Enhance Your Calm"; /* common use */
  3725. case 440:
  3726. return "Login Timeout"; /* common use */
  3727. case 509:
  3728. return "Bandwidth Limit Exceeded"; /* common use */
  3729. default:
  3730. /* This error code is unknown. This should not happen. */
  3731. if (conn) {
  3732. mg_cry_internal(conn,
  3733. "Unknown HTTP response code: %u",
  3734. response_code);
  3735. }
  3736. /* Return at least a category according to RFC 2616 Section 10. */
  3737. if (response_code >= 100 && response_code < 200) {
  3738. /* Unknown informational status code */
  3739. return "Information";
  3740. }
  3741. if (response_code >= 200 && response_code < 300) {
  3742. /* Unknown success code */
  3743. return "Success";
  3744. }
  3745. if (response_code >= 300 && response_code < 400) {
  3746. /* Unknown redirection code */
  3747. return "Redirection";
  3748. }
  3749. if (response_code >= 400 && response_code < 500) {
  3750. /* Unknown request error code */
  3751. return "Client Error";
  3752. }
  3753. if (response_code >= 500 && response_code < 600) {
  3754. /* Unknown server error code */
  3755. return "Server Error";
  3756. }
  3757. /* Response code not even within reasonable range */
  3758. return "";
  3759. }
  3760. }
  3761. static int
  3762. mg_send_http_error_impl(struct mg_connection *conn,
  3763. int status,
  3764. const char *fmt,
  3765. va_list args)
  3766. {
  3767. char errmsg_buf[MG_BUF_LEN];
  3768. va_list ap;
  3769. int has_body;
  3770. #if !defined(NO_FILESYSTEMS)
  3771. char path_buf[UTF8_PATH_MAX];
  3772. int len, i, page_handler_found, scope, truncated;
  3773. const char *error_handler = NULL;
  3774. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3775. const char *error_page_file_ext, *tstr;
  3776. #endif /* NO_FILESYSTEMS */
  3777. int handled_by_callback = 0;
  3778. if ((conn == NULL) || (fmt == NULL)) {
  3779. return -2;
  3780. }
  3781. /* Set status (for log) */
  3782. conn->status_code = status;
  3783. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3784. has_body = ((status > 199) && (status != 204) && (status != 304));
  3785. /* Prepare message in buf, if required */
  3786. if (has_body
  3787. || (!conn->in_error_handler
  3788. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3789. /* Store error message in errmsg_buf */
  3790. va_copy(ap, args);
  3791. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3792. va_end(ap);
  3793. /* In a debug build, print all html errors */
  3794. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3795. }
  3796. /* If there is a http_error callback, call it.
  3797. * But don't do it recursively, if callback calls mg_send_http_error again.
  3798. */
  3799. if (!conn->in_error_handler
  3800. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3801. /* Mark in_error_handler to avoid recursion and call user callback. */
  3802. conn->in_error_handler = 1;
  3803. handled_by_callback =
  3804. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3805. == 0);
  3806. conn->in_error_handler = 0;
  3807. }
  3808. if (!handled_by_callback) {
  3809. /* Check for recursion */
  3810. if (conn->in_error_handler) {
  3811. DEBUG_TRACE(
  3812. "Recursion when handling error %u - fall back to default",
  3813. status);
  3814. #if !defined(NO_FILESYSTEMS)
  3815. } else {
  3816. /* Send user defined error pages, if defined */
  3817. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3818. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3819. page_handler_found = 0;
  3820. if (error_handler != NULL) {
  3821. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3822. switch (scope) {
  3823. case 1: /* Handler for specific error, e.g. 404 error */
  3824. mg_snprintf(conn,
  3825. &truncated,
  3826. path_buf,
  3827. sizeof(path_buf) - 32,
  3828. "%serror%03u.",
  3829. error_handler,
  3830. status);
  3831. break;
  3832. case 2: /* Handler for error group, e.g., 5xx error
  3833. * handler
  3834. * for all server errors (500-599) */
  3835. mg_snprintf(conn,
  3836. &truncated,
  3837. path_buf,
  3838. sizeof(path_buf) - 32,
  3839. "%serror%01uxx.",
  3840. error_handler,
  3841. status / 100);
  3842. break;
  3843. default: /* Handler for all errors */
  3844. mg_snprintf(conn,
  3845. &truncated,
  3846. path_buf,
  3847. sizeof(path_buf) - 32,
  3848. "%serror.",
  3849. error_handler);
  3850. break;
  3851. }
  3852. /* String truncation in buf may only occur if
  3853. * error_handler is too long. This string is
  3854. * from the config, not from a client. */
  3855. (void)truncated;
  3856. /* The following code is redundant, but it should avoid
  3857. * false positives in static source code analyzers and
  3858. * vulnerability scanners.
  3859. */
  3860. path_buf[sizeof(path_buf) - 32] = 0;
  3861. len = (int)strlen(path_buf);
  3862. if (len > (int)sizeof(path_buf) - 32) {
  3863. len = (int)sizeof(path_buf) - 32;
  3864. }
  3865. /* Start with the file extenstion from the configuration. */
  3866. tstr = strchr(error_page_file_ext, '.');
  3867. while (tstr) {
  3868. for (i = 1;
  3869. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3870. i++) {
  3871. /* buffer overrun is not possible here, since
  3872. * (i < 32) && (len < sizeof(path_buf) - 32)
  3873. * ==> (i + len) < sizeof(path_buf) */
  3874. path_buf[len + i - 1] = tstr[i];
  3875. }
  3876. /* buffer overrun is not possible here, since
  3877. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3878. * ==> (i + len) <= sizeof(path_buf) */
  3879. path_buf[len + i - 1] = 0;
  3880. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3881. DEBUG_TRACE("Check error page %s - found",
  3882. path_buf);
  3883. page_handler_found = 1;
  3884. break;
  3885. }
  3886. DEBUG_TRACE("Check error page %s - not found",
  3887. path_buf);
  3888. /* Continue with the next file extenstion from the
  3889. * configuration (if there is a next one). */
  3890. tstr = strchr(tstr + i, '.');
  3891. }
  3892. }
  3893. }
  3894. if (page_handler_found) {
  3895. conn->in_error_handler = 1;
  3896. handle_file_based_request(conn, path_buf, &error_page_file);
  3897. conn->in_error_handler = 0;
  3898. return 0;
  3899. }
  3900. #endif /* NO_FILESYSTEMS */
  3901. }
  3902. /* No custom error page. Send default error page. */
  3903. conn->must_close = 1;
  3904. mg_response_header_start(conn, status);
  3905. send_no_cache_header(conn);
  3906. send_additional_header(conn);
  3907. send_cors_header(conn);
  3908. if (has_body) {
  3909. mg_response_header_add(conn,
  3910. "Content-Type",
  3911. "text/plain; charset=utf-8",
  3912. -1);
  3913. }
  3914. mg_response_header_send(conn);
  3915. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3916. if (has_body) {
  3917. /* For other errors, send a generic error message. */
  3918. const char *status_text = mg_get_response_code_text(conn, status);
  3919. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3920. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3921. } else {
  3922. /* No body allowed. Close the connection. */
  3923. DEBUG_TRACE("Error %i", status);
  3924. }
  3925. }
  3926. return 0;
  3927. }
  3928. CIVETWEB_API int
  3929. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3930. {
  3931. va_list ap;
  3932. int ret;
  3933. va_start(ap, fmt);
  3934. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3935. va_end(ap);
  3936. return ret;
  3937. }
  3938. CIVETWEB_API int
  3939. mg_send_http_ok(struct mg_connection *conn,
  3940. const char *mime_type,
  3941. long long content_length)
  3942. {
  3943. if ((mime_type == NULL) || (*mime_type == 0)) {
  3944. /* No content type defined: default to text/html */
  3945. mime_type = "text/html";
  3946. }
  3947. mg_response_header_start(conn, 200);
  3948. send_no_cache_header(conn);
  3949. send_additional_header(conn);
  3950. send_cors_header(conn);
  3951. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3952. if (content_length < 0) {
  3953. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3954. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3955. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3956. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3957. }
  3958. } else {
  3959. char len[32];
  3960. int trunc = 0;
  3961. mg_snprintf(conn,
  3962. &trunc,
  3963. len,
  3964. sizeof(len),
  3965. "%" UINT64_FMT,
  3966. (uint64_t)content_length);
  3967. if (!trunc) {
  3968. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3969. * !trunc is always true */
  3970. mg_response_header_add(conn, "Content-Length", len, -1);
  3971. }
  3972. }
  3973. mg_response_header_send(conn);
  3974. return 0;
  3975. }
  3976. CIVETWEB_API int
  3977. mg_send_http_redirect(struct mg_connection *conn,
  3978. const char *target_url,
  3979. int redirect_code)
  3980. {
  3981. /* Send a 30x redirect response.
  3982. *
  3983. * Redirect types (status codes):
  3984. *
  3985. * Status | Perm/Temp | Method | Version
  3986. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3987. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3988. * 303 | temporary | always use GET | HTTP/1.1
  3989. * 307 | temporary | always keep method | HTTP/1.1
  3990. * 308 | permanent | always keep method | HTTP/1.1
  3991. */
  3992. #if defined(MG_SEND_REDIRECT_BODY)
  3993. char redirect_body[MG_BUF_LEN];
  3994. size_t content_len = 0;
  3995. char content_len_text[32];
  3996. #endif
  3997. /* In case redirect_code=0, use 307. */
  3998. if (redirect_code == 0) {
  3999. redirect_code = 307;
  4000. }
  4001. /* In case redirect_code is none of the above, return error. */
  4002. if ((redirect_code != 301) && (redirect_code != 302)
  4003. && (redirect_code != 303) && (redirect_code != 307)
  4004. && (redirect_code != 308)) {
  4005. /* Parameter error */
  4006. return -2;
  4007. }
  4008. /* If target_url is not defined, redirect to "/". */
  4009. if ((target_url == NULL) || (*target_url == 0)) {
  4010. target_url = "/";
  4011. }
  4012. #if defined(MG_SEND_REDIRECT_BODY)
  4013. /* TODO: condition name? */
  4014. /* Prepare a response body with a hyperlink.
  4015. *
  4016. * According to RFC2616 (and RFC1945 before):
  4017. * Unless the request method was HEAD, the entity of the
  4018. * response SHOULD contain a short hypertext note with a hyperlink to
  4019. * the new URI(s).
  4020. *
  4021. * However, this response body is not useful in M2M communication.
  4022. * Probably the original reason in the RFC was, clients not supporting
  4023. * a 30x HTTP redirect could still show the HTML page and let the user
  4024. * press the link. Since current browsers support 30x HTTP, the additional
  4025. * HTML body does not seem to make sense anymore.
  4026. *
  4027. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4028. * but it only notes:
  4029. * The server's response payload usually contains a short
  4030. * hypertext note with a hyperlink to the new URI(s).
  4031. *
  4032. * Deactivated by default. If you need the 30x body, set the define.
  4033. */
  4034. mg_snprintf(
  4035. conn,
  4036. NULL /* ignore truncation */,
  4037. redirect_body,
  4038. sizeof(redirect_body),
  4039. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4040. redirect_text,
  4041. target_url,
  4042. target_url);
  4043. content_len = strlen(reply);
  4044. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4045. #endif
  4046. /* Send all required headers */
  4047. mg_response_header_start(conn, redirect_code);
  4048. mg_response_header_add(conn, "Location", target_url, -1);
  4049. if ((redirect_code == 301) || (redirect_code == 308)) {
  4050. /* Permanent redirect */
  4051. send_static_cache_header(conn);
  4052. } else {
  4053. /* Temporary redirect */
  4054. send_no_cache_header(conn);
  4055. }
  4056. send_additional_header(conn);
  4057. send_cors_header(conn);
  4058. #if defined(MG_SEND_REDIRECT_BODY)
  4059. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4060. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4061. #else
  4062. mg_response_header_add(conn, "Content-Length", "0", 1);
  4063. #endif
  4064. mg_response_header_send(conn);
  4065. #if defined(MG_SEND_REDIRECT_BODY)
  4066. /* Send response body */
  4067. /* ... unless it is a HEAD request */
  4068. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4069. ret = mg_write(conn, redirect_body, content_len);
  4070. }
  4071. #endif
  4072. return 1;
  4073. }
  4074. #if defined(_WIN32)
  4075. /* Create substitutes for POSIX functions in Win32. */
  4076. #if defined(GCC_DIAGNOSTIC)
  4077. /* Show no warning in case system functions are not used. */
  4078. #pragma GCC diagnostic push
  4079. #pragma GCC diagnostic ignored "-Wunused-function"
  4080. #endif
  4081. static int
  4082. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4083. {
  4084. (void)unused;
  4085. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4086. InitializeCriticalSection(&mutex->sec);
  4087. return 0;
  4088. }
  4089. static int
  4090. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4091. {
  4092. DeleteCriticalSection(&mutex->sec);
  4093. return 0;
  4094. }
  4095. static int
  4096. pthread_mutex_lock(pthread_mutex_t *mutex)
  4097. {
  4098. EnterCriticalSection(&mutex->sec);
  4099. return 0;
  4100. }
  4101. static int
  4102. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4103. {
  4104. LeaveCriticalSection(&mutex->sec);
  4105. return 0;
  4106. }
  4107. FUNCTION_MAY_BE_UNUSED
  4108. static int
  4109. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4110. {
  4111. (void)unused;
  4112. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4113. cv->waiting_thread = NULL;
  4114. return 0;
  4115. }
  4116. FUNCTION_MAY_BE_UNUSED
  4117. static int
  4118. pthread_cond_timedwait(pthread_cond_t *cv,
  4119. pthread_mutex_t *mutex,
  4120. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4121. {
  4122. struct mg_workerTLS **ptls,
  4123. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4124. int ok;
  4125. uint64_t nsnow, nswaitabs;
  4126. int64_t nswaitrel;
  4127. DWORD mswaitrel;
  4128. pthread_mutex_lock(&cv->threadIdSec);
  4129. /* Add this thread to cv's waiting list */
  4130. ptls = &cv->waiting_thread;
  4131. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4132. ;
  4133. tls->next_waiting_thread = NULL;
  4134. *ptls = tls;
  4135. pthread_mutex_unlock(&cv->threadIdSec);
  4136. if (abstime) {
  4137. nsnow = mg_get_current_time_ns();
  4138. nswaitabs =
  4139. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4140. nswaitrel = nswaitabs - nsnow;
  4141. if (nswaitrel < 0) {
  4142. nswaitrel = 0;
  4143. }
  4144. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4145. } else {
  4146. mswaitrel = (DWORD)INFINITE;
  4147. }
  4148. pthread_mutex_unlock(mutex);
  4149. ok = (WAIT_OBJECT_0
  4150. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4151. if (!ok) {
  4152. ok = 1;
  4153. pthread_mutex_lock(&cv->threadIdSec);
  4154. ptls = &cv->waiting_thread;
  4155. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4156. if (*ptls == tls) {
  4157. *ptls = tls->next_waiting_thread;
  4158. ok = 0;
  4159. break;
  4160. }
  4161. }
  4162. pthread_mutex_unlock(&cv->threadIdSec);
  4163. if (ok) {
  4164. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4165. (DWORD)INFINITE);
  4166. }
  4167. }
  4168. /* This thread has been removed from cv's waiting list */
  4169. pthread_mutex_lock(mutex);
  4170. return ok ? 0 : -1;
  4171. }
  4172. FUNCTION_MAY_BE_UNUSED
  4173. static int
  4174. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4175. {
  4176. return pthread_cond_timedwait(cv, mutex, NULL);
  4177. }
  4178. FUNCTION_MAY_BE_UNUSED
  4179. static int
  4180. pthread_cond_signal(pthread_cond_t *cv)
  4181. {
  4182. HANDLE wkup = NULL;
  4183. BOOL ok = FALSE;
  4184. pthread_mutex_lock(&cv->threadIdSec);
  4185. if (cv->waiting_thread) {
  4186. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4187. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4188. ok = SetEvent(wkup);
  4189. DEBUG_ASSERT(ok);
  4190. }
  4191. pthread_mutex_unlock(&cv->threadIdSec);
  4192. return ok ? 0 : 1;
  4193. }
  4194. FUNCTION_MAY_BE_UNUSED
  4195. static int
  4196. pthread_cond_broadcast(pthread_cond_t *cv)
  4197. {
  4198. pthread_mutex_lock(&cv->threadIdSec);
  4199. while (cv->waiting_thread) {
  4200. pthread_cond_signal(cv);
  4201. }
  4202. pthread_mutex_unlock(&cv->threadIdSec);
  4203. return 0;
  4204. }
  4205. FUNCTION_MAY_BE_UNUSED
  4206. static int
  4207. pthread_cond_destroy(pthread_cond_t *cv)
  4208. {
  4209. pthread_mutex_lock(&cv->threadIdSec);
  4210. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4211. pthread_mutex_unlock(&cv->threadIdSec);
  4212. pthread_mutex_destroy(&cv->threadIdSec);
  4213. return 0;
  4214. }
  4215. #if defined(ALTERNATIVE_QUEUE)
  4216. FUNCTION_MAY_BE_UNUSED
  4217. static void *
  4218. event_create(void)
  4219. {
  4220. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4221. }
  4222. FUNCTION_MAY_BE_UNUSED
  4223. static int
  4224. event_wait(void *eventhdl)
  4225. {
  4226. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4227. return (res == WAIT_OBJECT_0);
  4228. }
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static int
  4231. event_signal(void *eventhdl)
  4232. {
  4233. return (int)SetEvent((HANDLE)eventhdl);
  4234. }
  4235. FUNCTION_MAY_BE_UNUSED
  4236. static void
  4237. event_destroy(void *eventhdl)
  4238. {
  4239. CloseHandle((HANDLE)eventhdl);
  4240. }
  4241. #endif
  4242. #if defined(GCC_DIAGNOSTIC)
  4243. /* Enable unused function warning again */
  4244. #pragma GCC diagnostic pop
  4245. #endif
  4246. /* For Windows, change all slashes to backslashes in path names. */
  4247. static void
  4248. change_slashes_to_backslashes(char *path)
  4249. {
  4250. int i;
  4251. for (i = 0; path[i] != '\0'; i++) {
  4252. if (path[i] == '/') {
  4253. path[i] = '\\';
  4254. }
  4255. /* remove double backslash (check i > 0 to preserve UNC paths,
  4256. * like \\server\file.txt) */
  4257. if ((i > 0) && (path[i] == '\\')) {
  4258. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4259. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4260. }
  4261. }
  4262. }
  4263. }
  4264. static int
  4265. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4266. {
  4267. int diff;
  4268. do {
  4269. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4270. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4271. s1++;
  4272. s2++;
  4273. } while ((diff == 0) && (s1[-1] != L'\0'));
  4274. return diff;
  4275. }
  4276. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4277. * wbuf and wbuf_len is a target buffer and its length. */
  4278. static void
  4279. path_to_unicode(const struct mg_connection *conn,
  4280. const char *path,
  4281. wchar_t *wbuf,
  4282. size_t wbuf_len)
  4283. {
  4284. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4285. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4286. DWORD long_len, err;
  4287. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4288. mg_strlcpy(buf, path, sizeof(buf));
  4289. change_slashes_to_backslashes(buf);
  4290. /* Convert to Unicode and back. If doubly-converted string does not
  4291. * match the original, something is fishy, reject. */
  4292. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4293. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4294. WideCharToMultiByte(
  4295. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4296. if (strcmp(buf, buf2) != 0) {
  4297. wbuf[0] = L'\0';
  4298. }
  4299. /* Windows file systems are not case sensitive, but you can still use
  4300. * uppercase and lowercase letters (on all modern file systems).
  4301. * The server can check if the URI uses the same upper/lowercase
  4302. * letters an the file system, effectively making Windows servers
  4303. * case sensitive (like Linux servers are). It is still not possible
  4304. * to use two files with the same name in different cases on Windows
  4305. * (like /a and /A) - this would be possible in Linux.
  4306. * As a default, Windows is not case sensitive, but the case sensitive
  4307. * file name check can be activated by an additional configuration. */
  4308. if (conn) {
  4309. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4310. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4311. "yes")) {
  4312. /* Use case sensitive compare function */
  4313. fcompare = wcscmp;
  4314. }
  4315. }
  4316. (void)conn; /* conn is currently unused */
  4317. /* Only accept a full file path, not a Windows short (8.3) path. */
  4318. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4319. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4320. if (long_len == 0) {
  4321. err = GetLastError();
  4322. if (err == ERROR_FILE_NOT_FOUND) {
  4323. /* File does not exist. This is not always a problem here. */
  4324. return;
  4325. }
  4326. }
  4327. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4328. /* Short name is used. */
  4329. wbuf[0] = L'\0';
  4330. }
  4331. }
  4332. #if !defined(NO_FILESYSTEMS)
  4333. /* Get file information, return 1 if file exists, 0 if not */
  4334. static int
  4335. mg_stat(const struct mg_connection *conn,
  4336. const char *path,
  4337. struct mg_file_stat *filep)
  4338. {
  4339. wchar_t wbuf[UTF16_PATH_MAX];
  4340. WIN32_FILE_ATTRIBUTE_DATA info;
  4341. time_t creation_time;
  4342. size_t len;
  4343. if (!filep) {
  4344. return 0;
  4345. }
  4346. memset(filep, 0, sizeof(*filep));
  4347. if (mg_path_suspicious(conn, path)) {
  4348. return 0;
  4349. }
  4350. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4351. /* Windows happily opens files with some garbage at the end of file name.
  4352. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4353. * "a.cgi", despite one would expect an error back. */
  4354. len = strlen(path);
  4355. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4356. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4357. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4358. filep->last_modified =
  4359. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4360. info.ftLastWriteTime.dwHighDateTime);
  4361. /* On Windows, the file creation time can be higher than the
  4362. * modification time, e.g. when a file is copied.
  4363. * Since the Last-Modified timestamp is used for caching
  4364. * it should be based on the most recent timestamp. */
  4365. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4366. info.ftCreationTime.dwHighDateTime);
  4367. if (creation_time > filep->last_modified) {
  4368. filep->last_modified = creation_time;
  4369. }
  4370. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4371. return 1;
  4372. }
  4373. return 0;
  4374. }
  4375. #endif
  4376. static int
  4377. mg_remove(const struct mg_connection *conn, const char *path)
  4378. {
  4379. wchar_t wbuf[UTF16_PATH_MAX];
  4380. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4381. return DeleteFileW(wbuf) ? 0 : -1;
  4382. }
  4383. static int
  4384. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4385. {
  4386. wchar_t wbuf[UTF16_PATH_MAX];
  4387. (void)mode;
  4388. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4389. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4390. }
  4391. /* Create substitutes for POSIX functions in Win32. */
  4392. #if defined(GCC_DIAGNOSTIC)
  4393. /* Show no warning in case system functions are not used. */
  4394. #pragma GCC diagnostic push
  4395. #pragma GCC diagnostic ignored "-Wunused-function"
  4396. #endif
  4397. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4398. FUNCTION_MAY_BE_UNUSED
  4399. static DIR *
  4400. mg_opendir(const struct mg_connection *conn, const char *name)
  4401. {
  4402. DIR *dir = NULL;
  4403. wchar_t wpath[UTF16_PATH_MAX];
  4404. DWORD attrs;
  4405. if (name == NULL) {
  4406. SetLastError(ERROR_BAD_ARGUMENTS);
  4407. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4408. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4409. } else {
  4410. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4411. attrs = GetFileAttributesW(wpath);
  4412. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4413. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4414. (void)wcscat(wpath, L"\\*");
  4415. dir->handle = FindFirstFileW(wpath, &dir->info);
  4416. dir->result.d_name[0] = '\0';
  4417. } else {
  4418. mg_free(dir);
  4419. dir = NULL;
  4420. }
  4421. }
  4422. return dir;
  4423. }
  4424. FUNCTION_MAY_BE_UNUSED
  4425. static int
  4426. mg_closedir(DIR *dir)
  4427. {
  4428. int result = 0;
  4429. if (dir != NULL) {
  4430. if (dir->handle != INVALID_HANDLE_VALUE)
  4431. result = FindClose(dir->handle) ? 0 : -1;
  4432. mg_free(dir);
  4433. } else {
  4434. result = -1;
  4435. SetLastError(ERROR_BAD_ARGUMENTS);
  4436. }
  4437. return result;
  4438. }
  4439. FUNCTION_MAY_BE_UNUSED
  4440. static struct dirent *
  4441. mg_readdir(DIR *dir)
  4442. {
  4443. struct dirent *result = 0;
  4444. if (dir) {
  4445. if (dir->handle != INVALID_HANDLE_VALUE) {
  4446. result = &dir->result;
  4447. (void)WideCharToMultiByte(CP_UTF8,
  4448. 0,
  4449. dir->info.cFileName,
  4450. -1,
  4451. result->d_name,
  4452. sizeof(result->d_name),
  4453. NULL,
  4454. NULL);
  4455. if (!FindNextFileW(dir->handle, &dir->info)) {
  4456. (void)FindClose(dir->handle);
  4457. dir->handle = INVALID_HANDLE_VALUE;
  4458. }
  4459. } else {
  4460. SetLastError(ERROR_FILE_NOT_FOUND);
  4461. }
  4462. } else {
  4463. SetLastError(ERROR_BAD_ARGUMENTS);
  4464. }
  4465. return result;
  4466. }
  4467. #if !defined(HAVE_POLL)
  4468. #undef POLLIN
  4469. #undef POLLPRI
  4470. #undef POLLOUT
  4471. #undef POLLERR
  4472. #define POLLIN (1) /* Data ready - read will not block. */
  4473. #define POLLPRI (2) /* Priority data ready. */
  4474. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4475. #define POLLERR (8) /* Error event */
  4476. FUNCTION_MAY_BE_UNUSED
  4477. static int
  4478. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4479. {
  4480. struct timeval tv;
  4481. fd_set rset;
  4482. fd_set wset;
  4483. fd_set eset;
  4484. unsigned int i;
  4485. int result;
  4486. SOCKET maxfd = 0;
  4487. memset(&tv, 0, sizeof(tv));
  4488. tv.tv_sec = milliseconds / 1000;
  4489. tv.tv_usec = (milliseconds % 1000) * 1000;
  4490. FD_ZERO(&rset);
  4491. FD_ZERO(&wset);
  4492. FD_ZERO(&eset);
  4493. for (i = 0; i < n; i++) {
  4494. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4495. if (pfd[i].events & POLLIN) {
  4496. FD_SET(pfd[i].fd, &rset);
  4497. }
  4498. if (pfd[i].events & POLLOUT) {
  4499. FD_SET(pfd[i].fd, &wset);
  4500. }
  4501. /* Check for errors for any FD in the set */
  4502. FD_SET(pfd[i].fd, &eset);
  4503. }
  4504. pfd[i].revents = 0;
  4505. if (pfd[i].fd > maxfd) {
  4506. maxfd = pfd[i].fd;
  4507. }
  4508. }
  4509. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4510. for (i = 0; i < n; i++) {
  4511. if (FD_ISSET(pfd[i].fd, &rset)) {
  4512. pfd[i].revents |= POLLIN;
  4513. }
  4514. if (FD_ISSET(pfd[i].fd, &wset)) {
  4515. pfd[i].revents |= POLLOUT;
  4516. }
  4517. if (FD_ISSET(pfd[i].fd, &eset)) {
  4518. pfd[i].revents |= POLLERR;
  4519. }
  4520. }
  4521. }
  4522. /* We should subtract the time used in select from remaining
  4523. * "milliseconds", in particular if called from mg_poll with a
  4524. * timeout quantum.
  4525. * Unfortunately, the remaining time is not stored in "tv" in all
  4526. * implementations, so the result in "tv" must be considered undefined.
  4527. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4528. return result;
  4529. }
  4530. #endif /* HAVE_POLL */
  4531. #if defined(GCC_DIAGNOSTIC)
  4532. /* Enable unused function warning again */
  4533. #pragma GCC diagnostic pop
  4534. #endif
  4535. static void
  4536. set_close_on_exec(SOCKET sock,
  4537. const struct mg_connection *conn /* may be null */,
  4538. struct mg_context *ctx /* may be null */)
  4539. {
  4540. (void)conn; /* Unused. */
  4541. (void)ctx;
  4542. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4543. }
  4544. CIVETWEB_API int
  4545. mg_start_thread(mg_thread_func_t f, void *p)
  4546. {
  4547. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4548. /* Compile-time option to control stack size, e.g.
  4549. * -DUSE_STACK_SIZE=16384
  4550. */
  4551. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4552. == ((uintptr_t)(-1L)))
  4553. ? -1
  4554. : 0);
  4555. #else
  4556. return (
  4557. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4558. ? -1
  4559. : 0);
  4560. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4561. }
  4562. /* Start a thread storing the thread context. */
  4563. static int
  4564. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4565. void *p,
  4566. pthread_t *threadidptr)
  4567. {
  4568. uintptr_t uip;
  4569. HANDLE threadhandle;
  4570. int result = -1;
  4571. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4572. threadhandle = (HANDLE)uip;
  4573. if ((uip != 0) && (threadidptr != NULL)) {
  4574. *threadidptr = threadhandle;
  4575. result = 0;
  4576. }
  4577. return result;
  4578. }
  4579. /* Wait for a thread to finish. */
  4580. static int
  4581. mg_join_thread(pthread_t threadid)
  4582. {
  4583. int result;
  4584. DWORD dwevent;
  4585. result = -1;
  4586. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4587. if (dwevent == WAIT_FAILED) {
  4588. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4589. } else {
  4590. if (dwevent == WAIT_OBJECT_0) {
  4591. CloseHandle(threadid);
  4592. result = 0;
  4593. }
  4594. }
  4595. return result;
  4596. }
  4597. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4598. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4599. /* Create substitutes for POSIX functions in Win32. */
  4600. #if defined(GCC_DIAGNOSTIC)
  4601. /* Show no warning in case system functions are not used. */
  4602. #pragma GCC diagnostic push
  4603. #pragma GCC diagnostic ignored "-Wunused-function"
  4604. #endif
  4605. FUNCTION_MAY_BE_UNUSED
  4606. static HANDLE
  4607. dlopen(const char *dll_name, int flags)
  4608. {
  4609. wchar_t wbuf[UTF16_PATH_MAX];
  4610. (void)flags;
  4611. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4612. return LoadLibraryW(wbuf);
  4613. }
  4614. FUNCTION_MAY_BE_UNUSED
  4615. static int
  4616. dlclose(void *handle)
  4617. {
  4618. int result;
  4619. if (FreeLibrary((HMODULE)handle) != 0) {
  4620. result = 0;
  4621. } else {
  4622. result = -1;
  4623. }
  4624. return result;
  4625. }
  4626. #if defined(GCC_DIAGNOSTIC)
  4627. /* Enable unused function warning again */
  4628. #pragma GCC diagnostic pop
  4629. #endif
  4630. #endif
  4631. #if !defined(NO_CGI)
  4632. #define SIGKILL (0)
  4633. static int
  4634. kill(pid_t pid, int sig_num)
  4635. {
  4636. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4637. (void)CloseHandle((HANDLE)pid);
  4638. return 0;
  4639. }
  4640. #if !defined(WNOHANG)
  4641. #define WNOHANG (1)
  4642. #endif
  4643. static pid_t
  4644. waitpid(pid_t pid, int *status, int flags)
  4645. {
  4646. DWORD timeout = INFINITE;
  4647. DWORD waitres;
  4648. (void)status; /* Currently not used by any client here */
  4649. if ((flags | WNOHANG) == WNOHANG) {
  4650. timeout = 0;
  4651. }
  4652. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4653. if (waitres == WAIT_OBJECT_0) {
  4654. return pid;
  4655. }
  4656. if (waitres == WAIT_TIMEOUT) {
  4657. return 0;
  4658. }
  4659. return (pid_t)-1;
  4660. }
  4661. static void
  4662. trim_trailing_whitespaces(char *s)
  4663. {
  4664. char *e = s + strlen(s);
  4665. while ((e > s) && isspace((unsigned char)e[-1])) {
  4666. *(--e) = '\0';
  4667. }
  4668. }
  4669. static pid_t
  4670. spawn_process(struct mg_connection *conn,
  4671. const char *prog,
  4672. char *envblk,
  4673. char *envp[],
  4674. int fdin[2],
  4675. int fdout[2],
  4676. int fderr[2],
  4677. const char *dir,
  4678. unsigned char cgi_config_idx)
  4679. {
  4680. HANDLE me;
  4681. char *interp;
  4682. char *interp_arg = 0;
  4683. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4684. int truncated;
  4685. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4686. STARTUPINFOA si;
  4687. PROCESS_INFORMATION pi = {0};
  4688. (void)envp;
  4689. memset(&si, 0, sizeof(si));
  4690. si.cb = sizeof(si);
  4691. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4692. si.wShowWindow = SW_HIDE;
  4693. me = GetCurrentProcess();
  4694. DuplicateHandle(me,
  4695. (HANDLE)_get_osfhandle(fdin[0]),
  4696. me,
  4697. &si.hStdInput,
  4698. 0,
  4699. TRUE,
  4700. DUPLICATE_SAME_ACCESS);
  4701. DuplicateHandle(me,
  4702. (HANDLE)_get_osfhandle(fdout[1]),
  4703. me,
  4704. &si.hStdOutput,
  4705. 0,
  4706. TRUE,
  4707. DUPLICATE_SAME_ACCESS);
  4708. DuplicateHandle(me,
  4709. (HANDLE)_get_osfhandle(fderr[1]),
  4710. me,
  4711. &si.hStdError,
  4712. 0,
  4713. TRUE,
  4714. DUPLICATE_SAME_ACCESS);
  4715. /* Mark handles that should not be inherited. See
  4716. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4717. */
  4718. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4719. HANDLE_FLAG_INHERIT,
  4720. 0);
  4721. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4722. HANDLE_FLAG_INHERIT,
  4723. 0);
  4724. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4725. HANDLE_FLAG_INHERIT,
  4726. 0);
  4727. /* First check, if there is a CGI interpreter configured for all CGI
  4728. * scripts. */
  4729. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4730. if (interp != NULL) {
  4731. /* If there is a configured interpreter, check for additional arguments
  4732. */
  4733. interp_arg =
  4734. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4735. } else {
  4736. /* Otherwise, the interpreter must be stated in the first line of the
  4737. * CGI script file, after a #! (shebang) mark. */
  4738. buf[0] = buf[1] = '\0';
  4739. /* Get the full script path */
  4740. mg_snprintf(
  4741. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4742. if (truncated) {
  4743. pi.hProcess = (pid_t)-1;
  4744. goto spawn_cleanup;
  4745. }
  4746. /* Open the script file, to read the first line */
  4747. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4748. /* Read the first line of the script into the buffer */
  4749. mg_fgets(buf, sizeof(buf), &file);
  4750. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4751. buf[sizeof(buf) - 1] = '\0';
  4752. }
  4753. if ((buf[0] == '#') && (buf[1] == '!')) {
  4754. trim_trailing_whitespaces(buf + 2);
  4755. } else {
  4756. buf[2] = '\0';
  4757. }
  4758. interp = buf + 2;
  4759. }
  4760. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4761. if (interp[0] != '\0') {
  4762. /* This is an interpreted script file. We must call the interpreter. */
  4763. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4764. mg_snprintf(conn,
  4765. &truncated,
  4766. cmdline,
  4767. sizeof(cmdline),
  4768. "\"%s\" %s \"%s\\%s\"",
  4769. interp,
  4770. interp_arg,
  4771. full_dir,
  4772. prog);
  4773. } else {
  4774. mg_snprintf(conn,
  4775. &truncated,
  4776. cmdline,
  4777. sizeof(cmdline),
  4778. "\"%s\" \"%s\\%s\"",
  4779. interp,
  4780. full_dir,
  4781. prog);
  4782. }
  4783. } else {
  4784. /* This is (probably) a compiled program. We call it directly. */
  4785. mg_snprintf(conn,
  4786. &truncated,
  4787. cmdline,
  4788. sizeof(cmdline),
  4789. "\"%s\\%s\"",
  4790. full_dir,
  4791. prog);
  4792. }
  4793. if (truncated) {
  4794. pi.hProcess = (pid_t)-1;
  4795. goto spawn_cleanup;
  4796. }
  4797. DEBUG_TRACE("Running [%s]", cmdline);
  4798. if (CreateProcessA(NULL,
  4799. cmdline,
  4800. NULL,
  4801. NULL,
  4802. TRUE,
  4803. CREATE_NEW_PROCESS_GROUP,
  4804. envblk,
  4805. NULL,
  4806. &si,
  4807. &pi)
  4808. == 0) {
  4809. mg_cry_internal(
  4810. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4811. pi.hProcess = (pid_t)-1;
  4812. /* goto spawn_cleanup; */
  4813. }
  4814. spawn_cleanup:
  4815. (void)CloseHandle(si.hStdOutput);
  4816. (void)CloseHandle(si.hStdError);
  4817. (void)CloseHandle(si.hStdInput);
  4818. if (pi.hThread != NULL) {
  4819. (void)CloseHandle(pi.hThread);
  4820. }
  4821. return (pid_t)pi.hProcess;
  4822. }
  4823. #endif /* !NO_CGI */
  4824. static int
  4825. set_blocking_mode(SOCKET sock)
  4826. {
  4827. unsigned long non_blocking = 0;
  4828. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4829. }
  4830. static int
  4831. set_non_blocking_mode(SOCKET sock)
  4832. {
  4833. unsigned long non_blocking = 1;
  4834. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4835. }
  4836. #else
  4837. #if !defined(NO_FILESYSTEMS)
  4838. static int
  4839. mg_stat(const struct mg_connection *conn,
  4840. const char *path,
  4841. struct mg_file_stat *filep)
  4842. {
  4843. struct stat st;
  4844. if (!filep) {
  4845. return 0;
  4846. }
  4847. memset(filep, 0, sizeof(*filep));
  4848. if (mg_path_suspicious(conn, path)) {
  4849. return 0;
  4850. }
  4851. if (0 == stat(path, &st)) {
  4852. filep->size = (uint64_t)(st.st_size);
  4853. filep->last_modified = st.st_mtime;
  4854. filep->is_directory = S_ISDIR(st.st_mode);
  4855. return 1;
  4856. }
  4857. return 0;
  4858. }
  4859. #endif /* NO_FILESYSTEMS */
  4860. static void
  4861. set_close_on_exec(int fd,
  4862. const struct mg_connection *conn /* may be null */,
  4863. struct mg_context *ctx /* may be null */)
  4864. {
  4865. #if defined(__ZEPHYR__) || defined(ESP_PLATFORM)
  4866. (void)fd;
  4867. (void)conn;
  4868. (void)ctx;
  4869. #else
  4870. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4871. if (conn || ctx) {
  4872. struct mg_connection fc;
  4873. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4874. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4875. __func__,
  4876. strerror(ERRNO));
  4877. }
  4878. }
  4879. #endif
  4880. }
  4881. CIVETWEB_API int
  4882. mg_start_thread(mg_thread_func_t func, void *param)
  4883. {
  4884. cw_thread_handle_t thread_id;
  4885. int result;
  4886. #if defined(ESP_PLATFORM)
  4887. thread_id.stack_size = (HTTP_ESP_STACK + sizeof(StackType_t) - 1) / sizeof(StackType_t);
  4888. thread_id.task_buffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  4889. thread_id.x_stack = (StackType_t*) heap_caps_malloc(thread_id.stack_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  4890. thread_id.param = param;
  4891. thread_id.entry_func = func;
  4892. thread_id.task_handle = xTaskCreateStaticPinnedToCore(freeRTOSTaskEntryFunc, "civetweb", thread_id.stack_size, &thread_id,
  4893. CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT, thread_id.x_stack, thread_id.task_buffer, 1);
  4894. if (thread_id.task_handle != NULL) {
  4895. result = 0;
  4896. } else {
  4897. result = -1;
  4898. }
  4899. #else
  4900. pthread_attr_t attr;
  4901. (void)pthread_attr_init(&attr);
  4902. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4903. #if defined(__ZEPHYR__)
  4904. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4905. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4906. /* Compile-time option to control stack size,
  4907. * e.g. -DUSE_STACK_SIZE=16384 */
  4908. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4909. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4910. result = pthread_create(&thread_id, &attr, func, param);
  4911. pthread_attr_destroy(&attr);
  4912. #endif
  4913. return result;
  4914. }
  4915. /* Start a thread storing the thread context. */
  4916. static int
  4917. mg_start_thread_with_id(mg_thread_func_t func,
  4918. void *param,
  4919. cw_thread_handle_t *threadidptr)
  4920. {
  4921. cw_thread_handle_t thread_id;
  4922. int result;
  4923. #if defined(ESP_PLATFORM)
  4924. result = 0;
  4925. thread_id.stack_size = (HTTP_ESP_STACK + sizeof(StackType_t) - 1) / sizeof(StackType_t);
  4926. thread_id.task_buffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  4927. thread_id.x_stack = (StackType_t*) heap_caps_malloc(thread_id.stack_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  4928. thread_id.param = param;
  4929. thread_id.entry_func = func;
  4930. thread_id.task_handle = xTaskCreateStaticPinnedToCore(freeRTOSTaskEntryFunc, "civetweb", thread_id.stack_size, &thread_id,
  4931. CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT, thread_id.x_stack, thread_id.task_buffer, 1);
  4932. if (thread_id.task_handle != NULL) {
  4933. result = 0;
  4934. *threadidptr = thread_id;
  4935. } else {
  4936. result = -1;
  4937. }
  4938. #else
  4939. #if defined(__ZEPHYR__)
  4940. pthread_attr_setstack(&attr,
  4941. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4942. ZEPHYR_STACK_SIZE);
  4943. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4944. /* Compile-time option to control stack size,
  4945. * e.g. -DUSE_STACK_SIZE=16384 */
  4946. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4947. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4948. result = pthread_create(&thread_id, NULL, func, param);
  4949. if ((result == 0) && (threadidptr != NULL)) {
  4950. *threadidptr = thread_id;
  4951. }
  4952. #endif
  4953. return result;
  4954. }
  4955. /* Wait for a thread to finish. */
  4956. static int
  4957. mg_join_thread(cw_thread_handle_t threadid)
  4958. {
  4959. int result;
  4960. #if defined(ESP_PLATFORM)
  4961. //TODO FREERTOS JOIN, WILL REQUIRE A SEMAPHORE
  4962. result = 0;
  4963. #else
  4964. result = pthread_join(threadid, NULL);
  4965. #endif
  4966. return result;
  4967. }
  4968. #if !defined(NO_CGI)
  4969. static pid_t
  4970. spawn_process(struct mg_connection *conn,
  4971. const char *prog,
  4972. char *envblk,
  4973. char *envp[],
  4974. int fdin[2],
  4975. int fdout[2],
  4976. int fderr[2],
  4977. const char *dir,
  4978. unsigned char cgi_config_idx)
  4979. {
  4980. pid_t pid;
  4981. const char *interp;
  4982. (void)envblk;
  4983. if ((pid = fork()) == -1) {
  4984. /* Parent */
  4985. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4986. } else if (pid != 0) {
  4987. /* Make sure children close parent-side descriptors.
  4988. * The caller will close the child-side immediately. */
  4989. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4990. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4991. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4992. } else {
  4993. /* Child */
  4994. if (chdir(dir) != 0) {
  4995. mg_cry_internal(
  4996. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4997. } else if (dup2(fdin[0], 0) == -1) {
  4998. mg_cry_internal(conn,
  4999. "%s: dup2(%d, 0): %s",
  5000. __func__,
  5001. fdin[0],
  5002. strerror(ERRNO));
  5003. } else if (dup2(fdout[1], 1) == -1) {
  5004. mg_cry_internal(conn,
  5005. "%s: dup2(%d, 1): %s",
  5006. __func__,
  5007. fdout[1],
  5008. strerror(ERRNO));
  5009. } else if (dup2(fderr[1], 2) == -1) {
  5010. mg_cry_internal(conn,
  5011. "%s: dup2(%d, 2): %s",
  5012. __func__,
  5013. fderr[1],
  5014. strerror(ERRNO));
  5015. } else {
  5016. struct sigaction sa;
  5017. /* Keep stderr and stdout in two different pipes.
  5018. * Stdout will be sent back to the client,
  5019. * stderr should go into a server error log. */
  5020. (void)close(fdin[0]);
  5021. (void)close(fdout[1]);
  5022. (void)close(fderr[1]);
  5023. /* Close write end fdin and read end fdout and fderr */
  5024. (void)close(fdin[1]);
  5025. (void)close(fdout[0]);
  5026. (void)close(fderr[0]);
  5027. /* After exec, all signal handlers are restored to their default
  5028. * values, with one exception of SIGCHLD. According to
  5029. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5030. * will leave unchanged after exec if it was set to be ignored.
  5031. * Restore it to default action. */
  5032. memset(&sa, 0, sizeof(sa));
  5033. sa.sa_handler = SIG_DFL;
  5034. sigaction(SIGCHLD, &sa, NULL);
  5035. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5036. if (interp == NULL) {
  5037. /* no interpreter configured, call the programm directly */
  5038. (void)execle(prog, prog, NULL, envp);
  5039. mg_cry_internal(conn,
  5040. "%s: execle(%s): %s",
  5041. __func__,
  5042. prog,
  5043. strerror(ERRNO));
  5044. } else {
  5045. /* call the configured interpreter */
  5046. const char *interp_args =
  5047. conn->dom_ctx
  5048. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5049. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5050. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5051. } else {
  5052. (void)execle(interp, interp, prog, NULL, envp);
  5053. }
  5054. mg_cry_internal(conn,
  5055. "%s: execle(%s %s): %s",
  5056. __func__,
  5057. interp,
  5058. prog,
  5059. strerror(ERRNO));
  5060. }
  5061. }
  5062. exit(EXIT_FAILURE);
  5063. }
  5064. return pid;
  5065. }
  5066. #endif /* !NO_CGI */
  5067. static int
  5068. set_non_blocking_mode(SOCKET sock)
  5069. {
  5070. int flags = fcntl(sock, F_GETFL, 0);
  5071. if (flags < 0) {
  5072. return -1;
  5073. }
  5074. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5075. return -1;
  5076. }
  5077. return 0;
  5078. }
  5079. static int
  5080. set_blocking_mode(SOCKET sock)
  5081. {
  5082. int flags = fcntl(sock, F_GETFL, 0);
  5083. if (flags < 0) {
  5084. return -1;
  5085. }
  5086. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5087. return -1;
  5088. }
  5089. return 0;
  5090. }
  5091. #endif /* _WIN32 / else */
  5092. /* End of initial operating system specific define block. */
  5093. /* Get a random number (independent of C rand function) */
  5094. static uint64_t
  5095. get_random(void)
  5096. {
  5097. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5098. static uint64_t lcg = 0; /* Linear congruential generator */
  5099. uint64_t now = mg_get_current_time_ns();
  5100. if (lfsr == 0) {
  5101. /* lfsr will be only 0 if has not been initialized,
  5102. * so this code is called only once. */
  5103. lfsr = mg_get_current_time_ns();
  5104. lcg = mg_get_current_time_ns();
  5105. } else {
  5106. /* Get the next step of both random number generators. */
  5107. lfsr = (lfsr >> 1)
  5108. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5109. << 63);
  5110. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5111. }
  5112. /* Combining two pseudo-random number generators and a high resolution
  5113. * part
  5114. * of the current server time will make it hard (impossible?) to guess
  5115. * the
  5116. * next number. */
  5117. return (lfsr ^ lcg ^ now);
  5118. }
  5119. static int
  5120. mg_poll(struct mg_pollfd *pfd,
  5121. unsigned int n,
  5122. int milliseconds,
  5123. const stop_flag_t *stop_flag)
  5124. {
  5125. /* Call poll, but only for a maximum time of a few seconds.
  5126. * This will allow to stop the server after some seconds, instead
  5127. * of having to wait for a long socket timeout. */
  5128. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5129. int check_pollerr = 0;
  5130. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5131. /* If we wait for only one file descriptor, wait on error as well */
  5132. pfd[0].events |= POLLERR;
  5133. check_pollerr = 1;
  5134. }
  5135. do {
  5136. int result;
  5137. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5138. /* Shut down signal */
  5139. return -2;
  5140. }
  5141. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5142. ms_now = milliseconds;
  5143. }
  5144. result = poll(pfd, n, ms_now);
  5145. if (result != 0) {
  5146. /* Poll returned either success (1) or error (-1).
  5147. * Forward both to the caller. */
  5148. if ((check_pollerr)
  5149. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5150. == POLLERR)) {
  5151. /* One and only file descriptor returned error */
  5152. return -1;
  5153. }
  5154. return result;
  5155. }
  5156. /* Poll returned timeout (0). */
  5157. if (milliseconds > 0) {
  5158. milliseconds -= ms_now;
  5159. }
  5160. } while (milliseconds > 0);
  5161. /* timeout: return 0 */
  5162. return 0;
  5163. }
  5164. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5165. * descriptor.
  5166. * Return value:
  5167. * >=0 .. number of bytes successfully written
  5168. * -1 .. timeout
  5169. * -2 .. error
  5170. */
  5171. static int
  5172. push_inner(struct mg_context *ctx,
  5173. FILE *fp,
  5174. SOCKET sock,
  5175. SSL *ssl,
  5176. const char *buf,
  5177. int len,
  5178. double timeout)
  5179. {
  5180. uint64_t start = 0, now = 0, timeout_ns = 0;
  5181. int n, err;
  5182. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5183. #if defined(_WIN32)
  5184. typedef int len_t;
  5185. #else
  5186. typedef size_t len_t;
  5187. #endif
  5188. if (timeout > 0) {
  5189. now = mg_get_current_time_ns();
  5190. start = now;
  5191. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5192. }
  5193. if (ctx == NULL) {
  5194. return -2;
  5195. }
  5196. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5197. if (ssl) {
  5198. return -2;
  5199. }
  5200. #endif
  5201. /* Try to read until it succeeds, fails, times out, or the server
  5202. * shuts down. */
  5203. for (;;) {
  5204. #if defined(USE_MBEDTLS)
  5205. if (ssl != NULL) {
  5206. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5207. if (n <= 0) {
  5208. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5209. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5210. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5211. n = 0;
  5212. } else {
  5213. fprintf(stderr, "SSL write failed, error %d\n", n);
  5214. return -2;
  5215. }
  5216. } else {
  5217. err = 0;
  5218. }
  5219. } else
  5220. #elif !defined(NO_SSL)
  5221. if (ssl != NULL) {
  5222. ERR_clear_error();
  5223. n = SSL_write(ssl, buf, len);
  5224. if (n <= 0) {
  5225. err = SSL_get_error(ssl, n);
  5226. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5227. err = ERRNO;
  5228. } else if ((err == SSL_ERROR_WANT_READ)
  5229. || (err == SSL_ERROR_WANT_WRITE)) {
  5230. n = 0;
  5231. } else {
  5232. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5233. ERR_clear_error();
  5234. return -2;
  5235. }
  5236. ERR_clear_error();
  5237. } else {
  5238. err = 0;
  5239. }
  5240. } else
  5241. #endif
  5242. if (fp != NULL) {
  5243. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5244. if (ferror(fp)) {
  5245. n = -1;
  5246. err = ERRNO;
  5247. } else {
  5248. err = 0;
  5249. }
  5250. } else {
  5251. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5252. err = (n < 0) ? ERRNO : 0;
  5253. #if defined(_WIN32)
  5254. if (err == WSAEWOULDBLOCK) {
  5255. err = 0;
  5256. n = 0;
  5257. }
  5258. #else
  5259. if (ERROR_TRY_AGAIN(err)) {
  5260. err = 0;
  5261. n = 0;
  5262. }
  5263. #endif
  5264. if (n < 0) {
  5265. /* shutdown of the socket at client side */
  5266. return -2;
  5267. }
  5268. }
  5269. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5270. return -2;
  5271. }
  5272. if ((n > 0) || ((n == 0) && (len == 0))) {
  5273. /* some data has been read, or no data was requested */
  5274. return n;
  5275. }
  5276. if (n < 0) {
  5277. /* socket error - check errno */
  5278. DEBUG_TRACE("send() failed, error %d", err);
  5279. /* TODO (mid): error handling depending on the error code.
  5280. * These codes are different between Windows and Linux.
  5281. * Currently there is no problem with failing send calls,
  5282. * if there is a reproducible situation, it should be
  5283. * investigated in detail.
  5284. */
  5285. return -2;
  5286. }
  5287. /* Only in case n=0 (timeout), repeat calling the write function */
  5288. /* If send failed, wait before retry */
  5289. if (fp != NULL) {
  5290. /* For files, just wait a fixed time.
  5291. * Maybe it helps, maybe not. */
  5292. mg_sleep(5);
  5293. } else {
  5294. /* For sockets, wait for the socket using poll */
  5295. struct mg_pollfd pfd[1];
  5296. int pollres;
  5297. pfd[0].fd = sock;
  5298. pfd[0].events = POLLOUT;
  5299. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5300. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5301. return -2;
  5302. }
  5303. if (pollres > 0) {
  5304. continue;
  5305. }
  5306. }
  5307. if (timeout > 0) {
  5308. now = mg_get_current_time_ns();
  5309. if ((now - start) > timeout_ns) {
  5310. /* Timeout */
  5311. break;
  5312. }
  5313. }
  5314. }
  5315. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5316. used */
  5317. return -1;
  5318. }
  5319. static int
  5320. push_all(struct mg_context *ctx,
  5321. FILE *fp,
  5322. SOCKET sock,
  5323. SSL *ssl,
  5324. const char *buf,
  5325. int len)
  5326. {
  5327. double timeout = -1.0;
  5328. int n, nwritten = 0;
  5329. if (ctx == NULL) {
  5330. return -1;
  5331. }
  5332. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5333. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5334. }
  5335. if (timeout <= 0.0) {
  5336. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5337. / 1000.0;
  5338. }
  5339. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5340. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5341. if (n < 0) {
  5342. if (nwritten == 0) {
  5343. nwritten = -1; /* Propagate the error */
  5344. }
  5345. break;
  5346. } else if (n == 0) {
  5347. break; /* No more data to write */
  5348. } else {
  5349. nwritten += n;
  5350. len -= n;
  5351. }
  5352. }
  5353. return nwritten;
  5354. }
  5355. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5356. * Return value:
  5357. * >=0 .. number of bytes successfully read
  5358. * -1 .. timeout
  5359. * -2 .. error
  5360. */
  5361. static int
  5362. pull_inner(FILE *fp,
  5363. struct mg_connection *conn,
  5364. char *buf,
  5365. int len,
  5366. double timeout)
  5367. {
  5368. int nread, err = 0;
  5369. #if defined(_WIN32)
  5370. typedef int len_t;
  5371. #else
  5372. typedef size_t len_t;
  5373. #endif
  5374. /* We need an additional wait loop around this, because in some cases
  5375. * with TLSwe may get data from the socket but not from SSL_read.
  5376. * In this case we need to repeat at least once.
  5377. */
  5378. if (fp != NULL) {
  5379. /* Use read() instead of fread(), because if we're reading from the
  5380. * CGI pipe, fread() may block until IO buffer is filled up. We
  5381. * cannot afford to block and must pass all read bytes immediately
  5382. * to the client. */
  5383. nread = (int)read(fileno(fp), buf, (size_t)len);
  5384. err = (nread < 0) ? ERRNO : 0;
  5385. if ((nread == 0) && (len > 0)) {
  5386. /* Should get data, but got EOL */
  5387. return -2;
  5388. }
  5389. #if defined(USE_MBEDTLS)
  5390. } else if (conn->ssl != NULL) {
  5391. struct mg_pollfd pfd[1];
  5392. int to_read;
  5393. int pollres;
  5394. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5395. if (to_read > 0) {
  5396. /* We already know there is no more data buffered in conn->buf
  5397. * but there is more available in the SSL layer. So don't poll
  5398. * conn->client.sock yet. */
  5399. pollres = 1;
  5400. if (to_read > len)
  5401. to_read = len;
  5402. } else {
  5403. pfd[0].fd = conn->client.sock;
  5404. pfd[0].events = POLLIN;
  5405. to_read = len;
  5406. pollres = mg_poll(pfd,
  5407. 1,
  5408. (int)(timeout * 1000.0),
  5409. &(conn->phys_ctx->stop_flag));
  5410. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5411. return -2;
  5412. }
  5413. }
  5414. if (pollres > 0) {
  5415. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5416. if (nread <= 0) {
  5417. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5418. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5419. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5420. nread = 0;
  5421. } else {
  5422. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5423. return -2;
  5424. }
  5425. } else {
  5426. err = 0;
  5427. }
  5428. } else if (pollres < 0) {
  5429. /* Error */
  5430. return -2;
  5431. } else {
  5432. /* pollres = 0 means timeout */
  5433. nread = 0;
  5434. }
  5435. #elif !defined(NO_SSL)
  5436. } else if (conn->ssl != NULL) {
  5437. int ssl_pending;
  5438. struct mg_pollfd pfd[1];
  5439. int pollres;
  5440. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5441. /* We already know there is no more data buffered in conn->buf
  5442. * but there is more available in the SSL layer. So don't poll
  5443. * conn->client.sock yet. */
  5444. if (ssl_pending > len) {
  5445. ssl_pending = len;
  5446. }
  5447. pollres = 1;
  5448. } else {
  5449. pfd[0].fd = conn->client.sock;
  5450. pfd[0].events = POLLIN;
  5451. pollres = mg_poll(pfd,
  5452. 1,
  5453. (int)(timeout * 1000.0),
  5454. &(conn->phys_ctx->stop_flag));
  5455. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5456. return -2;
  5457. }
  5458. }
  5459. if (pollres > 0) {
  5460. ERR_clear_error();
  5461. nread =
  5462. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5463. if (nread <= 0) {
  5464. err = SSL_get_error(conn->ssl, nread);
  5465. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5466. err = ERRNO;
  5467. } else if ((err == SSL_ERROR_WANT_READ)
  5468. || (err == SSL_ERROR_WANT_WRITE)) {
  5469. nread = 0;
  5470. } else {
  5471. /* All errors should return -2 */
  5472. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5473. ERR_clear_error();
  5474. return -2;
  5475. }
  5476. ERR_clear_error();
  5477. } else {
  5478. err = 0;
  5479. }
  5480. } else if (pollres < 0) {
  5481. /* Error */
  5482. return -2;
  5483. } else {
  5484. /* pollres = 0 means timeout */
  5485. nread = 0;
  5486. }
  5487. #endif
  5488. } else {
  5489. struct mg_pollfd pfd[1];
  5490. int pollres;
  5491. pfd[0].fd = conn->client.sock;
  5492. pfd[0].events = POLLIN;
  5493. pollres = mg_poll(pfd,
  5494. 1,
  5495. (int)(timeout * 1000.0),
  5496. &(conn->phys_ctx->stop_flag));
  5497. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5498. return -2;
  5499. }
  5500. if (pollres > 0) {
  5501. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5502. err = (nread < 0) ? ERRNO : 0;
  5503. if (nread <= 0) {
  5504. /* shutdown of the socket at client side */
  5505. return -2;
  5506. }
  5507. } else if (pollres < 0) {
  5508. /* error callint poll */
  5509. return -2;
  5510. } else {
  5511. /* pollres = 0 means timeout */
  5512. nread = 0;
  5513. }
  5514. }
  5515. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5516. return -2;
  5517. }
  5518. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5519. /* some data has been read, or no data was requested */
  5520. return nread;
  5521. }
  5522. if (nread < 0) {
  5523. /* socket error - check errno */
  5524. #if defined(_WIN32)
  5525. if (err == WSAEWOULDBLOCK) {
  5526. /* TODO (low): check if this is still required */
  5527. /* standard case if called from close_socket_gracefully */
  5528. return -2;
  5529. } else if (err == WSAETIMEDOUT) {
  5530. /* TODO (low): check if this is still required */
  5531. /* timeout is handled by the while loop */
  5532. return 0;
  5533. } else if (err == WSAECONNABORTED) {
  5534. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5535. return -2;
  5536. } else {
  5537. DEBUG_TRACE("recv() failed, error %d", err);
  5538. return -2;
  5539. }
  5540. #else
  5541. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5542. * if the timeout is reached and if the socket was set to non-
  5543. * blocking in close_socket_gracefully, so we can not distinguish
  5544. * here. We have to wait for the timeout in both cases for now.
  5545. */
  5546. if (ERROR_TRY_AGAIN(err)) {
  5547. /* TODO (low): check if this is still required */
  5548. /* EAGAIN/EWOULDBLOCK:
  5549. * standard case if called from close_socket_gracefully
  5550. * => should return -1 */
  5551. /* or timeout occurred
  5552. * => the code must stay in the while loop */
  5553. /* EINTR can be generated on a socket with a timeout set even
  5554. * when SA_RESTART is effective for all relevant signals
  5555. * (see signal(7)).
  5556. * => stay in the while loop */
  5557. } else {
  5558. DEBUG_TRACE("recv() failed, error %d", err);
  5559. return -2;
  5560. }
  5561. #endif
  5562. }
  5563. /* Timeout occurred, but no data available. */
  5564. return -1;
  5565. }
  5566. static int
  5567. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5568. {
  5569. int n, nread = 0;
  5570. double timeout = -1.0;
  5571. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5572. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5573. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5574. }
  5575. if (timeout <= 0.0) {
  5576. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5577. / 1000.0;
  5578. }
  5579. start_time = mg_get_current_time_ns();
  5580. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5581. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5582. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5583. if (n == -2) {
  5584. if (nread == 0) {
  5585. nread = -1; /* Propagate the error */
  5586. }
  5587. break;
  5588. } else if (n == -1) {
  5589. /* timeout */
  5590. if (timeout >= 0.0) {
  5591. now = mg_get_current_time_ns();
  5592. if ((now - start_time) <= timeout_ns) {
  5593. continue;
  5594. }
  5595. }
  5596. break;
  5597. } else if (n == 0) {
  5598. break; /* No more data to read */
  5599. } else {
  5600. nread += n;
  5601. len -= n;
  5602. }
  5603. }
  5604. return nread;
  5605. }
  5606. static void
  5607. discard_unread_request_data(struct mg_connection *conn)
  5608. {
  5609. char buf[MG_BUF_LEN];
  5610. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5611. ;
  5612. }
  5613. static int
  5614. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5615. {
  5616. int64_t content_len, n, buffered_len, nread;
  5617. int64_t len64 =
  5618. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5619. * int, we may not read more
  5620. * bytes */
  5621. const char *body;
  5622. if (conn == NULL) {
  5623. return 0;
  5624. }
  5625. /* If Content-Length is not set for a response with body data,
  5626. * we do not know in advance how much data should be read. */
  5627. content_len = conn->content_len;
  5628. if (content_len < 0) {
  5629. /* The body data is completed when the connection is closed. */
  5630. content_len = INT64_MAX;
  5631. }
  5632. nread = 0;
  5633. if (conn->consumed_content < content_len) {
  5634. /* Adjust number of bytes to read. */
  5635. int64_t left_to_read = content_len - conn->consumed_content;
  5636. if (left_to_read < len64) {
  5637. /* Do not read more than the total content length of the
  5638. * request.
  5639. */
  5640. len64 = left_to_read;
  5641. }
  5642. /* Return buffered data */
  5643. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5644. - conn->consumed_content;
  5645. if (buffered_len > 0) {
  5646. if (len64 < buffered_len) {
  5647. buffered_len = len64;
  5648. }
  5649. body = conn->buf + conn->request_len + conn->consumed_content;
  5650. memcpy(buf, body, (size_t)buffered_len);
  5651. len64 -= buffered_len;
  5652. conn->consumed_content += buffered_len;
  5653. nread += buffered_len;
  5654. buf = (char *)buf + buffered_len;
  5655. }
  5656. /* We have returned all buffered data. Read new data from the remote
  5657. * socket.
  5658. */
  5659. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5660. conn->consumed_content += n;
  5661. nread += n;
  5662. } else {
  5663. nread = ((nread > 0) ? nread : n);
  5664. }
  5665. }
  5666. return (int)nread;
  5667. }
  5668. /* Forward declarations */
  5669. static void handle_request(struct mg_connection *);
  5670. static void log_access(const struct mg_connection *);
  5671. /* Handle request, update statistics and call access log */
  5672. static void
  5673. handle_request_stat_log(struct mg_connection *conn)
  5674. {
  5675. #if defined(USE_SERVER_STATS)
  5676. struct timespec tnow;
  5677. conn->conn_state = 4; /* processing */
  5678. #endif
  5679. handle_request(conn);
  5680. #if defined(USE_SERVER_STATS)
  5681. conn->conn_state = 5; /* processed */
  5682. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5683. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5684. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5685. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5686. conn->num_bytes_sent);
  5687. #endif
  5688. DEBUG_TRACE("%s", "handle_request done");
  5689. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5690. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5691. DEBUG_TRACE("%s", "end_request callback done");
  5692. }
  5693. log_access(conn);
  5694. }
  5695. #if defined(USE_HTTP2)
  5696. #if defined(NO_SSL)
  5697. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5698. #endif
  5699. #define USE_ALPN
  5700. #include "http2.inl"
  5701. /* Not supported with HTTP/2 */
  5702. #define HTTP1_only \
  5703. { \
  5704. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5705. http2_must_use_http1(conn); \
  5706. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5707. return; \
  5708. } \
  5709. }
  5710. #else
  5711. #define HTTP1_only
  5712. #endif
  5713. CIVETWEB_API int
  5714. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5715. {
  5716. if (len > INT_MAX) {
  5717. len = INT_MAX;
  5718. }
  5719. if (conn == NULL) {
  5720. return 0;
  5721. }
  5722. if (conn->is_chunked) {
  5723. size_t all_read = 0;
  5724. while (len > 0) {
  5725. if (conn->is_chunked >= 3) {
  5726. /* No more data left to read */
  5727. return 0;
  5728. }
  5729. if (conn->is_chunked != 1) {
  5730. /* Has error */
  5731. return -1;
  5732. }
  5733. if (conn->consumed_content != conn->content_len) {
  5734. /* copy from the current chunk */
  5735. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5736. if (read_ret < 1) {
  5737. /* read error */
  5738. conn->is_chunked = 2;
  5739. return -1;
  5740. }
  5741. all_read += (size_t)read_ret;
  5742. len -= (size_t)read_ret;
  5743. if (conn->consumed_content == conn->content_len) {
  5744. /* Add data bytes in the current chunk have been read,
  5745. * so we are expecting \r\n now. */
  5746. char x[2];
  5747. conn->content_len += 2;
  5748. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5749. || (x[1] != '\n')) {
  5750. /* Protocol violation */
  5751. conn->is_chunked = 2;
  5752. return -1;
  5753. }
  5754. }
  5755. } else {
  5756. /* fetch a new chunk */
  5757. size_t i;
  5758. char lenbuf[64];
  5759. char *end = NULL;
  5760. unsigned long chunkSize = 0;
  5761. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5762. conn->content_len++;
  5763. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5764. lenbuf[i] = 0;
  5765. }
  5766. if ((i > 0) && (lenbuf[i] == '\r')
  5767. && (lenbuf[i - 1] != '\r')) {
  5768. continue;
  5769. }
  5770. if ((i > 1) && (lenbuf[i] == '\n')
  5771. && (lenbuf[i - 1] == '\r')) {
  5772. lenbuf[i + 1] = 0;
  5773. chunkSize = strtoul(lenbuf, &end, 16);
  5774. if (chunkSize == 0) {
  5775. /* regular end of content */
  5776. conn->is_chunked = 3;
  5777. }
  5778. break;
  5779. }
  5780. if (!isxdigit((unsigned char)lenbuf[i])) {
  5781. /* illegal character for chunk length */
  5782. conn->is_chunked = 2;
  5783. return -1;
  5784. }
  5785. }
  5786. if ((end == NULL) || (*end != '\r')) {
  5787. /* chunksize not set correctly */
  5788. conn->is_chunked = 2;
  5789. return -1;
  5790. }
  5791. if (chunkSize == 0) {
  5792. /* try discarding trailer for keep-alive */
  5793. conn->content_len += 2;
  5794. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5795. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5796. conn->is_chunked = 4;
  5797. }
  5798. break;
  5799. }
  5800. /* append a new chunk */
  5801. conn->content_len += (int64_t)chunkSize;
  5802. }
  5803. }
  5804. return (int)all_read;
  5805. }
  5806. return mg_read_inner(conn, buf, len);
  5807. }
  5808. CIVETWEB_API int
  5809. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5810. {
  5811. time_t now;
  5812. int n, total, allowed;
  5813. if (conn == NULL) {
  5814. return 0;
  5815. }
  5816. if (len > INT_MAX) {
  5817. return -1;
  5818. }
  5819. /* Mark connection as "data sent" */
  5820. conn->request_state = 10;
  5821. #if defined(USE_HTTP2)
  5822. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5823. http2_data_frame_head(conn, len, 0);
  5824. }
  5825. #endif
  5826. if (conn->throttle > 0) {
  5827. if ((now = time(NULL)) != conn->last_throttle_time) {
  5828. conn->last_throttle_time = now;
  5829. conn->last_throttle_bytes = 0;
  5830. }
  5831. allowed = conn->throttle - conn->last_throttle_bytes;
  5832. if (allowed > (int)len) {
  5833. allowed = (int)len;
  5834. }
  5835. total = push_all(conn->phys_ctx,
  5836. NULL,
  5837. conn->client.sock,
  5838. conn->ssl,
  5839. (const char *)buf,
  5840. allowed);
  5841. if (total == allowed) {
  5842. buf = (const char *)buf + total;
  5843. conn->last_throttle_bytes += total;
  5844. while ((total < (int)len)
  5845. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5846. allowed = (conn->throttle > ((int)len - total))
  5847. ? (int)len - total
  5848. : conn->throttle;
  5849. n = push_all(conn->phys_ctx,
  5850. NULL,
  5851. conn->client.sock,
  5852. conn->ssl,
  5853. (const char *)buf,
  5854. allowed);
  5855. if (n != allowed) {
  5856. break;
  5857. }
  5858. sleep(1);
  5859. conn->last_throttle_bytes = allowed;
  5860. conn->last_throttle_time = time(NULL);
  5861. buf = (const char *)buf + n;
  5862. total += n;
  5863. }
  5864. }
  5865. } else {
  5866. total = push_all(conn->phys_ctx,
  5867. NULL,
  5868. conn->client.sock,
  5869. conn->ssl,
  5870. (const char *)buf,
  5871. (int)len);
  5872. }
  5873. if (total > 0) {
  5874. conn->num_bytes_sent += total;
  5875. }
  5876. return total;
  5877. }
  5878. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5879. CIVETWEB_API int
  5880. mg_send_chunk(struct mg_connection *conn,
  5881. const char *chunk,
  5882. unsigned int chunk_len)
  5883. {
  5884. char lenbuf[16];
  5885. size_t lenbuf_len;
  5886. int ret;
  5887. int t;
  5888. /* First store the length information in a text buffer. */
  5889. sprintf(lenbuf, "%x\r\n", chunk_len);
  5890. lenbuf_len = strlen(lenbuf);
  5891. /* Then send length information, chunk and terminating \r\n. */
  5892. ret = mg_write(conn, lenbuf, lenbuf_len);
  5893. if (ret != (int)lenbuf_len) {
  5894. return -1;
  5895. }
  5896. t = ret;
  5897. ret = mg_write(conn, chunk, chunk_len);
  5898. if (ret != (int)chunk_len) {
  5899. return -1;
  5900. }
  5901. t += ret;
  5902. ret = mg_write(conn, "\r\n", 2);
  5903. if (ret != 2) {
  5904. return -1;
  5905. }
  5906. t += ret;
  5907. return t;
  5908. }
  5909. #if defined(GCC_DIAGNOSTIC)
  5910. /* This block forwards format strings to printf implementations,
  5911. * so we need to disable the format-nonliteral warning. */
  5912. #pragma GCC diagnostic push
  5913. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5914. #endif
  5915. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5916. static int
  5917. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5918. {
  5919. va_list ap_copy;
  5920. size_t size = MG_BUF_LEN / 4;
  5921. int len = -1;
  5922. *buf = NULL;
  5923. while (len < 0) {
  5924. if (*buf) {
  5925. mg_free(*buf);
  5926. }
  5927. size *= 4;
  5928. *buf = (char *)mg_malloc(size);
  5929. if (!*buf) {
  5930. break;
  5931. }
  5932. va_copy(ap_copy, ap);
  5933. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5934. va_end(ap_copy);
  5935. (*buf)[size - 1] = 0;
  5936. }
  5937. return len;
  5938. }
  5939. /* Print message to buffer. If buffer is large enough to hold the message,
  5940. * return buffer. If buffer is to small, allocate large enough buffer on
  5941. * heap,
  5942. * and return allocated buffer. */
  5943. static int
  5944. alloc_vprintf(char **out_buf,
  5945. char *prealloc_buf,
  5946. size_t prealloc_size,
  5947. const char *fmt,
  5948. va_list ap)
  5949. {
  5950. va_list ap_copy;
  5951. int len;
  5952. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5953. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5954. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5955. * Therefore, we make two passes: on first pass, get required message
  5956. * length.
  5957. * On second pass, actually print the message. */
  5958. va_copy(ap_copy, ap);
  5959. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5960. va_end(ap_copy);
  5961. if (len < 0) {
  5962. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5963. * Switch to alternative code path that uses incremental
  5964. * allocations.
  5965. */
  5966. va_copy(ap_copy, ap);
  5967. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5968. va_end(ap_copy);
  5969. } else if ((size_t)(len) >= prealloc_size) {
  5970. /* The pre-allocated buffer not large enough. */
  5971. /* Allocate a new buffer. */
  5972. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5973. if (!*out_buf) {
  5974. /* Allocation failed. Return -1 as "out of memory" error. */
  5975. return -1;
  5976. }
  5977. /* Buffer allocation successful. Store the string there. */
  5978. va_copy(ap_copy, ap);
  5979. IGNORE_UNUSED_RESULT(
  5980. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5981. va_end(ap_copy);
  5982. } else {
  5983. /* The pre-allocated buffer is large enough.
  5984. * Use it to store the string and return the address. */
  5985. va_copy(ap_copy, ap);
  5986. IGNORE_UNUSED_RESULT(
  5987. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5988. va_end(ap_copy);
  5989. *out_buf = prealloc_buf;
  5990. }
  5991. return len;
  5992. }
  5993. static int
  5994. alloc_printf(char **out_buf, const char *fmt, ...)
  5995. {
  5996. va_list ap;
  5997. int result;
  5998. va_start(ap, fmt);
  5999. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6000. va_end(ap);
  6001. return result;
  6002. }
  6003. #if defined(GCC_DIAGNOSTIC)
  6004. /* Enable format-nonliteral warning again. */
  6005. #pragma GCC diagnostic pop
  6006. #endif
  6007. static int
  6008. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6009. {
  6010. char mem[MG_BUF_LEN];
  6011. char *buf = NULL;
  6012. int len;
  6013. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6014. len = mg_write(conn, buf, (size_t)len);
  6015. }
  6016. if (buf != mem) {
  6017. mg_free(buf);
  6018. }
  6019. return len;
  6020. }
  6021. CIVETWEB_API int
  6022. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6023. {
  6024. va_list ap;
  6025. int result;
  6026. va_start(ap, fmt);
  6027. result = mg_vprintf(conn, fmt, ap);
  6028. va_end(ap);
  6029. return result;
  6030. }
  6031. CIVETWEB_API int
  6032. mg_url_decode(const char *src,
  6033. int src_len,
  6034. char *dst,
  6035. int dst_len,
  6036. int is_form_url_encoded)
  6037. {
  6038. int i, j, a, b;
  6039. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6040. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6041. if ((i < src_len - 2) && (src[i] == '%')
  6042. && isxdigit((unsigned char)src[i + 1])
  6043. && isxdigit((unsigned char)src[i + 2])) {
  6044. a = tolower((unsigned char)src[i + 1]);
  6045. b = tolower((unsigned char)src[i + 2]);
  6046. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6047. i += 2;
  6048. } else if (is_form_url_encoded && (src[i] == '+')) {
  6049. dst[j] = ' ';
  6050. } else {
  6051. dst[j] = src[i];
  6052. }
  6053. }
  6054. dst[j] = '\0'; /* Null-terminate the destination */
  6055. return (i >= src_len) ? j : -1;
  6056. }
  6057. /* form url decoding of an entire string */
  6058. static void
  6059. url_decode_in_place(char *buf)
  6060. {
  6061. int len = (int)strlen(buf);
  6062. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6063. }
  6064. CIVETWEB_API int
  6065. mg_get_var(const char *data,
  6066. size_t data_len,
  6067. const char *name,
  6068. char *dst,
  6069. size_t dst_len)
  6070. {
  6071. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6072. }
  6073. CIVETWEB_API int
  6074. mg_get_var2(const char *data,
  6075. size_t data_len,
  6076. const char *name,
  6077. char *dst,
  6078. size_t dst_len,
  6079. size_t occurrence)
  6080. {
  6081. const char *p, *e, *s;
  6082. size_t name_len;
  6083. int len;
  6084. if ((dst == NULL) || (dst_len == 0)) {
  6085. len = -2;
  6086. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6087. len = -1;
  6088. dst[0] = '\0';
  6089. } else {
  6090. name_len = strlen(name);
  6091. e = data + data_len;
  6092. len = -1;
  6093. dst[0] = '\0';
  6094. /* data is "var1=val1&var2=val2...". Find variable first */
  6095. for (p = data; p + name_len < e; p++) {
  6096. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6097. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6098. /* Point p to variable value */
  6099. p += name_len + 1;
  6100. /* Point s to the end of the value */
  6101. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6102. if (s == NULL) {
  6103. s = e;
  6104. }
  6105. DEBUG_ASSERT(s >= p);
  6106. if (s < p) {
  6107. return -3;
  6108. }
  6109. /* Decode variable into destination buffer */
  6110. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6111. /* Redirect error code from -1 to -2 (destination buffer too
  6112. * small). */
  6113. if (len == -1) {
  6114. len = -2;
  6115. }
  6116. break;
  6117. }
  6118. }
  6119. }
  6120. return len;
  6121. }
  6122. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6123. CIVETWEB_API int
  6124. mg_split_form_urlencoded(char *data,
  6125. struct mg_header *form_fields,
  6126. unsigned num_form_fields)
  6127. {
  6128. char *b;
  6129. int i;
  6130. int num = 0;
  6131. if (data == NULL) {
  6132. /* parameter error */
  6133. return -1;
  6134. }
  6135. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6136. /* determine the number of expected fields */
  6137. if (data[0] == 0) {
  6138. return 0;
  6139. }
  6140. /* count number of & to return the number of key-value-pairs */
  6141. num = 1;
  6142. while (*data) {
  6143. if (*data == '&') {
  6144. num++;
  6145. }
  6146. data++;
  6147. }
  6148. return num;
  6149. }
  6150. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6151. /* parameter error */
  6152. return -1;
  6153. }
  6154. for (i = 0; i < (int)num_form_fields; i++) {
  6155. /* extract key-value pairs from input data */
  6156. while ((*data == ' ') || (*data == '\t')) {
  6157. /* skip initial spaces */
  6158. data++;
  6159. }
  6160. if (*data == 0) {
  6161. /* end of string reached */
  6162. break;
  6163. }
  6164. form_fields[num].name = data;
  6165. /* find & or = */
  6166. b = data;
  6167. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6168. b++;
  6169. }
  6170. if (*b == 0) {
  6171. /* last key without value */
  6172. form_fields[num].value = NULL;
  6173. } else if (*b == '&') {
  6174. /* mid key without value */
  6175. form_fields[num].value = NULL;
  6176. } else {
  6177. /* terminate string */
  6178. *b = 0;
  6179. /* value starts after '=' */
  6180. data = b + 1;
  6181. form_fields[num].value = data;
  6182. }
  6183. /* new field is stored */
  6184. num++;
  6185. /* find a next key */
  6186. b = strchr(data, '&');
  6187. if (b == 0) {
  6188. /* no more data */
  6189. break;
  6190. } else {
  6191. /* terminate value of last field at '&' */
  6192. *b = 0;
  6193. /* next key-value-pairs starts after '&' */
  6194. data = b + 1;
  6195. }
  6196. }
  6197. /* Decode all values */
  6198. for (i = 0; i < num; i++) {
  6199. if (form_fields[i].name) {
  6200. url_decode_in_place((char *)form_fields[i].name);
  6201. }
  6202. if (form_fields[i].value) {
  6203. url_decode_in_place((char *)form_fields[i].value);
  6204. }
  6205. }
  6206. /* return number of fields found */
  6207. return num;
  6208. }
  6209. /* HCP24: some changes to compare whole var_name */
  6210. CIVETWEB_API int
  6211. mg_get_cookie(const char *cookie_header,
  6212. const char *var_name,
  6213. char *dst,
  6214. size_t dst_size)
  6215. {
  6216. const char *s, *p, *end;
  6217. int name_len, len = -1;
  6218. if ((dst == NULL) || (dst_size == 0)) {
  6219. return -2;
  6220. }
  6221. dst[0] = '\0';
  6222. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6223. return -1;
  6224. }
  6225. name_len = (int)strlen(var_name);
  6226. end = s + strlen(s);
  6227. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6228. if (s[name_len] == '=') {
  6229. /* HCP24: now check is it a substring or a full cookie name */
  6230. if ((s == cookie_header) || (s[-1] == ' ')) {
  6231. s += name_len + 1;
  6232. if ((p = strchr(s, ' ')) == NULL) {
  6233. p = end;
  6234. }
  6235. if (p[-1] == ';') {
  6236. p--;
  6237. }
  6238. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6239. s++;
  6240. p--;
  6241. }
  6242. if ((size_t)(p - s) < dst_size) {
  6243. len = (int)(p - s);
  6244. mg_strlcpy(dst, s, (size_t)len + 1);
  6245. } else {
  6246. len = -3;
  6247. }
  6248. break;
  6249. }
  6250. }
  6251. }
  6252. return len;
  6253. }
  6254. CIVETWEB_API int
  6255. mg_base64_encode(const unsigned char *src,
  6256. size_t src_len,
  6257. char *dst,
  6258. size_t *dst_len)
  6259. {
  6260. static const char *b64 =
  6261. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6262. size_t i, j;
  6263. int a, b, c;
  6264. if (dst_len != NULL) {
  6265. /* Expected length including 0 termination: */
  6266. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6267. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6268. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6269. if (*dst_len < expected_len) {
  6270. if (*dst_len > 0) {
  6271. dst[0] = '\0';
  6272. }
  6273. *dst_len = expected_len;
  6274. return 0;
  6275. }
  6276. }
  6277. for (i = j = 0; i < src_len; i += 3) {
  6278. a = src[i];
  6279. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6280. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6281. dst[j++] = b64[a >> 2];
  6282. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6283. if (i + 1 < src_len) {
  6284. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6285. }
  6286. if (i + 2 < src_len) {
  6287. dst[j++] = b64[c & 63];
  6288. }
  6289. }
  6290. while (j % 4 != 0) {
  6291. dst[j++] = '=';
  6292. }
  6293. dst[j++] = '\0';
  6294. if (dst_len != NULL) {
  6295. *dst_len = (size_t)j;
  6296. }
  6297. /* Return -1 for "OK" */
  6298. return -1;
  6299. }
  6300. static unsigned char
  6301. b64reverse(char letter)
  6302. {
  6303. if ((letter >= 'A') && (letter <= 'Z')) {
  6304. return letter - 'A';
  6305. }
  6306. if ((letter >= 'a') && (letter <= 'z')) {
  6307. return letter - 'a' + 26;
  6308. }
  6309. if ((letter >= '0') && (letter <= '9')) {
  6310. return letter - '0' + 52;
  6311. }
  6312. if (letter == '+') {
  6313. return 62;
  6314. }
  6315. if (letter == '/') {
  6316. return 63;
  6317. }
  6318. if (letter == '=') {
  6319. return 255; /* normal end */
  6320. }
  6321. return 254; /* error */
  6322. }
  6323. CIVETWEB_API int
  6324. mg_base64_decode(const char *src,
  6325. size_t src_len,
  6326. unsigned char *dst,
  6327. size_t *dst_len)
  6328. {
  6329. size_t i;
  6330. unsigned char a, b, c, d;
  6331. size_t dst_len_limit = (size_t)-1;
  6332. size_t dst_len_used = 0;
  6333. if (dst_len != NULL) {
  6334. dst_len_limit = *dst_len;
  6335. *dst_len = 0;
  6336. }
  6337. for (i = 0; i < src_len; i += 4) {
  6338. /* Read 4 characters from BASE64 string */
  6339. a = b64reverse(src[i]);
  6340. if (a >= 254) {
  6341. return (int)i;
  6342. }
  6343. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6344. if (b >= 254) {
  6345. return (int)i + 1;
  6346. }
  6347. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6348. if (c == 254) {
  6349. return (int)i + 2;
  6350. }
  6351. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6352. if (d == 254) {
  6353. return (int)i + 3;
  6354. }
  6355. /* Add first (of 3) decoded character */
  6356. if (dst_len_used < dst_len_limit) {
  6357. dst[dst_len_used] = (a << 2) + (b >> 4);
  6358. }
  6359. dst_len_used++;
  6360. if (c != 255) {
  6361. if (dst_len_used < dst_len_limit) {
  6362. dst[dst_len_used] = (b << 4) + (c >> 2);
  6363. }
  6364. dst_len_used++;
  6365. if (d != 255) {
  6366. if (dst_len_used < dst_len_limit) {
  6367. dst[dst_len_used] = (c << 6) + d;
  6368. }
  6369. dst_len_used++;
  6370. }
  6371. }
  6372. }
  6373. /* Add terminating zero */
  6374. if (dst_len_used < dst_len_limit) {
  6375. dst[dst_len_used] = '\0';
  6376. }
  6377. dst_len_used++;
  6378. if (dst_len != NULL) {
  6379. *dst_len = dst_len_used;
  6380. }
  6381. if (dst_len_used > dst_len_limit) {
  6382. /* Out of memory */
  6383. return 0;
  6384. }
  6385. /* Return -1 for "OK" */
  6386. return -1;
  6387. }
  6388. static int
  6389. is_put_or_delete_method(const struct mg_connection *conn)
  6390. {
  6391. if (conn) {
  6392. const char *s = conn->request_info.request_method;
  6393. if (s != NULL) {
  6394. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6395. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6396. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6397. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6398. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6399. || !strcmp(s, "COPY"));
  6400. }
  6401. }
  6402. return 0;
  6403. }
  6404. static int
  6405. is_civetweb_webdav_method(const struct mg_connection *conn)
  6406. {
  6407. /* Note: Here we only have to identify the WebDav methods that need special
  6408. * handling in the CivetWeb code - not all methods used in WebDav. In
  6409. * particular, methods used on directories (when using Windows Explorer as
  6410. * WebDav client).
  6411. */
  6412. if (conn) {
  6413. const char *s = conn->request_info.request_method;
  6414. if (s != NULL) {
  6415. /* These are the civetweb builtin DAV methods */
  6416. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6417. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6418. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6419. }
  6420. }
  6421. return 0;
  6422. }
  6423. #if !defined(NO_FILES)
  6424. static int
  6425. extention_matches_script(
  6426. struct mg_connection *conn, /* in: request (must be valid) */
  6427. const char *filename /* in: filename (must be valid) */
  6428. )
  6429. {
  6430. #if !defined(NO_CGI)
  6431. unsigned char cgi_config_idx, inc, max;
  6432. #endif
  6433. #if defined(USE_LUA)
  6434. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6435. filename)
  6436. > 0) {
  6437. return 1;
  6438. }
  6439. #endif
  6440. #if defined(USE_DUKTAPE)
  6441. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6442. filename)
  6443. > 0) {
  6444. return 1;
  6445. }
  6446. #endif
  6447. #if !defined(NO_CGI)
  6448. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6449. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6450. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6451. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6452. && (match_prefix_strlen(
  6453. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6454. filename)
  6455. > 0)) {
  6456. return 1;
  6457. }
  6458. }
  6459. #endif
  6460. /* filename and conn could be unused, if all preocessor conditions
  6461. * are false (no script language supported). */
  6462. (void)filename;
  6463. (void)conn;
  6464. return 0;
  6465. }
  6466. static int
  6467. extention_matches_template_text(
  6468. struct mg_connection *conn, /* in: request (must be valid) */
  6469. const char *filename /* in: filename (must be valid) */
  6470. )
  6471. {
  6472. #if defined(USE_LUA)
  6473. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6474. filename)
  6475. > 0) {
  6476. return 1;
  6477. }
  6478. #endif
  6479. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6480. > 0) {
  6481. return 1;
  6482. }
  6483. return 0;
  6484. }
  6485. /* For given directory path, substitute it to valid index file.
  6486. * Return 1 if index file has been found, 0 if not found.
  6487. * If the file is found, it's stats is returned in stp. */
  6488. static int
  6489. substitute_index_file(struct mg_connection *conn,
  6490. char *path,
  6491. size_t path_len,
  6492. struct mg_file_stat *filestat)
  6493. {
  6494. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6495. struct vec filename_vec;
  6496. size_t n = strlen(path);
  6497. int found = 0;
  6498. /* The 'path' given to us points to the directory. Remove all trailing
  6499. * directory separator characters from the end of the path, and
  6500. * then append single directory separator character. */
  6501. while ((n > 0) && (path[n - 1] == '/')) {
  6502. n--;
  6503. }
  6504. path[n] = '/';
  6505. /* Traverse index files list. For each entry, append it to the given
  6506. * path and see if the file exists. If it exists, break the loop */
  6507. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6508. /* Ignore too long entries that may overflow path buffer */
  6509. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6510. continue;
  6511. }
  6512. /* Prepare full path to the index file */
  6513. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6514. /* Does it exist? */
  6515. if (mg_stat(conn, path, filestat)) {
  6516. /* Yes it does, break the loop */
  6517. found = 1;
  6518. break;
  6519. }
  6520. }
  6521. /* If no index file exists, restore directory path */
  6522. if (!found) {
  6523. path[n] = '\0';
  6524. }
  6525. return found;
  6526. }
  6527. #endif
  6528. static void
  6529. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6530. char *filename, /* out: filename */
  6531. size_t filename_buf_len, /* in: size of filename buffer */
  6532. struct mg_file_stat *filestat, /* out: file status structure */
  6533. int *is_found, /* out: file found (directly) */
  6534. int *is_script_resource, /* out: handled by a script? */
  6535. int *is_websocket_request, /* out: websocket connetion? */
  6536. int *is_put_or_delete_request, /* out: put/delete a file? */
  6537. int *is_webdav_request, /* out: webdav request? */
  6538. int *is_template_text /* out: SSI file or LSP file? */
  6539. )
  6540. {
  6541. char const *accept_encoding;
  6542. #if !defined(NO_FILES)
  6543. const char *uri = conn->request_info.local_uri;
  6544. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6545. const char *rewrite;
  6546. struct vec a, b;
  6547. ptrdiff_t match_len;
  6548. char gz_path[UTF8_PATH_MAX];
  6549. int truncated;
  6550. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6551. char *tmp_str;
  6552. size_t tmp_str_len, sep_pos;
  6553. int allow_substitute_script_subresources;
  6554. #endif
  6555. #else
  6556. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6557. #endif
  6558. /* Step 1: Set all initially unknown outputs to zero */
  6559. memset(filestat, 0, sizeof(*filestat));
  6560. *filename = 0;
  6561. *is_found = 0;
  6562. *is_script_resource = 0;
  6563. *is_template_text = 0;
  6564. /* Step 2: Classify the request method */
  6565. /* Step 2a: Check if the request attempts to modify the file system */
  6566. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6567. /* Step 2b: Check if the request uses WebDav method that requires special
  6568. * handling */
  6569. *is_webdav_request = is_civetweb_webdav_method(conn);
  6570. /* Step 3: Check if it is a websocket request, and modify the document
  6571. * root if required */
  6572. #if defined(USE_WEBSOCKET)
  6573. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6574. #if !defined(NO_FILES)
  6575. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6576. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6577. }
  6578. #endif /* !NO_FILES */
  6579. #else /* USE_WEBSOCKET */
  6580. *is_websocket_request = 0;
  6581. #endif /* USE_WEBSOCKET */
  6582. /* Step 4: Check if gzip encoded response is allowed */
  6583. conn->accept_gzip = 0;
  6584. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6585. if (strstr(accept_encoding, "gzip") != NULL) {
  6586. conn->accept_gzip = 1;
  6587. }
  6588. }
  6589. #if !defined(NO_FILES)
  6590. /* Step 5: If there is no root directory, don't look for files. */
  6591. /* Note that root == NULL is a regular use case here. This occurs,
  6592. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6593. * config is not required. */
  6594. if (root == NULL) {
  6595. /* all file related outputs have already been set to 0, just return
  6596. */
  6597. return;
  6598. }
  6599. /* Step 6: Determine the local file path from the root path and the
  6600. * request uri. */
  6601. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6602. * part of the path one byte on the right. */
  6603. truncated = 0;
  6604. mg_snprintf(
  6605. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6606. if (truncated) {
  6607. goto interpret_cleanup;
  6608. }
  6609. /* Step 7: URI rewriting */
  6610. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6611. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6612. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6613. mg_snprintf(conn,
  6614. &truncated,
  6615. filename,
  6616. filename_buf_len - 1,
  6617. "%.*s%s",
  6618. (int)b.len,
  6619. b.ptr,
  6620. uri + match_len);
  6621. break;
  6622. }
  6623. }
  6624. if (truncated) {
  6625. goto interpret_cleanup;
  6626. }
  6627. /* Step 8: Check if the file exists at the server */
  6628. /* Local file path and name, corresponding to requested URI
  6629. * is now stored in "filename" variable. */
  6630. if (mg_stat(conn, filename, filestat)) {
  6631. int uri_len = (int)strlen(uri);
  6632. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6633. /* 8.1: File exists. */
  6634. *is_found = 1;
  6635. /* 8.2: Check if it is a script type. */
  6636. if (extention_matches_script(conn, filename)) {
  6637. /* The request addresses a CGI resource, Lua script or
  6638. * server-side javascript.
  6639. * The URI corresponds to the script itself (like
  6640. * /path/script.cgi), and there is no additional resource
  6641. * path (like /path/script.cgi/something).
  6642. * Requests that modify (replace or delete) a resource, like
  6643. * PUT and DELETE requests, should replace/delete the script
  6644. * file.
  6645. * Requests that read or write from/to a resource, like GET and
  6646. * POST requests, should call the script and return the
  6647. * generated response. */
  6648. *is_script_resource = (!*is_put_or_delete_request);
  6649. }
  6650. /* 8.3: Check for SSI and LSP files */
  6651. if (extention_matches_template_text(conn, filename)) {
  6652. /* Same as above, but for *.lsp and *.shtml files. */
  6653. /* A "template text" is a file delivered directly to the client,
  6654. * but with some text tags replaced by dynamic content.
  6655. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6656. * (LP, LSP) file. */
  6657. *is_template_text = (!*is_put_or_delete_request);
  6658. }
  6659. /* 8.4: If the request target is a directory, there could be
  6660. * a substitute file (index.html, index.cgi, ...). */
  6661. /* But do not substitute a directory for a WebDav request */
  6662. if (filestat->is_directory && is_uri_end_slash
  6663. && (!*is_webdav_request)) {
  6664. /* Use a local copy here, since substitute_index_file will
  6665. * change the content of the file status */
  6666. struct mg_file_stat tmp_filestat;
  6667. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6668. if (substitute_index_file(
  6669. conn, filename, filename_buf_len, &tmp_filestat)) {
  6670. /* Substitute file found. Copy stat to the output, then
  6671. * check if the file is a script file */
  6672. *filestat = tmp_filestat;
  6673. if (extention_matches_script(conn, filename)) {
  6674. /* Substitute file is a script file */
  6675. *is_script_resource = 1;
  6676. } else if (extention_matches_template_text(conn, filename)) {
  6677. /* Substitute file is a LSP or SSI file */
  6678. *is_template_text = 1;
  6679. } else {
  6680. /* Substitute file is a regular file */
  6681. *is_script_resource = 0;
  6682. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6683. }
  6684. }
  6685. /* If there is no substitute file, the server could return
  6686. * a directory listing in a later step */
  6687. }
  6688. return;
  6689. }
  6690. /* Step 9: Check for zipped files: */
  6691. /* If we can't find the actual file, look for the file
  6692. * with the same name but a .gz extension. If we find it,
  6693. * use that and set the gzipped flag in the file struct
  6694. * to indicate that the response need to have the content-
  6695. * encoding: gzip header.
  6696. * We can only do this if the browser declares support. */
  6697. if (conn->accept_gzip) {
  6698. mg_snprintf(
  6699. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6700. if (truncated) {
  6701. goto interpret_cleanup;
  6702. }
  6703. if (mg_stat(conn, gz_path, filestat)) {
  6704. if (filestat) {
  6705. filestat->is_gzipped = 1;
  6706. *is_found = 1;
  6707. }
  6708. /* Currently gz files can not be scripts. */
  6709. return;
  6710. }
  6711. }
  6712. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6713. /* Step 10: Script resources may handle sub-resources */
  6714. /* Support PATH_INFO for CGI scripts. */
  6715. tmp_str_len = strlen(filename);
  6716. tmp_str =
  6717. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6718. if (!tmp_str) {
  6719. /* Out of memory */
  6720. goto interpret_cleanup;
  6721. }
  6722. memcpy(tmp_str, filename, tmp_str_len + 1);
  6723. /* Check config, if index scripts may have sub-resources */
  6724. allow_substitute_script_subresources =
  6725. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6726. "yes");
  6727. if (*is_webdav_request) {
  6728. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6729. * PROPFIND fo their subresources? */
  6730. /* allow_substitute_script_subresources = 0; */
  6731. }
  6732. sep_pos = tmp_str_len;
  6733. while (sep_pos > 0) {
  6734. sep_pos--;
  6735. if (tmp_str[sep_pos] == '/') {
  6736. int is_script = 0, does_exist = 0;
  6737. tmp_str[sep_pos] = 0;
  6738. if (tmp_str[0]) {
  6739. is_script = extention_matches_script(conn, tmp_str);
  6740. does_exist = mg_stat(conn, tmp_str, filestat);
  6741. }
  6742. if (does_exist && is_script) {
  6743. filename[sep_pos] = 0;
  6744. memmove(filename + sep_pos + 2,
  6745. filename + sep_pos + 1,
  6746. strlen(filename + sep_pos + 1) + 1);
  6747. conn->path_info = filename + sep_pos + 1;
  6748. filename[sep_pos + 1] = '/';
  6749. *is_script_resource = 1;
  6750. *is_found = 1;
  6751. break;
  6752. }
  6753. if (allow_substitute_script_subresources) {
  6754. if (substitute_index_file(
  6755. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6756. /* some intermediate directory has an index file */
  6757. if (extention_matches_script(conn, tmp_str)) {
  6758. size_t script_name_len = strlen(tmp_str);
  6759. /* subres_name read before this memory locatio will be
  6760. overwritten */
  6761. char *subres_name = filename + sep_pos;
  6762. size_t subres_name_len = strlen(subres_name);
  6763. DEBUG_TRACE("Substitute script %s serving path %s",
  6764. tmp_str,
  6765. filename);
  6766. /* this index file is a script */
  6767. if ((script_name_len + subres_name_len + 2)
  6768. >= filename_buf_len) {
  6769. mg_free(tmp_str);
  6770. goto interpret_cleanup;
  6771. }
  6772. conn->path_info =
  6773. filename + script_name_len + 1; /* new target */
  6774. memmove(conn->path_info, subres_name, subres_name_len);
  6775. conn->path_info[subres_name_len] = 0;
  6776. memcpy(filename, tmp_str, script_name_len + 1);
  6777. *is_script_resource = 1;
  6778. *is_found = 1;
  6779. break;
  6780. } else {
  6781. DEBUG_TRACE("Substitute file %s serving path %s",
  6782. tmp_str,
  6783. filename);
  6784. /* non-script files will not have sub-resources */
  6785. filename[sep_pos] = 0;
  6786. conn->path_info = 0;
  6787. *is_script_resource = 0;
  6788. *is_found = 0;
  6789. break;
  6790. }
  6791. }
  6792. }
  6793. tmp_str[sep_pos] = '/';
  6794. }
  6795. }
  6796. mg_free(tmp_str);
  6797. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6798. #endif /* !defined(NO_FILES) */
  6799. return;
  6800. #if !defined(NO_FILES)
  6801. /* Reset all outputs */
  6802. interpret_cleanup:
  6803. memset(filestat, 0, sizeof(*filestat));
  6804. *filename = 0;
  6805. *is_found = 0;
  6806. *is_script_resource = 0;
  6807. *is_websocket_request = 0;
  6808. *is_put_or_delete_request = 0;
  6809. #endif /* !defined(NO_FILES) */
  6810. }
  6811. /* Check whether full request is buffered. Return:
  6812. * -1 if request or response is malformed
  6813. * 0 if request or response is not yet fully buffered
  6814. * >0 actual request length, including last \r\n\r\n */
  6815. static int
  6816. get_http_header_len(const char *buf, int buflen)
  6817. {
  6818. int i;
  6819. for (i = 0; i < buflen; i++) {
  6820. /* Do an unsigned comparison in some conditions below */
  6821. const unsigned char c = (unsigned char)buf[i];
  6822. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6823. && !isprint(c)) {
  6824. /* abort scan as soon as one malformed character is found */
  6825. return -1;
  6826. }
  6827. if (i < buflen - 1) {
  6828. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6829. /* Two newline, no carriage return - not standard compliant,
  6830. * but it should be accepted */
  6831. return i + 2;
  6832. }
  6833. }
  6834. if (i < buflen - 3) {
  6835. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6836. && (buf[i + 3] == '\n')) {
  6837. /* Two \r\n - standard compliant */
  6838. return i + 4;
  6839. }
  6840. }
  6841. }
  6842. return 0;
  6843. }
  6844. #if !defined(NO_CACHING)
  6845. /* Convert month to the month number. Return -1 on error, or month number */
  6846. static int
  6847. get_month_index(const char *s)
  6848. {
  6849. size_t i;
  6850. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6851. if (!strcmp(s, month_names[i])) {
  6852. return (int)i;
  6853. }
  6854. }
  6855. return -1;
  6856. }
  6857. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6858. static time_t
  6859. parse_date_string(const char *datetime)
  6860. {
  6861. char month_str[32] = {0};
  6862. int second, minute, hour, day, month, year;
  6863. time_t result = (time_t)0;
  6864. struct tm tm;
  6865. if ((sscanf(datetime,
  6866. "%d/%3s/%d %d:%d:%d",
  6867. &day,
  6868. month_str,
  6869. &year,
  6870. &hour,
  6871. &minute,
  6872. &second)
  6873. == 6)
  6874. || (sscanf(datetime,
  6875. "%d %3s %d %d:%d:%d",
  6876. &day,
  6877. month_str,
  6878. &year,
  6879. &hour,
  6880. &minute,
  6881. &second)
  6882. == 6)
  6883. || (sscanf(datetime,
  6884. "%*3s, %d %3s %d %d:%d:%d",
  6885. &day,
  6886. month_str,
  6887. &year,
  6888. &hour,
  6889. &minute,
  6890. &second)
  6891. == 6)
  6892. || (sscanf(datetime,
  6893. "%d-%3s-%d %d:%d:%d",
  6894. &day,
  6895. month_str,
  6896. &year,
  6897. &hour,
  6898. &minute,
  6899. &second)
  6900. == 6)) {
  6901. month = get_month_index(month_str);
  6902. if ((month >= 0) && (year >= 1970)) {
  6903. memset(&tm, 0, sizeof(tm));
  6904. tm.tm_year = year - 1900;
  6905. tm.tm_mon = month;
  6906. tm.tm_mday = day;
  6907. tm.tm_hour = hour;
  6908. tm.tm_min = minute;
  6909. tm.tm_sec = second;
  6910. result = timegm(&tm);
  6911. }
  6912. }
  6913. return result;
  6914. }
  6915. #endif /* !NO_CACHING */
  6916. /* Pre-process URIs according to RFC + protect against directory disclosure
  6917. * attacks by removing '..', excessive '/' and '\' characters */
  6918. static void
  6919. remove_dot_segments(char *inout)
  6920. {
  6921. /* Windows backend protection
  6922. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6923. * in URI by slash */
  6924. char *out_end = inout;
  6925. char *in = inout;
  6926. if (!in) {
  6927. /* Param error. */
  6928. return;
  6929. }
  6930. while (*in) {
  6931. if (*in == '\\') {
  6932. *in = '/';
  6933. }
  6934. in++;
  6935. }
  6936. /* Algorithm "remove_dot_segments" from
  6937. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6938. /* Step 1:
  6939. * The input buffer is initialized.
  6940. * The output buffer is initialized to the empty string.
  6941. */
  6942. in = inout;
  6943. /* Step 2:
  6944. * While the input buffer is not empty, loop as follows:
  6945. */
  6946. /* Less than out_end of the inout buffer is used as output, so keep
  6947. * condition: out_end <= in */
  6948. while (*in) {
  6949. /* Step 2a:
  6950. * If the input buffer begins with a prefix of "../" or "./",
  6951. * then remove that prefix from the input buffer;
  6952. */
  6953. if (!strncmp(in, "../", 3)) {
  6954. in += 3;
  6955. } else if (!strncmp(in, "./", 2)) {
  6956. in += 2;
  6957. }
  6958. /* otherwise */
  6959. /* Step 2b:
  6960. * if the input buffer begins with a prefix of "/./" or "/.",
  6961. * where "." is a complete path segment, then replace that
  6962. * prefix with "/" in the input buffer;
  6963. */
  6964. else if (!strncmp(in, "/./", 3)) {
  6965. in += 2;
  6966. } else if (!strcmp(in, "/.")) {
  6967. in[1] = 0;
  6968. }
  6969. /* otherwise */
  6970. /* Step 2c:
  6971. * if the input buffer begins with a prefix of "/../" or "/..",
  6972. * where ".." is a complete path segment, then replace that
  6973. * prefix with "/" in the input buffer and remove the last
  6974. * segment and its preceding "/" (if any) from the output
  6975. * buffer;
  6976. */
  6977. else if (!strncmp(in, "/../", 4)) {
  6978. in += 3;
  6979. if (inout != out_end) {
  6980. /* remove last segment */
  6981. do {
  6982. out_end--;
  6983. } while ((inout != out_end) && (*out_end != '/'));
  6984. }
  6985. } else if (!strcmp(in, "/..")) {
  6986. in[1] = 0;
  6987. if (inout != out_end) {
  6988. /* remove last segment */
  6989. do {
  6990. out_end--;
  6991. } while ((inout != out_end) && (*out_end != '/'));
  6992. }
  6993. }
  6994. /* otherwise */
  6995. /* Step 2d:
  6996. * if the input buffer consists only of "." or "..", then remove
  6997. * that from the input buffer;
  6998. */
  6999. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7000. *in = 0;
  7001. }
  7002. /* otherwise */
  7003. /* Step 2e:
  7004. * move the first path segment in the input buffer to the end of
  7005. * the output buffer, including the initial "/" character (if
  7006. * any) and any subsequent characters up to, but not including,
  7007. * the next "/" character or the end of the input buffer.
  7008. */
  7009. else {
  7010. do {
  7011. *out_end = *in;
  7012. out_end++;
  7013. in++;
  7014. } while ((*in != 0) && (*in != '/'));
  7015. }
  7016. }
  7017. /* Step 3:
  7018. * Finally, the output buffer is returned as the result of
  7019. * remove_dot_segments.
  7020. */
  7021. /* Terminate output */
  7022. *out_end = 0;
  7023. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7024. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7025. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7026. * or "//" anymore.
  7027. */
  7028. out_end = in = inout;
  7029. while (*in) {
  7030. if (*in == '.') {
  7031. /* remove . at the end or preceding of / */
  7032. char *in_ahead = in;
  7033. do {
  7034. in_ahead++;
  7035. } while (*in_ahead == '.');
  7036. if (*in_ahead == '/') {
  7037. in = in_ahead;
  7038. if ((out_end != inout) && (out_end[-1] == '/')) {
  7039. /* remove generated // */
  7040. out_end--;
  7041. }
  7042. } else if (*in_ahead == 0) {
  7043. in = in_ahead;
  7044. } else {
  7045. do {
  7046. *out_end++ = '.';
  7047. in++;
  7048. } while (in != in_ahead);
  7049. }
  7050. } else if (*in == '/') {
  7051. /* replace // by / */
  7052. *out_end++ = '/';
  7053. do {
  7054. in++;
  7055. } while (*in == '/');
  7056. } else {
  7057. *out_end++ = *in;
  7058. in++;
  7059. }
  7060. }
  7061. *out_end = 0;
  7062. }
  7063. static const struct {
  7064. const char *extension;
  7065. size_t ext_len;
  7066. const char *mime_type;
  7067. } builtin_mime_types[] = {
  7068. /* IANA registered MIME types
  7069. * (http://www.iana.org/assignments/media-types)
  7070. * application types */
  7071. {".bin", 4, "application/octet-stream"},
  7072. {".deb", 4, "application/octet-stream"},
  7073. {".dmg", 4, "application/octet-stream"},
  7074. {".dll", 4, "application/octet-stream"},
  7075. {".doc", 4, "application/msword"},
  7076. {".eps", 4, "application/postscript"},
  7077. {".exe", 4, "application/octet-stream"},
  7078. {".iso", 4, "application/octet-stream"},
  7079. {".js", 3, "application/javascript"},
  7080. {".json", 5, "application/json"},
  7081. {".msi", 4, "application/octet-stream"},
  7082. {".pdf", 4, "application/pdf"},
  7083. {".ps", 3, "application/postscript"},
  7084. {".rtf", 4, "application/rtf"},
  7085. {".xhtml", 6, "application/xhtml+xml"},
  7086. {".xsl", 4, "application/xml"},
  7087. {".xslt", 5, "application/xml"},
  7088. /* fonts */
  7089. {".ttf", 4, "application/font-sfnt"},
  7090. {".cff", 4, "application/font-sfnt"},
  7091. {".otf", 4, "application/font-sfnt"},
  7092. {".aat", 4, "application/font-sfnt"},
  7093. {".sil", 4, "application/font-sfnt"},
  7094. {".pfr", 4, "application/font-tdpfr"},
  7095. {".woff", 5, "application/font-woff"},
  7096. {".woff2", 6, "application/font-woff2"},
  7097. /* audio */
  7098. {".mp3", 4, "audio/mpeg"},
  7099. {".oga", 4, "audio/ogg"},
  7100. {".ogg", 4, "audio/ogg"},
  7101. /* image */
  7102. {".gif", 4, "image/gif"},
  7103. {".ief", 4, "image/ief"},
  7104. {".jpeg", 5, "image/jpeg"},
  7105. {".jpg", 4, "image/jpeg"},
  7106. {".jpm", 4, "image/jpm"},
  7107. {".jpx", 4, "image/jpx"},
  7108. {".png", 4, "image/png"},
  7109. {".svg", 4, "image/svg+xml"},
  7110. {".tif", 4, "image/tiff"},
  7111. {".tiff", 5, "image/tiff"},
  7112. /* model */
  7113. {".wrl", 4, "model/vrml"},
  7114. /* text */
  7115. {".css", 4, "text/css"},
  7116. {".csv", 4, "text/csv"},
  7117. {".htm", 4, "text/html"},
  7118. {".html", 5, "text/html"},
  7119. {".sgm", 4, "text/sgml"},
  7120. {".shtm", 5, "text/html"},
  7121. {".shtml", 6, "text/html"},
  7122. {".txt", 4, "text/plain"},
  7123. {".xml", 4, "text/xml"},
  7124. /* video */
  7125. {".mov", 4, "video/quicktime"},
  7126. {".mp4", 4, "video/mp4"},
  7127. {".mpeg", 5, "video/mpeg"},
  7128. {".mpg", 4, "video/mpeg"},
  7129. {".ogv", 4, "video/ogg"},
  7130. {".qt", 3, "video/quicktime"},
  7131. /* not registered types
  7132. * (http://reference.sitepoint.com/html/mime-types-full,
  7133. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7134. {".arj", 4, "application/x-arj-compressed"},
  7135. {".gz", 3, "application/x-gunzip"},
  7136. {".rar", 4, "application/x-arj-compressed"},
  7137. {".swf", 4, "application/x-shockwave-flash"},
  7138. {".tar", 4, "application/x-tar"},
  7139. {".tgz", 4, "application/x-tar-gz"},
  7140. {".torrent", 8, "application/x-bittorrent"},
  7141. {".ppt", 4, "application/x-mspowerpoint"},
  7142. {".xls", 4, "application/x-msexcel"},
  7143. {".zip", 4, "application/x-zip-compressed"},
  7144. {".aac",
  7145. 4,
  7146. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7147. {".flac", 5, "audio/flac"},
  7148. {".aif", 4, "audio/x-aif"},
  7149. {".m3u", 4, "audio/x-mpegurl"},
  7150. {".mid", 4, "audio/x-midi"},
  7151. {".ra", 3, "audio/x-pn-realaudio"},
  7152. {".ram", 4, "audio/x-pn-realaudio"},
  7153. {".wav", 4, "audio/x-wav"},
  7154. {".bmp", 4, "image/bmp"},
  7155. {".ico", 4, "image/x-icon"},
  7156. {".pct", 4, "image/x-pct"},
  7157. {".pict", 5, "image/pict"},
  7158. {".rgb", 4, "image/x-rgb"},
  7159. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7160. {".asf", 4, "video/x-ms-asf"},
  7161. {".avi", 4, "video/x-msvideo"},
  7162. {".m4v", 4, "video/x-m4v"},
  7163. {NULL, 0, NULL}};
  7164. CIVETWEB_API const char *
  7165. mg_get_builtin_mime_type(const char *path)
  7166. {
  7167. const char *ext;
  7168. size_t i, path_len;
  7169. path_len = strlen(path);
  7170. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7171. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7172. if ((path_len > builtin_mime_types[i].ext_len)
  7173. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7174. return builtin_mime_types[i].mime_type;
  7175. }
  7176. }
  7177. return "text/plain";
  7178. }
  7179. /* Look at the "path" extension and figure what mime type it has.
  7180. * Store mime type in the vector. */
  7181. static void
  7182. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7183. {
  7184. struct vec ext_vec, mime_vec;
  7185. const char *list, *ext;
  7186. size_t path_len;
  7187. path_len = strlen(path);
  7188. if ((conn == NULL) || (vec == NULL)) {
  7189. if (vec != NULL) {
  7190. memset(vec, '\0', sizeof(struct vec));
  7191. }
  7192. return;
  7193. }
  7194. /* Scan user-defined mime types first, in case user wants to
  7195. * override default mime types. */
  7196. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7197. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7198. /* ext now points to the path suffix */
  7199. ext = path + path_len - ext_vec.len;
  7200. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7201. *vec = mime_vec;
  7202. return;
  7203. }
  7204. }
  7205. vec->ptr = mg_get_builtin_mime_type(path);
  7206. vec->len = strlen(vec->ptr);
  7207. }
  7208. /* Stringify binary data. Output buffer must be twice as big as input,
  7209. * because each byte takes 2 bytes in string representation */
  7210. static void
  7211. bin2str(char *to, const unsigned char *p, size_t len)
  7212. {
  7213. static const char *hex = "0123456789abcdef";
  7214. for (; len--; p++) {
  7215. *to++ = hex[p[0] >> 4];
  7216. *to++ = hex[p[0] & 0x0f];
  7217. }
  7218. *to = '\0';
  7219. }
  7220. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7221. */
  7222. CIVETWEB_API char *
  7223. mg_md5(char buf[33], ...)
  7224. {
  7225. md5_byte_t hash[16];
  7226. const char *p;
  7227. va_list ap;
  7228. md5_state_t ctx;
  7229. md5_init(&ctx);
  7230. va_start(ap, buf);
  7231. while ((p = va_arg(ap, const char *)) != NULL) {
  7232. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7233. }
  7234. va_end(ap);
  7235. md5_finish(&ctx, hash);
  7236. bin2str(buf, hash, sizeof(hash));
  7237. return buf;
  7238. }
  7239. /* Check the user's password, return 1 if OK */
  7240. static int
  7241. check_password_digest(const char *method,
  7242. const char *ha1,
  7243. const char *uri,
  7244. const char *nonce,
  7245. const char *nc,
  7246. const char *cnonce,
  7247. const char *qop,
  7248. const char *response)
  7249. {
  7250. char ha2[32 + 1], expected_response[32 + 1];
  7251. /* Some of the parameters may be NULL */
  7252. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7253. || (qop == NULL) || (response == NULL)) {
  7254. return 0;
  7255. }
  7256. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7257. if (strlen(response) != 32) {
  7258. return 0;
  7259. }
  7260. mg_md5(ha2, method, ":", uri, NULL);
  7261. mg_md5(expected_response,
  7262. ha1,
  7263. ":",
  7264. nonce,
  7265. ":",
  7266. nc,
  7267. ":",
  7268. cnonce,
  7269. ":",
  7270. qop,
  7271. ":",
  7272. ha2,
  7273. NULL);
  7274. return mg_strcasecmp(response, expected_response) == 0;
  7275. }
  7276. #if !defined(NO_FILESYSTEMS)
  7277. /* Use the global passwords file, if specified by auth_gpass option,
  7278. * or search for .htpasswd in the requested directory. */
  7279. static void
  7280. open_auth_file(struct mg_connection *conn,
  7281. const char *path,
  7282. struct mg_file *filep)
  7283. {
  7284. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7285. char name[UTF8_PATH_MAX];
  7286. const char *p, *e,
  7287. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7288. int truncated;
  7289. if (gpass != NULL) {
  7290. /* Use global passwords file */
  7291. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7292. #if defined(DEBUG)
  7293. /* Use mg_cry_internal here, since gpass has been
  7294. * configured. */
  7295. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7296. #endif
  7297. }
  7298. /* Important: using local struct mg_file to test path for
  7299. * is_directory flag. If filep is used, mg_stat() makes it
  7300. * appear as if auth file was opened.
  7301. * TODO(mid): Check if this is still required after rewriting
  7302. * mg_stat */
  7303. } else if (mg_stat(conn, path, &filep->stat)
  7304. && filep->stat.is_directory) {
  7305. mg_snprintf(conn,
  7306. &truncated,
  7307. name,
  7308. sizeof(name),
  7309. "%s/%s",
  7310. path,
  7311. PASSWORDS_FILE_NAME);
  7312. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7313. #if defined(DEBUG)
  7314. /* Don't use mg_cry_internal here, but only a trace, since
  7315. * this is a typical case. It will occur for every directory
  7316. * without a password file. */
  7317. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7318. #endif
  7319. }
  7320. } else {
  7321. /* Try to find .htpasswd in requested directory. */
  7322. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7323. if (e[0] == '/') {
  7324. break;
  7325. }
  7326. }
  7327. mg_snprintf(conn,
  7328. &truncated,
  7329. name,
  7330. sizeof(name),
  7331. "%.*s/%s",
  7332. (int)(e - p),
  7333. p,
  7334. PASSWORDS_FILE_NAME);
  7335. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7336. #if defined(DEBUG)
  7337. /* Don't use mg_cry_internal here, but only a trace, since
  7338. * this is a typical case. It will occur for every directory
  7339. * without a password file. */
  7340. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7341. #endif
  7342. }
  7343. }
  7344. }
  7345. }
  7346. #endif /* NO_FILESYSTEMS */
  7347. /* Parsed Authorization header */
  7348. struct ah {
  7349. char *user;
  7350. int type; /* 1 = basic, 2 = digest */
  7351. char *plain_password; /* Basic only */
  7352. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7353. };
  7354. /* Return 1 on success. Always initializes the ah structure. */
  7355. static int
  7356. parse_auth_header(struct mg_connection *conn,
  7357. char *buf,
  7358. size_t buf_size,
  7359. struct ah *ah)
  7360. {
  7361. char *name, *value, *s;
  7362. const char *auth_header;
  7363. uint64_t nonce;
  7364. if (!ah || !conn) {
  7365. return 0;
  7366. }
  7367. (void)memset(ah, 0, sizeof(*ah));
  7368. auth_header = mg_get_header(conn, "Authorization");
  7369. if (auth_header == NULL) {
  7370. /* No Authorization header at all */
  7371. return 0;
  7372. }
  7373. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7374. /* Basic Auth (we never asked for this, but some client may send it) */
  7375. char *split;
  7376. const char *userpw_b64 = auth_header + 6;
  7377. size_t userpw_b64_len = strlen(userpw_b64);
  7378. size_t buf_len_r = buf_size;
  7379. if (mg_base64_decode(
  7380. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7381. != -1) {
  7382. return 0; /* decode error */
  7383. }
  7384. split = strchr(buf, ':');
  7385. if (!split) {
  7386. return 0; /* Format error */
  7387. }
  7388. /* Separate string at ':' */
  7389. *split = 0;
  7390. /* User name is before ':', Password is after ':' */
  7391. ah->user = buf;
  7392. ah->type = 1;
  7393. ah->plain_password = split + 1;
  7394. return 1;
  7395. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7396. /* Digest Auth ... implemented below */
  7397. ah->type = 2;
  7398. } else {
  7399. /* Unknown or invalid Auth method */
  7400. return 0;
  7401. }
  7402. /* Make modifiable copy of the auth header */
  7403. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7404. s = buf;
  7405. /* Parse authorization header */
  7406. for (;;) {
  7407. /* Gobble initial spaces */
  7408. while (isspace((unsigned char)*s)) {
  7409. s++;
  7410. }
  7411. name = skip_quoted(&s, "=", " ", 0);
  7412. /* Value is either quote-delimited, or ends at first comma or space.
  7413. */
  7414. if (s[0] == '\"') {
  7415. s++;
  7416. value = skip_quoted(&s, "\"", " ", '\\');
  7417. if (s[0] == ',') {
  7418. s++;
  7419. }
  7420. } else {
  7421. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7422. * uses spaces */
  7423. }
  7424. if (*name == '\0') {
  7425. break;
  7426. }
  7427. if (!strcmp(name, "username")) {
  7428. ah->user = value;
  7429. } else if (!strcmp(name, "cnonce")) {
  7430. ah->cnonce = value;
  7431. } else if (!strcmp(name, "response")) {
  7432. ah->response = value;
  7433. } else if (!strcmp(name, "uri")) {
  7434. ah->uri = value;
  7435. } else if (!strcmp(name, "qop")) {
  7436. ah->qop = value;
  7437. } else if (!strcmp(name, "nc")) {
  7438. ah->nc = value;
  7439. } else if (!strcmp(name, "nonce")) {
  7440. ah->nonce = value;
  7441. }
  7442. }
  7443. #if !defined(NO_NONCE_CHECK)
  7444. /* Read the nonce from the response. */
  7445. if (ah->nonce == NULL) {
  7446. return 0;
  7447. }
  7448. s = NULL;
  7449. nonce = strtoull(ah->nonce, &s, 10);
  7450. if ((s == NULL) || (*s != 0)) {
  7451. return 0;
  7452. }
  7453. /* Convert the nonce from the client to a number. */
  7454. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7455. /* The converted number corresponds to the time the nounce has been
  7456. * created. This should not be earlier than the server start. */
  7457. /* Server side nonce check is valuable in all situations but one:
  7458. * if the server restarts frequently, but the client should not see
  7459. * that, so the server should accept nonces from previous starts. */
  7460. /* However, the reasonable default is to not accept a nonce from a
  7461. * previous start, so if anyone changed the access rights between
  7462. * two restarts, a new login is required. */
  7463. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7464. /* nonce is from a previous start of the server and no longer valid
  7465. * (replay attack?) */
  7466. return 0;
  7467. }
  7468. /* Check if the nonce is too high, so it has not (yet) been used by the
  7469. * server. */
  7470. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7471. + conn->dom_ctx->nonce_count)) {
  7472. return 0;
  7473. }
  7474. #else
  7475. (void)nonce;
  7476. #endif
  7477. return (ah->user != NULL);
  7478. }
  7479. static const char *
  7480. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7481. {
  7482. if (!filep) {
  7483. return NULL;
  7484. }
  7485. if (filep->access.fp != NULL) {
  7486. return fgets(buf, (int)size, filep->access.fp);
  7487. } else {
  7488. return NULL;
  7489. }
  7490. }
  7491. /* Define the initial recursion depth for procesesing htpasswd files that
  7492. * include other htpasswd
  7493. * (or even the same) files. It is not difficult to provide a file or files
  7494. * s.t. they force civetweb
  7495. * to infinitely recurse and then crash.
  7496. */
  7497. #define INITIAL_DEPTH 9
  7498. #if INITIAL_DEPTH <= 0
  7499. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7500. #endif
  7501. #if !defined(NO_FILESYSTEMS)
  7502. struct read_auth_file_struct {
  7503. struct mg_connection *conn;
  7504. struct ah ah;
  7505. const char *domain;
  7506. char buf[256 + 256 + 40];
  7507. const char *f_user;
  7508. const char *f_domain;
  7509. const char *f_ha1;
  7510. };
  7511. static int
  7512. read_auth_file(struct mg_file *filep,
  7513. struct read_auth_file_struct *workdata,
  7514. int depth)
  7515. {
  7516. int is_authorized = 0;
  7517. struct mg_file fp;
  7518. size_t l;
  7519. if (!filep || !workdata || (0 == depth)) {
  7520. return 0;
  7521. }
  7522. /* Loop over passwords file */
  7523. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7524. l = strlen(workdata->buf);
  7525. while (l > 0) {
  7526. if (isspace((unsigned char)workdata->buf[l - 1])
  7527. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7528. l--;
  7529. workdata->buf[l] = 0;
  7530. } else
  7531. break;
  7532. }
  7533. if (l < 1) {
  7534. continue;
  7535. }
  7536. workdata->f_user = workdata->buf;
  7537. if (workdata->f_user[0] == ':') {
  7538. /* user names may not contain a ':' and may not be empty,
  7539. * so lines starting with ':' may be used for a special purpose
  7540. */
  7541. if (workdata->f_user[1] == '#') {
  7542. /* :# is a comment */
  7543. continue;
  7544. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7545. if (mg_fopen(workdata->conn,
  7546. workdata->f_user + 9,
  7547. MG_FOPEN_MODE_READ,
  7548. &fp)) {
  7549. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7550. (void)mg_fclose(
  7551. &fp.access); /* ignore error on read only file */
  7552. /* No need to continue processing files once we have a
  7553. * match, since nothing will reset it back
  7554. * to 0.
  7555. */
  7556. if (is_authorized) {
  7557. return is_authorized;
  7558. }
  7559. } else {
  7560. mg_cry_internal(workdata->conn,
  7561. "%s: cannot open authorization file: %s",
  7562. __func__,
  7563. workdata->buf);
  7564. }
  7565. continue;
  7566. }
  7567. /* everything is invalid for the moment (might change in the
  7568. * future) */
  7569. mg_cry_internal(workdata->conn,
  7570. "%s: syntax error in authorization file: %s",
  7571. __func__,
  7572. workdata->buf);
  7573. continue;
  7574. }
  7575. workdata->f_domain = strchr(workdata->f_user, ':');
  7576. if (workdata->f_domain == NULL) {
  7577. mg_cry_internal(workdata->conn,
  7578. "%s: syntax error in authorization file: %s",
  7579. __func__,
  7580. workdata->buf);
  7581. continue;
  7582. }
  7583. *(char *)(workdata->f_domain) = 0;
  7584. (workdata->f_domain)++;
  7585. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7586. if (workdata->f_ha1 == NULL) {
  7587. mg_cry_internal(workdata->conn,
  7588. "%s: syntax error in authorization file: %s",
  7589. __func__,
  7590. workdata->buf);
  7591. continue;
  7592. }
  7593. *(char *)(workdata->f_ha1) = 0;
  7594. (workdata->f_ha1)++;
  7595. if (!strcmp(workdata->ah.user, workdata->f_user)
  7596. && !strcmp(workdata->domain, workdata->f_domain)) {
  7597. switch (workdata->ah.type) {
  7598. case 1: /* Basic */
  7599. {
  7600. size_t mlen = strlen(workdata->f_user)
  7601. + strlen(workdata->domain)
  7602. + strlen(workdata->ah.plain_password) + 3;
  7603. char md5[33];
  7604. mg_md5(md5,
  7605. workdata->f_user,
  7606. ":",
  7607. workdata->domain,
  7608. ":",
  7609. workdata->ah.plain_password,
  7610. NULL);
  7611. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7612. }
  7613. case 2: /* Digest */
  7614. return check_password_digest(
  7615. workdata->conn->request_info.request_method,
  7616. workdata->f_ha1,
  7617. workdata->ah.uri,
  7618. workdata->ah.nonce,
  7619. workdata->ah.nc,
  7620. workdata->ah.cnonce,
  7621. workdata->ah.qop,
  7622. workdata->ah.response);
  7623. default: /* None/Other/Unknown */
  7624. return 0;
  7625. }
  7626. }
  7627. }
  7628. return is_authorized;
  7629. }
  7630. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7631. static int
  7632. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7633. {
  7634. struct read_auth_file_struct workdata;
  7635. char buf[MG_BUF_LEN];
  7636. if (!conn || !conn->dom_ctx) {
  7637. return 0;
  7638. }
  7639. memset(&workdata, 0, sizeof(workdata));
  7640. workdata.conn = conn;
  7641. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7642. return 0;
  7643. }
  7644. /* CGI needs it as REMOTE_USER */
  7645. conn->request_info.remote_user =
  7646. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7647. if (realm) {
  7648. workdata.domain = realm;
  7649. } else {
  7650. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7651. }
  7652. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7653. }
  7654. /* Public function to check http digest authentication header */
  7655. CIVETWEB_API int
  7656. mg_check_digest_access_authentication(struct mg_connection *conn,
  7657. const char *realm,
  7658. const char *filename)
  7659. {
  7660. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7661. int auth;
  7662. if (!conn || !filename) {
  7663. return -1;
  7664. }
  7665. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7666. return -2;
  7667. }
  7668. auth = authorize(conn, &file, realm);
  7669. mg_fclose(&file.access);
  7670. return auth;
  7671. }
  7672. #endif /* NO_FILESYSTEMS */
  7673. /* Return 1 if request is authorised, 0 otherwise. */
  7674. static int
  7675. check_authorization(struct mg_connection *conn, const char *path)
  7676. {
  7677. #if !defined(NO_FILESYSTEMS)
  7678. char fname[UTF8_PATH_MAX];
  7679. struct vec uri_vec, filename_vec;
  7680. const char *list;
  7681. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7682. int authorized = 1, truncated;
  7683. if (!conn || !conn->dom_ctx) {
  7684. return 0;
  7685. }
  7686. list = conn->dom_ctx->config[PROTECT_URI];
  7687. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7688. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7689. mg_snprintf(conn,
  7690. &truncated,
  7691. fname,
  7692. sizeof(fname),
  7693. "%.*s",
  7694. (int)filename_vec.len,
  7695. filename_vec.ptr);
  7696. if (truncated
  7697. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7698. mg_cry_internal(conn,
  7699. "%s: cannot open %s: %s",
  7700. __func__,
  7701. fname,
  7702. strerror(errno));
  7703. }
  7704. break;
  7705. }
  7706. }
  7707. if (!is_file_opened(&file.access)) {
  7708. open_auth_file(conn, path, &file);
  7709. }
  7710. if (is_file_opened(&file.access)) {
  7711. authorized = authorize(conn, &file, NULL);
  7712. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7713. }
  7714. return authorized;
  7715. #else
  7716. (void)conn;
  7717. (void)path;
  7718. return 1;
  7719. #endif /* NO_FILESYSTEMS */
  7720. }
  7721. /* Internal function. Assumes conn is valid */
  7722. static void
  7723. send_authorization_request(struct mg_connection *conn, const char *realm)
  7724. {
  7725. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7726. int trunc = 0;
  7727. char buf[128];
  7728. if (!realm) {
  7729. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7730. }
  7731. mg_lock_context(conn->phys_ctx);
  7732. nonce += conn->dom_ctx->nonce_count;
  7733. ++conn->dom_ctx->nonce_count;
  7734. mg_unlock_context(conn->phys_ctx);
  7735. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7736. conn->must_close = 1;
  7737. /* Create 401 response */
  7738. mg_response_header_start(conn, 401);
  7739. send_no_cache_header(conn);
  7740. send_additional_header(conn);
  7741. mg_response_header_add(conn, "Content-Length", "0", -1);
  7742. /* Content for "WWW-Authenticate" header */
  7743. mg_snprintf(conn,
  7744. &trunc,
  7745. buf,
  7746. sizeof(buf),
  7747. "Digest qop=\"auth\", realm=\"%s\", "
  7748. "nonce=\"%" UINT64_FMT "\"",
  7749. realm,
  7750. nonce);
  7751. if (!trunc) {
  7752. /* !trunc should always be true */
  7753. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7754. }
  7755. /* Send all headers */
  7756. mg_response_header_send(conn);
  7757. }
  7758. /* Interface function. Parameters are provided by the user, so do
  7759. * at least some basic checks.
  7760. */
  7761. CIVETWEB_API int
  7762. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7763. const char *realm)
  7764. {
  7765. if (conn && conn->dom_ctx) {
  7766. send_authorization_request(conn, realm);
  7767. return 0;
  7768. }
  7769. return -1;
  7770. }
  7771. #if !defined(NO_FILES)
  7772. static int
  7773. is_authorized_for_put(struct mg_connection *conn)
  7774. {
  7775. int ret = 0;
  7776. if (conn) {
  7777. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7778. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7779. if (passfile != NULL
  7780. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7781. ret = authorize(conn, &file, NULL);
  7782. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7783. }
  7784. }
  7785. DEBUG_TRACE("file write autorization: %i", ret);
  7786. return ret;
  7787. }
  7788. #endif
  7789. CIVETWEB_API int
  7790. mg_modify_passwords_file_ha1(const char *fname,
  7791. const char *domain,
  7792. const char *user,
  7793. const char *ha1)
  7794. {
  7795. int found = 0, i, result = 1;
  7796. char line[512], u[256], d[256], h[256];
  7797. struct stat st = {0};
  7798. FILE *fp = NULL;
  7799. char *temp_file = NULL;
  7800. int temp_file_offs = 0;
  7801. /* Regard empty password as no password - remove user record. */
  7802. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7803. ha1 = NULL;
  7804. }
  7805. /* Other arguments must not be empty */
  7806. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7807. return 0;
  7808. }
  7809. /* Using the given file format, user name and domain must not contain
  7810. * the ':' character */
  7811. if (strchr(user, ':') != NULL) {
  7812. return 0;
  7813. }
  7814. if (strchr(domain, ':') != NULL) {
  7815. return 0;
  7816. }
  7817. /* Do not allow control characters like newline in user name and domain.
  7818. * Do not allow excessively long names either. */
  7819. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7820. if (iscntrl((unsigned char)user[i])) {
  7821. return 0;
  7822. }
  7823. }
  7824. if (user[i]) {
  7825. return 0; /* user name too long */
  7826. }
  7827. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7828. if (iscntrl((unsigned char)domain[i])) {
  7829. return 0;
  7830. }
  7831. }
  7832. if (domain[i]) {
  7833. return 0; /* domain name too long */
  7834. }
  7835. /* The maximum length of the path to the password file is limited */
  7836. if (strlen(fname) >= UTF8_PATH_MAX) {
  7837. return 0;
  7838. }
  7839. /* Check if the file exists, and get file size */
  7840. if (0 == stat(fname, &st)) {
  7841. int temp_buf_len = (int)st.st_size + 1024;
  7842. /* Allocate memory (instead of using a temporary file) */
  7843. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7844. if (!temp_file) {
  7845. /* Out of memory */
  7846. return 0;
  7847. }
  7848. /* File exists. Read it into a memory buffer. */
  7849. fp = fopen(fname, "r");
  7850. if (fp == NULL) {
  7851. /* Cannot read file. No permission? */
  7852. mg_free(temp_file);
  7853. return 0;
  7854. }
  7855. /* Read content and store in memory */
  7856. while ((fgets(line, sizeof(line), fp) != NULL)
  7857. && ((temp_file_offs + 600) < temp_buf_len)) {
  7858. /* file format is "user:domain:hash\n" */
  7859. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7860. continue;
  7861. }
  7862. u[255] = 0;
  7863. d[255] = 0;
  7864. h[255] = 0;
  7865. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7866. /* Found the user: change the password hash or drop the user
  7867. */
  7868. if ((ha1 != NULL) && (!found)) {
  7869. i = sprintf(temp_file + temp_file_offs,
  7870. "%s:%s:%s\n",
  7871. user,
  7872. domain,
  7873. ha1);
  7874. if (i < 1) {
  7875. fclose(fp);
  7876. mg_free(temp_file);
  7877. return 0;
  7878. }
  7879. temp_file_offs += i;
  7880. }
  7881. found = 1;
  7882. } else {
  7883. /* Copy existing user, including password hash */
  7884. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7885. if (i < 1) {
  7886. fclose(fp);
  7887. mg_free(temp_file);
  7888. return 0;
  7889. }
  7890. temp_file_offs += i;
  7891. }
  7892. }
  7893. fclose(fp);
  7894. }
  7895. /* Create new file */
  7896. fp = fopen(fname, "w");
  7897. if (!fp) {
  7898. mg_free(temp_file);
  7899. return 0;
  7900. }
  7901. #if !defined(_WIN32)
  7902. /* On Linux & co., restrict file read/write permissions to the owner */
  7903. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7904. result = 0;
  7905. }
  7906. #endif
  7907. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7908. /* Store buffered content of old file */
  7909. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7910. != (size_t)temp_file_offs) {
  7911. result = 0;
  7912. }
  7913. }
  7914. /* If new user, just add it */
  7915. if ((ha1 != NULL) && (!found)) {
  7916. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7917. result = 0;
  7918. }
  7919. }
  7920. /* All data written */
  7921. if (fclose(fp) != 0) {
  7922. result = 0;
  7923. }
  7924. mg_free(temp_file);
  7925. return result;
  7926. }
  7927. CIVETWEB_API int
  7928. mg_modify_passwords_file(const char *fname,
  7929. const char *domain,
  7930. const char *user,
  7931. const char *pass)
  7932. {
  7933. char ha1buf[33];
  7934. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7935. return 0;
  7936. }
  7937. if ((pass == NULL) || (pass[0] == 0)) {
  7938. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7939. }
  7940. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7941. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7942. }
  7943. static int
  7944. is_valid_port(unsigned long port)
  7945. {
  7946. return (port <= 0xffff);
  7947. }
  7948. static int
  7949. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7950. {
  7951. struct addrinfo hints, *res, *ressave;
  7952. int func_ret = 0;
  7953. int gai_ret;
  7954. memset(&hints, 0, sizeof(struct addrinfo));
  7955. hints.ai_family = af;
  7956. if (!resolve_src) {
  7957. hints.ai_flags = AI_NUMERICHOST;
  7958. }
  7959. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7960. if (gai_ret != 0) {
  7961. /* gai_strerror could be used to convert gai_ret to a string */
  7962. /* POSIX return values: see
  7963. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7964. */
  7965. /* Windows return values: see
  7966. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7967. */
  7968. return 0;
  7969. }
  7970. ressave = res;
  7971. while (res) {
  7972. if ((dstlen >= (size_t)res->ai_addrlen)
  7973. && (res->ai_addr->sa_family == af)) {
  7974. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7975. func_ret = 1;
  7976. }
  7977. res = res->ai_next;
  7978. }
  7979. freeaddrinfo(ressave);
  7980. return func_ret;
  7981. }
  7982. static int
  7983. connect_socket(
  7984. struct mg_context *ctx /* may be NULL */,
  7985. const char *host,
  7986. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7987. int use_ssl, /* 0 or 1 */
  7988. struct mg_error_data *error,
  7989. SOCKET *sock /* output: socket, must not be NULL */,
  7990. union usa *sa /* output: socket address, must not be NULL */
  7991. )
  7992. {
  7993. int ip_ver = 0;
  7994. int conn_ret = -1;
  7995. int sockerr = 0;
  7996. *sock = INVALID_SOCKET;
  7997. memset(sa, 0, sizeof(*sa));
  7998. if (host == NULL) {
  7999. if (error != NULL) {
  8000. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8001. mg_snprintf(NULL,
  8002. NULL, /* No truncation check for ebuf */
  8003. error->text,
  8004. error->text_buffer_size,
  8005. "%s",
  8006. "NULL host");
  8007. }
  8008. return 0;
  8009. }
  8010. #if defined(USE_X_DOM_SOCKET)
  8011. if (port == -99) {
  8012. /* Unix domain socket */
  8013. size_t hostlen = strlen(host);
  8014. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8015. if (error != NULL) {
  8016. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8017. mg_snprintf(NULL,
  8018. NULL, /* No truncation check for ebuf */
  8019. error->text,
  8020. error->text_buffer_size,
  8021. "%s",
  8022. "host length exceeds limit");
  8023. }
  8024. return 0;
  8025. }
  8026. } else
  8027. #endif
  8028. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8029. if (error != NULL) {
  8030. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8031. mg_snprintf(NULL,
  8032. NULL, /* No truncation check for ebuf */
  8033. error->text,
  8034. error->text_buffer_size,
  8035. "%s",
  8036. "invalid port");
  8037. }
  8038. return 0;
  8039. }
  8040. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  8041. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8042. if (use_ssl && (TLS_client_method == NULL)) {
  8043. if (error != NULL) {
  8044. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8045. mg_snprintf(NULL,
  8046. NULL, /* No truncation check for ebuf */
  8047. error->text,
  8048. error->text_buffer_size,
  8049. "%s",
  8050. "SSL is not initialized");
  8051. }
  8052. return 0;
  8053. }
  8054. #else
  8055. if (use_ssl && (SSLv23_client_method == NULL)) {
  8056. if (error != 0) {
  8057. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8058. mg_snprintf(NULL,
  8059. NULL, /* No truncation check for ebuf */
  8060. error->text,
  8061. error->text_buffer_size,
  8062. "%s",
  8063. "SSL is not initialized");
  8064. }
  8065. return 0;
  8066. }
  8067. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8068. #else
  8069. (void)use_ssl;
  8070. #endif /* NO SSL */
  8071. #if defined(USE_X_DOM_SOCKET)
  8072. if (port == -99) {
  8073. size_t hostlen = strlen(host);
  8074. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8075. ip_ver = -99;
  8076. sa->sun.sun_family = AF_UNIX;
  8077. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8078. memcpy(sa->sun.sun_path, host, hostlen);
  8079. } else
  8080. #endif
  8081. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8082. sa->sin.sin_port = htons((uint16_t)port);
  8083. ip_ver = 4;
  8084. #if defined(USE_IPV6)
  8085. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8086. sa->sin6.sin6_port = htons((uint16_t)port);
  8087. ip_ver = 6;
  8088. } else if (host[0] == '[') {
  8089. /* While getaddrinfo on Windows will work with [::1],
  8090. * getaddrinfo on Linux only works with ::1 (without []). */
  8091. size_t l = strlen(host + 1);
  8092. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8093. if (h) {
  8094. h[l - 1] = 0;
  8095. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8096. sa->sin6.sin6_port = htons((uint16_t)port);
  8097. ip_ver = 6;
  8098. }
  8099. mg_free(h);
  8100. }
  8101. #endif
  8102. }
  8103. if (ip_ver == 0) {
  8104. if (error != NULL) {
  8105. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8106. mg_snprintf(NULL,
  8107. NULL, /* No truncation check for ebuf */
  8108. error->text,
  8109. error->text_buffer_size,
  8110. "%s",
  8111. "host not found");
  8112. }
  8113. return 0;
  8114. }
  8115. if (ip_ver == 4) {
  8116. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8117. }
  8118. #if defined(USE_IPV6)
  8119. else if (ip_ver == 6) {
  8120. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8121. }
  8122. #endif
  8123. #if defined(USE_X_DOM_SOCKET)
  8124. else if (ip_ver == -99) {
  8125. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8126. }
  8127. #endif
  8128. if (*sock == INVALID_SOCKET) {
  8129. if (error != NULL) {
  8130. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8131. error->code_sub = ERRNO;
  8132. mg_snprintf(NULL,
  8133. NULL, /* No truncation check for ebuf */
  8134. error->text,
  8135. error->text_buffer_size,
  8136. "socket(): %s",
  8137. strerror(ERRNO));
  8138. }
  8139. return 0;
  8140. }
  8141. if (0 != set_non_blocking_mode(*sock)) {
  8142. if (error != NULL) {
  8143. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8144. error->code_sub = ERRNO;
  8145. mg_snprintf(NULL,
  8146. NULL, /* No truncation check for ebuf */
  8147. error->text,
  8148. error->text_buffer_size,
  8149. "Cannot set socket to non-blocking: %s",
  8150. strerror(ERRNO));
  8151. }
  8152. closesocket(*sock);
  8153. *sock = INVALID_SOCKET;
  8154. return 0;
  8155. }
  8156. set_close_on_exec(*sock, NULL, ctx);
  8157. if (ip_ver == 4) {
  8158. /* connected with IPv4 */
  8159. conn_ret = connect(*sock,
  8160. (struct sockaddr *)((void *)&sa->sin),
  8161. sizeof(sa->sin));
  8162. }
  8163. #if defined(USE_IPV6)
  8164. else if (ip_ver == 6) {
  8165. /* connected with IPv6 */
  8166. conn_ret = connect(*sock,
  8167. (struct sockaddr *)((void *)&sa->sin6),
  8168. sizeof(sa->sin6));
  8169. }
  8170. #endif
  8171. #if defined(USE_X_DOM_SOCKET)
  8172. else if (ip_ver == -99) {
  8173. /* connected to domain socket */
  8174. conn_ret = connect(*sock,
  8175. (struct sockaddr *)((void *)&sa->sun),
  8176. sizeof(sa->sun));
  8177. }
  8178. #endif
  8179. if (conn_ret != 0) {
  8180. sockerr = ERRNO;
  8181. }
  8182. #if defined(_WIN32)
  8183. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8184. #else
  8185. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8186. #endif
  8187. /* Data for getsockopt */
  8188. void *psockerr = &sockerr;
  8189. int ret;
  8190. #if defined(_WIN32)
  8191. int len = (int)sizeof(sockerr);
  8192. #else
  8193. socklen_t len = (socklen_t)sizeof(sockerr);
  8194. #endif
  8195. /* Data for poll */
  8196. struct mg_pollfd pfd[1];
  8197. int pollres;
  8198. int ms_wait = 10000; /* 10 second timeout */
  8199. stop_flag_t nonstop;
  8200. STOP_FLAG_ASSIGN(&nonstop, 0);
  8201. /* For a non-blocking socket, the connect sequence is:
  8202. * 1) call connect (will not block)
  8203. * 2) wait until the socket is ready for writing (select or poll)
  8204. * 3) check connection state with getsockopt
  8205. */
  8206. pfd[0].fd = *sock;
  8207. pfd[0].events = POLLOUT;
  8208. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8209. if (pollres != 1) {
  8210. /* Not connected */
  8211. if (error != NULL) {
  8212. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8213. mg_snprintf(NULL,
  8214. NULL, /* No truncation check for ebuf */
  8215. error->text,
  8216. error->text_buffer_size,
  8217. "connect(%s:%d): timeout",
  8218. host,
  8219. port);
  8220. }
  8221. closesocket(*sock);
  8222. *sock = INVALID_SOCKET;
  8223. return 0;
  8224. }
  8225. #if defined(_WIN32)
  8226. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8227. #else
  8228. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8229. #endif
  8230. if ((ret == 0) && (sockerr == 0)) {
  8231. conn_ret = 0;
  8232. }
  8233. }
  8234. if (conn_ret != 0) {
  8235. /* Not connected */
  8236. if (error != NULL) {
  8237. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8238. error->code_sub = ERRNO;
  8239. mg_snprintf(NULL,
  8240. NULL, /* No truncation check for ebuf */
  8241. error->text,
  8242. error->text_buffer_size,
  8243. "connect(%s:%d): error %s",
  8244. host,
  8245. port,
  8246. strerror(sockerr));
  8247. }
  8248. closesocket(*sock);
  8249. *sock = INVALID_SOCKET;
  8250. return 0;
  8251. }
  8252. return 1;
  8253. }
  8254. CIVETWEB_API int
  8255. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8256. {
  8257. static const char *dont_escape = "._-$,;~()";
  8258. static const char *hex = "0123456789abcdef";
  8259. char *pos = dst;
  8260. const char *end = dst + dst_len - 1;
  8261. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8262. if (isalnum((unsigned char)*src)
  8263. || (strchr(dont_escape, *src) != NULL)) {
  8264. *pos = *src;
  8265. } else if (pos + 2 < end) {
  8266. pos[0] = '%';
  8267. pos[1] = hex[(unsigned char)*src >> 4];
  8268. pos[2] = hex[(unsigned char)*src & 0xf];
  8269. pos += 2;
  8270. } else {
  8271. break;
  8272. }
  8273. }
  8274. *pos = '\0';
  8275. return (*src == '\0') ? (int)(pos - dst) : -1;
  8276. }
  8277. /* Return 0 on success, non-zero if an error occurs. */
  8278. static int
  8279. print_dir_entry(struct mg_connection *conn, struct de *de)
  8280. {
  8281. size_t namesize, escsize, i;
  8282. char *href, *esc, *p;
  8283. char size[64], mod[64];
  8284. #if defined(REENTRANT_TIME)
  8285. struct tm _tm;
  8286. struct tm *tm = &_tm;
  8287. #else
  8288. struct tm *tm;
  8289. #endif
  8290. /* Estimate worst case size for encoding and escaping */
  8291. namesize = strlen(de->file_name) + 1;
  8292. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8293. href = (char *)mg_malloc(namesize * 3 + escsize);
  8294. if (href == NULL) {
  8295. return -1;
  8296. }
  8297. mg_url_encode(de->file_name, href, namesize * 3);
  8298. esc = NULL;
  8299. if (escsize > 0) {
  8300. /* HTML escaping needed */
  8301. esc = href + namesize * 3;
  8302. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8303. mg_strlcpy(p, de->file_name + i, 2);
  8304. if (*p == '&') {
  8305. strcpy(p, "&amp;");
  8306. } else if (*p == '<') {
  8307. strcpy(p, "&lt;");
  8308. } else if (*p == '>') {
  8309. strcpy(p, "&gt;");
  8310. }
  8311. }
  8312. }
  8313. if (de->file.is_directory) {
  8314. mg_snprintf(conn,
  8315. NULL, /* Buffer is big enough */
  8316. size,
  8317. sizeof(size),
  8318. "%s",
  8319. "[DIRECTORY]");
  8320. } else {
  8321. /* We use (signed) cast below because MSVC 6 compiler cannot
  8322. * convert unsigned __int64 to double. Sigh. */
  8323. if (de->file.size < 1024) {
  8324. mg_snprintf(conn,
  8325. NULL, /* Buffer is big enough */
  8326. size,
  8327. sizeof(size),
  8328. "%d",
  8329. (int)de->file.size);
  8330. } else if (de->file.size < 0x100000) {
  8331. mg_snprintf(conn,
  8332. NULL, /* Buffer is big enough */
  8333. size,
  8334. sizeof(size),
  8335. "%.1fk",
  8336. (double)de->file.size / 1024.0);
  8337. } else if (de->file.size < 0x40000000) {
  8338. mg_snprintf(conn,
  8339. NULL, /* Buffer is big enough */
  8340. size,
  8341. sizeof(size),
  8342. "%.1fM",
  8343. (double)de->file.size / 1048576);
  8344. } else {
  8345. mg_snprintf(conn,
  8346. NULL, /* Buffer is big enough */
  8347. size,
  8348. sizeof(size),
  8349. "%.1fG",
  8350. (double)de->file.size / 1073741824);
  8351. }
  8352. }
  8353. /* Note: mg_snprintf will not cause a buffer overflow above.
  8354. * So, string truncation checks are not required here. */
  8355. #if defined(REENTRANT_TIME)
  8356. localtime_r(&de->file.last_modified, tm);
  8357. #else
  8358. tm = localtime(&de->file.last_modified);
  8359. #endif
  8360. if (tm != NULL) {
  8361. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8362. } else {
  8363. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8364. mod[sizeof(mod) - 1] = '\0';
  8365. }
  8366. mg_printf(conn,
  8367. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8368. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8369. href,
  8370. de->file.is_directory ? "/" : "",
  8371. esc ? esc : de->file_name,
  8372. de->file.is_directory ? "/" : "",
  8373. mod,
  8374. size);
  8375. mg_free(href);
  8376. return 0;
  8377. }
  8378. /* This function is called from send_directory() and used for
  8379. * sorting directory entries by size, name, or modification time. */
  8380. static int
  8381. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8382. {
  8383. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8384. if (p1 && p2) {
  8385. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8386. int cmp_result = 0;
  8387. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8388. query_string = "n";
  8389. }
  8390. /* Sort Directories vs Files */
  8391. if (a->file.is_directory && !b->file.is_directory) {
  8392. return -1; /* Always put directories on top */
  8393. } else if (!a->file.is_directory && b->file.is_directory) {
  8394. return 1; /* Always put directories on top */
  8395. }
  8396. /* Sort by size or date */
  8397. if (*query_string == 's') {
  8398. cmp_result = (a->file.size == b->file.size)
  8399. ? 0
  8400. : ((a->file.size > b->file.size) ? 1 : -1);
  8401. } else if (*query_string == 'd') {
  8402. cmp_result =
  8403. (a->file.last_modified == b->file.last_modified)
  8404. ? 0
  8405. : ((a->file.last_modified > b->file.last_modified) ? 1
  8406. : -1);
  8407. }
  8408. /* Sort by name:
  8409. * if (*query_string == 'n') ...
  8410. * but also sort files of same size/date by name as secondary criterion.
  8411. */
  8412. if (cmp_result == 0) {
  8413. cmp_result = strcmp(a->file_name, b->file_name);
  8414. }
  8415. /* For descending order, invert result */
  8416. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8417. }
  8418. return 0;
  8419. }
  8420. static int
  8421. must_hide_file(struct mg_connection *conn, const char *path)
  8422. {
  8423. if (conn && conn->dom_ctx) {
  8424. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8425. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8426. return (match_prefix_strlen(pw_pattern, path) > 0)
  8427. || (match_prefix_strlen(pattern, path) > 0);
  8428. }
  8429. return 0;
  8430. }
  8431. #if !defined(NO_FILESYSTEMS)
  8432. static int
  8433. scan_directory(struct mg_connection *conn,
  8434. const char *dir,
  8435. void *data,
  8436. int (*cb)(struct de *, void *))
  8437. {
  8438. char path[UTF8_PATH_MAX];
  8439. struct dirent *dp;
  8440. DIR *dirp;
  8441. struct de de;
  8442. int truncated;
  8443. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8444. return 0;
  8445. } else {
  8446. while ((dp = mg_readdir(dirp)) != NULL) {
  8447. /* Do not show current dir and hidden files */
  8448. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8449. || must_hide_file(conn, dp->d_name)) {
  8450. continue;
  8451. }
  8452. mg_snprintf(
  8453. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8454. /* If we don't memset stat structure to zero, mtime will have
  8455. * garbage and strftime() will segfault later on in
  8456. * print_dir_entry(). memset is required only if mg_stat()
  8457. * fails. For more details, see
  8458. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8459. memset(&de.file, 0, sizeof(de.file));
  8460. if (truncated) {
  8461. /* If the path is not complete, skip processing. */
  8462. continue;
  8463. }
  8464. if (!mg_stat(conn, path, &de.file)) {
  8465. mg_cry_internal(conn,
  8466. "%s: mg_stat(%s) failed: %s",
  8467. __func__,
  8468. path,
  8469. strerror(ERRNO));
  8470. }
  8471. de.file_name = dp->d_name;
  8472. if (cb(&de, data)) {
  8473. /* stopped */
  8474. break;
  8475. }
  8476. }
  8477. (void)mg_closedir(dirp);
  8478. }
  8479. return 1;
  8480. }
  8481. #endif /* NO_FILESYSTEMS */
  8482. #if !defined(NO_FILES)
  8483. static int
  8484. remove_directory(struct mg_connection *conn, const char *dir)
  8485. {
  8486. char path[UTF8_PATH_MAX];
  8487. struct dirent *dp;
  8488. DIR *dirp;
  8489. struct de de;
  8490. int truncated;
  8491. int ok = 1;
  8492. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8493. return 0;
  8494. } else {
  8495. while ((dp = mg_readdir(dirp)) != NULL) {
  8496. /* Do not show current dir (but show hidden files as they will
  8497. * also be removed) */
  8498. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8499. continue;
  8500. }
  8501. mg_snprintf(
  8502. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8503. /* If we don't memset stat structure to zero, mtime will have
  8504. * garbage and strftime() will segfault later on in
  8505. * print_dir_entry(). memset is required only if mg_stat()
  8506. * fails. For more details, see
  8507. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8508. memset(&de.file, 0, sizeof(de.file));
  8509. if (truncated) {
  8510. /* Do not delete anything shorter */
  8511. ok = 0;
  8512. continue;
  8513. }
  8514. if (!mg_stat(conn, path, &de.file)) {
  8515. mg_cry_internal(conn,
  8516. "%s: mg_stat(%s) failed: %s",
  8517. __func__,
  8518. path,
  8519. strerror(ERRNO));
  8520. ok = 0;
  8521. }
  8522. if (de.file.is_directory) {
  8523. if (remove_directory(conn, path) == 0) {
  8524. ok = 0;
  8525. }
  8526. } else {
  8527. /* This will fail file is the file is in memory */
  8528. if (mg_remove(conn, path) == 0) {
  8529. ok = 0;
  8530. }
  8531. }
  8532. }
  8533. (void)mg_closedir(dirp);
  8534. IGNORE_UNUSED_RESULT(rmdir(dir));
  8535. }
  8536. return ok;
  8537. }
  8538. #endif
  8539. struct dir_scan_data {
  8540. struct de *entries;
  8541. size_t num_entries;
  8542. size_t arr_size;
  8543. };
  8544. #if !defined(NO_FILESYSTEMS)
  8545. static int
  8546. dir_scan_callback(struct de *de, void *data)
  8547. {
  8548. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8549. struct de *entries = dsd->entries;
  8550. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8551. /* Here "entries" is a temporary pointer and can be replaced,
  8552. * "dsd->entries" is the original pointer */
  8553. entries =
  8554. (struct de *)mg_realloc(entries,
  8555. dsd->arr_size * 2 * sizeof(entries[0]));
  8556. if (entries == NULL) {
  8557. /* stop scan */
  8558. return 1;
  8559. }
  8560. dsd->entries = entries;
  8561. dsd->arr_size *= 2;
  8562. }
  8563. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8564. if (entries[dsd->num_entries].file_name == NULL) {
  8565. /* stop scan */
  8566. return 1;
  8567. }
  8568. entries[dsd->num_entries].file = de->file;
  8569. dsd->num_entries++;
  8570. return 0;
  8571. }
  8572. static void
  8573. handle_directory_request(struct mg_connection *conn, const char *dir)
  8574. {
  8575. size_t i;
  8576. int sort_direction;
  8577. struct dir_scan_data data = {NULL, 0, 128};
  8578. char date[64], *esc, *p;
  8579. const char *title;
  8580. time_t curtime = time(NULL);
  8581. if (!conn) {
  8582. return;
  8583. }
  8584. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8585. mg_send_http_error(conn,
  8586. 500,
  8587. "Error: Cannot open directory\nopendir(%s): %s",
  8588. dir,
  8589. strerror(ERRNO));
  8590. return;
  8591. }
  8592. gmt_time_string(date, sizeof(date), &curtime);
  8593. esc = NULL;
  8594. title = conn->request_info.local_uri;
  8595. if (title[strcspn(title, "&<>")]) {
  8596. /* HTML escaping needed */
  8597. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8598. if (esc) {
  8599. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8600. mg_strlcpy(p, title + i, 2);
  8601. if (*p == '&') {
  8602. strcpy(p, "&amp;");
  8603. } else if (*p == '<') {
  8604. strcpy(p, "&lt;");
  8605. } else if (*p == '>') {
  8606. strcpy(p, "&gt;");
  8607. }
  8608. }
  8609. } else {
  8610. title = "";
  8611. }
  8612. }
  8613. sort_direction = ((conn->request_info.query_string != NULL)
  8614. && (conn->request_info.query_string[0] != '\0')
  8615. && (conn->request_info.query_string[1] == 'd'))
  8616. ? 'a'
  8617. : 'd';
  8618. conn->must_close = 1;
  8619. /* Create 200 OK response */
  8620. mg_response_header_start(conn, 200);
  8621. send_static_cache_header(conn);
  8622. send_additional_header(conn);
  8623. mg_response_header_add(conn,
  8624. "Content-Type",
  8625. "text/html; charset=utf-8",
  8626. -1);
  8627. /* Send all headers */
  8628. mg_response_header_send(conn);
  8629. /* Body */
  8630. mg_printf(conn,
  8631. "<html><head><title>Index of %s</title>"
  8632. "<style>th {text-align: left;}</style></head>"
  8633. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8634. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8635. "<th><a href=\"?d%c\">Modified</a></th>"
  8636. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8637. "<tr><td colspan=\"3\"><hr></td></tr>",
  8638. esc ? esc : title,
  8639. esc ? esc : title,
  8640. sort_direction,
  8641. sort_direction,
  8642. sort_direction);
  8643. mg_free(esc);
  8644. /* Print first entry - link to a parent directory */
  8645. mg_printf(conn,
  8646. "<tr><td><a href=\"%s\">%s</a></td>"
  8647. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8648. "..",
  8649. "Parent directory",
  8650. "-",
  8651. "-");
  8652. /* Sort and print directory entries */
  8653. if (data.entries != NULL) {
  8654. mg_sort(data.entries,
  8655. data.num_entries,
  8656. sizeof(data.entries[0]),
  8657. compare_dir_entries,
  8658. (void *)conn->request_info.query_string);
  8659. for (i = 0; i < data.num_entries; i++) {
  8660. print_dir_entry(conn, &data.entries[i]);
  8661. mg_free(data.entries[i].file_name);
  8662. }
  8663. mg_free(data.entries);
  8664. }
  8665. mg_printf(conn, "%s", "</table></pre></body></html>");
  8666. conn->status_code = 200;
  8667. }
  8668. #endif /* NO_FILESYSTEMS */
  8669. /* Send len bytes from the opened file to the client. */
  8670. static void
  8671. send_file_data(struct mg_connection *conn,
  8672. struct mg_file *filep,
  8673. int64_t offset,
  8674. int64_t len,
  8675. int no_buffering)
  8676. {
  8677. char buf[MG_BUF_LEN];
  8678. int to_read, num_read, num_written;
  8679. int64_t size;
  8680. if (!filep || !conn) {
  8681. return;
  8682. }
  8683. /* Sanity check the offset */
  8684. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8685. : (int64_t)(filep->stat.size);
  8686. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8687. if (len > 0 && filep->access.fp != NULL) {
  8688. /* file stored on disk */
  8689. #if defined(__linux__)
  8690. /* sendfile is only available for Linux */
  8691. if ((conn->ssl == 0) && (conn->throttle == 0)
  8692. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8693. "yes"))) {
  8694. off_t sf_offs = (off_t)offset;
  8695. ssize_t sf_sent;
  8696. int sf_file = fileno(filep->access.fp);
  8697. int loop_cnt = 0;
  8698. do {
  8699. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8700. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8701. size_t sf_tosend =
  8702. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8703. sf_sent =
  8704. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8705. if (sf_sent > 0) {
  8706. len -= sf_sent;
  8707. offset += sf_sent;
  8708. } else if (loop_cnt == 0) {
  8709. /* This file can not be sent using sendfile.
  8710. * This might be the case for pseudo-files in the
  8711. * /sys/ and /proc/ file system.
  8712. * Use the regular user mode copy code instead. */
  8713. break;
  8714. } else if (sf_sent == 0) {
  8715. /* No error, but 0 bytes sent. May be EOF? */
  8716. return;
  8717. }
  8718. loop_cnt++;
  8719. } while ((len > 0) && (sf_sent >= 0));
  8720. if (sf_sent > 0) {
  8721. return; /* OK */
  8722. }
  8723. /* sf_sent<0 means error, thus fall back to the classic way */
  8724. /* This is always the case, if sf_file is not a "normal" file,
  8725. * e.g., for sending data from the output of a CGI process. */
  8726. offset = (int64_t)sf_offs;
  8727. }
  8728. #endif
  8729. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8730. mg_cry_internal(conn,
  8731. "%s: fseeko() failed: %s",
  8732. __func__,
  8733. strerror(ERRNO));
  8734. mg_send_http_error(
  8735. conn,
  8736. 500,
  8737. "%s",
  8738. "Error: Unable to access file at requested position.");
  8739. } else {
  8740. while (len > 0) {
  8741. /* Calculate how much to read from the file into the buffer. */
  8742. /* If no_buffering is set, we should not wait until the
  8743. * CGI->Server buffer is filled, but send everything
  8744. * immediately. In theory buffering could be turned off using
  8745. * setbuf(filep->access.fp, NULL);
  8746. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8747. * but in practice this does not work. A "Linux only" solution
  8748. * may be to use select(). The only portable way is to read byte
  8749. * by byte, but this is quite inefficient from a performance
  8750. * point of view. */
  8751. to_read = no_buffering ? 1 : sizeof(buf);
  8752. if ((int64_t)to_read > len) {
  8753. to_read = (int)len;
  8754. }
  8755. /* Read from file, exit the loop on error */
  8756. if ((num_read =
  8757. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8758. <= 0) {
  8759. break;
  8760. }
  8761. /* Send read bytes to the client, exit the loop on error */
  8762. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8763. != num_read) {
  8764. break;
  8765. }
  8766. /* Both read and were successful, adjust counters */
  8767. len -= num_written;
  8768. }
  8769. }
  8770. }
  8771. }
  8772. static int
  8773. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8774. {
  8775. return sscanf(header,
  8776. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8777. a,
  8778. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8779. // to an integer value, but function will not report
  8780. // conversion errors; consider using 'strtol' instead
  8781. }
  8782. static void
  8783. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8784. {
  8785. if ((filestat != NULL) && (buf != NULL)) {
  8786. mg_snprintf(NULL,
  8787. NULL, /* All calls to construct_etag use 64 byte buffer */
  8788. buf,
  8789. buf_len,
  8790. "\"%lx.%" INT64_FMT "\"",
  8791. (unsigned long)filestat->last_modified,
  8792. filestat->size);
  8793. }
  8794. }
  8795. static void
  8796. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8797. {
  8798. if (filep != NULL && filep->fp != NULL) {
  8799. #if defined(_WIN32)
  8800. (void)conn; /* Unused. */
  8801. #else
  8802. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8803. mg_cry_internal(conn,
  8804. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8805. __func__,
  8806. strerror(ERRNO));
  8807. }
  8808. #endif
  8809. }
  8810. }
  8811. #if defined(USE_ZLIB)
  8812. #include "mod_zlib.inl"
  8813. #endif
  8814. #if !defined(NO_FILESYSTEMS)
  8815. static void
  8816. handle_static_file_request(struct mg_connection *conn,
  8817. const char *path,
  8818. struct mg_file *filep,
  8819. const char *mime_type,
  8820. const char *additional_headers)
  8821. {
  8822. char lm[64], etag[64];
  8823. char range[128]; /* large enough, so there will be no overflow */
  8824. const char *range_hdr;
  8825. int64_t cl, r1, r2;
  8826. struct vec mime_vec;
  8827. int n, truncated;
  8828. char gz_path[UTF8_PATH_MAX];
  8829. const char *encoding = 0;
  8830. int is_head_request;
  8831. #if defined(USE_ZLIB)
  8832. /* Compression is allowed, unless there is a reason not to use
  8833. * compression. If the file is already compressed, too small or a
  8834. * "range" request was made, on the fly compression is not possible. */
  8835. int allow_on_the_fly_compression = 1;
  8836. #endif
  8837. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8838. return;
  8839. }
  8840. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8841. if (mime_type == NULL) {
  8842. get_mime_type(conn, path, &mime_vec);
  8843. } else {
  8844. mime_vec.ptr = mime_type;
  8845. mime_vec.len = strlen(mime_type);
  8846. }
  8847. if (filep->stat.size > INT64_MAX) {
  8848. mg_send_http_error(conn,
  8849. 500,
  8850. "Error: File size is too large to send\n%" INT64_FMT,
  8851. filep->stat.size);
  8852. return;
  8853. }
  8854. cl = (int64_t)filep->stat.size;
  8855. conn->status_code = 200;
  8856. range[0] = '\0';
  8857. #if defined(USE_ZLIB)
  8858. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8859. * it's important to rewrite the filename after resolving
  8860. * the mime type from it, to preserve the actual file's type */
  8861. if (!conn->accept_gzip) {
  8862. allow_on_the_fly_compression = 0;
  8863. }
  8864. #endif
  8865. /* Check if there is a range header */
  8866. range_hdr = mg_get_header(conn, "Range");
  8867. /* For gzipped files, add *.gz */
  8868. if (filep->stat.is_gzipped) {
  8869. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8870. if (truncated) {
  8871. mg_send_http_error(conn,
  8872. 500,
  8873. "Error: Path of zipped file too long (%s)",
  8874. path);
  8875. return;
  8876. }
  8877. path = gz_path;
  8878. encoding = "gzip";
  8879. #if defined(USE_ZLIB)
  8880. /* File is already compressed. No "on the fly" compression. */
  8881. allow_on_the_fly_compression = 0;
  8882. #endif
  8883. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8884. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8885. struct mg_file_stat file_stat;
  8886. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8887. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8888. && !file_stat.is_directory) {
  8889. file_stat.is_gzipped = 1;
  8890. filep->stat = file_stat;
  8891. cl = (int64_t)filep->stat.size;
  8892. path = gz_path;
  8893. encoding = "gzip";
  8894. #if defined(USE_ZLIB)
  8895. /* File is already compressed. No "on the fly" compression. */
  8896. allow_on_the_fly_compression = 0;
  8897. #endif
  8898. }
  8899. }
  8900. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8901. mg_send_http_error(conn,
  8902. 500,
  8903. "Error: Cannot open file\nfopen(%s): %s",
  8904. path,
  8905. strerror(ERRNO));
  8906. return;
  8907. }
  8908. fclose_on_exec(&filep->access, conn);
  8909. /* If "Range" request was made: parse header, send only selected part
  8910. * of the file. */
  8911. r1 = r2 = 0;
  8912. if ((range_hdr != NULL)
  8913. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8914. && (r2 >= 0)) {
  8915. /* actually, range requests don't play well with a pre-gzipped
  8916. * file (since the range is specified in the uncompressed space) */
  8917. if (filep->stat.is_gzipped) {
  8918. mg_send_http_error(
  8919. conn,
  8920. 416, /* 416 = Range Not Satisfiable */
  8921. "%s",
  8922. "Error: Range requests in gzipped files are not supported");
  8923. (void)mg_fclose(
  8924. &filep->access); /* ignore error on read only file */
  8925. return;
  8926. }
  8927. conn->status_code = 206;
  8928. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8929. mg_snprintf(conn,
  8930. NULL, /* range buffer is big enough */
  8931. range,
  8932. sizeof(range),
  8933. "bytes "
  8934. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8935. r1,
  8936. r1 + cl - 1,
  8937. filep->stat.size);
  8938. #if defined(USE_ZLIB)
  8939. /* Do not compress ranges. */
  8940. allow_on_the_fly_compression = 0;
  8941. #endif
  8942. }
  8943. /* Do not compress small files. Small files do not benefit from file
  8944. * compression, but there is still some overhead. */
  8945. #if defined(USE_ZLIB)
  8946. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8947. /* File is below the size limit. */
  8948. allow_on_the_fly_compression = 0;
  8949. }
  8950. #endif
  8951. /* Prepare Etag, and Last-Modified headers. */
  8952. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8953. construct_etag(etag, sizeof(etag), &filep->stat);
  8954. /* Create 2xx (200, 206) response */
  8955. mg_response_header_start(conn, conn->status_code);
  8956. send_static_cache_header(conn);
  8957. send_additional_header(conn);
  8958. send_cors_header(conn);
  8959. mg_response_header_add(conn,
  8960. "Content-Type",
  8961. mime_vec.ptr,
  8962. (int)mime_vec.len);
  8963. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8964. mg_response_header_add(conn, "Etag", etag, -1);
  8965. #if defined(USE_ZLIB)
  8966. /* On the fly compression allowed */
  8967. if (allow_on_the_fly_compression) {
  8968. /* For on the fly compression, we don't know the content size in
  8969. * advance, so we have to use chunked encoding */
  8970. encoding = "gzip";
  8971. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8972. /* HTTP/2 is always using "chunks" (frames) */
  8973. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8974. }
  8975. } else
  8976. #endif
  8977. {
  8978. /* Without on-the-fly compression, we know the content-length
  8979. * and we can use ranges (with on-the-fly compression we cannot).
  8980. * So we send these response headers only in this case. */
  8981. char len[32];
  8982. int trunc = 0;
  8983. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8984. if (!trunc) {
  8985. mg_response_header_add(conn, "Content-Length", len, -1);
  8986. }
  8987. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8988. }
  8989. if (encoding) {
  8990. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8991. }
  8992. if (range[0] != 0) {
  8993. mg_response_header_add(conn, "Content-Range", range, -1);
  8994. }
  8995. /* The code above does not add any header starting with X- to make
  8996. * sure no one of the additional_headers is included twice */
  8997. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8998. mg_response_header_add_lines(conn, additional_headers);
  8999. }
  9000. /* Send all headers */
  9001. mg_response_header_send(conn);
  9002. if (!is_head_request) {
  9003. #if defined(USE_ZLIB)
  9004. if (allow_on_the_fly_compression) {
  9005. /* Compress and send */
  9006. send_compressed_data(conn, filep);
  9007. } else
  9008. #endif
  9009. {
  9010. /* Send file directly */
  9011. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9012. }
  9013. }
  9014. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9015. }
  9016. CIVETWEB_API int
  9017. mg_send_file_body(struct mg_connection *conn, const char *path)
  9018. {
  9019. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9020. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9021. return -1;
  9022. }
  9023. fclose_on_exec(&file.access, conn);
  9024. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9025. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9026. return 0; /* >= 0 for OK */
  9027. }
  9028. #endif /* NO_FILESYSTEMS */
  9029. #if !defined(NO_CACHING)
  9030. /* Return True if we should reply 304 Not Modified. */
  9031. static int
  9032. is_not_modified(const struct mg_connection *conn,
  9033. const struct mg_file_stat *filestat)
  9034. {
  9035. char etag[64];
  9036. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9037. const char *inm = mg_get_header(conn, "If-None-Match");
  9038. construct_etag(etag, sizeof(etag), filestat);
  9039. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9040. || ((ims != NULL)
  9041. && (filestat->last_modified <= parse_date_string(ims)));
  9042. }
  9043. static void
  9044. handle_not_modified_static_file_request(struct mg_connection *conn,
  9045. struct mg_file *filep)
  9046. {
  9047. char lm[64], etag[64];
  9048. if ((conn == NULL) || (filep == NULL)) {
  9049. return;
  9050. }
  9051. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9052. construct_etag(etag, sizeof(etag), &filep->stat);
  9053. /* Create 304 "not modified" response */
  9054. mg_response_header_start(conn, 304);
  9055. send_static_cache_header(conn);
  9056. send_additional_header(conn);
  9057. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9058. mg_response_header_add(conn, "Etag", etag, -1);
  9059. /* Send all headers */
  9060. mg_response_header_send(conn);
  9061. }
  9062. #endif
  9063. #if !defined(NO_FILESYSTEMS)
  9064. CIVETWEB_API void
  9065. mg_send_file(struct mg_connection *conn, const char *path)
  9066. {
  9067. mg_send_mime_file2(conn, path, NULL, NULL);
  9068. }
  9069. CIVETWEB_API void
  9070. mg_send_mime_file(struct mg_connection *conn,
  9071. const char *path,
  9072. const char *mime_type)
  9073. {
  9074. mg_send_mime_file2(conn, path, mime_type, NULL);
  9075. }
  9076. CIVETWEB_API void
  9077. mg_send_mime_file2(struct mg_connection *conn,
  9078. const char *path,
  9079. const char *mime_type,
  9080. const char *additional_headers)
  9081. {
  9082. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9083. if (!conn) {
  9084. /* No conn */
  9085. return;
  9086. }
  9087. if (mg_stat(conn, path, &file.stat)) {
  9088. #if !defined(NO_CACHING)
  9089. if (is_not_modified(conn, &file.stat)) {
  9090. /* Send 304 "Not Modified" - this must not send any body data */
  9091. handle_not_modified_static_file_request(conn, &file);
  9092. } else
  9093. #endif /* NO_CACHING */
  9094. if (file.stat.is_directory) {
  9095. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9096. "yes")) {
  9097. handle_directory_request(conn, path);
  9098. } else {
  9099. mg_send_http_error(conn,
  9100. 403,
  9101. "%s",
  9102. "Error: Directory listing denied");
  9103. }
  9104. } else {
  9105. handle_static_file_request(
  9106. conn, path, &file, mime_type, additional_headers);
  9107. }
  9108. } else {
  9109. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9110. }
  9111. }
  9112. /* For a given PUT path, create all intermediate subdirectories.
  9113. * Return 0 if the path itself is a directory.
  9114. * Return 1 if the path leads to a file.
  9115. * Return -1 for if the path is too long.
  9116. * Return -2 if path can not be created.
  9117. */
  9118. static int
  9119. put_dir(struct mg_connection *conn, const char *path)
  9120. {
  9121. char buf[UTF8_PATH_MAX];
  9122. const char *s, *p;
  9123. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9124. size_t len;
  9125. int res = 1;
  9126. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9127. len = (size_t)(p - path);
  9128. if (len >= sizeof(buf)) {
  9129. /* path too long */
  9130. res = -1;
  9131. break;
  9132. }
  9133. memcpy(buf, path, len);
  9134. buf[len] = '\0';
  9135. /* Try to create intermediate directory */
  9136. DEBUG_TRACE("mkdir(%s)", buf);
  9137. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9138. /* path does not exixt and can not be created */
  9139. res = -2;
  9140. break;
  9141. }
  9142. /* Is path itself a directory? */
  9143. if (p[1] == '\0') {
  9144. res = 0;
  9145. }
  9146. }
  9147. return res;
  9148. }
  9149. static void
  9150. remove_bad_file(const struct mg_connection *conn, const char *path)
  9151. {
  9152. int r = mg_remove(conn, path);
  9153. if (r != 0) {
  9154. mg_cry_internal(conn,
  9155. "%s: Cannot remove invalid file %s",
  9156. __func__,
  9157. path);
  9158. }
  9159. }
  9160. CIVETWEB_API long long
  9161. mg_store_body(struct mg_connection *conn, const char *path)
  9162. {
  9163. char buf[MG_BUF_LEN];
  9164. long long len = 0;
  9165. int ret, n;
  9166. struct mg_file fi;
  9167. if (conn->consumed_content != 0) {
  9168. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9169. return -11;
  9170. }
  9171. ret = put_dir(conn, path);
  9172. if (ret < 0) {
  9173. /* -1 for path too long,
  9174. * -2 for path can not be created. */
  9175. return ret;
  9176. }
  9177. if (ret != 1) {
  9178. /* Return 0 means, path itself is a directory. */
  9179. return 0;
  9180. }
  9181. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9182. return -12;
  9183. }
  9184. ret = mg_read(conn, buf, sizeof(buf));
  9185. while (ret > 0) {
  9186. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9187. if (n != ret) {
  9188. (void)mg_fclose(
  9189. &fi.access); /* File is bad and will be removed anyway. */
  9190. remove_bad_file(conn, path);
  9191. return -13;
  9192. }
  9193. len += ret;
  9194. ret = mg_read(conn, buf, sizeof(buf));
  9195. }
  9196. /* File is open for writing. If fclose fails, there was probably an
  9197. * error flushing the buffer to disk, so the file on disk might be
  9198. * broken. Delete it and return an error to the caller. */
  9199. if (mg_fclose(&fi.access) != 0) {
  9200. remove_bad_file(conn, path);
  9201. return -14;
  9202. }
  9203. return len;
  9204. }
  9205. #endif /* NO_FILESYSTEMS */
  9206. /* Parse a buffer:
  9207. * Forward the string pointer till the end of a word, then
  9208. * terminate it and forward till the begin of the next word.
  9209. */
  9210. static int
  9211. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9212. {
  9213. /* Forward until a space is found - use isgraph here */
  9214. /* See http://www.cplusplus.com/reference/cctype/ */
  9215. while (isgraph((unsigned char)**ppw)) {
  9216. (*ppw)++;
  9217. }
  9218. /* Check end of word */
  9219. if (eol) {
  9220. /* must be a end of line */
  9221. if ((**ppw != '\r') && (**ppw != '\n')) {
  9222. return -1;
  9223. }
  9224. } else {
  9225. /* must be a end of a word, but not a line */
  9226. if (**ppw != ' ') {
  9227. return -1;
  9228. }
  9229. }
  9230. /* Terminate and forward to the next word */
  9231. do {
  9232. **ppw = 0;
  9233. (*ppw)++;
  9234. } while (isspace((unsigned char)**ppw));
  9235. /* Check after term */
  9236. if (!eol) {
  9237. /* if it's not the end of line, there must be a next word */
  9238. if (!isgraph((unsigned char)**ppw)) {
  9239. return -1;
  9240. }
  9241. }
  9242. /* ok */
  9243. return 1;
  9244. }
  9245. /* Parse HTTP headers from the given buffer, advance buf pointer
  9246. * to the point where parsing stopped.
  9247. * All parameters must be valid pointers (not NULL).
  9248. * Return <0 on error. */
  9249. static int
  9250. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9251. {
  9252. int i;
  9253. int num_headers = 0;
  9254. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9255. char *dp = *buf;
  9256. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9257. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9258. dp++;
  9259. }
  9260. if (dp == *buf) {
  9261. /* End of headers reached. */
  9262. break;
  9263. }
  9264. /* Drop all spaces after header name before : */
  9265. while (*dp == ' ') {
  9266. *dp = 0;
  9267. dp++;
  9268. }
  9269. if (*dp != ':') {
  9270. /* This is not a valid field. */
  9271. return -1;
  9272. }
  9273. /* End of header key (*dp == ':') */
  9274. /* Truncate here and set the key name */
  9275. *dp = 0;
  9276. hdr[i].name = *buf;
  9277. /* Skip all spaces */
  9278. do {
  9279. dp++;
  9280. } while ((*dp == ' ') || (*dp == '\t'));
  9281. /* The rest of the line is the value */
  9282. hdr[i].value = dp;
  9283. /* Find end of line */
  9284. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9285. dp++;
  9286. };
  9287. /* eliminate \r */
  9288. if (*dp == '\r') {
  9289. *dp = 0;
  9290. dp++;
  9291. if (*dp != '\n') {
  9292. /* This is not a valid line. */
  9293. return -1;
  9294. }
  9295. }
  9296. /* here *dp is either 0 or '\n' */
  9297. /* in any case, we have a new header */
  9298. num_headers = i + 1;
  9299. if (*dp) {
  9300. *dp = 0;
  9301. dp++;
  9302. *buf = dp;
  9303. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9304. /* This is the end of the header */
  9305. break;
  9306. }
  9307. } else {
  9308. *buf = dp;
  9309. break;
  9310. }
  9311. }
  9312. return num_headers;
  9313. }
  9314. struct mg_http_method_info {
  9315. const char *name;
  9316. int request_has_body;
  9317. int response_has_body;
  9318. int is_safe;
  9319. int is_idempotent;
  9320. int is_cacheable;
  9321. };
  9322. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9323. static const struct mg_http_method_info http_methods[] = {
  9324. /* HTTP (RFC 2616) */
  9325. {"GET", 0, 1, 1, 1, 1},
  9326. {"POST", 1, 1, 0, 0, 0},
  9327. {"PUT", 1, 0, 0, 1, 0},
  9328. {"DELETE", 0, 0, 0, 1, 0},
  9329. {"HEAD", 0, 0, 1, 1, 1},
  9330. {"OPTIONS", 0, 0, 1, 1, 0},
  9331. {"CONNECT", 1, 1, 0, 0, 0},
  9332. /* TRACE method (RFC 2616) is not supported for security reasons */
  9333. /* PATCH method (RFC 5789) */
  9334. {"PATCH", 1, 0, 0, 0, 0},
  9335. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9336. /* WEBDAV (RFC 2518) */
  9337. {"PROPFIND", 0, 1, 1, 1, 0},
  9338. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9339. * Some PROPFIND results MAY be cached, with care,
  9340. * as there is no cache validation mechanism for
  9341. * most properties. This method is both safe and
  9342. * idempotent (see Section 9.1 of [RFC2616]). */
  9343. {"MKCOL", 0, 0, 0, 1, 0},
  9344. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9345. * When MKCOL is invoked without a request body,
  9346. * the newly created collection SHOULD have no
  9347. * members. A MKCOL request message may contain
  9348. * a message body. The precise behavior of a MKCOL
  9349. * request when the body is present is undefined,
  9350. * ... ==> We do not support MKCOL with body data.
  9351. * This method is idempotent, but not safe (see
  9352. * Section 9.1 of [RFC2616]). Responses to this
  9353. * method MUST NOT be cached. */
  9354. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9355. {"LOCK", 1, 1, 0, 0, 0},
  9356. {"UNLOCK", 1, 0, 0, 0, 0},
  9357. {"PROPPATCH", 1, 1, 0, 0, 0},
  9358. {"COPY", 1, 0, 0, 0, 0},
  9359. {"MOVE", 1, 1, 0, 0, 0},
  9360. /* Unsupported WEBDAV Methods: */
  9361. /* + 11 methods from RFC 3253 */
  9362. /* ORDERPATCH (RFC 3648) */
  9363. /* ACL (RFC 3744) */
  9364. /* SEARCH (RFC 5323) */
  9365. /* + MicroSoft extensions
  9366. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9367. /* REPORT method (RFC 3253) */
  9368. {"REPORT", 1, 1, 1, 1, 1},
  9369. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9370. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9371. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9372. * to be useful for REST in case a "GET request with body" is
  9373. * required. */
  9374. {NULL, 0, 0, 0, 0, 0}
  9375. /* end of list */
  9376. };
  9377. /* All method names */
  9378. static char *all_methods = NULL; /* Built by mg_init_library */
  9379. static const struct mg_http_method_info *
  9380. get_http_method_info(const char *method)
  9381. {
  9382. /* Check if the method is known to the server. The list of all known
  9383. * HTTP methods can be found here at
  9384. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9385. */
  9386. const struct mg_http_method_info *m = http_methods;
  9387. while (m->name) {
  9388. if (!strcmp(m->name, method)) {
  9389. return m;
  9390. }
  9391. m++;
  9392. }
  9393. return NULL;
  9394. }
  9395. static int
  9396. is_valid_http_method(const char *method)
  9397. {
  9398. return (get_http_method_info(method) != NULL);
  9399. }
  9400. /* Parse HTTP request, fill in mg_request_info structure.
  9401. * This function modifies the buffer by NUL-terminating
  9402. * HTTP request components, header names and header values.
  9403. * Parameters:
  9404. * buf (in/out): pointer to the HTTP header to parse and split
  9405. * len (in): length of HTTP header buffer
  9406. * re (out): parsed header as mg_request_info
  9407. * buf and ri must be valid pointers (not NULL), len>0.
  9408. * Returns <0 on error. */
  9409. static int
  9410. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9411. {
  9412. int request_length;
  9413. int init_skip = 0;
  9414. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9415. * remote_port */
  9416. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9417. NULL;
  9418. ri->num_headers = 0;
  9419. /* RFC says that all initial whitespaces should be ignored */
  9420. /* This included all leading \r and \n (isspace) */
  9421. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9422. while ((len > 0) && isspace((unsigned char)*buf)) {
  9423. buf++;
  9424. len--;
  9425. init_skip++;
  9426. }
  9427. if (len == 0) {
  9428. /* Incomplete request */
  9429. return 0;
  9430. }
  9431. /* Control characters are not allowed, including zero */
  9432. if (iscntrl((unsigned char)*buf)) {
  9433. return -1;
  9434. }
  9435. /* Find end of HTTP header */
  9436. request_length = get_http_header_len(buf, len);
  9437. if (request_length <= 0) {
  9438. return request_length;
  9439. }
  9440. buf[request_length - 1] = '\0';
  9441. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9442. return -1;
  9443. }
  9444. /* The first word has to be the HTTP method */
  9445. ri->request_method = buf;
  9446. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9447. return -1;
  9448. }
  9449. /* The second word is the URI */
  9450. ri->request_uri = buf;
  9451. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9452. return -1;
  9453. }
  9454. /* Next would be the HTTP version */
  9455. ri->http_version = buf;
  9456. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9457. return -1;
  9458. }
  9459. /* Check for a valid HTTP version key */
  9460. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9461. /* Invalid request */
  9462. return -1;
  9463. }
  9464. ri->http_version += 5;
  9465. /* Check for a valid http method */
  9466. if (!is_valid_http_method(ri->request_method)) {
  9467. return -1;
  9468. }
  9469. /* Parse all HTTP headers */
  9470. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9471. if (ri->num_headers < 0) {
  9472. /* Error while parsing headers */
  9473. return -1;
  9474. }
  9475. return request_length + init_skip;
  9476. }
  9477. static int
  9478. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9479. {
  9480. int response_length;
  9481. int init_skip = 0;
  9482. char *tmp, *tmp2;
  9483. long l;
  9484. /* Initialize elements. */
  9485. ri->http_version = ri->status_text = NULL;
  9486. ri->num_headers = ri->status_code = 0;
  9487. /* RFC says that all initial whitespaces should be ingored */
  9488. /* This included all leading \r and \n (isspace) */
  9489. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9490. while ((len > 0) && isspace((unsigned char)*buf)) {
  9491. buf++;
  9492. len--;
  9493. init_skip++;
  9494. }
  9495. if (len == 0) {
  9496. /* Incomplete request */
  9497. return 0;
  9498. }
  9499. /* Control characters are not allowed, including zero */
  9500. if (iscntrl((unsigned char)*buf)) {
  9501. return -1;
  9502. }
  9503. /* Find end of HTTP header */
  9504. response_length = get_http_header_len(buf, len);
  9505. if (response_length <= 0) {
  9506. return response_length;
  9507. }
  9508. buf[response_length - 1] = '\0';
  9509. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9510. return -1;
  9511. }
  9512. /* The first word is the HTTP version */
  9513. /* Check for a valid HTTP version key */
  9514. if (strncmp(buf, "HTTP/", 5) != 0) {
  9515. /* Invalid request */
  9516. return -1;
  9517. }
  9518. buf += 5;
  9519. if (!isgraph((unsigned char)buf[0])) {
  9520. /* Invalid request */
  9521. return -1;
  9522. }
  9523. ri->http_version = buf;
  9524. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9525. return -1;
  9526. }
  9527. /* The second word is the status as a number */
  9528. tmp = buf;
  9529. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9530. return -1;
  9531. }
  9532. l = strtol(tmp, &tmp2, 10);
  9533. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9534. /* Everything else but a 3 digit code is invalid */
  9535. return -1;
  9536. }
  9537. ri->status_code = (int)l;
  9538. /* The rest of the line is the status text */
  9539. ri->status_text = buf;
  9540. /* Find end of status text */
  9541. /* isgraph or isspace = isprint */
  9542. while (isprint((unsigned char)*buf)) {
  9543. buf++;
  9544. }
  9545. if ((*buf != '\r') && (*buf != '\n')) {
  9546. return -1;
  9547. }
  9548. /* Terminate string and forward buf to next line */
  9549. do {
  9550. *buf = 0;
  9551. buf++;
  9552. } while (isspace((unsigned char)*buf));
  9553. /* Parse all HTTP headers */
  9554. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9555. if (ri->num_headers < 0) {
  9556. /* Error while parsing headers */
  9557. return -1;
  9558. }
  9559. return response_length + init_skip;
  9560. }
  9561. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9562. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9563. * buffer (which marks the end of HTTP request). Buffer buf may already
  9564. * have some data. The length of the data is stored in nread.
  9565. * Upon every read operation, increase nread by the number of bytes read. */
  9566. static int
  9567. read_message(FILE *fp,
  9568. struct mg_connection *conn,
  9569. char *buf,
  9570. int bufsiz,
  9571. int *nread)
  9572. {
  9573. int request_len, n = 0;
  9574. struct timespec last_action_time;
  9575. double request_timeout;
  9576. if (!conn) {
  9577. return 0;
  9578. }
  9579. memset(&last_action_time, 0, sizeof(last_action_time));
  9580. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9581. /* value of request_timeout is in seconds, config in milliseconds */
  9582. request_timeout =
  9583. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9584. } else {
  9585. request_timeout =
  9586. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9587. / 1000.0;
  9588. }
  9589. if (conn->handled_requests > 0) {
  9590. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9591. request_timeout =
  9592. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9593. / 1000.0;
  9594. }
  9595. }
  9596. request_len = get_http_header_len(buf, *nread);
  9597. while (request_len == 0) {
  9598. /* Full request not yet received */
  9599. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9600. /* Server is to be stopped. */
  9601. return -1;
  9602. }
  9603. if (*nread >= bufsiz) {
  9604. /* Request too long */
  9605. return -2;
  9606. }
  9607. n = pull_inner(
  9608. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9609. if (n == -2) {
  9610. /* Receive error */
  9611. return -1;
  9612. }
  9613. /* update clock after every read request */
  9614. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9615. if (n > 0) {
  9616. *nread += n;
  9617. request_len = get_http_header_len(buf, *nread);
  9618. }
  9619. if ((request_len == 0) && (request_timeout >= 0)) {
  9620. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9621. > request_timeout) {
  9622. /* Timeout */
  9623. return -1;
  9624. }
  9625. }
  9626. }
  9627. return request_len;
  9628. }
  9629. #if !defined(NO_CGI) || !defined(NO_FILES)
  9630. static int
  9631. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9632. {
  9633. const char *expect;
  9634. char buf[MG_BUF_LEN];
  9635. int success = 0;
  9636. if (!conn) {
  9637. return 0;
  9638. }
  9639. expect = mg_get_header(conn, "Expect");
  9640. DEBUG_ASSERT(fp != NULL);
  9641. if (!fp) {
  9642. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9643. return 0;
  9644. }
  9645. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9646. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9647. */
  9648. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9649. } else {
  9650. if (expect != NULL) {
  9651. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9652. conn->status_code = 100;
  9653. } else {
  9654. conn->status_code = 200;
  9655. }
  9656. DEBUG_ASSERT(conn->consumed_content == 0);
  9657. if (conn->consumed_content != 0) {
  9658. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9659. return 0;
  9660. }
  9661. for (;;) {
  9662. int nread = mg_read(conn, buf, sizeof(buf));
  9663. if (nread <= 0) {
  9664. success = (nread == 0);
  9665. break;
  9666. }
  9667. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9668. break;
  9669. }
  9670. }
  9671. /* Each error code path in this function must send an error */
  9672. if (!success) {
  9673. /* NOTE: Maybe some data has already been sent. */
  9674. /* TODO (low): If some data has been sent, a correct error
  9675. * reply can no longer be sent, so just close the connection */
  9676. mg_send_http_error(conn, 500, "%s", "");
  9677. }
  9678. }
  9679. return success;
  9680. }
  9681. #endif
  9682. #if defined(USE_TIMERS)
  9683. #define TIMER_API static
  9684. #include "timer.inl"
  9685. #endif /* USE_TIMERS */
  9686. #if !defined(NO_CGI)
  9687. /* This structure helps to create an environment for the spawned CGI
  9688. * program.
  9689. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9690. * last element must be NULL.
  9691. * However, on Windows there is a requirement that all these
  9692. * VARIABLE=VALUE\0
  9693. * strings must reside in a contiguous buffer. The end of the buffer is
  9694. * marked by two '\0' characters.
  9695. * We satisfy both worlds: we create an envp array (which is vars), all
  9696. * entries are actually pointers inside buf. */
  9697. struct cgi_environment {
  9698. struct mg_connection *conn;
  9699. /* Data block */
  9700. char *buf; /* Environment buffer */
  9701. size_t buflen; /* Space available in buf */
  9702. size_t bufused; /* Space taken in buf */
  9703. /* Index block */
  9704. char **var; /* char **envp */
  9705. size_t varlen; /* Number of variables available in var */
  9706. size_t varused; /* Number of variables stored in var */
  9707. };
  9708. static void addenv(struct cgi_environment *env,
  9709. PRINTF_FORMAT_STRING(const char *fmt),
  9710. ...) PRINTF_ARGS(2, 3);
  9711. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9712. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9713. static void
  9714. addenv(struct cgi_environment *env, const char *fmt, ...)
  9715. {
  9716. size_t i, n, space;
  9717. int truncated = 0;
  9718. char *added;
  9719. va_list ap;
  9720. if ((env->varlen - env->varused) < 2) {
  9721. mg_cry_internal(env->conn,
  9722. "%s: Cannot register CGI variable [%s]",
  9723. __func__,
  9724. fmt);
  9725. return;
  9726. }
  9727. /* Calculate how much space is left in the buffer */
  9728. space = (env->buflen - env->bufused);
  9729. do {
  9730. /* Space for "\0\0" is always needed. */
  9731. if (space <= 2) {
  9732. /* Allocate new buffer */
  9733. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9734. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9735. if (!added) {
  9736. /* Out of memory */
  9737. mg_cry_internal(
  9738. env->conn,
  9739. "%s: Cannot allocate memory for CGI variable [%s]",
  9740. __func__,
  9741. fmt);
  9742. return;
  9743. }
  9744. /* Retarget pointers */
  9745. env->buf = added;
  9746. env->buflen = n;
  9747. for (i = 0, n = 0; i < env->varused; i++) {
  9748. env->var[i] = added + n;
  9749. n += strlen(added + n) + 1;
  9750. }
  9751. space = (env->buflen - env->bufused);
  9752. }
  9753. /* Make a pointer to the free space int the buffer */
  9754. added = env->buf + env->bufused;
  9755. /* Copy VARIABLE=VALUE\0 string into the free space */
  9756. va_start(ap, fmt);
  9757. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9758. va_end(ap);
  9759. /* Do not add truncated strings to the environment */
  9760. if (truncated) {
  9761. /* Reallocate the buffer */
  9762. space = 0;
  9763. }
  9764. } while (truncated);
  9765. /* Calculate number of bytes added to the environment */
  9766. n = strlen(added) + 1;
  9767. env->bufused += n;
  9768. /* Append a pointer to the added string into the envp array */
  9769. env->var[env->varused] = added;
  9770. env->varused++;
  9771. }
  9772. /* Return 0 on success, non-zero if an error occurs. */
  9773. static int
  9774. prepare_cgi_environment(struct mg_connection *conn,
  9775. const char *prog,
  9776. struct cgi_environment *env,
  9777. unsigned char cgi_config_idx)
  9778. {
  9779. const char *s;
  9780. struct vec var_vec;
  9781. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9782. int i, truncated, uri_len;
  9783. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9784. return -1;
  9785. }
  9786. env->conn = conn;
  9787. env->buflen = CGI_ENVIRONMENT_SIZE;
  9788. env->bufused = 0;
  9789. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9790. if (env->buf == NULL) {
  9791. mg_cry_internal(conn,
  9792. "%s: Not enough memory for environmental buffer",
  9793. __func__);
  9794. return -1;
  9795. }
  9796. env->varlen = MAX_CGI_ENVIR_VARS;
  9797. env->varused = 0;
  9798. env->var =
  9799. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9800. if (env->var == NULL) {
  9801. mg_cry_internal(conn,
  9802. "%s: Not enough memory for environmental variables",
  9803. __func__);
  9804. mg_free(env->buf);
  9805. return -1;
  9806. }
  9807. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9808. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9809. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9810. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9811. /* Prepare the environment block */
  9812. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9813. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9814. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9815. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9816. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9817. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9818. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9819. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9820. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9821. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9822. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9823. /* SCRIPT_NAME */
  9824. uri_len = (int)strlen(conn->request_info.local_uri);
  9825. if (conn->path_info == NULL) {
  9826. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9827. /* URI: /path_to_script/script.cgi */
  9828. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9829. } else {
  9830. /* URI: /path_to_script/ ... using index.cgi */
  9831. const char *index_file = strrchr(prog, '/');
  9832. if (index_file) {
  9833. addenv(env,
  9834. "SCRIPT_NAME=%s%s",
  9835. conn->request_info.local_uri,
  9836. index_file + 1);
  9837. }
  9838. }
  9839. } else {
  9840. /* URI: /path_to_script/script.cgi/path_info */
  9841. addenv(env,
  9842. "SCRIPT_NAME=%.*s",
  9843. uri_len - (int)strlen(conn->path_info),
  9844. conn->request_info.local_uri);
  9845. }
  9846. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9847. if (conn->path_info == NULL) {
  9848. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9849. } else {
  9850. addenv(env,
  9851. "PATH_TRANSLATED=%s%s",
  9852. conn->dom_ctx->config[DOCUMENT_ROOT],
  9853. conn->path_info);
  9854. }
  9855. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9856. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9857. addenv(env, "CONTENT_TYPE=%s", s);
  9858. }
  9859. if (conn->request_info.query_string != NULL) {
  9860. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9861. }
  9862. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9863. addenv(env, "CONTENT_LENGTH=%s", s);
  9864. }
  9865. if ((s = getenv("PATH")) != NULL) {
  9866. addenv(env, "PATH=%s", s);
  9867. }
  9868. if (conn->path_info != NULL) {
  9869. addenv(env, "PATH_INFO=%s", conn->path_info);
  9870. }
  9871. if (conn->status_code > 0) {
  9872. /* CGI error handler should show the status code */
  9873. addenv(env, "STATUS=%d", conn->status_code);
  9874. }
  9875. #if defined(_WIN32)
  9876. if ((s = getenv("COMSPEC")) != NULL) {
  9877. addenv(env, "COMSPEC=%s", s);
  9878. }
  9879. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9880. addenv(env, "SYSTEMROOT=%s", s);
  9881. }
  9882. if ((s = getenv("SystemDrive")) != NULL) {
  9883. addenv(env, "SystemDrive=%s", s);
  9884. }
  9885. if ((s = getenv("ProgramFiles")) != NULL) {
  9886. addenv(env, "ProgramFiles=%s", s);
  9887. }
  9888. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9889. addenv(env, "ProgramFiles(x86)=%s", s);
  9890. }
  9891. #else
  9892. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9893. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9894. }
  9895. #endif /* _WIN32 */
  9896. if ((s = getenv("PERLLIB")) != NULL) {
  9897. addenv(env, "PERLLIB=%s", s);
  9898. }
  9899. if (conn->request_info.remote_user != NULL) {
  9900. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9901. addenv(env, "%s", "AUTH_TYPE=Digest");
  9902. }
  9903. /* Add all headers as HTTP_* variables */
  9904. for (i = 0; i < conn->request_info.num_headers; i++) {
  9905. (void)mg_snprintf(conn,
  9906. &truncated,
  9907. http_var_name,
  9908. sizeof(http_var_name),
  9909. "HTTP_%s",
  9910. conn->request_info.http_headers[i].name);
  9911. if (truncated) {
  9912. mg_cry_internal(conn,
  9913. "%s: HTTP header variable too long [%s]",
  9914. __func__,
  9915. conn->request_info.http_headers[i].name);
  9916. continue;
  9917. }
  9918. /* Convert variable name into uppercase, and change - to _ */
  9919. for (p = http_var_name; *p != '\0'; p++) {
  9920. if (*p == '-') {
  9921. *p = '_';
  9922. }
  9923. *p = (char)toupper((unsigned char)*p);
  9924. }
  9925. addenv(env,
  9926. "%s=%s",
  9927. http_var_name,
  9928. conn->request_info.http_headers[i].value);
  9929. }
  9930. /* Add user-specified variables */
  9931. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9932. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9933. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9934. }
  9935. env->var[env->varused] = NULL;
  9936. env->buf[env->bufused] = '\0';
  9937. return 0;
  9938. }
  9939. /* Data for CGI process control: PID and number of references */
  9940. struct process_control_data {
  9941. pid_t pid;
  9942. ptrdiff_t references;
  9943. };
  9944. static int
  9945. abort_cgi_process(void *data)
  9946. {
  9947. /* Waitpid checks for child status and won't work for a pid that does
  9948. * not identify a child of the current process. Thus, if the pid is
  9949. * reused, we will not affect a different process. */
  9950. struct process_control_data *proc = (struct process_control_data *)data;
  9951. int status = 0;
  9952. ptrdiff_t refs;
  9953. pid_t ret_pid;
  9954. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9955. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9956. /* Stop child process */
  9957. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9958. kill(proc->pid, SIGABRT);
  9959. /* Wait until process is terminated (don't leave zombies) */
  9960. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9961. ;
  9962. } else {
  9963. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9964. }
  9965. /* Dec reference counter */
  9966. refs = mg_atomic_dec(&proc->references);
  9967. if (refs == 0) {
  9968. /* no more references - free data */
  9969. mg_free(data);
  9970. }
  9971. return 0;
  9972. }
  9973. /* Local (static) function assumes all arguments are valid. */
  9974. static void
  9975. handle_cgi_request(struct mg_connection *conn,
  9976. const char *prog,
  9977. unsigned char cgi_config_idx)
  9978. {
  9979. char *buf;
  9980. size_t buflen;
  9981. int headers_len, data_len, i, truncated;
  9982. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9983. const char *status, *status_text;
  9984. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9985. struct mg_request_info ri;
  9986. struct cgi_environment blk;
  9987. FILE *in = NULL, *out = NULL, *err = NULL;
  9988. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9989. pid_t pid = (pid_t)-1;
  9990. struct process_control_data *proc = NULL;
  9991. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9992. int no_buffering = 0;
  9993. #if defined(USE_TIMERS)
  9994. double cgi_timeout;
  9995. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9996. /* Get timeout in seconds */
  9997. cgi_timeout =
  9998. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9999. } else {
  10000. cgi_timeout =
  10001. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10002. }
  10003. #endif
  10004. if (cfg_buffering != NULL) {
  10005. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10006. no_buffering = 1;
  10007. }
  10008. }
  10009. buf = NULL;
  10010. buflen = conn->phys_ctx->max_request_size;
  10011. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10012. if (i != 0) {
  10013. blk.buf = NULL;
  10014. blk.var = NULL;
  10015. goto done;
  10016. }
  10017. /* CGI must be executed in its own directory. 'dir' must point to the
  10018. * directory containing executable program, 'p' must point to the
  10019. * executable program name relative to 'dir'. */
  10020. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10021. if (truncated) {
  10022. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10023. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10024. goto done;
  10025. }
  10026. if ((p = strrchr(dir, '/')) != NULL) {
  10027. *p++ = '\0';
  10028. } else {
  10029. dir[0] = '.';
  10030. dir[1] = '\0';
  10031. p = (char *)prog;
  10032. }
  10033. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10034. status = strerror(ERRNO);
  10035. mg_cry_internal(
  10036. conn,
  10037. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10038. prog,
  10039. status);
  10040. mg_send_http_error(conn,
  10041. 500,
  10042. "Error: Cannot create CGI pipe: %s",
  10043. status);
  10044. goto done;
  10045. }
  10046. proc = (struct process_control_data *)
  10047. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10048. if (proc == NULL) {
  10049. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10050. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10051. goto done;
  10052. }
  10053. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10054. pid = spawn_process(
  10055. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10056. if (pid == (pid_t)-1) {
  10057. status = strerror(ERRNO);
  10058. mg_cry_internal(
  10059. conn,
  10060. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10061. prog,
  10062. status);
  10063. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10064. mg_free(proc);
  10065. proc = NULL;
  10066. goto done;
  10067. }
  10068. /* Store data in shared process_control_data */
  10069. proc->pid = pid;
  10070. proc->references = 1;
  10071. #if defined(USE_TIMERS)
  10072. if (cgi_timeout > 0.0) {
  10073. proc->references = 2;
  10074. // Start a timer for CGI
  10075. timer_add(conn->phys_ctx,
  10076. cgi_timeout /* in seconds */,
  10077. 0.0,
  10078. 1,
  10079. abort_cgi_process,
  10080. (void *)proc,
  10081. NULL);
  10082. }
  10083. #endif
  10084. /* Parent closes only one side of the pipes.
  10085. * If we don't mark them as closed, close() attempt before
  10086. * return from this function throws an exception on Windows.
  10087. * Windows does not like when closed descriptor is closed again. */
  10088. (void)close(fdin[0]);
  10089. (void)close(fdout[1]);
  10090. (void)close(fderr[1]);
  10091. fdin[0] = fdout[1] = fderr[1] = -1;
  10092. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10093. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10094. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10095. status = strerror(ERRNO);
  10096. mg_cry_internal(conn,
  10097. "Error: CGI program \"%s\": Can not open fd: %s",
  10098. prog,
  10099. status);
  10100. mg_send_http_error(conn,
  10101. 500,
  10102. "Error: CGI can not open fd\nfdopen: %s",
  10103. status);
  10104. goto done;
  10105. }
  10106. setbuf(in, NULL);
  10107. setbuf(out, NULL);
  10108. setbuf(err, NULL);
  10109. fout.access.fp = out;
  10110. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10111. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10112. conn->content_len);
  10113. /* This is a POST/PUT request, or another request with body data. */
  10114. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10115. /* Error sending the body data */
  10116. mg_cry_internal(
  10117. conn,
  10118. "Error: CGI program \"%s\": Forward body data failed",
  10119. prog);
  10120. goto done;
  10121. }
  10122. }
  10123. /* Close so child gets an EOF. */
  10124. fclose(in);
  10125. in = NULL;
  10126. fdin[1] = -1;
  10127. /* Now read CGI reply into a buffer. We need to set correct
  10128. * status code, thus we need to see all HTTP headers first.
  10129. * Do not send anything back to client, until we buffer in all
  10130. * HTTP headers. */
  10131. data_len = 0;
  10132. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10133. if (buf == NULL) {
  10134. mg_send_http_error(conn,
  10135. 500,
  10136. "Error: Not enough memory for CGI buffer (%u bytes)",
  10137. (unsigned int)buflen);
  10138. mg_cry_internal(
  10139. conn,
  10140. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10141. "bytes)",
  10142. prog,
  10143. (unsigned int)buflen);
  10144. goto done;
  10145. }
  10146. DEBUG_TRACE("CGI: %s", "wait for response");
  10147. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10148. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10149. if (headers_len <= 0) {
  10150. /* Could not parse the CGI response. Check if some error message on
  10151. * stderr. */
  10152. i = pull_all(err, conn, buf, (int)buflen);
  10153. if (i > 0) {
  10154. /* CGI program explicitly sent an error */
  10155. /* Write the error message to the internal log */
  10156. mg_cry_internal(conn,
  10157. "Error: CGI program \"%s\" sent error "
  10158. "message: [%.*s]",
  10159. prog,
  10160. i,
  10161. buf);
  10162. /* Don't send the error message back to the client */
  10163. mg_send_http_error(conn,
  10164. 500,
  10165. "Error: CGI program \"%s\" failed.",
  10166. prog);
  10167. } else {
  10168. /* CGI program did not explicitly send an error, but a broken
  10169. * respon header */
  10170. mg_cry_internal(conn,
  10171. "Error: CGI program sent malformed or too big "
  10172. "(>%u bytes) HTTP headers: [%.*s]",
  10173. (unsigned)buflen,
  10174. data_len,
  10175. buf);
  10176. mg_send_http_error(conn,
  10177. 500,
  10178. "Error: CGI program sent malformed or too big "
  10179. "(>%u bytes) HTTP headers: [%.*s]",
  10180. (unsigned)buflen,
  10181. data_len,
  10182. buf);
  10183. }
  10184. /* in both cases, abort processing CGI */
  10185. goto done;
  10186. }
  10187. pbuf = buf;
  10188. buf[headers_len - 1] = '\0';
  10189. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10190. /* Make up and send the status line */
  10191. status_text = "OK";
  10192. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10193. != NULL) {
  10194. conn->status_code = atoi(status);
  10195. status_text = status;
  10196. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10197. status_text++;
  10198. }
  10199. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10200. != NULL) {
  10201. conn->status_code = 307;
  10202. } else {
  10203. conn->status_code = 200;
  10204. }
  10205. if (!should_keep_alive(conn)) {
  10206. conn->must_close = 1;
  10207. }
  10208. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10209. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10210. /* Send headers */
  10211. for (i = 0; i < ri.num_headers; i++) {
  10212. DEBUG_TRACE("CGI header: %s: %s",
  10213. ri.http_headers[i].name,
  10214. ri.http_headers[i].value);
  10215. mg_printf(conn,
  10216. "%s: %s\r\n",
  10217. ri.http_headers[i].name,
  10218. ri.http_headers[i].value);
  10219. }
  10220. mg_write(conn, "\r\n", 2);
  10221. /* Send chunk of data that may have been read after the headers */
  10222. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10223. /* Read the rest of CGI output and send to the client */
  10224. DEBUG_TRACE("CGI: %s", "forward all data");
  10225. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10226. DEBUG_TRACE("CGI: %s", "all data sent");
  10227. done:
  10228. mg_free(blk.var);
  10229. mg_free(blk.buf);
  10230. if (pid != (pid_t)-1) {
  10231. abort_cgi_process((void *)proc);
  10232. }
  10233. if (fdin[0] != -1) {
  10234. close(fdin[0]);
  10235. }
  10236. if (fdout[1] != -1) {
  10237. close(fdout[1]);
  10238. }
  10239. if (fderr[1] != -1) {
  10240. close(fderr[1]);
  10241. }
  10242. if (in != NULL) {
  10243. fclose(in);
  10244. } else if (fdin[1] != -1) {
  10245. close(fdin[1]);
  10246. }
  10247. if (out != NULL) {
  10248. fclose(out);
  10249. } else if (fdout[0] != -1) {
  10250. close(fdout[0]);
  10251. }
  10252. if (err != NULL) {
  10253. fclose(err);
  10254. } else if (fderr[0] != -1) {
  10255. close(fderr[0]);
  10256. }
  10257. mg_free(buf);
  10258. }
  10259. #endif /* !NO_CGI */
  10260. #if !defined(NO_FILES)
  10261. static void
  10262. dav_mkcol(struct mg_connection *conn, const char *path)
  10263. {
  10264. int rc, body_len;
  10265. struct de de;
  10266. if (conn == NULL) {
  10267. return;
  10268. }
  10269. /* TODO (mid): Check the mg_send_http_error situations in this function
  10270. */
  10271. memset(&de.file, 0, sizeof(de.file));
  10272. if (!mg_stat(conn, path, &de.file)) {
  10273. mg_cry_internal(conn,
  10274. "%s: mg_stat(%s) failed: %s",
  10275. __func__,
  10276. path,
  10277. strerror(ERRNO));
  10278. }
  10279. if (de.file.last_modified) {
  10280. /* TODO (mid): This check does not seem to make any sense ! */
  10281. /* TODO (mid): Add a webdav unit test first, before changing
  10282. * anything here. */
  10283. mg_send_http_error(
  10284. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10285. return;
  10286. }
  10287. body_len = conn->data_len - conn->request_len;
  10288. if (body_len > 0) {
  10289. mg_send_http_error(
  10290. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10291. return;
  10292. }
  10293. rc = mg_mkdir(conn, path, 0755);
  10294. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10295. if (rc == 0) {
  10296. /* Create 201 "Created" response */
  10297. mg_response_header_start(conn, 201);
  10298. send_static_cache_header(conn);
  10299. send_additional_header(conn);
  10300. mg_response_header_add(conn, "Content-Length", "0", -1);
  10301. /* Send all headers - there is no body */
  10302. mg_response_header_send(conn);
  10303. } else {
  10304. int http_status = 500;
  10305. switch (errno) {
  10306. case EEXIST:
  10307. http_status = 405;
  10308. break;
  10309. case EACCES:
  10310. http_status = 403;
  10311. break;
  10312. case ENOENT:
  10313. http_status = 409;
  10314. break;
  10315. }
  10316. mg_send_http_error(conn,
  10317. http_status,
  10318. "Error processing %s: %s",
  10319. path,
  10320. strerror(ERRNO));
  10321. }
  10322. }
  10323. /* Forward decrlaration */
  10324. static int get_uri_type(const char *uri);
  10325. static const char *
  10326. get_rel_url_at_current_server(const char *uri,
  10327. const struct mg_connection *conn);
  10328. static void
  10329. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10330. {
  10331. const char *overwrite_hdr;
  10332. const char *destination_hdr;
  10333. const char *root;
  10334. int rc, dest_uri_type;
  10335. int http_status = 400;
  10336. int do_overwrite = 0;
  10337. int destination_ok = 0;
  10338. char dest_path[UTF8_PATH_MAX];
  10339. struct mg_file_stat ignored;
  10340. if (conn == NULL) {
  10341. return;
  10342. }
  10343. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10344. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10345. destination_hdr = mg_get_header(conn, "Destination");
  10346. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10347. do_overwrite = 1;
  10348. }
  10349. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10350. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10351. return;
  10352. }
  10353. if (root != NULL) {
  10354. char *local_dest = NULL;
  10355. dest_uri_type = get_uri_type(destination_hdr);
  10356. if (dest_uri_type == 2) {
  10357. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10358. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10359. const char *h =
  10360. get_rel_url_at_current_server(destination_hdr, conn);
  10361. if (h) {
  10362. int len = (int)strlen(h);
  10363. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10364. mg_url_decode(h, len, local_dest, len + 1, 0);
  10365. }
  10366. }
  10367. if (local_dest != NULL) {
  10368. remove_dot_segments(local_dest);
  10369. if (local_dest[0] == '/') {
  10370. int trunc_check = 0;
  10371. mg_snprintf(conn,
  10372. &trunc_check,
  10373. dest_path,
  10374. sizeof(dest_path),
  10375. "%s/%s",
  10376. root,
  10377. local_dest);
  10378. if (trunc_check == 0) {
  10379. destination_ok = 1;
  10380. }
  10381. }
  10382. mg_free(local_dest);
  10383. }
  10384. }
  10385. if (!destination_ok) {
  10386. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10387. return;
  10388. }
  10389. /* Check now if this file exists */
  10390. if (mg_stat(conn, dest_path, &ignored)) {
  10391. /* File exists */
  10392. if (do_overwrite) {
  10393. /* Overwrite allowed: delete the file first */
  10394. if (0 != remove(dest_path)) {
  10395. /* No overwrite: return error */
  10396. mg_send_http_error(conn,
  10397. 403,
  10398. "Cannot overwrite file: %s",
  10399. dest_path);
  10400. return;
  10401. }
  10402. } else {
  10403. /* No overwrite: return error */
  10404. mg_send_http_error(conn,
  10405. 412,
  10406. "Destination already exists: %s",
  10407. dest_path);
  10408. return;
  10409. }
  10410. }
  10411. /* Copy / Move / Rename operation. */
  10412. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10413. #if defined(_WIN32)
  10414. {
  10415. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10416. wchar_t wSource[UTF16_PATH_MAX];
  10417. wchar_t wDest[UTF16_PATH_MAX];
  10418. BOOL ok;
  10419. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10420. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10421. if (do_copy) {
  10422. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10423. } else {
  10424. ok = MoveFileExW(wSource,
  10425. wDest,
  10426. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10427. }
  10428. if (ok) {
  10429. rc = 0;
  10430. } else {
  10431. DWORD lastErr = GetLastError();
  10432. if (lastErr == ERROR_ALREADY_EXISTS) {
  10433. mg_send_http_error(conn,
  10434. 412,
  10435. "Destination already exists: %s",
  10436. dest_path);
  10437. return;
  10438. }
  10439. rc = -1;
  10440. http_status = 400;
  10441. }
  10442. }
  10443. #else
  10444. {
  10445. /* Linux uses already UTF-8, we don't need to convert file names. */
  10446. if (do_copy) {
  10447. /* TODO: COPY for Linux. */
  10448. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10449. return;
  10450. }
  10451. rc = rename(path, dest_path);
  10452. if (rc) {
  10453. switch (errno) {
  10454. case EEXIST:
  10455. http_status = 412;
  10456. break;
  10457. case EACCES:
  10458. http_status = 403;
  10459. break;
  10460. case ENOENT:
  10461. http_status = 409;
  10462. break;
  10463. }
  10464. }
  10465. }
  10466. #endif
  10467. if (rc == 0) {
  10468. /* Create 204 "No Content" response */
  10469. mg_response_header_start(conn, 204);
  10470. mg_response_header_add(conn, "Content-Length", "0", -1);
  10471. /* Send all headers - there is no body */
  10472. mg_response_header_send(conn);
  10473. } else {
  10474. mg_send_http_error(conn, http_status, "Operation failed");
  10475. }
  10476. }
  10477. static void
  10478. put_file(struct mg_connection *conn, const char *path)
  10479. {
  10480. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10481. const char *range;
  10482. int64_t r1, r2;
  10483. int rc;
  10484. if (conn == NULL) {
  10485. return;
  10486. }
  10487. DEBUG_TRACE("store %s", path);
  10488. if (mg_stat(conn, path, &file.stat)) {
  10489. /* File already exists */
  10490. conn->status_code = 200;
  10491. if (file.stat.is_directory) {
  10492. /* This is an already existing directory,
  10493. * so there is nothing to do for the server. */
  10494. rc = 0;
  10495. } else {
  10496. /* File exists and is not a directory. */
  10497. /* Can it be replaced? */
  10498. /* Check if the server may write this file */
  10499. if (access(path, W_OK) == 0) {
  10500. /* Access granted */
  10501. rc = 1;
  10502. } else {
  10503. mg_send_http_error(
  10504. conn,
  10505. 403,
  10506. "Error: Put not possible\nReplacing %s is not allowed",
  10507. path);
  10508. return;
  10509. }
  10510. }
  10511. } else {
  10512. /* File should be created */
  10513. conn->status_code = 201;
  10514. rc = put_dir(conn, path);
  10515. }
  10516. if (rc == 0) {
  10517. /* put_dir returns 0 if path is a directory */
  10518. /* Create response */
  10519. mg_response_header_start(conn, conn->status_code);
  10520. send_no_cache_header(conn);
  10521. send_additional_header(conn);
  10522. mg_response_header_add(conn, "Content-Length", "0", -1);
  10523. /* Send all headers - there is no body */
  10524. mg_response_header_send(conn);
  10525. /* Request to create a directory has been fulfilled successfully.
  10526. * No need to put a file. */
  10527. return;
  10528. }
  10529. if (rc == -1) {
  10530. /* put_dir returns -1 if the path is too long */
  10531. mg_send_http_error(conn,
  10532. 414,
  10533. "Error: Path too long\nput_dir(%s): %s",
  10534. path,
  10535. strerror(ERRNO));
  10536. return;
  10537. }
  10538. if (rc == -2) {
  10539. /* put_dir returns -2 if the directory can not be created */
  10540. mg_send_http_error(conn,
  10541. 500,
  10542. "Error: Can not create directory\nput_dir(%s): %s",
  10543. path,
  10544. strerror(ERRNO));
  10545. return;
  10546. }
  10547. /* A file should be created or overwritten. */
  10548. /* Currently CivetWeb does not nead read+write access. */
  10549. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10550. || file.access.fp == NULL) {
  10551. (void)mg_fclose(&file.access);
  10552. mg_send_http_error(conn,
  10553. 500,
  10554. "Error: Can not create file\nfopen(%s): %s",
  10555. path,
  10556. strerror(ERRNO));
  10557. return;
  10558. }
  10559. fclose_on_exec(&file.access, conn);
  10560. range = mg_get_header(conn, "Content-Range");
  10561. r1 = r2 = 0;
  10562. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10563. conn->status_code = 206; /* Partial content */
  10564. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10565. mg_send_http_error(conn,
  10566. 500,
  10567. "Error: Internal error processing file %s",
  10568. path);
  10569. return;
  10570. }
  10571. }
  10572. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10573. /* forward_body_data failed.
  10574. * The error code has already been sent to the client,
  10575. * and conn->status_code is already set. */
  10576. (void)mg_fclose(&file.access);
  10577. return;
  10578. }
  10579. if (mg_fclose(&file.access) != 0) {
  10580. /* fclose failed. This might have different reasons, but a likely
  10581. * one is "no space on disk", http 507. */
  10582. conn->status_code = 507;
  10583. }
  10584. /* Create response (status_code has been set before) */
  10585. mg_response_header_start(conn, conn->status_code);
  10586. send_no_cache_header(conn);
  10587. send_additional_header(conn);
  10588. mg_response_header_add(conn, "Content-Length", "0", -1);
  10589. /* Send all headers - there is no body */
  10590. mg_response_header_send(conn);
  10591. }
  10592. static void
  10593. delete_file(struct mg_connection *conn, const char *path)
  10594. {
  10595. struct de de;
  10596. memset(&de.file, 0, sizeof(de.file));
  10597. if (!mg_stat(conn, path, &de.file)) {
  10598. /* mg_stat returns 0 if the file does not exist */
  10599. mg_send_http_error(conn,
  10600. 404,
  10601. "Error: Cannot delete file\nFile %s not found",
  10602. path);
  10603. return;
  10604. }
  10605. DEBUG_TRACE("delete %s", path);
  10606. if (de.file.is_directory) {
  10607. if (remove_directory(conn, path)) {
  10608. /* Delete is successful: Return 204 without content. */
  10609. mg_send_http_error(conn, 204, "%s", "");
  10610. } else {
  10611. /* Delete is not successful: Return 500 (Server error). */
  10612. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10613. }
  10614. return;
  10615. }
  10616. /* This is an existing file (not a directory).
  10617. * Check if write permission is granted. */
  10618. if (access(path, W_OK) != 0) {
  10619. /* File is read only */
  10620. mg_send_http_error(
  10621. conn,
  10622. 403,
  10623. "Error: Delete not possible\nDeleting %s is not allowed",
  10624. path);
  10625. return;
  10626. }
  10627. /* Try to delete it. */
  10628. if (mg_remove(conn, path) == 0) {
  10629. /* Delete was successful: Return 204 without content. */
  10630. mg_response_header_start(conn, 204);
  10631. send_no_cache_header(conn);
  10632. send_additional_header(conn);
  10633. mg_response_header_add(conn, "Content-Length", "0", -1);
  10634. mg_response_header_send(conn);
  10635. } else {
  10636. /* Delete not successful (file locked). */
  10637. mg_send_http_error(conn,
  10638. 423,
  10639. "Error: Cannot delete file\nremove(%s): %s",
  10640. path,
  10641. strerror(ERRNO));
  10642. }
  10643. }
  10644. #endif /* !NO_FILES */
  10645. #if !defined(NO_FILESYSTEMS)
  10646. static void
  10647. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10648. static void
  10649. do_ssi_include(struct mg_connection *conn,
  10650. const char *ssi,
  10651. char *tag,
  10652. int include_level)
  10653. {
  10654. char file_name[MG_BUF_LEN], path[512], *p;
  10655. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10656. size_t len;
  10657. int truncated = 0;
  10658. if (conn == NULL) {
  10659. return;
  10660. }
  10661. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10662. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10663. * always < MG_BUF_LEN. */
  10664. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10665. /* File name is relative to the webserver root */
  10666. file_name[511] = 0;
  10667. (void)mg_snprintf(conn,
  10668. &truncated,
  10669. path,
  10670. sizeof(path),
  10671. "%s/%s",
  10672. conn->dom_ctx->config[DOCUMENT_ROOT],
  10673. file_name);
  10674. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10675. /* File name is relative to the webserver working directory
  10676. * or it is absolute system path */
  10677. file_name[511] = 0;
  10678. (void)
  10679. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10680. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10681. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10682. /* File name is relative to the currect document */
  10683. file_name[511] = 0;
  10684. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10685. if (!truncated) {
  10686. if ((p = strrchr(path, '/')) != NULL) {
  10687. p[1] = '\0';
  10688. }
  10689. len = strlen(path);
  10690. (void)mg_snprintf(conn,
  10691. &truncated,
  10692. path + len,
  10693. sizeof(path) - len,
  10694. "%s",
  10695. file_name);
  10696. }
  10697. } else {
  10698. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10699. return;
  10700. }
  10701. if (truncated) {
  10702. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10703. return;
  10704. }
  10705. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10706. mg_cry_internal(conn,
  10707. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10708. tag,
  10709. path,
  10710. strerror(ERRNO));
  10711. } else {
  10712. fclose_on_exec(&file.access, conn);
  10713. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10714. > 0) {
  10715. send_ssi_file(conn, path, &file, include_level + 1);
  10716. } else {
  10717. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10718. }
  10719. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10720. }
  10721. }
  10722. #if !defined(NO_POPEN)
  10723. static void
  10724. do_ssi_exec(struct mg_connection *conn, char *tag)
  10725. {
  10726. char cmd[1024] = "";
  10727. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10728. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10729. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10730. } else {
  10731. cmd[1023] = 0;
  10732. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10733. mg_cry_internal(conn,
  10734. "Cannot SSI #exec: [%s]: %s",
  10735. cmd,
  10736. strerror(ERRNO));
  10737. } else {
  10738. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10739. pclose(file.access.fp);
  10740. }
  10741. }
  10742. }
  10743. #endif /* !NO_POPEN */
  10744. static int
  10745. mg_fgetc(struct mg_file *filep)
  10746. {
  10747. if (filep == NULL) {
  10748. return EOF;
  10749. }
  10750. if (filep->access.fp != NULL) {
  10751. return fgetc(filep->access.fp);
  10752. } else {
  10753. return EOF;
  10754. }
  10755. }
  10756. static void
  10757. send_ssi_file(struct mg_connection *conn,
  10758. const char *path,
  10759. struct mg_file *filep,
  10760. int include_level)
  10761. {
  10762. char buf[MG_BUF_LEN];
  10763. int ch, len, in_tag, in_ssi_tag;
  10764. if (include_level > 10) {
  10765. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10766. return;
  10767. }
  10768. in_tag = in_ssi_tag = len = 0;
  10769. /* Read file, byte by byte, and look for SSI include tags */
  10770. while ((ch = mg_fgetc(filep)) != EOF) {
  10771. if (in_tag) {
  10772. /* We are in a tag, either SSI tag or html tag */
  10773. if (ch == '>') {
  10774. /* Tag is closing */
  10775. buf[len++] = '>';
  10776. if (in_ssi_tag) {
  10777. /* Handle SSI tag */
  10778. buf[len] = 0;
  10779. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10780. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10781. #if !defined(NO_POPEN)
  10782. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10783. do_ssi_exec(conn, buf + 9);
  10784. #endif /* !NO_POPEN */
  10785. } else {
  10786. mg_cry_internal(conn,
  10787. "%s: unknown SSI "
  10788. "command: \"%s\"",
  10789. path,
  10790. buf);
  10791. }
  10792. len = 0;
  10793. in_ssi_tag = in_tag = 0;
  10794. } else {
  10795. /* Not an SSI tag */
  10796. /* Flush buffer */
  10797. (void)mg_write(conn, buf, (size_t)len);
  10798. len = 0;
  10799. in_tag = 0;
  10800. }
  10801. } else {
  10802. /* Tag is still open */
  10803. buf[len++] = (char)(ch & 0xff);
  10804. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10805. /* All SSI tags start with <!--# */
  10806. in_ssi_tag = 1;
  10807. }
  10808. if ((len + 2) > (int)sizeof(buf)) {
  10809. /* Tag to long for buffer */
  10810. mg_cry_internal(conn, "%s: tag is too large", path);
  10811. return;
  10812. }
  10813. }
  10814. } else {
  10815. /* We are not in a tag yet. */
  10816. if (ch == '<') {
  10817. /* Tag is opening */
  10818. in_tag = 1;
  10819. if (len > 0) {
  10820. /* Flush current buffer.
  10821. * Buffer is filled with "len" bytes. */
  10822. (void)mg_write(conn, buf, (size_t)len);
  10823. }
  10824. /* Store the < */
  10825. len = 1;
  10826. buf[0] = '<';
  10827. } else {
  10828. /* No Tag */
  10829. /* Add data to buffer */
  10830. buf[len++] = (char)(ch & 0xff);
  10831. /* Flush if buffer is full */
  10832. if (len == (int)sizeof(buf)) {
  10833. mg_write(conn, buf, (size_t)len);
  10834. len = 0;
  10835. }
  10836. }
  10837. }
  10838. }
  10839. /* Send the rest of buffered data */
  10840. if (len > 0) {
  10841. mg_write(conn, buf, (size_t)len);
  10842. }
  10843. }
  10844. static void
  10845. handle_ssi_file_request(struct mg_connection *conn,
  10846. const char *path,
  10847. struct mg_file *filep)
  10848. {
  10849. char date[64];
  10850. time_t curtime = time(NULL);
  10851. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10852. return;
  10853. }
  10854. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10855. /* File exists (precondition for calling this function),
  10856. * but can not be opened by the server. */
  10857. mg_send_http_error(conn,
  10858. 500,
  10859. "Error: Cannot read file\nfopen(%s): %s",
  10860. path,
  10861. strerror(ERRNO));
  10862. } else {
  10863. /* Set "must_close" for HTTP/1.x, since we do not know the
  10864. * content length */
  10865. conn->must_close = 1;
  10866. gmt_time_string(date, sizeof(date), &curtime);
  10867. fclose_on_exec(&filep->access, conn);
  10868. /* 200 OK response */
  10869. mg_response_header_start(conn, 200);
  10870. send_no_cache_header(conn);
  10871. send_additional_header(conn);
  10872. send_cors_header(conn);
  10873. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10874. mg_response_header_send(conn);
  10875. /* Header sent, now send body */
  10876. send_ssi_file(conn, path, filep, 0);
  10877. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10878. }
  10879. }
  10880. #endif /* NO_FILESYSTEMS */
  10881. #if !defined(NO_FILES)
  10882. static void
  10883. send_options(struct mg_connection *conn)
  10884. {
  10885. if (!conn || !all_methods) {
  10886. return;
  10887. }
  10888. /* We do not set a "Cache-Control" header here, but leave the default.
  10889. * Since browsers do not send an OPTIONS request, we can not test the
  10890. * effect anyway. */
  10891. mg_response_header_start(conn, 200);
  10892. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10893. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10894. /* Use the same as before */
  10895. mg_response_header_add(conn, "Allow", all_methods, -1);
  10896. mg_response_header_add(conn, "DAV", "1", -1);
  10897. } else {
  10898. /* TODO: Check this later for HTTP/2 */
  10899. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10900. }
  10901. send_additional_header(conn);
  10902. mg_response_header_send(conn);
  10903. }
  10904. /* Writes PROPFIND properties for a collection element */
  10905. static int
  10906. print_props(struct mg_connection *conn,
  10907. const char *uri,
  10908. const char *name,
  10909. struct mg_file_stat *filep)
  10910. {
  10911. size_t i;
  10912. char mtime[64];
  10913. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10914. char *link_concat;
  10915. size_t link_concat_len;
  10916. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10917. return 0;
  10918. }
  10919. link_concat_len = strlen(uri) + strlen(name) + 1;
  10920. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10921. if (!link_concat) {
  10922. return 0;
  10923. }
  10924. strcpy(link_concat, uri);
  10925. strcat(link_concat, name);
  10926. /* Get full link used in request */
  10927. mg_construct_local_link(
  10928. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10929. /*
  10930. OutputDebugStringA("print_props:\n uri: ");
  10931. OutputDebugStringA(uri);
  10932. OutputDebugStringA("\n name: ");
  10933. OutputDebugStringA(name);
  10934. OutputDebugStringA("\n link: ");
  10935. OutputDebugStringA(link_buf);
  10936. OutputDebugStringA("\n");
  10937. */
  10938. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10939. mg_printf(conn,
  10940. "<d:response>"
  10941. "<d:href>%s</d:href>"
  10942. "<d:propstat>"
  10943. "<d:prop>"
  10944. "<d:resourcetype>%s</d:resourcetype>"
  10945. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10946. "<d:getlastmodified>%s</d:getlastmodified>"
  10947. "<d:lockdiscovery>",
  10948. link_buf,
  10949. filep->is_directory ? "<d:collection/>" : "",
  10950. filep->size,
  10951. mtime);
  10952. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10953. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10954. if (!strcmp(dav_lock[i].path, link_buf)) {
  10955. mg_printf(conn,
  10956. "<d:activelock>"
  10957. "<d:locktype><d:write/></d:locktype>"
  10958. "<d:lockscope><d:exclusive/></d:lockscope>"
  10959. "<d:depth>0</d:depth>"
  10960. "<d:owner>%s</d:owner>"
  10961. "<d:timeout>Second-%u</d:timeout>"
  10962. "<d:locktoken>"
  10963. "<d:href>%s</d:href>"
  10964. "</d:locktoken>"
  10965. "</d:activelock>\n",
  10966. dav_lock[i].user,
  10967. (unsigned)LOCK_DURATION_S,
  10968. dav_lock[i].token);
  10969. }
  10970. }
  10971. mg_printf(conn,
  10972. "</d:lockdiscovery>"
  10973. "</d:prop>"
  10974. "<d:status>HTTP/1.1 200 OK</d:status>"
  10975. "</d:propstat>"
  10976. "</d:response>\n");
  10977. mg_free(link_concat);
  10978. return 1;
  10979. }
  10980. static int
  10981. print_dav_dir_entry(struct de *de, void *data)
  10982. {
  10983. struct mg_connection *conn = (struct mg_connection *)data;
  10984. if (!de || !conn
  10985. || !print_props(
  10986. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10987. /* stop scan */
  10988. return 1;
  10989. }
  10990. return 0;
  10991. }
  10992. static void
  10993. handle_propfind(struct mg_connection *conn,
  10994. const char *path,
  10995. struct mg_file_stat *filep)
  10996. {
  10997. const char *depth = mg_get_header(conn, "Depth");
  10998. if (!conn || !path || !filep || !conn->dom_ctx) {
  10999. return;
  11000. }
  11001. /* return 207 "Multi-Status" */
  11002. conn->must_close = 1;
  11003. mg_response_header_start(conn, 207);
  11004. send_static_cache_header(conn);
  11005. send_additional_header(conn);
  11006. mg_response_header_add(conn,
  11007. "Content-Type",
  11008. "application/xml; charset=utf-8",
  11009. -1);
  11010. mg_response_header_send(conn);
  11011. /* Content */
  11012. mg_printf(conn,
  11013. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11014. "<d:multistatus xmlns:d='DAV:'>\n");
  11015. /* Print properties for the requested resource itself */
  11016. print_props(conn, conn->request_info.local_uri, "", filep);
  11017. /* If it is a directory, print directory entries too if Depth is not 0
  11018. */
  11019. if (filep->is_directory
  11020. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11021. "yes")
  11022. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11023. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11024. }
  11025. mg_printf(conn, "%s\n", "</d:multistatus>");
  11026. }
  11027. static void
  11028. dav_lock_file(struct mg_connection *conn, const char *path)
  11029. {
  11030. /* internal function - therefore conn is assumed to be valid */
  11031. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11032. uint64_t new_locktime;
  11033. int lock_index = -1;
  11034. int i;
  11035. uint64_t LOCK_DURATION_NS =
  11036. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11037. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11038. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11039. return;
  11040. }
  11041. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11042. /* const char *refresh = mg_get_header(conn, "If"); */
  11043. /* Link refresh should have an "If" header:
  11044. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11045. * But it seems Windows Explorer does not send them.
  11046. */
  11047. mg_lock_context(conn->phys_ctx);
  11048. new_locktime = mg_get_current_time_ns();
  11049. /* Find a slot for a lock */
  11050. while (lock_index < 0) {
  11051. /* find existing lock */
  11052. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11053. if (!strcmp(dav_lock[i].path, link_buf)) {
  11054. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11055. /* locked by the same user */
  11056. dav_lock[i].locktime = new_locktime;
  11057. lock_index = i;
  11058. break;
  11059. } else {
  11060. /* already locked by someone else */
  11061. if (new_locktime
  11062. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11063. /* Lock expired */
  11064. dav_lock[i].path[0] = 0;
  11065. } else {
  11066. /* Lock still valid */
  11067. mg_unlock_context(conn->phys_ctx);
  11068. mg_send_http_error(conn, 423, "%s", "Already locked");
  11069. return;
  11070. }
  11071. }
  11072. }
  11073. }
  11074. /* create new lock token */
  11075. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11076. if (dav_lock[i].path[0] == 0) {
  11077. char s[32];
  11078. dav_lock[i].locktime = mg_get_current_time_ns();
  11079. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11080. mg_md5(dav_lock[i].token,
  11081. link_buf,
  11082. "\x01",
  11083. s,
  11084. "\x01",
  11085. conn->request_info.remote_user,
  11086. NULL);
  11087. strncpy(dav_lock[i].path,
  11088. link_buf,
  11089. sizeof(dav_lock[i].path) - 1);
  11090. strncpy(dav_lock[i].user,
  11091. conn->request_info.remote_user,
  11092. sizeof(dav_lock[i].user) - 1);
  11093. lock_index = i;
  11094. break;
  11095. }
  11096. }
  11097. if (lock_index < 0) {
  11098. /* too many locks. Find oldest lock */
  11099. uint64_t oldest_locktime = dav_lock[0].locktime;
  11100. lock_index = 0;
  11101. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11102. if (dav_lock[i].locktime < oldest_locktime) {
  11103. oldest_locktime = dav_lock[i].locktime;
  11104. lock_index = i;
  11105. }
  11106. }
  11107. /* invalidate oldest lock */
  11108. dav_lock[lock_index].path[0] = 0;
  11109. }
  11110. }
  11111. mg_unlock_context(conn->phys_ctx);
  11112. /* return 200 "OK" */
  11113. conn->must_close = 1;
  11114. mg_response_header_start(conn, 200);
  11115. send_static_cache_header(conn);
  11116. send_additional_header(conn);
  11117. mg_response_header_add(conn,
  11118. "Content-Type",
  11119. "application/xml; charset=utf-8",
  11120. -1);
  11121. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11122. mg_response_header_send(conn);
  11123. /* Content */
  11124. mg_printf(conn,
  11125. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11126. "<d:prop xmlns:d=\"DAV:\">\n"
  11127. " <d:lockdiscovery>\n"
  11128. " <d:activelock>\n"
  11129. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11130. " <d:locktype><d:write/></d:locktype>\n"
  11131. " <d:owner>\n"
  11132. " <d:href>%s</d:href>\n"
  11133. " </d:owner>\n"
  11134. " <d:timeout>Second-%u</d:timeout>\n"
  11135. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11136. " <d:lockroot>\n"
  11137. " <d:href>%s</d:href>\n"
  11138. " </d:lockroot>\n"
  11139. " </d:activelock>\n"
  11140. " </d:lockdiscovery>\n"
  11141. " </d:prop>\n",
  11142. dav_lock[lock_index].user,
  11143. (LOCK_DURATION_S),
  11144. dav_lock[lock_index].token,
  11145. dav_lock[lock_index].path);
  11146. }
  11147. static void
  11148. dav_unlock_file(struct mg_connection *conn, const char *path)
  11149. {
  11150. /* internal function - therefore conn is assumed to be valid */
  11151. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11152. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11153. int lock_index;
  11154. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11155. return;
  11156. }
  11157. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11158. mg_lock_context(conn->phys_ctx);
  11159. /* find existing lock */
  11160. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11161. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11162. /* Success: return 204 "No Content" */
  11163. mg_unlock_context(conn->phys_ctx);
  11164. conn->must_close = 1;
  11165. mg_response_header_start(conn, 204);
  11166. mg_response_header_send(conn);
  11167. return;
  11168. }
  11169. }
  11170. mg_unlock_context(conn->phys_ctx);
  11171. /* Error: Cannot unlock a resource that is not locked */
  11172. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11173. }
  11174. static void
  11175. dav_proppatch(struct mg_connection *conn, const char *path)
  11176. {
  11177. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11178. if (!conn || !path || !conn->dom_ctx) {
  11179. return;
  11180. }
  11181. /* return 207 "Multi-Status" */
  11182. conn->must_close = 1;
  11183. mg_response_header_start(conn, 207);
  11184. send_static_cache_header(conn);
  11185. send_additional_header(conn);
  11186. mg_response_header_add(conn,
  11187. "Content-Type",
  11188. "application/xml; charset=utf-8",
  11189. -1);
  11190. mg_response_header_send(conn);
  11191. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11192. /* Content */
  11193. mg_printf(conn,
  11194. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11195. "<d:multistatus xmlns:d='DAV:'>\n"
  11196. "<d:response>\n<d:href>%s</d:href>\n",
  11197. link_buf);
  11198. mg_printf(conn,
  11199. "<d:propstat><d:status>HTTP/1.1 403 "
  11200. "Forbidden</d:status></d:propstat>\n");
  11201. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11202. }
  11203. #endif
  11204. CIVETWEB_API void
  11205. mg_lock_connection(struct mg_connection *conn)
  11206. {
  11207. if (conn) {
  11208. (void)pthread_mutex_lock(&conn->mutex);
  11209. }
  11210. }
  11211. CIVETWEB_API void
  11212. mg_unlock_connection(struct mg_connection *conn)
  11213. {
  11214. if (conn) {
  11215. (void)pthread_mutex_unlock(&conn->mutex);
  11216. }
  11217. }
  11218. CIVETWEB_API void
  11219. mg_lock_context(struct mg_context *ctx)
  11220. {
  11221. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11222. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11223. }
  11224. }
  11225. CIVETWEB_API void
  11226. mg_unlock_context(struct mg_context *ctx)
  11227. {
  11228. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11229. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11230. }
  11231. }
  11232. #if defined(USE_LUA)
  11233. #include "mod_lua.inl"
  11234. #endif /* USE_LUA */
  11235. #if defined(USE_DUKTAPE)
  11236. #include "mod_duktape.inl"
  11237. #endif /* USE_DUKTAPE */
  11238. #if defined(USE_WEBSOCKET)
  11239. #if !defined(NO_SSL_DL)
  11240. #if !defined(OPENSSL_API_3_0)
  11241. #define SHA_API static
  11242. #include "sha1.inl"
  11243. #endif
  11244. #endif
  11245. static int
  11246. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11247. {
  11248. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11249. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11250. size_t dst_len = sizeof(b64_sha);
  11251. #if !defined(OPENSSL_API_3_0)
  11252. SHA_CTX sha_ctx;
  11253. #endif
  11254. int truncated;
  11255. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11256. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11257. if (truncated) {
  11258. conn->must_close = 1;
  11259. return 0;
  11260. }
  11261. DEBUG_TRACE("%s", "Send websocket handshake");
  11262. #if defined(OPENSSL_API_3_0)
  11263. EVP_Digest((unsigned char *)buf,
  11264. (uint32_t)strlen(buf),
  11265. (unsigned char *)sha,
  11266. NULL,
  11267. EVP_get_digestbyname("sha1"),
  11268. NULL);
  11269. #else
  11270. SHA1_Init(&sha_ctx);
  11271. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11272. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11273. #endif
  11274. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11275. mg_printf(conn,
  11276. "HTTP/1.1 101 Switching Protocols\r\n"
  11277. "Upgrade: websocket\r\n"
  11278. "Connection: Upgrade\r\n"
  11279. "Sec-WebSocket-Accept: %s\r\n",
  11280. b64_sha);
  11281. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11282. // Send negotiated compression extension parameters
  11283. websocket_deflate_response(conn);
  11284. #endif
  11285. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11286. mg_printf(conn,
  11287. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11288. conn->request_info.acceptedWebSocketSubprotocol);
  11289. } else {
  11290. mg_printf(conn, "%s", "\r\n");
  11291. }
  11292. return 1;
  11293. }
  11294. #if !defined(MG_MAX_UNANSWERED_PING)
  11295. /* Configuration of the maximum number of websocket PINGs that might
  11296. * stay unanswered before the connection is considered broken.
  11297. * Note: The name of this define may still change (until it is
  11298. * defined as a compile parameter in a documentation).
  11299. */
  11300. #define MG_MAX_UNANSWERED_PING (5)
  11301. #endif
  11302. static void
  11303. read_websocket(struct mg_connection *conn,
  11304. mg_websocket_data_handler ws_data_handler,
  11305. void *callback_data)
  11306. {
  11307. /* Pointer to the beginning of the portion of the incoming websocket
  11308. * message queue.
  11309. * The original websocket upgrade request is never removed, so the queue
  11310. * begins after it. */
  11311. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11312. int n, error, exit_by_callback;
  11313. int ret;
  11314. /* body_len is the length of the entire queue in bytes
  11315. * len is the length of the current message
  11316. * data_len is the length of the current message's data payload
  11317. * header_len is the length of the current message's header */
  11318. size_t i, len, mask_len = 0, header_len, body_len;
  11319. uint64_t data_len = 0;
  11320. /* "The masking key is a 32-bit value chosen at random by the client."
  11321. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11322. */
  11323. unsigned char mask[4];
  11324. /* data points to the place where the message is stored when passed to
  11325. * the websocket_data callback. This is either mem on the stack, or a
  11326. * dynamically allocated buffer if it is too large. */
  11327. unsigned char mem[4096];
  11328. unsigned char mop; /* mask flag and opcode */
  11329. /* Variables used for connection monitoring */
  11330. double timeout = -1.0;
  11331. int enable_ping_pong = 0;
  11332. int ping_count = 0;
  11333. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11334. enable_ping_pong =
  11335. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11336. "yes");
  11337. }
  11338. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11339. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11340. }
  11341. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11342. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11343. }
  11344. if (timeout <= 0.0) {
  11345. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11346. }
  11347. /* Enter data processing loop */
  11348. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11349. conn->request_info.remote_addr,
  11350. conn->request_info.remote_port);
  11351. conn->in_websocket_handling = 1;
  11352. mg_set_thread_name("wsock");
  11353. /* Loop continuously, reading messages from the socket, invoking the
  11354. * callback, and waiting repeatedly until an error occurs. */
  11355. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11356. && (!conn->must_close)) {
  11357. header_len = 0;
  11358. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11359. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11360. len = buf[1] & 127;
  11361. mask_len = (buf[1] & 128) ? 4 : 0;
  11362. if ((len < 126) && (body_len >= mask_len)) {
  11363. /* inline 7-bit length field */
  11364. data_len = len;
  11365. header_len = 2 + mask_len;
  11366. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11367. /* 16-bit length field */
  11368. header_len = 4 + mask_len;
  11369. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11370. } else if (body_len >= (10 + mask_len)) {
  11371. /* 64-bit length field */
  11372. uint32_t l1, l2;
  11373. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11374. memcpy(&l2, &buf[6], 4);
  11375. header_len = 10 + mask_len;
  11376. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11377. if (data_len > (uint64_t)0x7FFF0000ul) {
  11378. /* no can do */
  11379. mg_cry_internal(
  11380. conn,
  11381. "%s",
  11382. "websocket out of memory; closing connection");
  11383. break;
  11384. }
  11385. }
  11386. }
  11387. if ((header_len > 0) && (body_len >= header_len)) {
  11388. /* Allocate space to hold websocket payload */
  11389. unsigned char *data = mem;
  11390. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11391. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11392. conn->phys_ctx);
  11393. if (data == NULL) {
  11394. /* Allocation failed, exit the loop and then close the
  11395. * connection */
  11396. mg_cry_internal(
  11397. conn,
  11398. "%s",
  11399. "websocket out of memory; closing connection");
  11400. break;
  11401. }
  11402. }
  11403. /* Copy the mask before we shift the queue and destroy it */
  11404. if (mask_len > 0) {
  11405. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11406. } else {
  11407. memset(mask, 0, sizeof(mask));
  11408. }
  11409. /* Read frame payload from the first message in the queue into
  11410. * data and advance the queue by moving the memory in place. */
  11411. DEBUG_ASSERT(body_len >= header_len);
  11412. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11413. mop = buf[0]; /* current mask and opcode */
  11414. /* Overflow case */
  11415. len = body_len - header_len;
  11416. memcpy(data, buf + header_len, len);
  11417. error = 0;
  11418. while ((uint64_t)len < data_len) {
  11419. n = pull_inner(NULL,
  11420. conn,
  11421. (char *)(data + len),
  11422. (int)(data_len - len),
  11423. timeout);
  11424. if (n <= -2) {
  11425. error = 1;
  11426. break;
  11427. } else if (n > 0) {
  11428. len += (size_t)n;
  11429. } else {
  11430. /* Timeout: should retry */
  11431. /* TODO: retry condition */
  11432. }
  11433. }
  11434. if (error) {
  11435. mg_cry_internal(
  11436. conn,
  11437. "%s",
  11438. "Websocket pull failed; closing connection");
  11439. if (data != mem) {
  11440. mg_free(data);
  11441. }
  11442. break;
  11443. }
  11444. conn->data_len = conn->request_len;
  11445. } else {
  11446. mop = buf[0]; /* current mask and opcode, overwritten by
  11447. * memmove() */
  11448. /* Length of the message being read at the front of the
  11449. * queue. Cast to 31 bit is OK, since we limited
  11450. * data_len before. */
  11451. len = (size_t)data_len + header_len;
  11452. /* Copy the data payload into the data pointer for the
  11453. * callback. Cast to 31 bit is OK, since we
  11454. * limited data_len */
  11455. memcpy(data, buf + header_len, (size_t)data_len);
  11456. /* Move the queue forward len bytes */
  11457. memmove(buf, buf + len, body_len - len);
  11458. /* Mark the queue as advanced */
  11459. conn->data_len -= (int)len;
  11460. }
  11461. /* Apply mask if necessary */
  11462. if (mask_len > 0) {
  11463. for (i = 0; i < (size_t)data_len; i++) {
  11464. data[i] ^= mask[i & 3];
  11465. }
  11466. }
  11467. exit_by_callback = 0;
  11468. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11469. /* filter PONG messages */
  11470. DEBUG_TRACE("PONG from %s:%u",
  11471. conn->request_info.remote_addr,
  11472. conn->request_info.remote_port);
  11473. /* No unanwered PINGs left */
  11474. ping_count = 0;
  11475. } else if (enable_ping_pong
  11476. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11477. /* reply PING messages */
  11478. DEBUG_TRACE("Reply PING from %s:%u",
  11479. conn->request_info.remote_addr,
  11480. conn->request_info.remote_port);
  11481. ret = mg_websocket_write(conn,
  11482. MG_WEBSOCKET_OPCODE_PONG,
  11483. (char *)data,
  11484. (size_t)data_len);
  11485. if (ret <= 0) {
  11486. /* Error: send failed */
  11487. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11488. break;
  11489. }
  11490. } else {
  11491. /* Exit the loop if callback signals to exit (server side),
  11492. * or "connection close" opcode received (client side). */
  11493. if (ws_data_handler != NULL) {
  11494. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11495. if (mop & 0x40) {
  11496. /* Inflate the data received if bit RSV1 is set. */
  11497. if (!conn->websocket_deflate_initialized) {
  11498. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11499. exit_by_callback = 1;
  11500. }
  11501. if (!exit_by_callback) {
  11502. size_t inflate_buf_size_old = 0;
  11503. size_t inflate_buf_size =
  11504. data_len
  11505. * 4; // Initial guess of the inflated message
  11506. // size. We double the memory when needed.
  11507. Bytef *inflated = NULL;
  11508. Bytef *new_mem = NULL;
  11509. conn->websocket_inflate_state.avail_in =
  11510. (uInt)(data_len + 4);
  11511. conn->websocket_inflate_state.next_in = data;
  11512. // Add trailing 0x00 0x00 0xff 0xff bytes
  11513. data[data_len] = '\x00';
  11514. data[data_len + 1] = '\x00';
  11515. data[data_len + 2] = '\xff';
  11516. data[data_len + 3] = '\xff';
  11517. do {
  11518. if (inflate_buf_size_old == 0) {
  11519. new_mem =
  11520. (Bytef *)mg_calloc(inflate_buf_size,
  11521. sizeof(Bytef));
  11522. } else {
  11523. inflate_buf_size *= 2;
  11524. new_mem =
  11525. (Bytef *)mg_realloc(inflated,
  11526. inflate_buf_size);
  11527. }
  11528. if (new_mem == NULL) {
  11529. mg_cry_internal(
  11530. conn,
  11531. "Out of memory: Cannot allocate "
  11532. "inflate buffer of %lu bytes",
  11533. (unsigned long)inflate_buf_size);
  11534. exit_by_callback = 1;
  11535. break;
  11536. }
  11537. inflated = new_mem;
  11538. conn->websocket_inflate_state.avail_out =
  11539. (uInt)(inflate_buf_size
  11540. - inflate_buf_size_old);
  11541. conn->websocket_inflate_state.next_out =
  11542. inflated + inflate_buf_size_old;
  11543. ret = inflate(&conn->websocket_inflate_state,
  11544. Z_SYNC_FLUSH);
  11545. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11546. || ret == Z_MEM_ERROR) {
  11547. mg_cry_internal(
  11548. conn,
  11549. "ZLIB inflate error: %i %s",
  11550. ret,
  11551. (conn->websocket_inflate_state.msg
  11552. ? conn->websocket_inflate_state.msg
  11553. : "<no error message>"));
  11554. exit_by_callback = 1;
  11555. break;
  11556. }
  11557. inflate_buf_size_old = inflate_buf_size;
  11558. } while (conn->websocket_inflate_state.avail_out
  11559. == 0);
  11560. inflate_buf_size -=
  11561. conn->websocket_inflate_state.avail_out;
  11562. if (!ws_data_handler(conn,
  11563. mop,
  11564. (char *)inflated,
  11565. inflate_buf_size,
  11566. callback_data)) {
  11567. exit_by_callback = 1;
  11568. }
  11569. mg_free(inflated);
  11570. }
  11571. } else
  11572. #endif
  11573. if (!ws_data_handler(conn,
  11574. mop,
  11575. (char *)data,
  11576. (size_t)data_len,
  11577. callback_data)) {
  11578. exit_by_callback = 1;
  11579. }
  11580. }
  11581. }
  11582. /* It a buffer has been allocated, free it again */
  11583. if (data != mem) {
  11584. mg_free(data);
  11585. }
  11586. if (exit_by_callback) {
  11587. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11588. conn->request_info.remote_addr,
  11589. conn->request_info.remote_port);
  11590. break;
  11591. }
  11592. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11593. /* Opcode == 8, connection close */
  11594. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11595. conn->request_info.remote_addr,
  11596. conn->request_info.remote_port);
  11597. break;
  11598. }
  11599. /* Not breaking the loop, process next websocket frame. */
  11600. } else {
  11601. /* Read from the socket into the next available location in the
  11602. * message queue. */
  11603. n = pull_inner(NULL,
  11604. conn,
  11605. conn->buf + conn->data_len,
  11606. conn->buf_size - conn->data_len,
  11607. timeout);
  11608. if (n <= -2) {
  11609. /* Error, no bytes read */
  11610. DEBUG_TRACE("PULL from %s:%u failed",
  11611. conn->request_info.remote_addr,
  11612. conn->request_info.remote_port);
  11613. break;
  11614. }
  11615. if (n > 0) {
  11616. conn->data_len += n;
  11617. /* Reset open PING count */
  11618. ping_count = 0;
  11619. } else {
  11620. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11621. && (!conn->must_close)) {
  11622. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11623. /* Stop sending PING */
  11624. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11625. "- closing connection",
  11626. ping_count,
  11627. conn->request_info.remote_addr,
  11628. conn->request_info.remote_port);
  11629. break;
  11630. }
  11631. if (enable_ping_pong) {
  11632. /* Send Websocket PING message */
  11633. DEBUG_TRACE("PING to %s:%u",
  11634. conn->request_info.remote_addr,
  11635. conn->request_info.remote_port);
  11636. ret = mg_websocket_write(conn,
  11637. MG_WEBSOCKET_OPCODE_PING,
  11638. NULL,
  11639. 0);
  11640. if (ret <= 0) {
  11641. /* Error: send failed */
  11642. DEBUG_TRACE("Send PING failed (%i)", ret);
  11643. break;
  11644. }
  11645. ping_count++;
  11646. }
  11647. }
  11648. /* Timeout: should retry */
  11649. /* TODO: get timeout def */
  11650. }
  11651. }
  11652. }
  11653. /* Leave data processing loop */
  11654. mg_set_thread_name("worker");
  11655. conn->in_websocket_handling = 0;
  11656. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11657. conn->request_info.remote_addr,
  11658. conn->request_info.remote_port);
  11659. }
  11660. static int
  11661. mg_websocket_write_exec(struct mg_connection *conn,
  11662. int opcode,
  11663. const char *data,
  11664. size_t dataLen,
  11665. uint32_t masking_key)
  11666. {
  11667. unsigned char header[14];
  11668. size_t headerLen;
  11669. int retval;
  11670. #if defined(GCC_DIAGNOSTIC)
  11671. /* Disable spurious conversion warning for GCC */
  11672. #pragma GCC diagnostic push
  11673. #pragma GCC diagnostic ignored "-Wconversion"
  11674. #endif
  11675. /* Note that POSIX/Winsock's send() is threadsafe
  11676. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11677. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11678. * push(), although that is only a problem if the packet is large or
  11679. * outgoing buffer is full). */
  11680. /* TODO: Check if this lock should be moved to user land.
  11681. * Currently the server sets this lock for websockets, but
  11682. * not for any other connection. It must be set for every
  11683. * conn read/written by more than one thread, no matter if
  11684. * it is a websocket or regular connection. */
  11685. (void)mg_lock_connection(conn);
  11686. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11687. size_t deflated_size = 0;
  11688. Bytef *deflated = 0;
  11689. // Deflate websocket messages over 100kb
  11690. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11691. if (use_deflate) {
  11692. if (!conn->websocket_deflate_initialized) {
  11693. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11694. return 0;
  11695. }
  11696. // Deflating the message
  11697. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11698. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11699. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11700. deflated_size = (size_t)compressBound((uLong)dataLen);
  11701. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11702. if (deflated == NULL) {
  11703. mg_cry_internal(
  11704. conn,
  11705. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11706. (unsigned long)deflated_size);
  11707. mg_unlock_connection(conn);
  11708. return -1;
  11709. }
  11710. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11711. conn->websocket_deflate_state.next_out = deflated;
  11712. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11713. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11714. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11715. } else
  11716. #endif
  11717. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11718. #if defined(GCC_DIAGNOSTIC)
  11719. #pragma GCC diagnostic pop
  11720. #endif
  11721. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11722. if (dataLen < 126) {
  11723. /* inline 7-bit length field */
  11724. header[1] = (unsigned char)dataLen;
  11725. headerLen = 2;
  11726. } else if (dataLen <= 0xFFFF) {
  11727. /* 16-bit length field */
  11728. uint16_t len = htons((uint16_t)dataLen);
  11729. header[1] = 126;
  11730. memcpy(header + 2, &len, 2);
  11731. headerLen = 4;
  11732. } else {
  11733. /* 64-bit length field */
  11734. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11735. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11736. header[1] = 127;
  11737. memcpy(header + 2, &len1, 4);
  11738. memcpy(header + 6, &len2, 4);
  11739. headerLen = 10;
  11740. }
  11741. if (masking_key) {
  11742. /* add mask */
  11743. header[1] |= 0x80;
  11744. memcpy(header + headerLen, &masking_key, 4);
  11745. headerLen += 4;
  11746. }
  11747. retval = mg_write(conn, header, headerLen);
  11748. if (retval != (int)headerLen) {
  11749. /* Did not send complete header */
  11750. retval = -1;
  11751. } else {
  11752. if (dataLen > 0) {
  11753. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11754. if (use_deflate) {
  11755. retval = mg_write(conn, deflated, dataLen);
  11756. mg_free(deflated);
  11757. } else
  11758. #endif
  11759. retval = mg_write(conn, data, dataLen);
  11760. }
  11761. /* if dataLen == 0, the header length (2) is returned */
  11762. }
  11763. /* TODO: Remove this unlock as well, when lock is removed. */
  11764. mg_unlock_connection(conn);
  11765. return retval;
  11766. }
  11767. CIVETWEB_API int
  11768. mg_websocket_write(struct mg_connection *conn,
  11769. int opcode,
  11770. const char *data,
  11771. size_t dataLen)
  11772. {
  11773. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11774. }
  11775. static void
  11776. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11777. {
  11778. size_t i = 0;
  11779. i = 0;
  11780. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11781. /* Convert in 32 bit words, if data is 4 byte aligned */
  11782. while (i < (in_len - 3)) {
  11783. *(uint32_t *)(void *)(out + i) =
  11784. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11785. i += 4;
  11786. }
  11787. }
  11788. if (i != in_len) {
  11789. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11790. while (i < in_len) {
  11791. *(uint8_t *)(void *)(out + i) =
  11792. *(uint8_t *)(void *)(in + i)
  11793. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11794. i++;
  11795. }
  11796. }
  11797. }
  11798. CIVETWEB_API int
  11799. mg_websocket_client_write(struct mg_connection *conn,
  11800. int opcode,
  11801. const char *data,
  11802. size_t dataLen)
  11803. {
  11804. int retval = -1;
  11805. char *masked_data =
  11806. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11807. uint32_t masking_key = 0;
  11808. if (masked_data == NULL) {
  11809. /* Return -1 in an error case */
  11810. mg_cry_internal(conn,
  11811. "%s",
  11812. "Cannot allocate buffer for masked websocket response: "
  11813. "Out of memory");
  11814. return -1;
  11815. }
  11816. do {
  11817. /* Get a masking key - but not 0 */
  11818. masking_key = (uint32_t)get_random();
  11819. } while (masking_key == 0);
  11820. mask_data(data, dataLen, masking_key, masked_data);
  11821. retval = mg_websocket_write_exec(
  11822. conn, opcode, masked_data, dataLen, masking_key);
  11823. mg_free(masked_data);
  11824. return retval;
  11825. }
  11826. static void
  11827. handle_websocket_request(struct mg_connection *conn,
  11828. const char *path,
  11829. int is_callback_resource,
  11830. struct mg_websocket_subprotocols *subprotocols,
  11831. mg_websocket_connect_handler ws_connect_handler,
  11832. mg_websocket_ready_handler ws_ready_handler,
  11833. mg_websocket_data_handler ws_data_handler,
  11834. mg_websocket_close_handler ws_close_handler,
  11835. void *cbData)
  11836. {
  11837. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11838. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11839. ptrdiff_t lua_websock = 0;
  11840. #if !defined(USE_LUA)
  11841. (void)path;
  11842. #endif
  11843. /* Step 1: Check websocket protocol version. */
  11844. /* Step 1.1: Check Sec-WebSocket-Key. */
  11845. if (!websock_key) {
  11846. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11847. * requires a Sec-WebSocket-Key header.
  11848. */
  11849. /* It could be the hixie draft version
  11850. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11851. */
  11852. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11853. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11854. char key3[8];
  11855. if ((key1 != NULL) && (key2 != NULL)) {
  11856. /* This version uses 8 byte body data in a GET request */
  11857. conn->content_len = 8;
  11858. if (8 == mg_read(conn, key3, 8)) {
  11859. /* This is the hixie version */
  11860. mg_send_http_error(conn,
  11861. 426,
  11862. "%s",
  11863. "Protocol upgrade to RFC 6455 required");
  11864. return;
  11865. }
  11866. }
  11867. /* This is an unknown version */
  11868. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11869. return;
  11870. }
  11871. /* Step 1.2: Check websocket protocol version. */
  11872. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11873. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11874. /* Reject wrong versions */
  11875. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11876. return;
  11877. }
  11878. /* Step 1.3: Could check for "Host", but we do not really nead this
  11879. * value for anything, so just ignore it. */
  11880. /* Step 2: If a callback is responsible, call it. */
  11881. if (is_callback_resource) {
  11882. /* Step 2.1 check and select subprotocol */
  11883. const char *protocols[64]; // max 64 headers
  11884. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11885. "Sec-WebSocket-Protocol",
  11886. protocols,
  11887. 64);
  11888. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11889. int headerNo, idx;
  11890. size_t len;
  11891. const char *sep, *curSubProtocol,
  11892. *acceptedWebSocketSubprotocol = NULL;
  11893. /* look for matching subprotocol */
  11894. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11895. /* There might be multiple headers ... */
  11896. const char *protocol = protocols[headerNo];
  11897. curSubProtocol = protocol;
  11898. /* ... and in every header there might be a , separated list */
  11899. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11900. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11901. curSubProtocol++;
  11902. sep = strchr(curSubProtocol, ',');
  11903. if (sep) {
  11904. len = (size_t)(sep - curSubProtocol);
  11905. } else {
  11906. len = strlen(curSubProtocol);
  11907. }
  11908. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11909. // COMPARE: curSubProtocol ==
  11910. // subprotocols->subprotocols[idx]
  11911. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11912. && (strncmp(curSubProtocol,
  11913. subprotocols->subprotocols[idx],
  11914. len)
  11915. == 0)) {
  11916. acceptedWebSocketSubprotocol =
  11917. subprotocols->subprotocols[idx];
  11918. break;
  11919. }
  11920. }
  11921. curSubProtocol += len;
  11922. }
  11923. }
  11924. conn->request_info.acceptedWebSocketSubprotocol =
  11925. acceptedWebSocketSubprotocol;
  11926. }
  11927. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11928. websocket_deflate_negotiate(conn);
  11929. #endif
  11930. if ((ws_connect_handler != NULL)
  11931. && (ws_connect_handler(conn, cbData) != 0)) {
  11932. /* C callback has returned non-zero, do not proceed with
  11933. * handshake.
  11934. */
  11935. /* Note that C callbacks are no longer called when Lua is
  11936. * responsible, so C can no longer filter callbacks for Lua. */
  11937. return;
  11938. }
  11939. }
  11940. #if defined(USE_LUA)
  11941. /* Step 3: No callback. Check if Lua is responsible. */
  11942. else {
  11943. /* Step 3.1: Check if Lua is responsible. */
  11944. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11945. lua_websock = match_prefix_strlen(
  11946. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11947. }
  11948. if (lua_websock > 0) {
  11949. /* Step 3.2: Lua is responsible: call it. */
  11950. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11951. if (!conn->lua_websocket_state) {
  11952. /* Lua rejected the new client */
  11953. return;
  11954. }
  11955. }
  11956. }
  11957. #endif
  11958. /* Step 4: Check if there is a responsible websocket handler. */
  11959. if (!is_callback_resource && !lua_websock) {
  11960. /* There is no callback, and Lua is not responsible either. */
  11961. /* Reply with a 404 Not Found. We are still at a standard
  11962. * HTTP request here, before the websocket handshake, so
  11963. * we can still send standard HTTP error replies. */
  11964. mg_send_http_error(conn, 404, "%s", "Not found");
  11965. return;
  11966. }
  11967. /* Step 5: The websocket connection has been accepted */
  11968. if (!send_websocket_handshake(conn, websock_key)) {
  11969. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11970. return;
  11971. }
  11972. /* Step 6: Call the ready handler */
  11973. if (is_callback_resource) {
  11974. if (ws_ready_handler != NULL) {
  11975. ws_ready_handler(conn, cbData);
  11976. }
  11977. #if defined(USE_LUA)
  11978. } else if (lua_websock) {
  11979. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11980. /* the ready handler returned false */
  11981. return;
  11982. }
  11983. #endif
  11984. }
  11985. /* Step 7: Enter the read loop */
  11986. if (is_callback_resource) {
  11987. read_websocket(conn, ws_data_handler, cbData);
  11988. #if defined(USE_LUA)
  11989. } else if (lua_websock) {
  11990. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11991. #endif
  11992. }
  11993. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11994. /* Step 8: Close the deflate & inflate buffers */
  11995. if (conn->websocket_deflate_initialized) {
  11996. deflateEnd(&conn->websocket_deflate_state);
  11997. inflateEnd(&conn->websocket_inflate_state);
  11998. }
  11999. #endif
  12000. /* Step 9: Call the close handler */
  12001. if (ws_close_handler) {
  12002. ws_close_handler(conn, cbData);
  12003. }
  12004. }
  12005. #endif /* !USE_WEBSOCKET */
  12006. /* Is upgrade request:
  12007. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12008. * 1 = upgrade to websocket
  12009. * 2 = upgrade to HTTP/2
  12010. * -1 = upgrade to unknown protocol
  12011. */
  12012. static int
  12013. should_switch_to_protocol(const struct mg_connection *conn)
  12014. {
  12015. const char *connection_headers[8];
  12016. const char *upgrade_to;
  12017. int connection_header_count, i, should_upgrade;
  12018. /* A websocket protocoll has the following HTTP headers:
  12019. *
  12020. * Connection: Upgrade
  12021. * Upgrade: Websocket
  12022. *
  12023. * It seems some clients use multiple headers:
  12024. * see https://github.com/civetweb/civetweb/issues/1083
  12025. */
  12026. connection_header_count = get_req_headers(&conn->request_info,
  12027. "Connection",
  12028. connection_headers,
  12029. 8);
  12030. should_upgrade = 0;
  12031. for (i = 0; i < connection_header_count; i++) {
  12032. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12033. should_upgrade = 1;
  12034. }
  12035. }
  12036. if (!should_upgrade) {
  12037. return PROTOCOL_TYPE_HTTP1;
  12038. }
  12039. upgrade_to = mg_get_header(conn, "Upgrade");
  12040. if (upgrade_to == NULL) {
  12041. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12042. return -1;
  12043. }
  12044. /* Upgrade to ... */
  12045. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12046. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12047. * "Sec-WebSocket-Version" are also required.
  12048. * Don't check them here, since even an unsupported websocket protocol
  12049. * request still IS a websocket request (in contrast to a standard HTTP
  12050. * request). It will fail later in handle_websocket_request.
  12051. */
  12052. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12053. }
  12054. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12055. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12056. }
  12057. /* Upgrade to another protocol */
  12058. return -1;
  12059. }
  12060. static int
  12061. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12062. {
  12063. int n;
  12064. unsigned int a, b, c, d, slash;
  12065. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12066. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12067. // integer value, but function will not report conversion
  12068. // errors; consider using 'strtol' instead
  12069. slash = 32;
  12070. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12071. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12072. // an integer value, but function will not report conversion
  12073. // errors; consider using 'strtol' instead
  12074. n = 0;
  12075. }
  12076. }
  12077. if ((n > 0) && ((size_t)n == vec->len)) {
  12078. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12079. /* IPv4 format */
  12080. if (sa->sa.sa_family == AF_INET) {
  12081. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12082. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12083. | ((uint32_t)c << 8) | (uint32_t)d;
  12084. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12085. return (ip & mask) == net;
  12086. }
  12087. return 0;
  12088. }
  12089. }
  12090. #if defined(USE_IPV6)
  12091. else {
  12092. char ad[50];
  12093. const char *p;
  12094. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12095. slash = 128;
  12096. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12097. n = 0;
  12098. }
  12099. }
  12100. if ((n <= 0) && no_strict) {
  12101. /* no square brackets? */
  12102. p = strchr(vec->ptr, '/');
  12103. if (p && (p < (vec->ptr + vec->len))) {
  12104. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12105. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12106. n += (int)(p - vec->ptr);
  12107. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12108. } else {
  12109. n = 0;
  12110. }
  12111. } else if (vec->len < sizeof(ad)) {
  12112. n = (int)vec->len;
  12113. slash = 128;
  12114. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12115. }
  12116. }
  12117. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12118. p = ad;
  12119. c = 0;
  12120. /* zone indexes are unsupported, at least two colons are needed */
  12121. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12122. if (*(p++) == ':') {
  12123. c++;
  12124. }
  12125. }
  12126. if ((*p == '\0') && (c >= 2)) {
  12127. struct sockaddr_in6 sin6;
  12128. unsigned int i;
  12129. /* for strict validation, an actual IPv6 argument is needed */
  12130. if (sa->sa.sa_family != AF_INET6) {
  12131. return 0;
  12132. }
  12133. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12134. /* IPv6 format */
  12135. for (i = 0; i < 16; i++) {
  12136. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12137. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12138. uint8_t mask = 0;
  12139. if (8 * i + 8 < slash) {
  12140. mask = 0xFFu;
  12141. } else if (8 * i < slash) {
  12142. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12143. }
  12144. if ((ip & mask) != net) {
  12145. return 0;
  12146. }
  12147. }
  12148. return 1;
  12149. }
  12150. }
  12151. }
  12152. }
  12153. #else
  12154. (void)no_strict;
  12155. #endif
  12156. /* malformed */
  12157. return -1;
  12158. }
  12159. static int
  12160. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12161. {
  12162. int throttle = 0;
  12163. struct vec vec, val;
  12164. char mult;
  12165. double v;
  12166. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12167. mult = ',';
  12168. if ((val.ptr == NULL)
  12169. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12170. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12171. // to an integer value, but function will not report
  12172. // conversion errors; consider using 'strtol' instead
  12173. || (v < 0)
  12174. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12175. && (mult != ','))) {
  12176. continue;
  12177. }
  12178. v *= (lowercase(&mult) == 'k')
  12179. ? 1024
  12180. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12181. if (vec.len == 1 && vec.ptr[0] == '*') {
  12182. throttle = (int)v;
  12183. } else {
  12184. int matched = parse_match_net(&vec, rsa, 0);
  12185. if (matched >= 0) {
  12186. /* a valid IP subnet */
  12187. if (matched) {
  12188. throttle = (int)v;
  12189. }
  12190. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12191. throttle = (int)v;
  12192. }
  12193. }
  12194. }
  12195. return throttle;
  12196. }
  12197. /* The mg_upload function is superseeded by mg_handle_form_request. */
  12198. #include "handle_form.inl"
  12199. static int
  12200. get_first_ssl_listener_index(const struct mg_context *ctx)
  12201. {
  12202. unsigned int i;
  12203. int idx = -1;
  12204. if (ctx) {
  12205. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12206. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12207. }
  12208. }
  12209. return idx;
  12210. }
  12211. /* Return host (without port) */
  12212. static void
  12213. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12214. {
  12215. const char *host_header =
  12216. get_header(ri->http_headers, ri->num_headers, "Host");
  12217. host->ptr = NULL;
  12218. host->len = 0;
  12219. if (host_header != NULL) {
  12220. const char *pos;
  12221. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12222. * is found. */
  12223. if (*host_header == '[') {
  12224. pos = strchr(host_header, ']');
  12225. if (!pos) {
  12226. /* Malformed hostname starts with '[', but no ']' found */
  12227. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12228. return;
  12229. }
  12230. /* terminate after ']' */
  12231. host->ptr = host_header;
  12232. host->len = (size_t)(pos + 1 - host_header);
  12233. } else {
  12234. /* Otherwise, a ':' separates hostname and port number */
  12235. pos = strchr(host_header, ':');
  12236. if (pos != NULL) {
  12237. host->len = (size_t)(pos - host_header);
  12238. } else {
  12239. host->len = strlen(host_header);
  12240. }
  12241. host->ptr = host_header;
  12242. }
  12243. }
  12244. }
  12245. static int
  12246. switch_domain_context(struct mg_connection *conn)
  12247. {
  12248. struct vec host;
  12249. get_host_from_request_info(&host, &conn->request_info);
  12250. if (host.ptr) {
  12251. if (conn->ssl) {
  12252. /* This is a HTTPS connection, maybe we have a hostname
  12253. * from SNI (set in ssl_servername_callback). */
  12254. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12255. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12256. /* We are not using the default domain */
  12257. if ((strlen(sslhost) != host.len)
  12258. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12259. /* Mismatch between SNI domain and HTTP domain */
  12260. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12261. sslhost,
  12262. (int)host.len,
  12263. host.ptr);
  12264. return 0;
  12265. }
  12266. }
  12267. } else {
  12268. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12269. while (dom) {
  12270. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12271. size_t domNameLen = strlen(domName);
  12272. if ((domNameLen == host.len)
  12273. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12274. /* Found matching domain */
  12275. DEBUG_TRACE("HTTP domain %s found",
  12276. dom->config[AUTHENTICATION_DOMAIN]);
  12277. /* TODO: Check if this is a HTTP or HTTPS domain */
  12278. conn->dom_ctx = dom;
  12279. break;
  12280. }
  12281. mg_lock_context(conn->phys_ctx);
  12282. dom = dom->next;
  12283. mg_unlock_context(conn->phys_ctx);
  12284. }
  12285. }
  12286. DEBUG_TRACE("HTTP%s Host: %.*s",
  12287. conn->ssl ? "S" : "",
  12288. (int)host.len,
  12289. host.ptr);
  12290. } else {
  12291. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12292. return 1;
  12293. }
  12294. return 1;
  12295. }
  12296. static void
  12297. redirect_to_https_port(struct mg_connection *conn, int port)
  12298. {
  12299. char target_url[MG_BUF_LEN];
  12300. int truncated = 0;
  12301. const char *expect_proto =
  12302. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12303. /* Use "308 Permanent Redirect" */
  12304. int redirect_code = 308;
  12305. /* In any case, close the current connection */
  12306. conn->must_close = 1;
  12307. /* Send host, port, uri and (if it exists) ?query_string */
  12308. if (mg_construct_local_link(
  12309. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12310. < 0) {
  12311. truncated = 1;
  12312. } else if (conn->request_info.query_string != NULL) {
  12313. size_t slen1 = strlen(target_url);
  12314. size_t slen2 = strlen(conn->request_info.query_string);
  12315. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12316. target_url[slen1] = '?';
  12317. memcpy(target_url + slen1 + 1,
  12318. conn->request_info.query_string,
  12319. slen2);
  12320. target_url[slen1 + slen2 + 1] = 0;
  12321. } else {
  12322. truncated = 1;
  12323. }
  12324. }
  12325. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12326. * is used as buffer size) */
  12327. if (truncated) {
  12328. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12329. return;
  12330. }
  12331. /* Use redirect helper function */
  12332. mg_send_http_redirect(conn, target_url, redirect_code);
  12333. }
  12334. static void
  12335. mg_set_handler_type(struct mg_context *phys_ctx,
  12336. struct mg_domain_context *dom_ctx,
  12337. const char *uri,
  12338. int handler_type,
  12339. int is_delete_request,
  12340. mg_request_handler handler,
  12341. struct mg_websocket_subprotocols *subprotocols,
  12342. mg_websocket_connect_handler connect_handler,
  12343. mg_websocket_ready_handler ready_handler,
  12344. mg_websocket_data_handler data_handler,
  12345. mg_websocket_close_handler close_handler,
  12346. mg_authorization_handler auth_handler,
  12347. void *cbdata)
  12348. {
  12349. struct mg_handler_info *tmp_rh, **lastref;
  12350. size_t urilen = strlen(uri);
  12351. if (handler_type == WEBSOCKET_HANDLER) {
  12352. DEBUG_ASSERT(handler == NULL);
  12353. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12354. || ready_handler != NULL || data_handler != NULL
  12355. || close_handler != NULL);
  12356. DEBUG_ASSERT(auth_handler == NULL);
  12357. if (handler != NULL) {
  12358. return;
  12359. }
  12360. if (!is_delete_request && (connect_handler == NULL)
  12361. && (ready_handler == NULL) && (data_handler == NULL)
  12362. && (close_handler == NULL)) {
  12363. return;
  12364. }
  12365. if (auth_handler != NULL) {
  12366. return;
  12367. }
  12368. } else if (handler_type == REQUEST_HANDLER) {
  12369. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12370. && data_handler == NULL && close_handler == NULL);
  12371. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12372. DEBUG_ASSERT(auth_handler == NULL);
  12373. if ((connect_handler != NULL) || (ready_handler != NULL)
  12374. || (data_handler != NULL) || (close_handler != NULL)) {
  12375. return;
  12376. }
  12377. if (!is_delete_request && (handler == NULL)) {
  12378. return;
  12379. }
  12380. if (auth_handler != NULL) {
  12381. return;
  12382. }
  12383. } else if (handler_type == AUTH_HANDLER) {
  12384. DEBUG_ASSERT(handler == NULL);
  12385. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12386. && data_handler == NULL && close_handler == NULL);
  12387. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12388. if (handler != NULL) {
  12389. return;
  12390. }
  12391. if ((connect_handler != NULL) || (ready_handler != NULL)
  12392. || (data_handler != NULL) || (close_handler != NULL)) {
  12393. return;
  12394. }
  12395. if (!is_delete_request && (auth_handler == NULL)) {
  12396. return;
  12397. }
  12398. } else {
  12399. /* Unknown handler type. */
  12400. return;
  12401. }
  12402. if (!phys_ctx || !dom_ctx) {
  12403. /* no context available */
  12404. return;
  12405. }
  12406. mg_lock_context(phys_ctx);
  12407. /* first try to find an existing handler */
  12408. do {
  12409. lastref = &(dom_ctx->handlers);
  12410. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12411. tmp_rh = tmp_rh->next) {
  12412. if (tmp_rh->handler_type == handler_type
  12413. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12414. if (!is_delete_request) {
  12415. /* update existing handler */
  12416. if (handler_type == REQUEST_HANDLER) {
  12417. /* Wait for end of use before updating */
  12418. if (tmp_rh->refcount) {
  12419. mg_unlock_context(phys_ctx);
  12420. mg_sleep(1);
  12421. mg_lock_context(phys_ctx);
  12422. /* tmp_rh might have been freed, search again. */
  12423. break;
  12424. }
  12425. /* Ok, the handler is no more use -> Update it */
  12426. tmp_rh->handler = handler;
  12427. } else if (handler_type == WEBSOCKET_HANDLER) {
  12428. tmp_rh->subprotocols = subprotocols;
  12429. tmp_rh->connect_handler = connect_handler;
  12430. tmp_rh->ready_handler = ready_handler;
  12431. tmp_rh->data_handler = data_handler;
  12432. tmp_rh->close_handler = close_handler;
  12433. } else { /* AUTH_HANDLER */
  12434. tmp_rh->auth_handler = auth_handler;
  12435. }
  12436. tmp_rh->cbdata = cbdata;
  12437. } else {
  12438. /* remove existing handler */
  12439. if (handler_type == REQUEST_HANDLER) {
  12440. /* Wait for end of use before removing */
  12441. if (tmp_rh->refcount) {
  12442. tmp_rh->removing = 1;
  12443. mg_unlock_context(phys_ctx);
  12444. mg_sleep(1);
  12445. mg_lock_context(phys_ctx);
  12446. /* tmp_rh might have been freed, search again. */
  12447. break;
  12448. }
  12449. /* Ok, the handler is no more used */
  12450. }
  12451. *lastref = tmp_rh->next;
  12452. mg_free(tmp_rh->uri);
  12453. mg_free(tmp_rh);
  12454. }
  12455. mg_unlock_context(phys_ctx);
  12456. return;
  12457. }
  12458. lastref = &(tmp_rh->next);
  12459. }
  12460. } while (tmp_rh != NULL);
  12461. if (is_delete_request) {
  12462. /* no handler to set, this was a remove request to a non-existing
  12463. * handler */
  12464. mg_unlock_context(phys_ctx);
  12465. return;
  12466. }
  12467. tmp_rh =
  12468. (struct mg_handler_info *)mg_calloc_ctx(1,
  12469. sizeof(struct mg_handler_info),
  12470. phys_ctx);
  12471. if (tmp_rh == NULL) {
  12472. mg_unlock_context(phys_ctx);
  12473. mg_cry_ctx_internal(phys_ctx,
  12474. "%s",
  12475. "Cannot create new request handler struct, OOM");
  12476. return;
  12477. }
  12478. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12479. if (!tmp_rh->uri) {
  12480. mg_unlock_context(phys_ctx);
  12481. mg_free(tmp_rh);
  12482. mg_cry_ctx_internal(phys_ctx,
  12483. "%s",
  12484. "Cannot create new request handler struct, OOM");
  12485. return;
  12486. }
  12487. tmp_rh->uri_len = urilen;
  12488. if (handler_type == REQUEST_HANDLER) {
  12489. tmp_rh->refcount = 0;
  12490. tmp_rh->removing = 0;
  12491. tmp_rh->handler = handler;
  12492. } else if (handler_type == WEBSOCKET_HANDLER) {
  12493. tmp_rh->subprotocols = subprotocols;
  12494. tmp_rh->connect_handler = connect_handler;
  12495. tmp_rh->ready_handler = ready_handler;
  12496. tmp_rh->data_handler = data_handler;
  12497. tmp_rh->close_handler = close_handler;
  12498. } else { /* AUTH_HANDLER */
  12499. tmp_rh->auth_handler = auth_handler;
  12500. }
  12501. tmp_rh->cbdata = cbdata;
  12502. tmp_rh->handler_type = handler_type;
  12503. tmp_rh->next = NULL;
  12504. *lastref = tmp_rh;
  12505. mg_unlock_context(phys_ctx);
  12506. }
  12507. CIVETWEB_API void
  12508. mg_set_request_handler(struct mg_context *ctx,
  12509. const char *uri,
  12510. mg_request_handler handler,
  12511. void *cbdata)
  12512. {
  12513. mg_set_handler_type(ctx,
  12514. &(ctx->dd),
  12515. uri,
  12516. REQUEST_HANDLER,
  12517. handler == NULL,
  12518. handler,
  12519. NULL,
  12520. NULL,
  12521. NULL,
  12522. NULL,
  12523. NULL,
  12524. NULL,
  12525. cbdata);
  12526. }
  12527. CIVETWEB_API void
  12528. mg_set_websocket_handler(struct mg_context *ctx,
  12529. const char *uri,
  12530. mg_websocket_connect_handler connect_handler,
  12531. mg_websocket_ready_handler ready_handler,
  12532. mg_websocket_data_handler data_handler,
  12533. mg_websocket_close_handler close_handler,
  12534. void *cbdata)
  12535. {
  12536. mg_set_websocket_handler_with_subprotocols(ctx,
  12537. uri,
  12538. NULL,
  12539. connect_handler,
  12540. ready_handler,
  12541. data_handler,
  12542. close_handler,
  12543. cbdata);
  12544. }
  12545. CIVETWEB_API void
  12546. mg_set_websocket_handler_with_subprotocols(
  12547. struct mg_context *ctx,
  12548. const char *uri,
  12549. struct mg_websocket_subprotocols *subprotocols,
  12550. mg_websocket_connect_handler connect_handler,
  12551. mg_websocket_ready_handler ready_handler,
  12552. mg_websocket_data_handler data_handler,
  12553. mg_websocket_close_handler close_handler,
  12554. void *cbdata)
  12555. {
  12556. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12557. && (data_handler == NULL)
  12558. && (close_handler == NULL);
  12559. mg_set_handler_type(ctx,
  12560. &(ctx->dd),
  12561. uri,
  12562. WEBSOCKET_HANDLER,
  12563. is_delete_request,
  12564. NULL,
  12565. subprotocols,
  12566. connect_handler,
  12567. ready_handler,
  12568. data_handler,
  12569. close_handler,
  12570. NULL,
  12571. cbdata);
  12572. }
  12573. CIVETWEB_API void
  12574. mg_set_auth_handler(struct mg_context *ctx,
  12575. const char *uri,
  12576. mg_authorization_handler handler,
  12577. void *cbdata)
  12578. {
  12579. mg_set_handler_type(ctx,
  12580. &(ctx->dd),
  12581. uri,
  12582. AUTH_HANDLER,
  12583. handler == NULL,
  12584. NULL,
  12585. NULL,
  12586. NULL,
  12587. NULL,
  12588. NULL,
  12589. NULL,
  12590. handler,
  12591. cbdata);
  12592. }
  12593. static int
  12594. get_request_handler(struct mg_connection *conn,
  12595. int handler_type,
  12596. mg_request_handler *handler,
  12597. struct mg_websocket_subprotocols **subprotocols,
  12598. mg_websocket_connect_handler *connect_handler,
  12599. mg_websocket_ready_handler *ready_handler,
  12600. mg_websocket_data_handler *data_handler,
  12601. mg_websocket_close_handler *close_handler,
  12602. mg_authorization_handler *auth_handler,
  12603. void **cbdata,
  12604. struct mg_handler_info **handler_info)
  12605. {
  12606. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12607. if (request_info) {
  12608. const char *uri = request_info->local_uri;
  12609. size_t urilen = strlen(uri);
  12610. struct mg_handler_info *tmp_rh;
  12611. int step, matched;
  12612. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12613. return 0;
  12614. }
  12615. mg_lock_context(conn->phys_ctx);
  12616. for (step = 0; step < 3; step++) {
  12617. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12618. tmp_rh = tmp_rh->next) {
  12619. if (tmp_rh->handler_type != handler_type) {
  12620. continue;
  12621. }
  12622. if (step == 0) {
  12623. /* first try for an exact match */
  12624. matched = (tmp_rh->uri_len == urilen)
  12625. && (strcmp(tmp_rh->uri, uri) == 0);
  12626. } else if (step == 1) {
  12627. /* next try for a partial match, we will accept
  12628. uri/something */
  12629. matched =
  12630. (tmp_rh->uri_len < urilen)
  12631. && (uri[tmp_rh->uri_len] == '/')
  12632. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12633. } else {
  12634. /* finally try for pattern match */
  12635. matched =
  12636. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12637. }
  12638. if (matched) {
  12639. if (handler_type == WEBSOCKET_HANDLER) {
  12640. *subprotocols = tmp_rh->subprotocols;
  12641. *connect_handler = tmp_rh->connect_handler;
  12642. *ready_handler = tmp_rh->ready_handler;
  12643. *data_handler = tmp_rh->data_handler;
  12644. *close_handler = tmp_rh->close_handler;
  12645. } else if (handler_type == REQUEST_HANDLER) {
  12646. if (tmp_rh->removing) {
  12647. /* Treat as none found */
  12648. step = 2;
  12649. break;
  12650. }
  12651. *handler = tmp_rh->handler;
  12652. /* Acquire handler and give it back */
  12653. tmp_rh->refcount++;
  12654. *handler_info = tmp_rh;
  12655. } else { /* AUTH_HANDLER */
  12656. *auth_handler = tmp_rh->auth_handler;
  12657. }
  12658. *cbdata = tmp_rh->cbdata;
  12659. mg_unlock_context(conn->phys_ctx);
  12660. return 1;
  12661. }
  12662. }
  12663. }
  12664. mg_unlock_context(conn->phys_ctx);
  12665. }
  12666. return 0; /* none found */
  12667. }
  12668. /* Check if the script file is in a path, allowed for script files.
  12669. * This can be used if uploading files is possible not only for the server
  12670. * admin, and the upload mechanism does not check the file extension.
  12671. */
  12672. static int
  12673. is_in_script_path(const struct mg_connection *conn, const char *path)
  12674. {
  12675. /* TODO (Feature): Add config value for allowed script path.
  12676. * Default: All allowed. */
  12677. (void)conn;
  12678. (void)path;
  12679. return 1;
  12680. }
  12681. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12682. static int
  12683. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12684. int bits,
  12685. char *data,
  12686. size_t len,
  12687. void *cbdata)
  12688. {
  12689. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12690. if (pcallbacks->websocket_data) {
  12691. return pcallbacks->websocket_data(conn, bits, data, len);
  12692. }
  12693. /* No handler set - assume "OK" */
  12694. return 1;
  12695. }
  12696. static void
  12697. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12698. void *cbdata)
  12699. {
  12700. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12701. if (pcallbacks->connection_close) {
  12702. pcallbacks->connection_close(conn);
  12703. }
  12704. }
  12705. #endif
  12706. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12707. */
  12708. static void
  12709. release_handler_ref(struct mg_connection *conn,
  12710. struct mg_handler_info *handler_info)
  12711. {
  12712. if (handler_info != NULL) {
  12713. /* Use context lock for ref counter */
  12714. mg_lock_context(conn->phys_ctx);
  12715. handler_info->refcount--;
  12716. mg_unlock_context(conn->phys_ctx);
  12717. }
  12718. }
  12719. /* This is the heart of the Civetweb's logic.
  12720. * This function is called when the request is read, parsed and validated,
  12721. * and Civetweb must decide what action to take: serve a file, or
  12722. * a directory, or call embedded function, etcetera. */
  12723. static void
  12724. handle_request(struct mg_connection *conn)
  12725. {
  12726. struct mg_request_info *ri = &conn->request_info;
  12727. char path[UTF8_PATH_MAX];
  12728. int uri_len, ssl_index;
  12729. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12730. is_put_or_delete_request = 0, is_callback_resource = 0,
  12731. is_template_text_file = 0, is_webdav_request = 0;
  12732. int i;
  12733. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12734. mg_request_handler callback_handler = NULL;
  12735. struct mg_handler_info *handler_info = NULL;
  12736. struct mg_websocket_subprotocols *subprotocols;
  12737. mg_websocket_connect_handler ws_connect_handler = NULL;
  12738. mg_websocket_ready_handler ws_ready_handler = NULL;
  12739. mg_websocket_data_handler ws_data_handler = NULL;
  12740. mg_websocket_close_handler ws_close_handler = NULL;
  12741. void *callback_data = NULL;
  12742. mg_authorization_handler auth_handler = NULL;
  12743. void *auth_callback_data = NULL;
  12744. int handler_type;
  12745. time_t curtime = time(NULL);
  12746. char date[64];
  12747. char *tmp;
  12748. path[0] = 0;
  12749. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12750. conn->request_state = 0;
  12751. /* 1. get the request url */
  12752. /* 1.1. split into url and query string */
  12753. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12754. != NULL) {
  12755. *((char *)conn->request_info.query_string++) = '\0';
  12756. }
  12757. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12758. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12759. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12760. if (ssl_index >= 0) {
  12761. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12762. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12763. redirect_to_https_port(conn, port);
  12764. } else {
  12765. /* A http to https forward port has been specified,
  12766. * but no https port to forward to. */
  12767. mg_send_http_error(conn,
  12768. 503,
  12769. "%s",
  12770. "Error: SSL forward not configured properly");
  12771. mg_cry_internal(conn,
  12772. "%s",
  12773. "Can not redirect to SSL, no SSL port available");
  12774. }
  12775. return;
  12776. }
  12777. uri_len = (int)strlen(ri->local_uri);
  12778. /* 1.3. decode url (if config says so) */
  12779. if (should_decode_url(conn)) {
  12780. url_decode_in_place((char *)ri->local_uri);
  12781. }
  12782. /* URL decode the query-string only if explicity set in the configuration */
  12783. if (conn->request_info.query_string) {
  12784. if (should_decode_query_string(conn)) {
  12785. url_decode_in_place((char *)conn->request_info.query_string);
  12786. }
  12787. }
  12788. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12789. * possible. The fact that we cleaned the URI is stored in that the
  12790. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12791. * ri->local_uri_raw still points to memory allocated in
  12792. * worker_thread_run(). ri->local_uri is private to the request so we
  12793. * don't have to use preallocated memory here. */
  12794. tmp = mg_strdup(ri->local_uri_raw);
  12795. if (!tmp) {
  12796. /* Out of memory. We cannot do anything reasonable here. */
  12797. return;
  12798. }
  12799. remove_dot_segments(tmp);
  12800. ri->local_uri = tmp;
  12801. /* step 1. completed, the url is known now */
  12802. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12803. /* 2. if this ip has limited speed, set it for this connection */
  12804. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12805. &conn->client.rsa,
  12806. ri->local_uri);
  12807. /* 3. call a "handle everything" callback, if registered */
  12808. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12809. /* Note that since V1.7 the "begin_request" function is called
  12810. * before an authorization check. If an authorization check is
  12811. * required, use a request_handler instead. */
  12812. i = conn->phys_ctx->callbacks.begin_request(conn);
  12813. if (i > 0) {
  12814. /* callback already processed the request. Store the
  12815. return value as a status code for the access log. */
  12816. conn->status_code = i;
  12817. if (!conn->must_close) {
  12818. discard_unread_request_data(conn);
  12819. }
  12820. DEBUG_TRACE("%s", "begin_request handled request");
  12821. return;
  12822. } else if (i == 0) {
  12823. /* civetweb should process the request */
  12824. } else {
  12825. /* unspecified - may change with the next version */
  12826. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12827. return;
  12828. }
  12829. }
  12830. /* request not yet handled by a handler or redirect, so the request
  12831. * is processed here */
  12832. /* 4. Check for CORS preflight requests and handle them (if configured).
  12833. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12834. */
  12835. if (!strcmp(ri->request_method, "OPTIONS")) {
  12836. /* Send a response to CORS preflights only if
  12837. * access_control_allow_methods is not NULL and not an empty string.
  12838. * In this case, scripts can still handle CORS. */
  12839. const char *cors_meth_cfg =
  12840. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12841. const char *cors_orig_cfg =
  12842. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12843. const char *cors_origin =
  12844. get_header(ri->http_headers, ri->num_headers, "Origin");
  12845. const char *cors_acrm = get_header(ri->http_headers,
  12846. ri->num_headers,
  12847. "Access-Control-Request-Method");
  12848. /* Todo: check if cors_origin is in cors_orig_cfg.
  12849. * Or, let the client check this. */
  12850. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12851. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12852. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12853. /* This is a valid CORS preflight, and the server is configured
  12854. * to handle it automatically. */
  12855. const char *cors_acrh =
  12856. get_header(ri->http_headers,
  12857. ri->num_headers,
  12858. "Access-Control-Request-Headers");
  12859. gmt_time_string(date, sizeof(date), &curtime);
  12860. mg_printf(conn,
  12861. "HTTP/1.1 200 OK\r\n"
  12862. "Date: %s\r\n"
  12863. "Access-Control-Allow-Origin: %s\r\n"
  12864. "Access-Control-Allow-Methods: %s\r\n"
  12865. "Content-Length: 0\r\n"
  12866. "Connection: %s\r\n",
  12867. date,
  12868. cors_orig_cfg,
  12869. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12870. suggest_connection_header(conn));
  12871. if (cors_acrh != NULL) {
  12872. /* CORS request is asking for additional headers */
  12873. const char *cors_hdr_cfg =
  12874. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12875. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12876. /* Allow only if access_control_allow_headers is
  12877. * not NULL and not an empty string. If this
  12878. * configuration is set to *, allow everything.
  12879. * Otherwise this configuration must be a list
  12880. * of allowed HTTP header names. */
  12881. mg_printf(conn,
  12882. "Access-Control-Allow-Headers: %s\r\n",
  12883. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12884. : cors_hdr_cfg));
  12885. }
  12886. }
  12887. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12888. mg_printf(conn, "\r\n");
  12889. DEBUG_TRACE("%s", "OPTIONS done");
  12890. return;
  12891. }
  12892. }
  12893. /* 5. interpret the url to find out how the request must be handled
  12894. */
  12895. /* 5.1. first test, if the request targets the regular http(s)://
  12896. * protocol namespace or the websocket ws(s):// protocol namespace.
  12897. */
  12898. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12899. #if defined(USE_WEBSOCKET)
  12900. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12901. #else
  12902. handler_type = REQUEST_HANDLER;
  12903. #endif /* defined(USE_WEBSOCKET) */
  12904. if (is_websocket_request) {
  12905. HTTP1_only;
  12906. }
  12907. /* 5.2. check if the request will be handled by a callback */
  12908. if (get_request_handler(conn,
  12909. handler_type,
  12910. &callback_handler,
  12911. &subprotocols,
  12912. &ws_connect_handler,
  12913. &ws_ready_handler,
  12914. &ws_data_handler,
  12915. &ws_close_handler,
  12916. NULL,
  12917. &callback_data,
  12918. &handler_info)) {
  12919. /* 5.2.1. A callback will handle this request. All requests
  12920. * handled by a callback have to be considered as requests
  12921. * to a script resource. */
  12922. is_callback_resource = 1;
  12923. is_script_resource = 1;
  12924. is_put_or_delete_request = is_put_or_delete_method(conn);
  12925. /* Never handle a C callback according to File WebDav rules,
  12926. * even if it is a webdav method */
  12927. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12928. } else {
  12929. no_callback_resource:
  12930. /* 5.2.2. No callback is responsible for this request. The URI
  12931. * addresses a file based resource (static content or Lua/cgi
  12932. * scripts in the file system). */
  12933. is_callback_resource = 0;
  12934. interpret_uri(conn,
  12935. path,
  12936. sizeof(path),
  12937. &file.stat,
  12938. &is_found,
  12939. &is_script_resource,
  12940. &is_websocket_request,
  12941. &is_put_or_delete_request,
  12942. &is_webdav_request,
  12943. &is_template_text_file);
  12944. }
  12945. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12946. if (is_webdav_request) {
  12947. /* TODO: Do we need a config option? */
  12948. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12949. if (webdav_enable[0] != 'y') {
  12950. mg_send_http_error(conn,
  12951. 405,
  12952. "%s method not allowed",
  12953. conn->request_info.request_method);
  12954. DEBUG_TRACE("%s", "webdav rejected");
  12955. return;
  12956. }
  12957. }
  12958. /* 6. authorization check */
  12959. /* 6.1. a custom authorization handler is installed */
  12960. if (get_request_handler(conn,
  12961. AUTH_HANDLER,
  12962. NULL,
  12963. NULL,
  12964. NULL,
  12965. NULL,
  12966. NULL,
  12967. NULL,
  12968. &auth_handler,
  12969. &auth_callback_data,
  12970. NULL)) {
  12971. if (!auth_handler(conn, auth_callback_data)) {
  12972. /* Callback handler will not be used anymore. Release it */
  12973. release_handler_ref(conn, handler_info);
  12974. DEBUG_TRACE("%s", "auth handler rejected request");
  12975. return;
  12976. }
  12977. } else if (is_put_or_delete_request && !is_script_resource
  12978. && !is_callback_resource) {
  12979. HTTP1_only;
  12980. /* 6.2. this request is a PUT/DELETE to a real file */
  12981. /* 6.2.1. thus, the server must have real files */
  12982. #if defined(NO_FILES)
  12983. if (1) {
  12984. #else
  12985. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  12986. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  12987. #endif
  12988. /* This code path will not be called for request handlers */
  12989. DEBUG_ASSERT(handler_info == NULL);
  12990. /* This server does not have any real files, thus the
  12991. * PUT/DELETE methods are not valid. */
  12992. mg_send_http_error(conn,
  12993. 405,
  12994. "%s method not allowed",
  12995. conn->request_info.request_method);
  12996. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  12997. return;
  12998. }
  12999. #if !defined(NO_FILES)
  13000. /* 6.2.2. Check if put authorization for static files is
  13001. * available.
  13002. */
  13003. if (!is_authorized_for_put(conn)) {
  13004. send_authorization_request(conn, NULL);
  13005. DEBUG_TRACE("%s", "file write needs authorization");
  13006. return;
  13007. }
  13008. #endif
  13009. } else {
  13010. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13011. * or it is a PUT or DELETE request to a resource that does not
  13012. * correspond to a file. Check authorization. */
  13013. if (!check_authorization(conn, path)) {
  13014. send_authorization_request(conn, NULL);
  13015. /* Callback handler will not be used anymore. Release it */
  13016. release_handler_ref(conn, handler_info);
  13017. DEBUG_TRACE("%s", "access authorization required");
  13018. return;
  13019. }
  13020. }
  13021. /* request is authorized or does not need authorization */
  13022. /* 7. check if there are request handlers for this uri */
  13023. if (is_callback_resource) {
  13024. HTTP1_only;
  13025. if (!is_websocket_request) {
  13026. i = callback_handler(conn, callback_data);
  13027. /* Callback handler will not be used anymore. Release it */
  13028. release_handler_ref(conn, handler_info);
  13029. if (i > 0) {
  13030. /* Do nothing, callback has served the request. Store
  13031. * then return value as status code for the log and discard
  13032. * all data from the client not used by the callback. */
  13033. conn->status_code = i;
  13034. if (!conn->must_close) {
  13035. discard_unread_request_data(conn);
  13036. }
  13037. } else {
  13038. /* The handler did NOT handle the request. */
  13039. /* Some proper reactions would be:
  13040. * a) close the connections without sending anything
  13041. * b) send a 404 not found
  13042. * c) try if there is a file matching the URI
  13043. * It would be possible to do a, b or c in the callback
  13044. * implementation, and return 1 - we cannot do anything
  13045. * here, that is not possible in the callback.
  13046. *
  13047. * TODO: What would be the best reaction here?
  13048. * (Note: The reaction may change, if there is a better
  13049. * idea.)
  13050. */
  13051. /* For the moment, use option c: We look for a proper file,
  13052. * but since a file request is not always a script resource,
  13053. * the authorization check might be different. */
  13054. callback_handler = NULL;
  13055. /* Here we are at a dead end:
  13056. * According to URI matching, a callback should be
  13057. * responsible for handling the request,
  13058. * we called it, but the callback declared itself
  13059. * not responsible.
  13060. * We use a goto here, to get out of this dead end,
  13061. * and continue with the default handling.
  13062. * A goto here is simpler and better to understand
  13063. * than some curious loop. */
  13064. goto no_callback_resource;
  13065. }
  13066. } else {
  13067. #if defined(USE_WEBSOCKET)
  13068. handle_websocket_request(conn,
  13069. path,
  13070. is_callback_resource,
  13071. subprotocols,
  13072. ws_connect_handler,
  13073. ws_ready_handler,
  13074. ws_data_handler,
  13075. ws_close_handler,
  13076. callback_data);
  13077. #endif
  13078. }
  13079. DEBUG_TRACE("%s", "websocket handling done");
  13080. return;
  13081. }
  13082. /* 8. handle websocket requests */
  13083. #if defined(USE_WEBSOCKET)
  13084. if (is_websocket_request) {
  13085. HTTP1_only;
  13086. if (is_script_resource) {
  13087. if (is_in_script_path(conn, path)) {
  13088. /* Websocket Lua script */
  13089. handle_websocket_request(conn,
  13090. path,
  13091. 0 /* Lua Script */,
  13092. NULL,
  13093. NULL,
  13094. NULL,
  13095. NULL,
  13096. NULL,
  13097. conn->phys_ctx->user_data);
  13098. } else {
  13099. /* Script was in an illegal path */
  13100. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13101. }
  13102. } else {
  13103. mg_send_http_error(conn, 404, "%s", "Not found");
  13104. }
  13105. DEBUG_TRACE("%s", "websocket script done");
  13106. return;
  13107. } else
  13108. #endif
  13109. #if defined(NO_FILES)
  13110. /* 9a. In case the server uses only callbacks, this uri is
  13111. * unknown.
  13112. * Then, all request handling ends here. */
  13113. mg_send_http_error(conn, 404, "%s", "Not Found");
  13114. #else
  13115. /* 9b. This request is either for a static file or resource handled
  13116. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13117. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13118. mg_send_http_error(conn, 404, "%s", "Not Found");
  13119. DEBUG_TRACE("%s", "no document root available");
  13120. return;
  13121. }
  13122. /* 10. Request is handled by a script */
  13123. if (is_script_resource) {
  13124. HTTP1_only;
  13125. handle_file_based_request(conn, path, &file);
  13126. DEBUG_TRACE("%s", "script handling done");
  13127. return;
  13128. }
  13129. /* Request was not handled by a callback or script. It will be
  13130. * handled by a server internal method. */
  13131. /* 11. Handle put/delete/mkcol requests */
  13132. if (is_put_or_delete_request) {
  13133. HTTP1_only;
  13134. /* 11.1. PUT method */
  13135. if (!strcmp(ri->request_method, "PUT")) {
  13136. put_file(conn, path);
  13137. DEBUG_TRACE("handling %s request to %s done",
  13138. ri->request_method,
  13139. path);
  13140. return;
  13141. }
  13142. /* 11.2. DELETE method */
  13143. if (!strcmp(ri->request_method, "DELETE")) {
  13144. delete_file(conn, path);
  13145. DEBUG_TRACE("handling %s request to %s done",
  13146. ri->request_method,
  13147. path);
  13148. return;
  13149. }
  13150. /* 11.3. MKCOL method */
  13151. if (!strcmp(ri->request_method, "MKCOL")) {
  13152. dav_mkcol(conn, path);
  13153. DEBUG_TRACE("handling %s request to %s done",
  13154. ri->request_method,
  13155. path);
  13156. return;
  13157. }
  13158. /* 11.4. MOVE method */
  13159. if (!strcmp(ri->request_method, "MOVE")) {
  13160. dav_move_file(conn, path, 0);
  13161. DEBUG_TRACE("handling %s request to %s done",
  13162. ri->request_method,
  13163. path);
  13164. return;
  13165. }
  13166. if (!strcmp(ri->request_method, "COPY")) {
  13167. dav_move_file(conn, path, 1);
  13168. DEBUG_TRACE("handling %s request to %s done",
  13169. ri->request_method,
  13170. path);
  13171. return;
  13172. }
  13173. /* 11.5. LOCK method */
  13174. if (!strcmp(ri->request_method, "LOCK")) {
  13175. dav_lock_file(conn, path);
  13176. DEBUG_TRACE("handling %s request to %s done",
  13177. ri->request_method,
  13178. path);
  13179. return;
  13180. }
  13181. /* 11.6. UNLOCK method */
  13182. if (!strcmp(ri->request_method, "UNLOCK")) {
  13183. dav_unlock_file(conn, path);
  13184. DEBUG_TRACE("handling %s request to %s done",
  13185. ri->request_method,
  13186. path);
  13187. return;
  13188. }
  13189. /* 11.7. PROPPATCH method */
  13190. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13191. dav_proppatch(conn, path);
  13192. DEBUG_TRACE("handling %s request to %s done",
  13193. ri->request_method,
  13194. path);
  13195. return;
  13196. }
  13197. /* 11.8. Other methods, e.g.: PATCH
  13198. * This method is not supported for static resources,
  13199. * only for scripts (Lua, CGI) and callbacks. */
  13200. mg_send_http_error(conn,
  13201. 405,
  13202. "%s method not allowed",
  13203. conn->request_info.request_method);
  13204. DEBUG_TRACE("method %s on %s is not supported",
  13205. ri->request_method,
  13206. path);
  13207. return;
  13208. }
  13209. /* 11. File does not exist, or it was configured that it should be
  13210. * hidden */
  13211. if (!is_found || (must_hide_file(conn, path))) {
  13212. mg_send_http_error(conn, 404, "%s", "Not found");
  13213. DEBUG_TRACE("handling %s request to %s: file not found",
  13214. ri->request_method,
  13215. path);
  13216. return;
  13217. }
  13218. /* 12. Directory uris should end with a slash */
  13219. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13220. && (ri->local_uri[uri_len - 1] != '/')) {
  13221. /* Path + server root */
  13222. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13223. char *new_path;
  13224. if (ri->query_string) {
  13225. buflen += strlen(ri->query_string);
  13226. }
  13227. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13228. if (!new_path) {
  13229. mg_send_http_error(conn, 500, "out or memory");
  13230. } else {
  13231. mg_get_request_link(conn, new_path, buflen - 1);
  13232. strcat(new_path, "/");
  13233. if (ri->query_string) {
  13234. /* Append ? and query string */
  13235. strcat(new_path, "?");
  13236. strcat(new_path, ri->query_string);
  13237. }
  13238. mg_send_http_redirect(conn, new_path, 301);
  13239. mg_free(new_path);
  13240. }
  13241. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13242. ri->request_method,
  13243. path);
  13244. return;
  13245. }
  13246. /* 13. Handle other methods than GET/HEAD */
  13247. /* 13.1. Handle PROPFIND */
  13248. if (!strcmp(ri->request_method, "PROPFIND")) {
  13249. handle_propfind(conn, path, &file.stat);
  13250. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13251. return;
  13252. }
  13253. /* 13.2. Handle OPTIONS for files */
  13254. if (!strcmp(ri->request_method, "OPTIONS")) {
  13255. /* This standard handler is only used for real files.
  13256. * Scripts should support the OPTIONS method themselves, to allow a
  13257. * maximum flexibility.
  13258. * Lua and CGI scripts may fully support CORS this way (including
  13259. * preflights). */
  13260. send_options(conn);
  13261. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13262. return;
  13263. }
  13264. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13265. if ((0 != strcmp(ri->request_method, "GET"))
  13266. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13267. mg_send_http_error(conn,
  13268. 405,
  13269. "%s method not allowed",
  13270. conn->request_info.request_method);
  13271. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13272. return;
  13273. }
  13274. /* 14. directories */
  13275. if (file.stat.is_directory) {
  13276. /* Substitute files have already been handled above. */
  13277. /* Here we can either generate and send a directory listing,
  13278. * or send an "access denied" error. */
  13279. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13280. "yes")) {
  13281. handle_directory_request(conn, path);
  13282. } else {
  13283. mg_send_http_error(conn,
  13284. 403,
  13285. "%s",
  13286. "Error: Directory listing denied");
  13287. }
  13288. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13289. return;
  13290. }
  13291. /* 15. Files with search/replace patterns: LSP and SSI */
  13292. if (is_template_text_file) {
  13293. HTTP1_only;
  13294. handle_file_based_request(conn, path, &file);
  13295. DEBUG_TRACE("handling %s request to %s done (template)",
  13296. ri->request_method,
  13297. path);
  13298. return;
  13299. }
  13300. /* 16. Static file - maybe cached */
  13301. #if !defined(NO_CACHING)
  13302. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13303. /* Send 304 "Not Modified" - this must not send any body data */
  13304. handle_not_modified_static_file_request(conn, &file);
  13305. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13306. ri->request_method,
  13307. path);
  13308. return;
  13309. }
  13310. #endif /* !NO_CACHING */
  13311. /* 17. Static file - not cached */
  13312. handle_static_file_request(conn, path, &file, NULL, NULL);
  13313. DEBUG_TRACE("handling %s request to %s done (static)",
  13314. ri->request_method,
  13315. path);
  13316. #endif /* !defined(NO_FILES) */
  13317. }
  13318. #if !defined(NO_FILESYSTEMS)
  13319. static void
  13320. handle_file_based_request(struct mg_connection *conn,
  13321. const char *path,
  13322. struct mg_file *file)
  13323. {
  13324. #if !defined(NO_CGI)
  13325. unsigned char cgi_config_idx, inc, max;
  13326. #endif
  13327. if (!conn || !conn->dom_ctx) {
  13328. return;
  13329. }
  13330. #if defined(USE_LUA)
  13331. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13332. path)
  13333. > 0) {
  13334. if (is_in_script_path(conn, path)) {
  13335. /* Lua server page: an SSI like page containing mostly plain
  13336. * html code plus some tags with server generated contents. */
  13337. handle_lsp_request(conn, path, file, NULL);
  13338. } else {
  13339. /* Script was in an illegal path */
  13340. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13341. }
  13342. return;
  13343. }
  13344. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13345. > 0) {
  13346. if (is_in_script_path(conn, path)) {
  13347. /* Lua in-server module script: a CGI like script used to
  13348. * generate the entire reply. */
  13349. mg_exec_lua_script(conn, path, NULL);
  13350. } else {
  13351. /* Script was in an illegal path */
  13352. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13353. }
  13354. return;
  13355. }
  13356. #endif
  13357. #if defined(USE_DUKTAPE)
  13358. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13359. path)
  13360. > 0) {
  13361. if (is_in_script_path(conn, path)) {
  13362. /* Call duktape to generate the page */
  13363. mg_exec_duktape_script(conn, path);
  13364. } else {
  13365. /* Script was in an illegal path */
  13366. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13367. }
  13368. return;
  13369. }
  13370. #endif
  13371. #if !defined(NO_CGI)
  13372. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13373. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13374. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13375. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13376. if (match_prefix_strlen(
  13377. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13378. path)
  13379. > 0) {
  13380. if (is_in_script_path(conn, path)) {
  13381. /* CGI scripts may support all HTTP methods */
  13382. handle_cgi_request(conn, path, cgi_config_idx);
  13383. } else {
  13384. /* Script was in an illegal path */
  13385. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13386. }
  13387. return;
  13388. }
  13389. }
  13390. }
  13391. #endif /* !NO_CGI */
  13392. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13393. if (is_in_script_path(conn, path)) {
  13394. handle_ssi_file_request(conn, path, file);
  13395. } else {
  13396. /* Script was in an illegal path */
  13397. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13398. }
  13399. return;
  13400. }
  13401. #if !defined(NO_CACHING)
  13402. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13403. /* Send 304 "Not Modified" - this must not send any body data */
  13404. handle_not_modified_static_file_request(conn, file);
  13405. return;
  13406. }
  13407. #endif /* !NO_CACHING */
  13408. handle_static_file_request(conn, path, file, NULL, NULL);
  13409. }
  13410. #endif /* NO_FILESYSTEMS */
  13411. static void
  13412. close_all_listening_sockets(struct mg_context *ctx)
  13413. {
  13414. unsigned int i;
  13415. if (!ctx) {
  13416. return;
  13417. }
  13418. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13419. closesocket(ctx->listening_sockets[i].sock);
  13420. #if defined(USE_X_DOM_SOCKET)
  13421. /* For unix domain sockets, the socket name represents a file that has
  13422. * to be deleted. */
  13423. /* See
  13424. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13425. */
  13426. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13427. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13428. IGNORE_UNUSED_RESULT(
  13429. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13430. }
  13431. #endif
  13432. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13433. }
  13434. mg_free(ctx->listening_sockets);
  13435. ctx->listening_sockets = NULL;
  13436. mg_free(ctx->listening_socket_fds);
  13437. ctx->listening_socket_fds = NULL;
  13438. }
  13439. /* Valid listening port specification is: [ip_address:]port[s]
  13440. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13441. * Examples for IPv6: [::]:80, [::1]:80,
  13442. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13443. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13444. * In order to bind to both, IPv4 and IPv6, you can either add
  13445. * both ports using 8080,[::]:8080, or the short form +8080.
  13446. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13447. * one only accepting IPv4 the other only IPv6. +8080 creates
  13448. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13449. * environment, they might work differently, or might not work
  13450. * at all - it must be tested what options work best in the
  13451. * relevant network environment.
  13452. */
  13453. static int
  13454. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13455. {
  13456. unsigned int a, b, c, d;
  13457. unsigned port;
  13458. unsigned long portUL;
  13459. int ch, len;
  13460. const char *cb;
  13461. char *endptr;
  13462. #if defined(USE_IPV6)
  13463. char buf[100] = {0};
  13464. #endif
  13465. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13466. * Also, all-zeroes in the socket address means binding to all addresses
  13467. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13468. memset(so, 0, sizeof(*so));
  13469. so->lsa.sin.sin_family = AF_INET;
  13470. *ip_version = 0;
  13471. /* Initialize len as invalid. */
  13472. port = 0;
  13473. len = 0;
  13474. /* Test for different ways to format this string */
  13475. if (sscanf(vec->ptr,
  13476. "%u.%u.%u.%u:%u%n",
  13477. &a,
  13478. &b,
  13479. &c,
  13480. &d,
  13481. &port,
  13482. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13483. // to an integer value, but function will not report
  13484. // conversion errors; consider using 'strtol' instead
  13485. == 5) {
  13486. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13487. so->lsa.sin.sin_addr.s_addr =
  13488. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13489. so->lsa.sin.sin_port = htons((uint16_t)port);
  13490. *ip_version = 4;
  13491. #if defined(USE_IPV6)
  13492. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13493. && ((size_t)len <= vec->len)
  13494. && mg_inet_pton(
  13495. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13496. /* IPv6 address, examples: see above */
  13497. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13498. */
  13499. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13500. *ip_version = 6;
  13501. #endif
  13502. } else if ((vec->ptr[0] == '+')
  13503. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13504. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13505. // string to an integer value, but function will not
  13506. // report conversion errors; consider using 'strtol'
  13507. // instead
  13508. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13509. /* Add 1 to len for the + character we skipped before */
  13510. len++;
  13511. #if defined(USE_IPV6)
  13512. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13513. so->lsa.sin6.sin6_family = AF_INET6;
  13514. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13515. *ip_version = 4 + 6;
  13516. #else
  13517. /* Bind to IPv4 only, since IPv6 is not built in. */
  13518. so->lsa.sin.sin_port = htons((uint16_t)port);
  13519. *ip_version = 4;
  13520. #endif
  13521. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13522. && (vec->ptr != endptr)) {
  13523. len = (int)(endptr - vec->ptr);
  13524. port = (uint16_t)portUL;
  13525. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13526. so->lsa.sin.sin_port = htons((uint16_t)port);
  13527. *ip_version = 4;
  13528. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13529. /* String could be a hostname. This check algotithm
  13530. * will only work for RFC 952 compliant hostnames,
  13531. * starting with a letter, containing only letters,
  13532. * digits and hyphen ('-'). Newer specs may allow
  13533. * more, but this is not guaranteed here, since it
  13534. * may interfere with rules for port option lists. */
  13535. /* According to RFC 1035, hostnames are restricted to 255 characters
  13536. * in total (63 between two dots). */
  13537. char hostname[256];
  13538. size_t hostnlen = (size_t)(cb - vec->ptr);
  13539. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13540. /* This would be invalid in any case */
  13541. *ip_version = 0;
  13542. return 0;
  13543. }
  13544. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13545. if (mg_inet_pton(
  13546. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13547. if (sscanf(cb + 1, "%u%n", &port, &len)
  13548. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13549. // string to an integer value, but function will not
  13550. // report conversion errors; consider using 'strtol'
  13551. // instead
  13552. *ip_version = 4;
  13553. so->lsa.sin.sin_port = htons((uint16_t)port);
  13554. len += (int)(hostnlen + 1);
  13555. } else {
  13556. len = 0;
  13557. }
  13558. #if defined(USE_IPV6)
  13559. } else if (mg_inet_pton(AF_INET6,
  13560. hostname,
  13561. &so->lsa.sin6,
  13562. sizeof(so->lsa.sin6),
  13563. 1)) {
  13564. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13565. *ip_version = 6;
  13566. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13567. len += (int)(hostnlen + 1);
  13568. } else {
  13569. len = 0;
  13570. }
  13571. #endif
  13572. } else {
  13573. len = 0;
  13574. }
  13575. #if defined(USE_X_DOM_SOCKET)
  13576. } else if (vec->ptr[0] == 'x') {
  13577. /* unix (linux) domain socket */
  13578. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13579. len = vec->len;
  13580. so->lsa.sun.sun_family = AF_UNIX;
  13581. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13582. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13583. port = 0;
  13584. *ip_version = 99;
  13585. } else {
  13586. /* String too long */
  13587. len = 0;
  13588. }
  13589. #endif
  13590. } else {
  13591. /* Parsing failure. */
  13592. len = 0;
  13593. }
  13594. /* sscanf and the option splitting code ensure the following condition
  13595. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13596. if ((len > 0) && is_valid_port(port)
  13597. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13598. /* Next character after the port number */
  13599. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13600. so->is_ssl = (ch == 's');
  13601. so->ssl_redir = (ch == 'r');
  13602. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13603. return 1;
  13604. }
  13605. }
  13606. /* Reset ip_version to 0 if there is an error */
  13607. *ip_version = 0;
  13608. return 0;
  13609. }
  13610. /* Is there any SSL port in use? */
  13611. static int
  13612. is_ssl_port_used(const char *ports)
  13613. {
  13614. if (ports) {
  13615. /* There are several different allowed syntax variants:
  13616. * - "80" for a single port using every network interface
  13617. * - "localhost:80" for a single port using only localhost
  13618. * - "80,localhost:8080" for two ports, one bound to localhost
  13619. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13620. * to IPv4 localhost, one to IPv6 localhost
  13621. * - "+80" use port 80 for IPv4 and IPv6
  13622. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13623. * for both: IPv4 and IPv4
  13624. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13625. * additionally port 8080 bound to localhost connections
  13626. *
  13627. * If we just look for 's' anywhere in the string, "localhost:80"
  13628. * will be detected as SSL (false positive).
  13629. * Looking for 's' after a digit may cause false positives in
  13630. * "my24service:8080".
  13631. * Looking from 's' backward if there are only ':' and numbers
  13632. * before will not work for "24service:8080" (non SSL, port 8080)
  13633. * or "24s" (SSL, port 24).
  13634. *
  13635. * Remark: Initially hostnames were not allowed to start with a
  13636. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13637. * Section 2.1).
  13638. *
  13639. * To get this correct, the entire string must be parsed as a whole,
  13640. * reading it as a list element for element and parsing with an
  13641. * algorithm equivalent to parse_port_string.
  13642. *
  13643. * In fact, we use local interface names here, not arbitrary
  13644. * hostnames, so in most cases the only name will be "localhost".
  13645. *
  13646. * So, for now, we use this simple algorithm, that may still return
  13647. * a false positive in bizarre cases.
  13648. */
  13649. int i;
  13650. int portslen = (int)strlen(ports);
  13651. char prevIsNumber = 0;
  13652. for (i = 0; i < portslen; i++) {
  13653. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13654. return 1;
  13655. }
  13656. if (ports[i] >= '0' && ports[i] <= '9') {
  13657. prevIsNumber = 1;
  13658. } else {
  13659. prevIsNumber = 0;
  13660. }
  13661. }
  13662. }
  13663. return 0;
  13664. }
  13665. static int
  13666. set_ports_option(struct mg_context *phys_ctx)
  13667. {
  13668. const char *list;
  13669. int on = 1;
  13670. #if defined(USE_IPV6)
  13671. int off = 0;
  13672. #endif
  13673. struct vec vec;
  13674. struct socket so, *ptr;
  13675. struct mg_pollfd *pfd;
  13676. union usa usa;
  13677. socklen_t len;
  13678. int ip_version;
  13679. int portsTotal = 0;
  13680. int portsOk = 0;
  13681. const char *opt_txt;
  13682. long opt_listen_backlog;
  13683. if (!phys_ctx) {
  13684. return 0;
  13685. }
  13686. memset(&so, 0, sizeof(so));
  13687. memset(&usa, 0, sizeof(usa));
  13688. len = sizeof(usa);
  13689. list = phys_ctx->dd.config[LISTENING_PORTS];
  13690. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13691. portsTotal++;
  13692. if (!parse_port_string(&vec, &so, &ip_version)) {
  13693. mg_cry_ctx_internal(
  13694. phys_ctx,
  13695. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13696. (int)vec.len,
  13697. vec.ptr,
  13698. portsTotal,
  13699. "[IP_ADDRESS:]PORT[s|r]");
  13700. continue;
  13701. }
  13702. #if !defined(NO_SSL)
  13703. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13704. mg_cry_ctx_internal(phys_ctx,
  13705. "Cannot add SSL socket (entry %i)",
  13706. portsTotal);
  13707. continue;
  13708. }
  13709. #endif
  13710. /* Create socket. */
  13711. /* For a list of protocol numbers (e.g., TCP==6) see:
  13712. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13713. */
  13714. if ((so.sock =
  13715. socket(so.lsa.sa.sa_family,
  13716. SOCK_STREAM,
  13717. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13718. == INVALID_SOCKET) {
  13719. mg_cry_ctx_internal(phys_ctx,
  13720. "cannot create socket (entry %i)",
  13721. portsTotal);
  13722. continue;
  13723. }
  13724. #if defined(_WIN32)
  13725. /* Windows SO_REUSEADDR lets many procs binds to a
  13726. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13727. * if someone already has the socket -- DTL */
  13728. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13729. * Windows might need a few seconds before
  13730. * the same port can be used again in the
  13731. * same process, so a short Sleep may be
  13732. * required between mg_stop and mg_start.
  13733. */
  13734. if (setsockopt(so.sock,
  13735. SOL_SOCKET,
  13736. SO_EXCLUSIVEADDRUSE,
  13737. (SOCK_OPT_TYPE)&on,
  13738. sizeof(on))
  13739. != 0) {
  13740. /* Set reuse option, but don't abort on errors. */
  13741. mg_cry_ctx_internal(
  13742. phys_ctx,
  13743. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13744. portsTotal);
  13745. }
  13746. #else
  13747. if (setsockopt(so.sock,
  13748. SOL_SOCKET,
  13749. SO_REUSEADDR,
  13750. (SOCK_OPT_TYPE)&on,
  13751. sizeof(on))
  13752. != 0) {
  13753. /* Set reuse option, but don't abort on errors. */
  13754. mg_cry_ctx_internal(
  13755. phys_ctx,
  13756. "cannot set socket option SO_REUSEADDR (entry %i)",
  13757. portsTotal);
  13758. }
  13759. #endif
  13760. #if defined(USE_X_DOM_SOCKET)
  13761. if (ip_version == 99) {
  13762. /* Unix domain socket */
  13763. } else
  13764. #endif
  13765. if (ip_version > 4) {
  13766. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13767. #if defined(USE_IPV6)
  13768. if (ip_version > 6) {
  13769. if (so.lsa.sa.sa_family == AF_INET6
  13770. && setsockopt(so.sock,
  13771. IPPROTO_IPV6,
  13772. IPV6_V6ONLY,
  13773. (void *)&off,
  13774. sizeof(off))
  13775. != 0) {
  13776. /* Set IPv6 only option, but don't abort on errors. */
  13777. mg_cry_ctx_internal(phys_ctx,
  13778. "cannot set socket option "
  13779. "IPV6_V6ONLY=off (entry %i)",
  13780. portsTotal);
  13781. }
  13782. } else {
  13783. if (so.lsa.sa.sa_family == AF_INET6
  13784. && setsockopt(so.sock,
  13785. IPPROTO_IPV6,
  13786. IPV6_V6ONLY,
  13787. (void *)&on,
  13788. sizeof(on))
  13789. != 0) {
  13790. /* Set IPv6 only option, but don't abort on errors. */
  13791. mg_cry_ctx_internal(phys_ctx,
  13792. "cannot set socket option "
  13793. "IPV6_V6ONLY=on (entry %i)",
  13794. portsTotal);
  13795. }
  13796. }
  13797. #else
  13798. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13799. closesocket(so.sock);
  13800. so.sock = INVALID_SOCKET;
  13801. continue;
  13802. #endif
  13803. }
  13804. if (so.lsa.sa.sa_family == AF_INET) {
  13805. len = sizeof(so.lsa.sin);
  13806. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13807. mg_cry_ctx_internal(phys_ctx,
  13808. "cannot bind to %.*s: %d (%s)",
  13809. (int)vec.len,
  13810. vec.ptr,
  13811. (int)ERRNO,
  13812. strerror(errno));
  13813. closesocket(so.sock);
  13814. so.sock = INVALID_SOCKET;
  13815. continue;
  13816. }
  13817. }
  13818. #if defined(USE_IPV6)
  13819. else if (so.lsa.sa.sa_family == AF_INET6) {
  13820. len = sizeof(so.lsa.sin6);
  13821. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13822. mg_cry_ctx_internal(phys_ctx,
  13823. "cannot bind to IPv6 %.*s: %d (%s)",
  13824. (int)vec.len,
  13825. vec.ptr,
  13826. (int)ERRNO,
  13827. strerror(errno));
  13828. closesocket(so.sock);
  13829. so.sock = INVALID_SOCKET;
  13830. continue;
  13831. }
  13832. }
  13833. #endif
  13834. #if defined(USE_X_DOM_SOCKET)
  13835. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13836. len = sizeof(so.lsa.sun);
  13837. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13838. mg_cry_ctx_internal(phys_ctx,
  13839. "cannot bind to unix socket %s: %d (%s)",
  13840. so.lsa.sun.sun_path,
  13841. (int)ERRNO,
  13842. strerror(errno));
  13843. closesocket(so.sock);
  13844. so.sock = INVALID_SOCKET;
  13845. continue;
  13846. }
  13847. }
  13848. #endif
  13849. else {
  13850. mg_cry_ctx_internal(
  13851. phys_ctx,
  13852. "cannot bind: address family not supported (entry %i)",
  13853. portsTotal);
  13854. closesocket(so.sock);
  13855. so.sock = INVALID_SOCKET;
  13856. continue;
  13857. }
  13858. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13859. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13860. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13861. mg_cry_ctx_internal(phys_ctx,
  13862. "%s value \"%s\" is invalid",
  13863. config_options[LISTEN_BACKLOG_SIZE].name,
  13864. opt_txt);
  13865. closesocket(so.sock);
  13866. so.sock = INVALID_SOCKET;
  13867. continue;
  13868. }
  13869. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13870. mg_cry_ctx_internal(phys_ctx,
  13871. "cannot listen to %.*s: %d (%s)",
  13872. (int)vec.len,
  13873. vec.ptr,
  13874. (int)ERRNO,
  13875. strerror(errno));
  13876. closesocket(so.sock);
  13877. so.sock = INVALID_SOCKET;
  13878. continue;
  13879. }
  13880. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13881. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13882. int err = (int)ERRNO;
  13883. mg_cry_ctx_internal(phys_ctx,
  13884. "call to getsockname failed %.*s: %d (%s)",
  13885. (int)vec.len,
  13886. vec.ptr,
  13887. err,
  13888. strerror(errno));
  13889. closesocket(so.sock);
  13890. so.sock = INVALID_SOCKET;
  13891. continue;
  13892. }
  13893. /* Update lsa port in case of random free ports */
  13894. #if defined(USE_IPV6)
  13895. if (so.lsa.sa.sa_family == AF_INET6) {
  13896. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13897. } else
  13898. #endif
  13899. {
  13900. so.lsa.sin.sin_port = usa.sin.sin_port;
  13901. }
  13902. if ((ptr = (struct socket *)
  13903. mg_realloc_ctx(phys_ctx->listening_sockets,
  13904. (phys_ctx->num_listening_sockets + 1)
  13905. * sizeof(phys_ctx->listening_sockets[0]),
  13906. phys_ctx))
  13907. == NULL) {
  13908. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13909. closesocket(so.sock);
  13910. so.sock = INVALID_SOCKET;
  13911. continue;
  13912. }
  13913. if ((pfd = (struct mg_pollfd *)
  13914. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13915. (phys_ctx->num_listening_sockets + 1)
  13916. * sizeof(phys_ctx->listening_socket_fds[0]),
  13917. phys_ctx))
  13918. == NULL) {
  13919. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13920. closesocket(so.sock);
  13921. so.sock = INVALID_SOCKET;
  13922. mg_free(ptr);
  13923. continue;
  13924. }
  13925. set_close_on_exec(so.sock, NULL, phys_ctx);
  13926. phys_ctx->listening_sockets = ptr;
  13927. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13928. phys_ctx->listening_socket_fds = pfd;
  13929. phys_ctx->num_listening_sockets++;
  13930. portsOk++;
  13931. }
  13932. if (portsOk != portsTotal) {
  13933. close_all_listening_sockets(phys_ctx);
  13934. portsOk = 0;
  13935. }
  13936. return portsOk;
  13937. }
  13938. static const char *
  13939. header_val(const struct mg_connection *conn, const char *header)
  13940. {
  13941. const char *header_value;
  13942. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13943. return "-";
  13944. } else {
  13945. return header_value;
  13946. }
  13947. }
  13948. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13949. #include "external_log_access.inl"
  13950. #elif !defined(NO_FILESYSTEMS)
  13951. static void
  13952. log_access(const struct mg_connection *conn)
  13953. {
  13954. const struct mg_request_info *ri;
  13955. struct mg_file fi;
  13956. char date[64], src_addr[IP_ADDR_STR_LEN];
  13957. #if defined(REENTRANT_TIME)
  13958. struct tm _tm;
  13959. struct tm *tm = &_tm;
  13960. #else
  13961. struct tm *tm;
  13962. #endif
  13963. const char *referer;
  13964. const char *user_agent;
  13965. char log_buf[4096];
  13966. if (!conn || !conn->dom_ctx) {
  13967. return;
  13968. }
  13969. /* Set log message to "empty" */
  13970. log_buf[0] = 0;
  13971. #if defined(USE_LUA)
  13972. if (conn->phys_ctx->lua_bg_log_available) {
  13973. int ret;
  13974. struct mg_context *ctx = conn->phys_ctx;
  13975. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13976. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13977. /* call "log()" in Lua */
  13978. lua_getglobal(lstate, "log");
  13979. prepare_lua_request_info_inner(conn, lstate);
  13980. push_lua_response_log_data(conn, lstate);
  13981. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13982. if (ret == 0) {
  13983. int t = lua_type(lstate, -1);
  13984. if (t == LUA_TBOOLEAN) {
  13985. if (lua_toboolean(lstate, -1) == 0) {
  13986. /* log() returned false: do not log */
  13987. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13988. return;
  13989. }
  13990. /* log returned true: continue logging */
  13991. } else if (t == LUA_TSTRING) {
  13992. size_t len;
  13993. const char *txt = lua_tolstring(lstate, -1, &len);
  13994. if ((len == 0) || (*txt == 0)) {
  13995. /* log() returned empty string: do not log */
  13996. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13997. return;
  13998. }
  13999. /* Copy test from Lua into log_buf */
  14000. if (len >= sizeof(log_buf)) {
  14001. len = sizeof(log_buf) - 1;
  14002. }
  14003. memcpy(log_buf, txt, len);
  14004. log_buf[len] = 0;
  14005. }
  14006. } else {
  14007. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14008. }
  14009. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14010. }
  14011. #endif
  14012. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14013. if (mg_fopen(conn,
  14014. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14015. MG_FOPEN_MODE_APPEND,
  14016. &fi)
  14017. == 0) {
  14018. fi.access.fp = NULL;
  14019. }
  14020. } else {
  14021. fi.access.fp = NULL;
  14022. }
  14023. /* Log is written to a file and/or a callback. If both are not set,
  14024. * executing the rest of the function is pointless. */
  14025. if ((fi.access.fp == NULL)
  14026. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14027. return;
  14028. }
  14029. /* If we did not get a log message from Lua, create it here. */
  14030. if (!log_buf[0]) {
  14031. #if defined(REENTRANT_TIME)
  14032. localtime_r(&conn->conn_birth_time, tm);
  14033. #else
  14034. tm = localtime(&conn->conn_birth_time);
  14035. #endif
  14036. if (tm != NULL) {
  14037. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14038. } else {
  14039. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14040. date[sizeof(date) - 1] = '\0';
  14041. }
  14042. ri = &conn->request_info;
  14043. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14044. referer = header_val(conn, "Referer");
  14045. user_agent = header_val(conn, "User-Agent");
  14046. mg_snprintf(conn,
  14047. NULL, /* Ignore truncation in access log */
  14048. log_buf,
  14049. sizeof(log_buf),
  14050. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14051. " %s %s",
  14052. src_addr,
  14053. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14054. date,
  14055. ri->request_method ? ri->request_method : "-",
  14056. ri->request_uri ? ri->request_uri : "-",
  14057. ri->query_string ? "?" : "",
  14058. ri->query_string ? ri->query_string : "",
  14059. ri->http_version,
  14060. conn->status_code,
  14061. conn->num_bytes_sent,
  14062. referer,
  14063. user_agent);
  14064. }
  14065. /* Here we have a log message in log_buf. Call the callback */
  14066. if (conn->phys_ctx->callbacks.log_access) {
  14067. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14068. /* do not log if callack returns non-zero */
  14069. if (fi.access.fp) {
  14070. mg_fclose(&fi.access);
  14071. }
  14072. return;
  14073. }
  14074. }
  14075. /* Store in file */
  14076. if (fi.access.fp) {
  14077. int ok = 1;
  14078. flockfile(fi.access.fp);
  14079. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14080. ok = 0;
  14081. }
  14082. if (fflush(fi.access.fp) != 0) {
  14083. ok = 0;
  14084. }
  14085. funlockfile(fi.access.fp);
  14086. if (mg_fclose(&fi.access) != 0) {
  14087. ok = 0;
  14088. }
  14089. if (!ok) {
  14090. mg_cry_internal(conn,
  14091. "Error writing log file %s",
  14092. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14093. }
  14094. }
  14095. }
  14096. #else
  14097. #error "Either enable filesystems or provide a custom log_access implementation"
  14098. #endif /* Externally provided function */
  14099. /* Verify given socket address against the ACL.
  14100. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14101. */
  14102. static int
  14103. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14104. {
  14105. int allowed, flag, matched;
  14106. struct vec vec;
  14107. if (phys_ctx) {
  14108. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14109. /* If any ACL is set, deny by default */
  14110. allowed = (list == NULL) ? '+' : '-';
  14111. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14112. flag = vec.ptr[0];
  14113. matched = -1;
  14114. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14115. vec.ptr++;
  14116. vec.len--;
  14117. matched = parse_match_net(&vec, sa, 1);
  14118. }
  14119. if (matched < 0) {
  14120. mg_cry_ctx_internal(phys_ctx,
  14121. "%s: subnet must be [+|-]IP-addr[/x]",
  14122. __func__);
  14123. return -1;
  14124. }
  14125. if (matched) {
  14126. allowed = flag;
  14127. }
  14128. }
  14129. return allowed == '+';
  14130. }
  14131. return -1;
  14132. }
  14133. #if !defined(_WIN32) && !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  14134. static int
  14135. set_uid_option(struct mg_context *phys_ctx)
  14136. {
  14137. int success = 0;
  14138. if (phys_ctx) {
  14139. /* We are currently running as curr_uid. */
  14140. const uid_t curr_uid = getuid();
  14141. /* If set, we want to run as run_as_user. */
  14142. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14143. const struct passwd *to_pw = NULL;
  14144. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14145. /* run_as_user does not exist on the system. We can't proceed
  14146. * further. */
  14147. mg_cry_ctx_internal(phys_ctx,
  14148. "%s: unknown user [%s]",
  14149. __func__,
  14150. run_as_user);
  14151. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14152. /* There was either no request to change user, or we're already
  14153. * running as run_as_user. Nothing else to do.
  14154. */
  14155. success = 1;
  14156. } else {
  14157. /* Valid change request. */
  14158. if (setgid(to_pw->pw_gid) == -1) {
  14159. mg_cry_ctx_internal(phys_ctx,
  14160. "%s: setgid(%s): %s",
  14161. __func__,
  14162. run_as_user,
  14163. strerror(errno));
  14164. } else if (setgroups(0, NULL) == -1) {
  14165. mg_cry_ctx_internal(phys_ctx,
  14166. "%s: setgroups(): %s",
  14167. __func__,
  14168. strerror(errno));
  14169. } else if (setuid(to_pw->pw_uid) == -1) {
  14170. mg_cry_ctx_internal(phys_ctx,
  14171. "%s: setuid(%s): %s",
  14172. __func__,
  14173. run_as_user,
  14174. strerror(errno));
  14175. } else {
  14176. success = 1;
  14177. }
  14178. }
  14179. }
  14180. return success;
  14181. }
  14182. #endif /* !_WIN32 */
  14183. static void
  14184. tls_dtor(void *key)
  14185. {
  14186. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14187. /* key == pthread_getspecific(sTlsKey); */
  14188. if (tls) {
  14189. if (tls->is_master == 2) {
  14190. tls->is_master = -3; /* Mark memory as dead */
  14191. mg_free(tls);
  14192. }
  14193. }
  14194. pthread_setspecific(sTlsKey, NULL);
  14195. }
  14196. #if defined(USE_MBEDTLS)
  14197. /* Check if SSL is required.
  14198. * If so, set up ctx->ssl_ctx pointer. */
  14199. static int
  14200. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14201. {
  14202. if (!phys_ctx) {
  14203. return 0;
  14204. }
  14205. if (!dom_ctx) {
  14206. dom_ctx = &(phys_ctx->dd);
  14207. }
  14208. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14209. /* No SSL port is set. No need to setup SSL. */
  14210. return 1;
  14211. }
  14212. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14213. if (dom_ctx->ssl_ctx == NULL) {
  14214. fprintf(stderr, "ssl_ctx malloc failed\n");
  14215. return 0;
  14216. }
  14217. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14218. == 0
  14219. ? 1
  14220. : 0;
  14221. }
  14222. #elif !defined(NO_SSL)
  14223. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14224. struct mg_domain_context *dom_ctx,
  14225. const char *pem,
  14226. const char *chain);
  14227. static const char *ssl_error(void);
  14228. static int
  14229. refresh_trust(struct mg_connection *conn)
  14230. {
  14231. struct stat cert_buf;
  14232. int64_t t = 0;
  14233. const char *pem;
  14234. const char *chain;
  14235. int should_verify_peer;
  14236. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14237. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14238. * refresh_trust still can not work. */
  14239. return 0;
  14240. }
  14241. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14242. if (chain == NULL) {
  14243. /* pem is not NULL here */
  14244. chain = pem;
  14245. }
  14246. if (*chain == 0) {
  14247. chain = NULL;
  14248. }
  14249. if (stat(pem, &cert_buf) != -1) {
  14250. t = (int64_t)cert_buf.st_mtime;
  14251. }
  14252. mg_lock_context(conn->phys_ctx);
  14253. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14254. conn->dom_ctx->ssl_cert_last_mtime = t;
  14255. should_verify_peer = 0;
  14256. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14257. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14258. == 0) {
  14259. should_verify_peer = 1;
  14260. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14261. "optional")
  14262. == 0) {
  14263. should_verify_peer = 1;
  14264. }
  14265. }
  14266. if (should_verify_peer) {
  14267. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14268. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14269. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14270. ca_file,
  14271. ca_path)
  14272. != 1) {
  14273. mg_unlock_context(conn->phys_ctx);
  14274. mg_cry_ctx_internal(
  14275. conn->phys_ctx,
  14276. "SSL_CTX_load_verify_locations error: %s "
  14277. "ssl_verify_peer requires setting "
  14278. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14279. "present in "
  14280. "the .conf file?",
  14281. ssl_error());
  14282. return 0;
  14283. }
  14284. }
  14285. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14286. mg_unlock_context(conn->phys_ctx);
  14287. return 0;
  14288. }
  14289. }
  14290. mg_unlock_context(conn->phys_ctx);
  14291. return 1;
  14292. }
  14293. #if defined(OPENSSL_API_1_1)
  14294. #else
  14295. static pthread_mutex_t *ssl_mutexes;
  14296. #endif /* OPENSSL_API_1_1 */
  14297. static int
  14298. sslize(struct mg_connection *conn,
  14299. int (*func)(SSL *),
  14300. const struct mg_client_options *client_options)
  14301. {
  14302. int ret, err;
  14303. int short_trust;
  14304. unsigned timeout = 1024;
  14305. unsigned i;
  14306. if (!conn) {
  14307. return 0;
  14308. }
  14309. short_trust =
  14310. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14311. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14312. if (short_trust) {
  14313. int trust_ret = refresh_trust(conn);
  14314. if (!trust_ret) {
  14315. return trust_ret;
  14316. }
  14317. }
  14318. mg_lock_context(conn->phys_ctx);
  14319. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14320. mg_unlock_context(conn->phys_ctx);
  14321. if (conn->ssl == NULL) {
  14322. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14323. OPENSSL_REMOVE_THREAD_STATE();
  14324. return 0;
  14325. }
  14326. SSL_set_app_data(conn->ssl, (char *)conn);
  14327. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14328. if (ret != 1) {
  14329. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14330. SSL_free(conn->ssl);
  14331. conn->ssl = NULL;
  14332. OPENSSL_REMOVE_THREAD_STATE();
  14333. return 0;
  14334. }
  14335. if (client_options) {
  14336. if (client_options->host_name) {
  14337. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14338. }
  14339. }
  14340. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14341. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14342. /* NOTE: The loop below acts as a back-off, so we can end
  14343. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14344. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14345. if (to >= 0) {
  14346. timeout = (unsigned)to;
  14347. }
  14348. }
  14349. /* SSL functions may fail and require to be called again:
  14350. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14351. * Here "func" could be SSL_connect or SSL_accept. */
  14352. for (i = 0; i <= timeout; i += 50) {
  14353. ERR_clear_error();
  14354. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14355. ret = func(conn->ssl);
  14356. if (ret != 1) {
  14357. err = SSL_get_error(conn->ssl, ret);
  14358. if ((err == SSL_ERROR_WANT_CONNECT)
  14359. || (err == SSL_ERROR_WANT_ACCEPT)
  14360. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14361. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14362. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14363. /* Don't wait if the server is going to be stopped. */
  14364. break;
  14365. }
  14366. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14367. /* Simply retry the function call. */
  14368. mg_sleep(50);
  14369. } else {
  14370. /* Need to retry the function call "later".
  14371. * See https://linux.die.net/man/3/ssl_get_error
  14372. * This is typical for non-blocking sockets. */
  14373. struct mg_pollfd pfd;
  14374. int pollres;
  14375. pfd.fd = conn->client.sock;
  14376. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14377. || (err == SSL_ERROR_WANT_WRITE))
  14378. ? POLLOUT
  14379. : POLLIN;
  14380. pollres =
  14381. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14382. if (pollres < 0) {
  14383. /* Break if error occured (-1)
  14384. * or server shutdown (-2) */
  14385. break;
  14386. }
  14387. }
  14388. } else if (err == SSL_ERROR_SYSCALL) {
  14389. /* This is an IO error. Look at errno. */
  14390. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14391. break;
  14392. } else {
  14393. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14394. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14395. break;
  14396. }
  14397. } else {
  14398. /* success */
  14399. break;
  14400. }
  14401. }
  14402. ERR_clear_error();
  14403. if (ret != 1) {
  14404. SSL_free(conn->ssl);
  14405. conn->ssl = NULL;
  14406. OPENSSL_REMOVE_THREAD_STATE();
  14407. return 0;
  14408. }
  14409. return 1;
  14410. }
  14411. /* Return OpenSSL error message (from CRYPTO lib) */
  14412. static const char *
  14413. ssl_error(void)
  14414. {
  14415. unsigned long err;
  14416. err = ERR_get_error();
  14417. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14418. }
  14419. static int
  14420. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14421. {
  14422. int i;
  14423. const char hexdigit[] = "0123456789abcdef";
  14424. if ((memlen <= 0) || (buflen <= 0)) {
  14425. return 0;
  14426. }
  14427. if (buflen < (3 * memlen)) {
  14428. return 0;
  14429. }
  14430. for (i = 0; i < memlen; i++) {
  14431. if (i > 0) {
  14432. buf[3 * i - 1] = ' ';
  14433. }
  14434. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14435. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14436. }
  14437. buf[3 * memlen - 1] = 0;
  14438. return 1;
  14439. }
  14440. static int
  14441. ssl_get_client_cert_info(const struct mg_connection *conn,
  14442. struct mg_client_cert *client_cert)
  14443. {
  14444. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14445. if (cert) {
  14446. char str_buf[1024];
  14447. unsigned char buf[256];
  14448. char *str_serial = NULL;
  14449. unsigned int ulen;
  14450. int ilen;
  14451. unsigned char *tmp_buf;
  14452. unsigned char *tmp_p;
  14453. /* Handle to algorithm used for fingerprint */
  14454. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14455. /* Get Subject and issuer */
  14456. X509_NAME *subj = X509_get_subject_name(cert);
  14457. X509_NAME *iss = X509_get_issuer_name(cert);
  14458. /* Get serial number */
  14459. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14460. /* Translate serial number to a hex string */
  14461. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14462. if (serial_bn) {
  14463. str_serial = BN_bn2hex(serial_bn);
  14464. BN_free(serial_bn);
  14465. }
  14466. client_cert->serial =
  14467. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14468. /* Translate subject and issuer to a string */
  14469. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14470. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14471. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14472. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14473. /* Calculate SHA1 fingerprint and store as a hex string */
  14474. ulen = 0;
  14475. /* ASN1_digest is deprecated. Do the calculation manually,
  14476. * using EVP_Digest. */
  14477. ilen = i2d_X509(cert, NULL);
  14478. tmp_buf = (ilen > 0)
  14479. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14480. conn->phys_ctx)
  14481. : NULL;
  14482. if (tmp_buf) {
  14483. tmp_p = tmp_buf;
  14484. (void)i2d_X509(cert, &tmp_p);
  14485. if (!EVP_Digest(
  14486. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14487. ulen = 0;
  14488. }
  14489. mg_free(tmp_buf);
  14490. }
  14491. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14492. *str_buf = 0;
  14493. }
  14494. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14495. client_cert->peer_cert = (void *)cert;
  14496. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14497. * see https://linux.die.net/man/3/bn_bn2hex */
  14498. OPENSSL_free(str_serial);
  14499. return 1;
  14500. }
  14501. return 0;
  14502. }
  14503. #if defined(OPENSSL_API_1_1)
  14504. #else
  14505. static void
  14506. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14507. {
  14508. (void)line;
  14509. (void)file;
  14510. if (mode & 1) {
  14511. /* 1 is CRYPTO_LOCK */
  14512. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14513. } else {
  14514. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14515. }
  14516. }
  14517. #endif /* OPENSSL_API_1_1 */
  14518. #if !defined(NO_SSL_DL)
  14519. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14520. static void *
  14521. load_tls_dll(char *ebuf,
  14522. size_t ebuf_len,
  14523. const char *dll_name,
  14524. struct ssl_func *sw,
  14525. int *feature_missing)
  14526. {
  14527. union {
  14528. void *p;
  14529. void (*fp)(void);
  14530. } u;
  14531. void *dll_handle;
  14532. struct ssl_func *fp;
  14533. int ok;
  14534. int truncated = 0;
  14535. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14536. mg_snprintf(NULL,
  14537. NULL, /* No truncation check for ebuf */
  14538. ebuf,
  14539. ebuf_len,
  14540. "%s: cannot load %s",
  14541. __func__,
  14542. dll_name);
  14543. return NULL;
  14544. }
  14545. ok = 1;
  14546. for (fp = sw; fp->name != NULL; fp++) {
  14547. #if defined(_WIN32)
  14548. /* GetProcAddress() returns pointer to function */
  14549. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14550. #else
  14551. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14552. * pointers to function pointers. We need to use a union to make a
  14553. * cast. */
  14554. u.p = dlsym(dll_handle, fp->name);
  14555. #endif /* _WIN32 */
  14556. /* Set pointer (might be NULL) */
  14557. fp->ptr = u.fp;
  14558. if (u.fp == NULL) {
  14559. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14560. if (feature_missing) {
  14561. feature_missing[fp->required]++;
  14562. }
  14563. if (fp->required == TLS_Mandatory) {
  14564. /* Mandatory function is missing */
  14565. if (ok) {
  14566. /* This is the first missing function.
  14567. * Create a new error message. */
  14568. mg_snprintf(NULL,
  14569. &truncated,
  14570. ebuf,
  14571. ebuf_len,
  14572. "%s: %s: cannot find %s",
  14573. __func__,
  14574. dll_name,
  14575. fp->name);
  14576. ok = 0;
  14577. } else {
  14578. /* This is yet anothermissing function.
  14579. * Append existing error message. */
  14580. size_t cur_len = strlen(ebuf);
  14581. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14582. mg_snprintf(NULL,
  14583. &truncated,
  14584. ebuf + cur_len,
  14585. ebuf_len - cur_len - 3,
  14586. ", %s",
  14587. fp->name);
  14588. if (truncated) {
  14589. /* If truncated, add "..." */
  14590. strcat(ebuf, "...");
  14591. }
  14592. }
  14593. }
  14594. }
  14595. }
  14596. }
  14597. if (!ok) {
  14598. (void)dlclose(dll_handle);
  14599. return NULL;
  14600. }
  14601. return dll_handle;
  14602. }
  14603. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14604. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14605. #endif /* NO_SSL_DL */
  14606. #if defined(SSL_ALREADY_INITIALIZED)
  14607. static volatile ptrdiff_t cryptolib_users =
  14608. 1; /* Reference counter for crypto library. */
  14609. #else
  14610. static volatile ptrdiff_t cryptolib_users =
  14611. 0; /* Reference counter for crypto library. */
  14612. #endif
  14613. static int
  14614. initialize_openssl(char *ebuf, size_t ebuf_len)
  14615. {
  14616. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14617. int i, num_locks;
  14618. size_t size;
  14619. #endif
  14620. if (ebuf_len > 0) {
  14621. ebuf[0] = 0;
  14622. }
  14623. #if !defined(NO_SSL_DL)
  14624. if (!cryptolib_dll_handle) {
  14625. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14626. cryptolib_dll_handle = load_tls_dll(
  14627. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14628. if (!cryptolib_dll_handle) {
  14629. mg_snprintf(NULL,
  14630. NULL, /* No truncation check for ebuf */
  14631. ebuf,
  14632. ebuf_len,
  14633. "%s: error loading library %s",
  14634. __func__,
  14635. CRYPTO_LIB);
  14636. DEBUG_TRACE("%s", ebuf);
  14637. return 0;
  14638. }
  14639. }
  14640. #endif /* NO_SSL_DL */
  14641. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14642. return 1;
  14643. }
  14644. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14645. /* Initialize locking callbacks, needed for thread safety.
  14646. * http://www.openssl.org/support/faq.html#PROG1
  14647. */
  14648. num_locks = CRYPTO_num_locks();
  14649. if (num_locks < 0) {
  14650. num_locks = 0;
  14651. }
  14652. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14653. /* allocate mutex array, if required */
  14654. if (num_locks == 0) {
  14655. /* No mutex array required */
  14656. ssl_mutexes = NULL;
  14657. } else {
  14658. /* Mutex array required - allocate it */
  14659. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14660. /* Check OOM */
  14661. if (ssl_mutexes == NULL) {
  14662. mg_snprintf(NULL,
  14663. NULL, /* No truncation check for ebuf */
  14664. ebuf,
  14665. ebuf_len,
  14666. "%s: cannot allocate mutexes: %s",
  14667. __func__,
  14668. ssl_error());
  14669. DEBUG_TRACE("%s", ebuf);
  14670. return 0;
  14671. }
  14672. /* initialize mutex array */
  14673. for (i = 0; i < num_locks; i++) {
  14674. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14675. mg_snprintf(NULL,
  14676. NULL, /* No truncation check for ebuf */
  14677. ebuf,
  14678. ebuf_len,
  14679. "%s: error initializing mutex %i of %i",
  14680. __func__,
  14681. i,
  14682. num_locks);
  14683. DEBUG_TRACE("%s", ebuf);
  14684. mg_free(ssl_mutexes);
  14685. return 0;
  14686. }
  14687. }
  14688. }
  14689. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14690. CRYPTO_set_id_callback(&mg_current_thread_id);
  14691. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14692. #if !defined(NO_SSL_DL)
  14693. if (!ssllib_dll_handle) {
  14694. ssllib_dll_handle =
  14695. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14696. if (!ssllib_dll_handle) {
  14697. #if !defined(OPENSSL_API_1_1)
  14698. mg_free(ssl_mutexes);
  14699. #endif
  14700. DEBUG_TRACE("%s", ebuf);
  14701. return 0;
  14702. }
  14703. }
  14704. #endif /* NO_SSL_DL */
  14705. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14706. && !defined(NO_SSL_DL)
  14707. /* Initialize SSL library */
  14708. OPENSSL_init_ssl(0, NULL);
  14709. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14710. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14711. NULL);
  14712. #else
  14713. /* Initialize SSL library */
  14714. SSL_library_init();
  14715. SSL_load_error_strings();
  14716. #endif
  14717. return 1;
  14718. }
  14719. static int
  14720. ssl_use_pem_file(struct mg_context *phys_ctx,
  14721. struct mg_domain_context *dom_ctx,
  14722. const char *pem,
  14723. const char *chain)
  14724. {
  14725. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14726. mg_cry_ctx_internal(phys_ctx,
  14727. "%s: cannot open certificate file %s: %s",
  14728. __func__,
  14729. pem,
  14730. ssl_error());
  14731. return 0;
  14732. }
  14733. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14734. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14735. mg_cry_ctx_internal(phys_ctx,
  14736. "%s: cannot open private key file %s: %s",
  14737. __func__,
  14738. pem,
  14739. ssl_error());
  14740. return 0;
  14741. }
  14742. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14743. mg_cry_ctx_internal(phys_ctx,
  14744. "%s: certificate and private key do not match: %s",
  14745. __func__,
  14746. pem);
  14747. return 0;
  14748. }
  14749. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14750. * chain files that contain private keys and certificates in
  14751. * SSL_CTX_use_certificate_chain_file.
  14752. * The CivetWeb-Server used pem-Files that contained both information.
  14753. * In order to make wolfSSL work, it is split in two files.
  14754. * One file that contains key and certificate used by the server and
  14755. * an optional chain file for the ssl stack.
  14756. */
  14757. if (chain) {
  14758. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14759. mg_cry_ctx_internal(phys_ctx,
  14760. "%s: cannot use certificate chain file %s: %s",
  14761. __func__,
  14762. chain,
  14763. ssl_error());
  14764. return 0;
  14765. }
  14766. }
  14767. return 1;
  14768. }
  14769. #if defined(OPENSSL_API_1_1)
  14770. static unsigned long
  14771. ssl_get_protocol(int version_id)
  14772. {
  14773. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14774. if (version_id > 0)
  14775. ret |= SSL_OP_NO_SSLv2;
  14776. if (version_id > 1)
  14777. ret |= SSL_OP_NO_SSLv3;
  14778. if (version_id > 2)
  14779. ret |= SSL_OP_NO_TLSv1;
  14780. if (version_id > 3)
  14781. ret |= SSL_OP_NO_TLSv1_1;
  14782. if (version_id > 4)
  14783. ret |= SSL_OP_NO_TLSv1_2;
  14784. #if defined(SSL_OP_NO_TLSv1_3)
  14785. if (version_id > 5)
  14786. ret |= SSL_OP_NO_TLSv1_3;
  14787. #endif
  14788. return ret;
  14789. }
  14790. #else
  14791. static long
  14792. ssl_get_protocol(int version_id)
  14793. {
  14794. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14795. if (version_id > 0)
  14796. ret |= SSL_OP_NO_SSLv2;
  14797. if (version_id > 1)
  14798. ret |= SSL_OP_NO_SSLv3;
  14799. if (version_id > 2)
  14800. ret |= SSL_OP_NO_TLSv1;
  14801. if (version_id > 3)
  14802. ret |= SSL_OP_NO_TLSv1_1;
  14803. if (version_id > 4)
  14804. ret |= SSL_OP_NO_TLSv1_2;
  14805. #if defined(SSL_OP_NO_TLSv1_3)
  14806. if (version_id > 5)
  14807. ret |= SSL_OP_NO_TLSv1_3;
  14808. #endif
  14809. return (long)ret;
  14810. }
  14811. #endif /* OPENSSL_API_1_1 */
  14812. /* SSL callback documentation:
  14813. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14814. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14815. * https://linux.die.net/man/3/ssl_set_info_callback */
  14816. /* Note: There is no "const" for the first argument in the documentation
  14817. * examples, however some (maybe most, but not all) headers of OpenSSL
  14818. * versions / OpenSSL compatibility layers have it. Having a different
  14819. * definition will cause a warning in C and an error in C++. Use "const SSL
  14820. * *", while automatical conversion from "SSL *" works for all compilers,
  14821. * but not other way around */
  14822. static void
  14823. ssl_info_callback(const SSL *ssl, int what, int ret)
  14824. {
  14825. (void)ret;
  14826. if (what & SSL_CB_HANDSHAKE_START) {
  14827. SSL_get_app_data(ssl);
  14828. }
  14829. if (what & SSL_CB_HANDSHAKE_DONE) {
  14830. /* TODO: check for openSSL 1.1 */
  14831. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14832. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14833. }
  14834. }
  14835. static int
  14836. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14837. {
  14838. #if defined(GCC_DIAGNOSTIC)
  14839. #pragma GCC diagnostic push
  14840. #pragma GCC diagnostic ignored "-Wcast-align"
  14841. #endif /* defined(GCC_DIAGNOSTIC) */
  14842. /* We used an aligned pointer in SSL_set_app_data */
  14843. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14844. #if defined(GCC_DIAGNOSTIC)
  14845. #pragma GCC diagnostic pop
  14846. #endif /* defined(GCC_DIAGNOSTIC) */
  14847. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14848. (void)ad;
  14849. (void)arg;
  14850. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14851. DEBUG_ASSERT(0);
  14852. return SSL_TLSEXT_ERR_NOACK;
  14853. }
  14854. conn->dom_ctx = &(conn->phys_ctx->dd);
  14855. /* Old clients (Win XP) will not support SNI. Then, there
  14856. * is no server name available in the request - we can
  14857. * only work with the default certificate.
  14858. * Multiple HTTPS hosts on one IP+port are only possible
  14859. * with a certificate containing all alternative names.
  14860. */
  14861. if ((servername == NULL) || (*servername == 0)) {
  14862. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14863. mg_lock_context(conn->phys_ctx);
  14864. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14865. mg_unlock_context(conn->phys_ctx);
  14866. return SSL_TLSEXT_ERR_NOACK;
  14867. }
  14868. DEBUG_TRACE("TLS connection to host %s", servername);
  14869. while (conn->dom_ctx) {
  14870. if (!mg_strcasecmp(servername,
  14871. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14872. /* Found matching domain */
  14873. DEBUG_TRACE("TLS domain %s found",
  14874. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14875. break;
  14876. }
  14877. mg_lock_context(conn->phys_ctx);
  14878. conn->dom_ctx = conn->dom_ctx->next;
  14879. mg_unlock_context(conn->phys_ctx);
  14880. }
  14881. if (conn->dom_ctx == NULL) {
  14882. /* Default domain */
  14883. DEBUG_TRACE("TLS default domain %s used",
  14884. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14885. conn->dom_ctx = &(conn->phys_ctx->dd);
  14886. }
  14887. mg_lock_context(conn->phys_ctx);
  14888. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14889. mg_unlock_context(conn->phys_ctx);
  14890. return SSL_TLSEXT_ERR_OK;
  14891. }
  14892. #if defined(USE_ALPN)
  14893. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14894. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14895. alpn_proto_list + 3 + 8,
  14896. NULL};
  14897. #if defined(USE_HTTP2)
  14898. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14899. alpn_proto_list + 3,
  14900. alpn_proto_list + 3 + 8,
  14901. NULL};
  14902. #endif
  14903. static int
  14904. alpn_select_cb(SSL *ssl,
  14905. const unsigned char **out,
  14906. unsigned char *outlen,
  14907. const unsigned char *in,
  14908. unsigned int inlen,
  14909. void *arg)
  14910. {
  14911. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14912. unsigned int i, j, enable_http2 = 0;
  14913. const char **alpn_proto_order = alpn_proto_order_http1;
  14914. struct mg_workerTLS *tls =
  14915. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14916. (void)ssl;
  14917. if (tls == NULL) {
  14918. /* Need to store protocol in Thread Local Storage */
  14919. /* If there is no Thread Local Storage, don't use ALPN */
  14920. return SSL_TLSEXT_ERR_NOACK;
  14921. }
  14922. #if defined(USE_HTTP2)
  14923. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14924. if (enable_http2) {
  14925. alpn_proto_order = alpn_proto_order_http2;
  14926. }
  14927. #endif
  14928. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14929. /* check all accepted protocols in this order */
  14930. const char *alpn_proto = alpn_proto_order[j];
  14931. /* search input for matching protocol */
  14932. for (i = 0; i < inlen; i++) {
  14933. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14934. *out = in + i + 1;
  14935. *outlen = in[i];
  14936. tls->alpn_proto = alpn_proto;
  14937. return SSL_TLSEXT_ERR_OK;
  14938. }
  14939. }
  14940. }
  14941. /* Nothing found */
  14942. return SSL_TLSEXT_ERR_NOACK;
  14943. }
  14944. static int
  14945. next_protos_advertised_cb(SSL *ssl,
  14946. const unsigned char **data,
  14947. unsigned int *len,
  14948. void *arg)
  14949. {
  14950. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14951. *data = (const unsigned char *)alpn_proto_list;
  14952. *len = (unsigned int)strlen((const char *)data);
  14953. (void)ssl;
  14954. (void)dom_ctx;
  14955. return SSL_TLSEXT_ERR_OK;
  14956. }
  14957. static int
  14958. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14959. {
  14960. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14961. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14962. (const unsigned char *)alpn_proto_list,
  14963. alpn_len);
  14964. if (ret != 0) {
  14965. mg_cry_ctx_internal(phys_ctx,
  14966. "SSL_CTX_set_alpn_protos error: %s",
  14967. ssl_error());
  14968. }
  14969. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14970. alpn_select_cb,
  14971. (void *)dom_ctx);
  14972. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14973. next_protos_advertised_cb,
  14974. (void *)dom_ctx);
  14975. return ret;
  14976. }
  14977. #endif
  14978. /* Setup SSL CTX as required by CivetWeb */
  14979. static int
  14980. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14981. struct mg_domain_context *dom_ctx,
  14982. const char *pem,
  14983. const char *chain)
  14984. {
  14985. int callback_ret;
  14986. int should_verify_peer;
  14987. int peer_certificate_optional;
  14988. const char *ca_path;
  14989. const char *ca_file;
  14990. int use_default_verify_paths;
  14991. int verify_depth;
  14992. struct timespec now_mt;
  14993. md5_byte_t ssl_context_id[16];
  14994. md5_state_t md5state;
  14995. int protocol_ver;
  14996. int ssl_cache_timeout;
  14997. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14998. && !defined(NO_SSL_DL)
  14999. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15000. mg_cry_ctx_internal(phys_ctx,
  15001. "SSL_CTX_new (server) error: %s",
  15002. ssl_error());
  15003. return 0;
  15004. }
  15005. #else
  15006. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15007. mg_cry_ctx_internal(phys_ctx,
  15008. "SSL_CTX_new (server) error: %s",
  15009. ssl_error());
  15010. return 0;
  15011. }
  15012. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15013. #if defined(SSL_OP_NO_TLSv1_3)
  15014. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15015. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15016. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15017. | SSL_OP_NO_TLSv1_3);
  15018. #else
  15019. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15020. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15021. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15022. #endif
  15023. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15024. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15025. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15026. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15027. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15028. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15029. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15030. #if defined(SSL_OP_NO_RENEGOTIATION)
  15031. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15032. #endif
  15033. #if !defined(NO_SSL_DL)
  15034. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15035. #endif /* NO_SSL_DL */
  15036. /* In SSL documentation examples callback defined without const
  15037. * specifier 'void (*)(SSL *, int, int)' See:
  15038. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15039. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15040. * But in the source code const SSL is used:
  15041. * 'void (*)(const SSL *, int, int)' See:
  15042. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15043. * Problem about wrong documentation described, but not resolved:
  15044. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15045. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15046. * But when compiled with modern C++ compiler, correct const should be
  15047. * provided
  15048. */
  15049. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15050. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15051. ssl_servername_callback);
  15052. /* If a callback has been specified, call it. */
  15053. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15054. ? 0
  15055. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15056. phys_ctx->user_data));
  15057. /* If callback returns 0, civetweb sets up the SSL certificate.
  15058. * If it returns 1, civetweb assumes the calback already did this.
  15059. * If it returns -1, initializing ssl fails. */
  15060. if (callback_ret < 0) {
  15061. mg_cry_ctx_internal(phys_ctx,
  15062. "SSL callback returned error: %i",
  15063. callback_ret);
  15064. return 0;
  15065. }
  15066. if (callback_ret > 0) {
  15067. /* Callback did everything. */
  15068. return 1;
  15069. }
  15070. /* If a domain callback has been specified, call it. */
  15071. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15072. ? 0
  15073. : (phys_ctx->callbacks.init_ssl_domain(
  15074. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15075. dom_ctx->ssl_ctx,
  15076. phys_ctx->user_data));
  15077. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15078. * If it returns 1, civetweb assumes the calback already did this.
  15079. * If it returns -1, initializing ssl fails. */
  15080. if (callback_ret < 0) {
  15081. mg_cry_ctx_internal(phys_ctx,
  15082. "Domain SSL callback returned error: %i",
  15083. callback_ret);
  15084. return 0;
  15085. }
  15086. if (callback_ret > 0) {
  15087. /* Domain callback did everything. */
  15088. return 1;
  15089. }
  15090. /* Use some combination of start time, domain and port as a SSL
  15091. * context ID. This should be unique on the current machine. */
  15092. md5_init(&md5state);
  15093. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15094. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15095. md5_append(&md5state,
  15096. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15097. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15098. md5_append(&md5state,
  15099. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15100. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15101. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15102. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15103. md5_finish(&md5state, ssl_context_id);
  15104. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15105. (unsigned char *)ssl_context_id,
  15106. sizeof(ssl_context_id));
  15107. if (pem != NULL) {
  15108. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15109. return 0;
  15110. }
  15111. }
  15112. /* Should we support client certificates? */
  15113. /* Default is "no". */
  15114. should_verify_peer = 0;
  15115. peer_certificate_optional = 0;
  15116. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15117. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15118. /* Yes, they are mandatory */
  15119. should_verify_peer = 1;
  15120. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15121. "optional")
  15122. == 0) {
  15123. /* Yes, they are optional */
  15124. should_verify_peer = 1;
  15125. peer_certificate_optional = 1;
  15126. }
  15127. }
  15128. use_default_verify_paths =
  15129. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15130. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15131. == 0);
  15132. if (should_verify_peer) {
  15133. ca_path = dom_ctx->config[SSL_CA_PATH];
  15134. ca_file = dom_ctx->config[SSL_CA_FILE];
  15135. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15136. != 1) {
  15137. mg_cry_ctx_internal(phys_ctx,
  15138. "SSL_CTX_load_verify_locations error: %s "
  15139. "ssl_verify_peer requires setting "
  15140. "either ssl_ca_path or ssl_ca_file. "
  15141. "Is any of them present in the "
  15142. ".conf file?",
  15143. ssl_error());
  15144. return 0;
  15145. }
  15146. if (peer_certificate_optional) {
  15147. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15148. } else {
  15149. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15150. SSL_VERIFY_PEER
  15151. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15152. NULL);
  15153. }
  15154. if (use_default_verify_paths
  15155. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15156. mg_cry_ctx_internal(phys_ctx,
  15157. "SSL_CTX_set_default_verify_paths error: %s",
  15158. ssl_error());
  15159. return 0;
  15160. }
  15161. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15162. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15163. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15164. }
  15165. }
  15166. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15167. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15168. dom_ctx->config[SSL_CIPHER_LIST])
  15169. != 1) {
  15170. mg_cry_ctx_internal(phys_ctx,
  15171. "SSL_CTX_set_cipher_list error: %s",
  15172. ssl_error());
  15173. }
  15174. }
  15175. /* SSL session caching */
  15176. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15177. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15178. : 0);
  15179. if (ssl_cache_timeout > 0) {
  15180. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15181. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15182. * default */
  15183. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15184. }
  15185. #if defined(USE_ALPN)
  15186. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15187. #if !defined(NO_SSL_DL)
  15188. if (!tls_feature_missing[TLS_ALPN])
  15189. #endif
  15190. {
  15191. init_alpn(phys_ctx, dom_ctx);
  15192. }
  15193. #endif
  15194. return 1;
  15195. }
  15196. /* Check if SSL is required.
  15197. * If so, dynamically load SSL library
  15198. * and set up ctx->ssl_ctx pointer. */
  15199. static int
  15200. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15201. {
  15202. void *ssl_ctx = 0;
  15203. int callback_ret;
  15204. const char *pem;
  15205. const char *chain;
  15206. char ebuf[128];
  15207. if (!phys_ctx) {
  15208. return 0;
  15209. }
  15210. if (!dom_ctx) {
  15211. dom_ctx = &(phys_ctx->dd);
  15212. }
  15213. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15214. /* No SSL port is set. No need to setup SSL. */
  15215. return 1;
  15216. }
  15217. /* Check for external SSL_CTX */
  15218. callback_ret =
  15219. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15220. ? 0
  15221. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15222. phys_ctx->user_data));
  15223. if (callback_ret < 0) {
  15224. /* Callback exists and returns <0: Initializing failed. */
  15225. mg_cry_ctx_internal(phys_ctx,
  15226. "external_ssl_ctx callback returned error: %i",
  15227. callback_ret);
  15228. return 0;
  15229. } else if (callback_ret > 0) {
  15230. /* Callback exists and returns >0: Initializing complete,
  15231. * civetweb should not modify the SSL context. */
  15232. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15233. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15234. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15235. return 0;
  15236. }
  15237. return 1;
  15238. }
  15239. /* If the callback does not exist or return 0, civetweb must initialize
  15240. * the SSL context. Handle "domain" callback next. */
  15241. /* Check for external domain SSL_CTX callback. */
  15242. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15243. ? 0
  15244. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15245. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15246. &ssl_ctx,
  15247. phys_ctx->user_data));
  15248. if (callback_ret < 0) {
  15249. /* Callback < 0: Error. Abort init. */
  15250. mg_cry_ctx_internal(
  15251. phys_ctx,
  15252. "external_ssl_ctx_domain callback returned error: %i",
  15253. callback_ret);
  15254. return 0;
  15255. } else if (callback_ret > 0) {
  15256. /* Callback > 0: Consider init done. */
  15257. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15258. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15259. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15260. return 0;
  15261. }
  15262. return 1;
  15263. }
  15264. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15265. * 0, CivetWeb should continue initializing SSL */
  15266. /* If PEM file is not specified and the init_ssl callbacks
  15267. * are not specified, setup will fail. */
  15268. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15269. && (phys_ctx->callbacks.init_ssl == NULL)
  15270. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15271. /* No certificate and no init_ssl callbacks:
  15272. * Essential data to set up TLS is missing.
  15273. */
  15274. mg_cry_ctx_internal(phys_ctx,
  15275. "Initializing SSL failed: -%s is not set",
  15276. config_options[SSL_CERTIFICATE].name);
  15277. return 0;
  15278. }
  15279. /* If a certificate chain is configured, use it. */
  15280. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15281. if (chain == NULL) {
  15282. /* Default: certificate chain in PEM file */
  15283. chain = pem;
  15284. }
  15285. if ((chain != NULL) && (*chain == 0)) {
  15286. /* If the chain is an empty string, don't use it. */
  15287. chain = NULL;
  15288. }
  15289. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15290. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15291. return 0;
  15292. }
  15293. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15294. }
  15295. static void
  15296. uninitialize_openssl(void)
  15297. {
  15298. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15299. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15300. /* Shutdown according to
  15301. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15302. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15303. */
  15304. CONF_modules_unload(1);
  15305. #else
  15306. int i;
  15307. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15308. /* Shutdown according to
  15309. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15310. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15311. */
  15312. CRYPTO_set_locking_callback(NULL);
  15313. CRYPTO_set_id_callback(NULL);
  15314. ENGINE_cleanup();
  15315. CONF_modules_unload(1);
  15316. ERR_free_strings();
  15317. EVP_cleanup();
  15318. CRYPTO_cleanup_all_ex_data();
  15319. OPENSSL_REMOVE_THREAD_STATE();
  15320. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15321. pthread_mutex_destroy(&ssl_mutexes[i]);
  15322. }
  15323. mg_free(ssl_mutexes);
  15324. ssl_mutexes = NULL;
  15325. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15326. }
  15327. }
  15328. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15329. #if !defined(NO_FILESYSTEMS)
  15330. static int
  15331. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15332. {
  15333. if (phys_ctx) {
  15334. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15335. const char *path;
  15336. struct mg_connection fc;
  15337. if (!dom_ctx) {
  15338. dom_ctx = &(phys_ctx->dd);
  15339. }
  15340. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15341. if ((path != NULL)
  15342. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15343. mg_cry_ctx_internal(phys_ctx,
  15344. "Cannot open %s: %s",
  15345. path,
  15346. strerror(ERRNO));
  15347. return 0;
  15348. }
  15349. return 1;
  15350. }
  15351. return 0;
  15352. }
  15353. #endif /* NO_FILESYSTEMS */
  15354. static int
  15355. set_acl_option(struct mg_context *phys_ctx)
  15356. {
  15357. union usa sa;
  15358. memset(&sa, 0, sizeof(sa));
  15359. #if defined(USE_IPV6)
  15360. sa.sin6.sin6_family = AF_INET6;
  15361. #else
  15362. sa.sin.sin_family = AF_INET;
  15363. #endif
  15364. return check_acl(phys_ctx, &sa) != -1;
  15365. }
  15366. static void
  15367. reset_per_request_attributes(struct mg_connection *conn)
  15368. {
  15369. if (!conn) {
  15370. return;
  15371. }
  15372. conn->num_bytes_sent = conn->consumed_content = 0;
  15373. conn->path_info = NULL;
  15374. conn->status_code = -1;
  15375. conn->content_len = -1;
  15376. conn->is_chunked = 0;
  15377. conn->must_close = 0;
  15378. conn->request_len = 0;
  15379. conn->request_state = 0;
  15380. conn->throttle = 0;
  15381. conn->accept_gzip = 0;
  15382. conn->response_info.content_length = conn->request_info.content_length = -1;
  15383. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15384. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15385. conn->response_info.status_text = NULL;
  15386. conn->response_info.status_code = 0;
  15387. conn->request_info.remote_user = NULL;
  15388. conn->request_info.request_method = NULL;
  15389. conn->request_info.request_uri = NULL;
  15390. /* Free cleaned local URI (if any) */
  15391. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15392. mg_free((void *)conn->request_info.local_uri);
  15393. conn->request_info.local_uri = NULL;
  15394. }
  15395. conn->request_info.local_uri = NULL;
  15396. #if defined(USE_SERVER_STATS)
  15397. conn->processing_time = 0;
  15398. #endif
  15399. }
  15400. static int
  15401. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15402. {
  15403. if ((so->lsa.sa.sa_family == AF_INET)
  15404. || (so->lsa.sa.sa_family == AF_INET6)) {
  15405. /* Only for TCP sockets */
  15406. if (setsockopt(so->sock,
  15407. IPPROTO_TCP,
  15408. TCP_NODELAY,
  15409. (SOCK_OPT_TYPE)&nodelay_on,
  15410. sizeof(nodelay_on))
  15411. != 0) {
  15412. /* Error */
  15413. return 1;
  15414. }
  15415. }
  15416. /* OK */
  15417. return 0;
  15418. }
  15419. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  15420. static void
  15421. close_socket_gracefully(struct mg_connection *conn)
  15422. {
  15423. #if defined(_WIN32)
  15424. char buf[MG_BUF_LEN];
  15425. int n;
  15426. #endif
  15427. struct linger linger;
  15428. int error_code = 0;
  15429. int linger_timeout = -2;
  15430. socklen_t opt_len = sizeof(error_code);
  15431. if (!conn) {
  15432. return;
  15433. }
  15434. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15435. * "Note that enabling a nonzero timeout on a nonblocking socket
  15436. * is not recommended.", so set it to blocking now */
  15437. set_blocking_mode(conn->client.sock);
  15438. /* Send FIN to the client */
  15439. shutdown(conn->client.sock, SHUTDOWN_WR);
  15440. #if defined(_WIN32)
  15441. /* Read and discard pending incoming data. If we do not do that and
  15442. * close
  15443. * the socket, the data in the send buffer may be discarded. This
  15444. * behaviour is seen on Windows, when client keeps sending data
  15445. * when server decides to close the connection; then when client
  15446. * does recv() it gets no data back. */
  15447. do {
  15448. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15449. } while (n > 0);
  15450. #endif
  15451. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15452. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15453. }
  15454. /* Set linger option according to configuration */
  15455. if (linger_timeout >= 0) {
  15456. /* Set linger option to avoid socket hanging out after close. This
  15457. * prevent ephemeral port exhaust problem under high QPS. */
  15458. linger.l_onoff = 1;
  15459. #if defined(_MSC_VER)
  15460. #pragma warning(push)
  15461. #pragma warning(disable : 4244)
  15462. #endif
  15463. #if defined(GCC_DIAGNOSTIC)
  15464. #pragma GCC diagnostic push
  15465. #pragma GCC diagnostic ignored "-Wconversion"
  15466. #endif
  15467. /* Data type of linger structure elements may differ,
  15468. * so we don't know what cast we need here.
  15469. * Disable type conversion warnings. */
  15470. linger.l_linger = (linger_timeout + 999) / 1000;
  15471. #if defined(GCC_DIAGNOSTIC)
  15472. #pragma GCC diagnostic pop
  15473. #endif
  15474. #if defined(_MSC_VER)
  15475. #pragma warning(pop)
  15476. #endif
  15477. } else {
  15478. linger.l_onoff = 0;
  15479. linger.l_linger = 0;
  15480. }
  15481. if (linger_timeout < -1) {
  15482. /* Default: don't configure any linger */
  15483. } else if (getsockopt(conn->client.sock,
  15484. SOL_SOCKET,
  15485. SO_ERROR,
  15486. #if defined(_WIN32) /* WinSock uses different data type here */
  15487. (char *)&error_code,
  15488. #else
  15489. &error_code,
  15490. #endif
  15491. &opt_len)
  15492. != 0) {
  15493. /* Cannot determine if socket is already closed. This should
  15494. * not occur and never did in a test. Log an error message
  15495. * and continue. */
  15496. mg_cry_internal(conn,
  15497. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15498. __func__,
  15499. strerror(ERRNO));
  15500. #if defined(_WIN32)
  15501. } else if (error_code == WSAECONNRESET) {
  15502. #else
  15503. } else if (error_code == ECONNRESET) {
  15504. #endif
  15505. /* Socket already closed by client/peer, close socket without linger
  15506. */
  15507. } else {
  15508. /* Set linger timeout */
  15509. if (setsockopt(conn->client.sock,
  15510. SOL_SOCKET,
  15511. SO_LINGER,
  15512. (char *)&linger,
  15513. sizeof(linger))
  15514. != 0) {
  15515. mg_cry_internal(
  15516. conn,
  15517. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15518. __func__,
  15519. linger.l_onoff,
  15520. linger.l_linger,
  15521. strerror(ERRNO));
  15522. }
  15523. }
  15524. /* Now we know that our FIN is ACK-ed, safe to close */
  15525. closesocket(conn->client.sock);
  15526. conn->client.sock = INVALID_SOCKET;
  15527. }
  15528. #endif
  15529. static void
  15530. close_connection(struct mg_connection *conn)
  15531. {
  15532. #if defined(USE_SERVER_STATS)
  15533. conn->conn_state = 6; /* to close */
  15534. #endif
  15535. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15536. if (conn->lua_websocket_state) {
  15537. lua_websocket_close(conn, conn->lua_websocket_state);
  15538. conn->lua_websocket_state = NULL;
  15539. }
  15540. #endif
  15541. mg_lock_connection(conn);
  15542. /* Set close flag, so keep-alive loops will stop */
  15543. conn->must_close = 1;
  15544. /* call the connection_close callback if assigned */
  15545. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15546. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15547. conn->phys_ctx->callbacks.connection_close(conn);
  15548. }
  15549. }
  15550. /* Reset user data, after close callback is called.
  15551. * Do not reuse it. If the user needs a destructor,
  15552. * it must be done in the connection_close callback. */
  15553. mg_set_user_connection_data(conn, NULL);
  15554. #if defined(USE_SERVER_STATS)
  15555. conn->conn_state = 7; /* closing */
  15556. #endif
  15557. #if defined(USE_MBEDTLS)
  15558. if (conn->ssl != NULL) {
  15559. mbed_ssl_close(conn->ssl);
  15560. conn->ssl = NULL;
  15561. }
  15562. #elif !defined(NO_SSL)
  15563. if (conn->ssl != NULL) {
  15564. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15565. */
  15566. SSL_shutdown(conn->ssl);
  15567. SSL_free(conn->ssl);
  15568. OPENSSL_REMOVE_THREAD_STATE();
  15569. conn->ssl = NULL;
  15570. }
  15571. #endif
  15572. if (conn->client.sock != INVALID_SOCKET) {
  15573. #if defined(__ZEPHYR__) || defined(ESP_PLATFORM)
  15574. closesocket(conn->client.sock);
  15575. #else
  15576. close_socket_gracefully(conn);
  15577. #endif
  15578. conn->client.sock = INVALID_SOCKET;
  15579. }
  15580. /* call the connection_closed callback if assigned */
  15581. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15582. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15583. conn->phys_ctx->callbacks.connection_closed(conn);
  15584. }
  15585. }
  15586. mg_unlock_connection(conn);
  15587. #if defined(USE_SERVER_STATS)
  15588. conn->conn_state = 8; /* closed */
  15589. #endif
  15590. }
  15591. CIVETWEB_API void
  15592. mg_close_connection(struct mg_connection *conn)
  15593. {
  15594. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15595. return;
  15596. }
  15597. #if defined(USE_WEBSOCKET)
  15598. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15599. if (conn->in_websocket_handling) {
  15600. /* Set close flag, so the server thread can exit. */
  15601. conn->must_close = 1;
  15602. return;
  15603. }
  15604. }
  15605. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15606. unsigned int i;
  15607. /* client context: loops must end */
  15608. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15609. conn->must_close = 1;
  15610. /* We need to get the client thread out of the select/recv call
  15611. * here. */
  15612. /* Since we use a sleep quantum of some seconds to check for recv
  15613. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15614. /* join worker thread */
  15615. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15616. // mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15617. }
  15618. }
  15619. #endif /* defined(USE_WEBSOCKET) */
  15620. close_connection(conn);
  15621. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15622. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15623. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15624. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15625. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15626. }
  15627. #endif
  15628. #if defined(USE_WEBSOCKET)
  15629. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15630. mg_free(conn->phys_ctx->worker_threadids);
  15631. (void)pthread_mutex_destroy(&conn->mutex);
  15632. mg_free(conn);
  15633. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15634. (void)pthread_mutex_destroy(&conn->mutex);
  15635. mg_free(conn);
  15636. }
  15637. #else
  15638. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15639. (void)pthread_mutex_destroy(&conn->mutex);
  15640. mg_free(conn);
  15641. }
  15642. #endif /* defined(USE_WEBSOCKET) */
  15643. }
  15644. static struct mg_connection *
  15645. mg_connect_client_impl(const struct mg_client_options *client_options,
  15646. int use_ssl,
  15647. struct mg_init_data *init,
  15648. struct mg_error_data *error)
  15649. {
  15650. struct mg_connection *conn = NULL;
  15651. SOCKET sock;
  15652. union usa sa;
  15653. struct sockaddr *psa;
  15654. socklen_t len;
  15655. unsigned max_req_size =
  15656. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15657. /* Size of structures, aligned to 8 bytes */
  15658. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15659. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15660. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15661. (void)init; /* TODO: Implement required options */
  15662. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15663. if (error != NULL) {
  15664. error->code = MG_ERROR_DATA_CODE_OK;
  15665. error->code_sub = 0;
  15666. if (error->text_buffer_size > 0) {
  15667. error->text[0] = 0;
  15668. }
  15669. }
  15670. if (conn == NULL) {
  15671. if (error != NULL) {
  15672. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15673. error->code_sub = (unsigned)alloc_size;
  15674. mg_snprintf(NULL,
  15675. NULL, /* No truncation check for ebuf */
  15676. error->text,
  15677. error->text_buffer_size,
  15678. "calloc(): %s",
  15679. strerror(ERRNO));
  15680. }
  15681. return NULL;
  15682. }
  15683. #if defined(GCC_DIAGNOSTIC)
  15684. #pragma GCC diagnostic push
  15685. #pragma GCC diagnostic ignored "-Wcast-align"
  15686. #endif /* defined(GCC_DIAGNOSTIC) */
  15687. /* conn_size is aligned to 8 bytes */
  15688. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15689. #if defined(GCC_DIAGNOSTIC)
  15690. #pragma GCC diagnostic pop
  15691. #endif /* defined(GCC_DIAGNOSTIC) */
  15692. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15693. conn->buf_size = (int)max_req_size;
  15694. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15695. conn->dom_ctx = &(conn->phys_ctx->dd);
  15696. if (!connect_socket(conn->phys_ctx,
  15697. client_options->host,
  15698. client_options->port,
  15699. use_ssl,
  15700. error,
  15701. &sock,
  15702. &sa)) {
  15703. /* "error" will be set by connect_socket. */
  15704. /* free all memory and return NULL; */
  15705. mg_free(conn);
  15706. return NULL;
  15707. }
  15708. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15709. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15710. && !defined(NO_SSL_DL)
  15711. if (use_ssl
  15712. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15713. == NULL) {
  15714. if (error != NULL) {
  15715. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15716. mg_snprintf(NULL,
  15717. NULL, /* No truncation check for ebuf */
  15718. error->text,
  15719. error->text_buffer_size,
  15720. "SSL_CTX_new error: %s",
  15721. ssl_error());
  15722. }
  15723. closesocket(sock);
  15724. mg_free(conn);
  15725. return NULL;
  15726. }
  15727. #else
  15728. if (use_ssl
  15729. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15730. == NULL) {
  15731. if (error != NULL) {
  15732. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15733. mg_snprintf(NULL,
  15734. NULL, /* No truncation check for ebuf */
  15735. error->text,
  15736. error->text_buffer_size,
  15737. "SSL_CTX_new error: %s",
  15738. ssl_error());
  15739. }
  15740. closesocket(sock);
  15741. mg_free(conn);
  15742. return NULL;
  15743. }
  15744. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15745. #endif /* NO_SSL */
  15746. #if defined(USE_IPV6)
  15747. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15748. : sizeof(conn->client.rsa.sin6);
  15749. psa = (sa.sa.sa_family == AF_INET)
  15750. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15751. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15752. #else
  15753. len = sizeof(conn->client.rsa.sin);
  15754. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15755. #endif
  15756. conn->client.sock = sock;
  15757. conn->client.lsa = sa;
  15758. if (getsockname(sock, psa, &len) != 0) {
  15759. mg_cry_internal(conn,
  15760. "%s: getsockname() failed: %s",
  15761. __func__,
  15762. strerror(ERRNO));
  15763. }
  15764. conn->client.is_ssl = use_ssl ? 1 : 0;
  15765. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15766. if (error != NULL) {
  15767. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15768. error->code_sub = (unsigned)ERRNO;
  15769. mg_snprintf(NULL,
  15770. NULL, /* No truncation check for ebuf */
  15771. error->text,
  15772. error->text_buffer_size,
  15773. "Can not create mutex");
  15774. }
  15775. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15776. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15777. #endif
  15778. closesocket(sock);
  15779. mg_free(conn);
  15780. return NULL;
  15781. }
  15782. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15783. if (use_ssl) {
  15784. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15785. * SSL_CTX_set_verify call is needed to switch off server
  15786. * certificate checking, which is off by default in OpenSSL and
  15787. * on in yaSSL. */
  15788. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15789. * SSL_VERIFY_PEER, verify_ssl_server); */
  15790. if (client_options->client_cert) {
  15791. if (!ssl_use_pem_file(conn->phys_ctx,
  15792. conn->dom_ctx,
  15793. client_options->client_cert,
  15794. NULL)) {
  15795. if (error != NULL) {
  15796. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15797. mg_snprintf(NULL,
  15798. NULL, /* No truncation check for ebuf */
  15799. error->text,
  15800. error->text_buffer_size,
  15801. "Can not use SSL client certificate");
  15802. }
  15803. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15804. closesocket(sock);
  15805. mg_free(conn);
  15806. return NULL;
  15807. }
  15808. }
  15809. if (client_options->server_cert) {
  15810. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15811. client_options->server_cert,
  15812. NULL)
  15813. != 1) {
  15814. if (error != NULL) {
  15815. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15816. mg_snprintf(NULL,
  15817. NULL, /* No truncation check for ebuf */
  15818. error->text,
  15819. error->text_buffer_size,
  15820. "SSL_CTX_load_verify_locations error: %s",
  15821. ssl_error());
  15822. }
  15823. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15824. closesocket(sock);
  15825. mg_free(conn);
  15826. return NULL;
  15827. }
  15828. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15829. } else {
  15830. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15831. }
  15832. if (!sslize(conn, SSL_connect, client_options)) {
  15833. if (error != NULL) {
  15834. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15835. mg_snprintf(NULL,
  15836. NULL, /* No truncation check for ebuf */
  15837. error->text,
  15838. error->text_buffer_size,
  15839. "SSL connection error");
  15840. }
  15841. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15842. closesocket(sock);
  15843. mg_free(conn);
  15844. return NULL;
  15845. }
  15846. }
  15847. #endif
  15848. return conn;
  15849. }
  15850. CIVETWEB_API struct mg_connection *
  15851. mg_connect_client_secure(const struct mg_client_options *client_options,
  15852. char *error_buffer,
  15853. size_t error_buffer_size)
  15854. {
  15855. struct mg_init_data init;
  15856. struct mg_error_data error;
  15857. memset(&init, 0, sizeof(init));
  15858. memset(&error, 0, sizeof(error));
  15859. error.text_buffer_size = error_buffer_size;
  15860. error.text = error_buffer;
  15861. return mg_connect_client_impl(client_options, 1, &init, &error);
  15862. }
  15863. CIVETWEB_API struct mg_connection *
  15864. mg_connect_client(const char *host,
  15865. int port,
  15866. int use_ssl,
  15867. char *error_buffer,
  15868. size_t error_buffer_size)
  15869. {
  15870. struct mg_client_options opts;
  15871. struct mg_init_data init;
  15872. struct mg_error_data error;
  15873. memset(&init, 0, sizeof(init));
  15874. memset(&error, 0, sizeof(error));
  15875. error.text_buffer_size = error_buffer_size;
  15876. error.text = error_buffer;
  15877. memset(&opts, 0, sizeof(opts));
  15878. opts.host = host;
  15879. opts.port = port;
  15880. if (use_ssl) {
  15881. opts.host_name = host;
  15882. }
  15883. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15884. }
  15885. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15886. CIVETWEB_API struct mg_connection *
  15887. mg_connect_client2(const char *host,
  15888. const char *protocol,
  15889. int port,
  15890. const char *path,
  15891. struct mg_init_data *init,
  15892. struct mg_error_data *error)
  15893. {
  15894. (void)path;
  15895. int is_ssl, is_ws;
  15896. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15897. if (error != NULL) {
  15898. error->code = MG_ERROR_DATA_CODE_OK;
  15899. error->code_sub = 0;
  15900. if (error->text_buffer_size > 0) {
  15901. *error->text = 0;
  15902. }
  15903. }
  15904. if ((host == NULL) || (protocol == NULL)) {
  15905. if (error != NULL) {
  15906. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15907. mg_snprintf(NULL,
  15908. NULL, /* No truncation check for error buffers */
  15909. error->text,
  15910. error->text_buffer_size,
  15911. "%s",
  15912. "Invalid parameters");
  15913. }
  15914. return NULL;
  15915. }
  15916. /* check all known protocolls */
  15917. if (!mg_strcasecmp(protocol, "http")) {
  15918. is_ssl = 0;
  15919. is_ws = 0;
  15920. } else if (!mg_strcasecmp(protocol, "https")) {
  15921. is_ssl = 1;
  15922. is_ws = 0;
  15923. #if defined(USE_WEBSOCKET)
  15924. } else if (!mg_strcasecmp(protocol, "ws")) {
  15925. is_ssl = 0;
  15926. is_ws = 1;
  15927. } else if (!mg_strcasecmp(protocol, "wss")) {
  15928. is_ssl = 1;
  15929. is_ws = 1;
  15930. #endif
  15931. } else {
  15932. if (error != NULL) {
  15933. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15934. mg_snprintf(NULL,
  15935. NULL, /* No truncation check for error buffers */
  15936. error->text,
  15937. error->text_buffer_size,
  15938. "Protocol %s not supported",
  15939. protocol);
  15940. }
  15941. return NULL;
  15942. }
  15943. /* TODO: The current implementation here just calls the old
  15944. * implementations, without using any new options. This is just a first
  15945. * step to test the new interfaces. */
  15946. #if defined(USE_WEBSOCKET)
  15947. if (is_ws) {
  15948. /* TODO: implement all options */
  15949. return mg_connect_websocket_client(
  15950. host,
  15951. port,
  15952. is_ssl,
  15953. ((error != NULL) ? error->text : NULL),
  15954. ((error != NULL) ? error->text_buffer_size : 0),
  15955. (path ? path : ""),
  15956. NULL /* TODO: origin */,
  15957. experimental_websocket_client_data_wrapper,
  15958. experimental_websocket_client_close_wrapper,
  15959. (void *)init->callbacks);
  15960. }
  15961. #else
  15962. (void)is_ws;
  15963. #endif
  15964. /* TODO: all additional options */
  15965. struct mg_client_options opts;
  15966. memset(&opts, 0, sizeof(opts));
  15967. opts.host = host;
  15968. opts.port = port;
  15969. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15970. }
  15971. #endif
  15972. static const struct {
  15973. const char *proto;
  15974. size_t proto_len;
  15975. unsigned default_port;
  15976. } abs_uri_protocols[] = {{"http://", 7, 80},
  15977. {"https://", 8, 443},
  15978. {"ws://", 5, 80},
  15979. {"wss://", 6, 443},
  15980. {NULL, 0, 0}};
  15981. /* Check if the uri is valid.
  15982. * return 0 for invalid uri,
  15983. * return 1 for *,
  15984. * return 2 for relative uri,
  15985. * return 3 for absolute uri without port,
  15986. * return 4 for absolute uri with port */
  15987. static int
  15988. get_uri_type(const char *uri)
  15989. {
  15990. int i;
  15991. const char *hostend, *portbegin;
  15992. char *portend;
  15993. unsigned long port;
  15994. /* According to the HTTP standard
  15995. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15996. * URI can be an asterisk (*) or should start with slash (relative uri),
  15997. * or it should start with the protocol (absolute uri). */
  15998. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15999. /* asterisk */
  16000. return 1;
  16001. }
  16002. /* Valid URIs according to RFC 3986
  16003. * (https://www.ietf.org/rfc/rfc3986.txt)
  16004. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16005. * and unreserved characters A-Z a-z 0-9 and -._~
  16006. * and % encoded symbols.
  16007. */
  16008. for (i = 0; uri[i] != 0; i++) {
  16009. if (uri[i] < 33) {
  16010. /* control characters and spaces are invalid */
  16011. return 0;
  16012. }
  16013. /* Allow everything else here (See #894) */
  16014. }
  16015. /* A relative uri starts with a / character */
  16016. if (uri[0] == '/') {
  16017. /* relative uri */
  16018. return 2;
  16019. }
  16020. /* It could be an absolute uri: */
  16021. /* This function only checks if the uri is valid, not if it is
  16022. * addressing the current server. So civetweb can also be used
  16023. * as a proxy server. */
  16024. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16025. if (mg_strncasecmp(uri,
  16026. abs_uri_protocols[i].proto,
  16027. abs_uri_protocols[i].proto_len)
  16028. == 0) {
  16029. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16030. if (!hostend) {
  16031. return 0;
  16032. }
  16033. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16034. if (!portbegin) {
  16035. return 3;
  16036. }
  16037. port = strtoul(portbegin + 1, &portend, 10);
  16038. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16039. return 0;
  16040. }
  16041. return 4;
  16042. }
  16043. }
  16044. return 0;
  16045. }
  16046. /* Return NULL or the relative uri at the current server */
  16047. static const char *
  16048. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16049. {
  16050. const char *server_domain;
  16051. size_t server_domain_len;
  16052. size_t request_domain_len = 0;
  16053. unsigned long port = 0;
  16054. int i, auth_domain_check_enabled;
  16055. const char *hostbegin = NULL;
  16056. const char *hostend = NULL;
  16057. const char *portbegin;
  16058. char *portend;
  16059. auth_domain_check_enabled =
  16060. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16061. /* DNS is case insensitive, so use case insensitive string compare here
  16062. */
  16063. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16064. if (mg_strncasecmp(uri,
  16065. abs_uri_protocols[i].proto,
  16066. abs_uri_protocols[i].proto_len)
  16067. == 0) {
  16068. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16069. hostend = strchr(hostbegin, '/');
  16070. if (!hostend) {
  16071. return 0;
  16072. }
  16073. portbegin = strchr(hostbegin, ':');
  16074. if ((!portbegin) || (portbegin > hostend)) {
  16075. port = abs_uri_protocols[i].default_port;
  16076. request_domain_len = (size_t)(hostend - hostbegin);
  16077. } else {
  16078. port = strtoul(portbegin + 1, &portend, 10);
  16079. if ((portend != hostend) || (port <= 0)
  16080. || !is_valid_port(port)) {
  16081. return 0;
  16082. }
  16083. request_domain_len = (size_t)(portbegin - hostbegin);
  16084. }
  16085. /* protocol found, port set */
  16086. break;
  16087. }
  16088. }
  16089. if (!port) {
  16090. /* port remains 0 if the protocol is not found */
  16091. return 0;
  16092. }
  16093. /* Check if the request is directed to a different server. */
  16094. /* First check if the port is the same. */
  16095. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16096. /* Request is directed to a different port */
  16097. return 0;
  16098. }
  16099. /* Finally check if the server corresponds to the authentication
  16100. * domain of the server (the server domain).
  16101. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16102. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16103. * but do not allow substrings (like
  16104. * http://notmydomain.com/path/file.ext
  16105. * or http://mydomain.com.fake/path/file.ext).
  16106. */
  16107. if (auth_domain_check_enabled) {
  16108. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16109. server_domain_len = strlen(server_domain);
  16110. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16111. return 0;
  16112. }
  16113. if ((request_domain_len == server_domain_len)
  16114. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16115. /* Request is directed to this server - full name match. */
  16116. } else {
  16117. if (request_domain_len < (server_domain_len + 2)) {
  16118. /* Request is directed to another server: The server name
  16119. * is longer than the request name.
  16120. * Drop this case here to avoid overflows in the
  16121. * following checks. */
  16122. return 0;
  16123. }
  16124. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16125. /* Request is directed to another server: It could be a
  16126. * substring
  16127. * like notmyserver.com */
  16128. return 0;
  16129. }
  16130. if (0
  16131. != memcmp(server_domain,
  16132. hostbegin + request_domain_len - server_domain_len,
  16133. server_domain_len)) {
  16134. /* Request is directed to another server:
  16135. * The server name is different. */
  16136. return 0;
  16137. }
  16138. }
  16139. }
  16140. return hostend;
  16141. }
  16142. static int
  16143. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16144. {
  16145. if (ebuf_len > 0) {
  16146. ebuf[0] = '\0';
  16147. }
  16148. *err = 0;
  16149. reset_per_request_attributes(conn);
  16150. if (!conn) {
  16151. mg_snprintf(conn,
  16152. NULL, /* No truncation check for ebuf */
  16153. ebuf,
  16154. ebuf_len,
  16155. "%s",
  16156. "Internal error");
  16157. *err = 500;
  16158. return 0;
  16159. }
  16160. /* Set the time the request was received. This value should be used for
  16161. * timeouts. */
  16162. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16163. conn->request_len =
  16164. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16165. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16166. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16167. mg_snprintf(conn,
  16168. NULL, /* No truncation check for ebuf */
  16169. ebuf,
  16170. ebuf_len,
  16171. "%s",
  16172. "Invalid message size");
  16173. *err = 500;
  16174. return 0;
  16175. }
  16176. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16177. mg_snprintf(conn,
  16178. NULL, /* No truncation check for ebuf */
  16179. ebuf,
  16180. ebuf_len,
  16181. "%s",
  16182. "Message too large");
  16183. *err = 413;
  16184. return 0;
  16185. }
  16186. if (conn->request_len <= 0) {
  16187. if (conn->data_len > 0) {
  16188. mg_snprintf(conn,
  16189. NULL, /* No truncation check for ebuf */
  16190. ebuf,
  16191. ebuf_len,
  16192. "%s",
  16193. "Malformed message");
  16194. *err = 400;
  16195. } else {
  16196. /* Server did not recv anything -> just close the connection */
  16197. conn->must_close = 1;
  16198. mg_snprintf(conn,
  16199. NULL, /* No truncation check for ebuf */
  16200. ebuf,
  16201. ebuf_len,
  16202. "%s",
  16203. "No data received");
  16204. *err = 0;
  16205. }
  16206. return 0;
  16207. }
  16208. return 1;
  16209. }
  16210. static int
  16211. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16212. {
  16213. const char *cl;
  16214. conn->connection_type =
  16215. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16216. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16217. return 0;
  16218. }
  16219. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16220. <= 0) {
  16221. mg_snprintf(conn,
  16222. NULL, /* No truncation check for ebuf */
  16223. ebuf,
  16224. ebuf_len,
  16225. "%s",
  16226. "Bad request");
  16227. *err = 400;
  16228. return 0;
  16229. }
  16230. /* Message is a valid request */
  16231. if (!switch_domain_context(conn)) {
  16232. mg_snprintf(conn,
  16233. NULL, /* No truncation check for ebuf */
  16234. ebuf,
  16235. ebuf_len,
  16236. "%s",
  16237. "Bad request: Host mismatch");
  16238. *err = 400;
  16239. return 0;
  16240. }
  16241. #if USE_ZLIB
  16242. if (((cl = get_header(conn->request_info.http_headers,
  16243. conn->request_info.num_headers,
  16244. "Accept-Encoding"))
  16245. != NULL)
  16246. && strstr(cl, "gzip")) {
  16247. conn->accept_gzip = 1;
  16248. }
  16249. #endif
  16250. if (((cl = get_header(conn->request_info.http_headers,
  16251. conn->request_info.num_headers,
  16252. "Transfer-Encoding"))
  16253. != NULL)
  16254. && mg_strcasecmp(cl, "identity")) {
  16255. if (mg_strcasecmp(cl, "chunked")) {
  16256. mg_snprintf(conn,
  16257. NULL, /* No truncation check for ebuf */
  16258. ebuf,
  16259. ebuf_len,
  16260. "%s",
  16261. "Bad request");
  16262. *err = 400;
  16263. return 0;
  16264. }
  16265. conn->is_chunked = 1;
  16266. conn->content_len = 0; /* not yet read */
  16267. } else if ((cl = get_header(conn->request_info.http_headers,
  16268. conn->request_info.num_headers,
  16269. "Content-Length"))
  16270. != NULL) {
  16271. /* Request has content length set */
  16272. char *endptr = NULL;
  16273. conn->content_len = strtoll(cl, &endptr, 10);
  16274. if ((endptr == cl) || (conn->content_len < 0)) {
  16275. mg_snprintf(conn,
  16276. NULL, /* No truncation check for ebuf */
  16277. ebuf,
  16278. ebuf_len,
  16279. "%s",
  16280. "Bad request");
  16281. *err = 411;
  16282. return 0;
  16283. }
  16284. /* Publish the content length back to the request info. */
  16285. conn->request_info.content_length = conn->content_len;
  16286. } else {
  16287. /* There is no exception, see RFC7230. */
  16288. conn->content_len = 0;
  16289. }
  16290. return 1;
  16291. }
  16292. /* conn is assumed to be valid in this internal function */
  16293. static int
  16294. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16295. {
  16296. const char *cl;
  16297. conn->connection_type =
  16298. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16299. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16300. return 0;
  16301. }
  16302. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16303. <= 0) {
  16304. mg_snprintf(conn,
  16305. NULL, /* No truncation check for ebuf */
  16306. ebuf,
  16307. ebuf_len,
  16308. "%s",
  16309. "Bad response");
  16310. *err = 400;
  16311. return 0;
  16312. }
  16313. /* Message is a valid response */
  16314. if (((cl = get_header(conn->response_info.http_headers,
  16315. conn->response_info.num_headers,
  16316. "Transfer-Encoding"))
  16317. != NULL)
  16318. && mg_strcasecmp(cl, "identity")) {
  16319. if (mg_strcasecmp(cl, "chunked")) {
  16320. mg_snprintf(conn,
  16321. NULL, /* No truncation check for ebuf */
  16322. ebuf,
  16323. ebuf_len,
  16324. "%s",
  16325. "Bad request");
  16326. *err = 400;
  16327. return 0;
  16328. }
  16329. conn->is_chunked = 1;
  16330. conn->content_len = 0; /* not yet read */
  16331. } else if ((cl = get_header(conn->response_info.http_headers,
  16332. conn->response_info.num_headers,
  16333. "Content-Length"))
  16334. != NULL) {
  16335. char *endptr = NULL;
  16336. conn->content_len = strtoll(cl, &endptr, 10);
  16337. if ((endptr == cl) || (conn->content_len < 0)) {
  16338. mg_snprintf(conn,
  16339. NULL, /* No truncation check for ebuf */
  16340. ebuf,
  16341. ebuf_len,
  16342. "%s",
  16343. "Bad request");
  16344. *err = 411;
  16345. return 0;
  16346. }
  16347. /* Publish the content length back to the response info. */
  16348. conn->response_info.content_length = conn->content_len;
  16349. /* TODO: check if it is still used in response_info */
  16350. conn->request_info.content_length = conn->content_len;
  16351. /* TODO: we should also consider HEAD method */
  16352. if (conn->response_info.status_code == 304) {
  16353. conn->content_len = 0;
  16354. }
  16355. } else {
  16356. /* TODO: we should also consider HEAD method */
  16357. if (((conn->response_info.status_code >= 100)
  16358. && (conn->response_info.status_code <= 199))
  16359. || (conn->response_info.status_code == 204)
  16360. || (conn->response_info.status_code == 304)) {
  16361. conn->content_len = 0;
  16362. } else {
  16363. conn->content_len = -1; /* unknown content length */
  16364. }
  16365. }
  16366. return 1;
  16367. }
  16368. CIVETWEB_API int
  16369. mg_get_response(struct mg_connection *conn,
  16370. char *ebuf,
  16371. size_t ebuf_len,
  16372. int timeout)
  16373. {
  16374. int err, ret;
  16375. char txt[32]; /* will not overflow */
  16376. char *save_timeout;
  16377. char *new_timeout;
  16378. if (ebuf_len > 0) {
  16379. ebuf[0] = '\0';
  16380. }
  16381. if (!conn) {
  16382. mg_snprintf(conn,
  16383. NULL, /* No truncation check for ebuf */
  16384. ebuf,
  16385. ebuf_len,
  16386. "%s",
  16387. "Parameter error");
  16388. return -1;
  16389. }
  16390. /* Reset the previous responses */
  16391. conn->data_len = 0;
  16392. /* Implementation of API function for HTTP clients */
  16393. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16394. if (timeout >= 0) {
  16395. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16396. new_timeout = txt;
  16397. } else {
  16398. new_timeout = NULL;
  16399. }
  16400. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16401. ret = get_response(conn, ebuf, ebuf_len, &err);
  16402. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16403. /* TODO: here, the URI is the http response code */
  16404. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16405. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16406. /* TODO (mid): Define proper return values - maybe return length?
  16407. * For the first test use <0 for error and >0 for OK */
  16408. return (ret == 0) ? -1 : +1;
  16409. }
  16410. CIVETWEB_API struct mg_connection *
  16411. mg_download(const char *host,
  16412. int port,
  16413. int use_ssl,
  16414. char *ebuf,
  16415. size_t ebuf_len,
  16416. const char *fmt,
  16417. ...)
  16418. {
  16419. struct mg_connection *conn;
  16420. va_list ap;
  16421. int i;
  16422. int reqerr;
  16423. if (ebuf_len > 0) {
  16424. ebuf[0] = '\0';
  16425. }
  16426. va_start(ap, fmt);
  16427. /* open a connection */
  16428. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16429. if (conn != NULL) {
  16430. i = mg_vprintf(conn, fmt, ap);
  16431. if (i <= 0) {
  16432. mg_snprintf(conn,
  16433. NULL, /* No truncation check for ebuf */
  16434. ebuf,
  16435. ebuf_len,
  16436. "%s",
  16437. "Error sending request");
  16438. } else {
  16439. /* make sure the buffer is clear */
  16440. conn->data_len = 0;
  16441. get_response(conn, ebuf, ebuf_len, &reqerr);
  16442. /* TODO: here, the URI is the http response code */
  16443. conn->request_info.local_uri = conn->request_info.request_uri;
  16444. }
  16445. }
  16446. /* if an error occurred, close the connection */
  16447. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16448. mg_close_connection(conn);
  16449. conn = NULL;
  16450. }
  16451. va_end(ap);
  16452. return conn;
  16453. }
  16454. struct websocket_client_thread_data {
  16455. struct mg_connection *conn;
  16456. mg_websocket_data_handler data_handler;
  16457. mg_websocket_close_handler close_handler;
  16458. void *callback_data;
  16459. };
  16460. #if defined(USE_WEBSOCKET)
  16461. #if defined(_WIN32)
  16462. static unsigned __stdcall websocket_client_thread(void *data)
  16463. #else
  16464. static void *
  16465. websocket_client_thread(void *data)
  16466. #endif
  16467. {
  16468. struct websocket_client_thread_data *cdata =
  16469. (struct websocket_client_thread_data *)data;
  16470. void *user_thread_ptr = NULL;
  16471. #if !defined(_WIN32) && !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  16472. struct sigaction sa;
  16473. /* Ignore SIGPIPE */
  16474. memset(&sa, 0, sizeof(sa));
  16475. sa.sa_handler = SIG_IGN;
  16476. sigaction(SIGPIPE, &sa, NULL);
  16477. #endif
  16478. mg_set_thread_name("ws-clnt");
  16479. if (cdata->conn->phys_ctx) {
  16480. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16481. /* 3 indicates a websocket client thread */
  16482. /* TODO: check if conn->phys_ctx can be set */
  16483. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16484. cdata->conn->phys_ctx, 3);
  16485. }
  16486. }
  16487. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16488. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16489. if (cdata->close_handler != NULL) {
  16490. cdata->close_handler(cdata->conn, cdata->callback_data);
  16491. }
  16492. /* The websocket_client context has only this thread. If it runs out,
  16493. set the stop_flag to 2 (= "stopped"). */
  16494. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16495. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16496. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16497. 3,
  16498. user_thread_ptr);
  16499. }
  16500. mg_free((void *)cdata);
  16501. #if defined(_WIN32)
  16502. return 0;
  16503. #else
  16504. return NULL;
  16505. #endif
  16506. }
  16507. #endif
  16508. static struct mg_connection *
  16509. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16510. int use_ssl,
  16511. char *error_buffer,
  16512. size_t error_buffer_size,
  16513. const char *path,
  16514. const char *origin,
  16515. const char *extensions,
  16516. mg_websocket_data_handler data_func,
  16517. mg_websocket_close_handler close_func,
  16518. void *user_data)
  16519. {
  16520. struct mg_connection *conn = NULL;
  16521. #if defined(USE_WEBSOCKET)
  16522. struct websocket_client_thread_data *thread_data;
  16523. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16524. const char *host = client_options->host;
  16525. int i;
  16526. struct mg_init_data init;
  16527. struct mg_error_data error;
  16528. memset(&init, 0, sizeof(init));
  16529. memset(&error, 0, sizeof(error));
  16530. error.text_buffer_size = error_buffer_size;
  16531. error.text = error_buffer;
  16532. #if defined(__clang__)
  16533. #pragma clang diagnostic push
  16534. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16535. #endif
  16536. /* Establish the client connection and request upgrade */
  16537. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16538. /* Connection object will be null if something goes wrong */
  16539. if (conn == NULL) {
  16540. /* error_buffer should be already filled ... */
  16541. if (!error_buffer[0]) {
  16542. /* ... if not add an error message */
  16543. mg_snprintf(conn,
  16544. NULL, /* No truncation check for ebuf */
  16545. error_buffer,
  16546. error_buffer_size,
  16547. "Unexpected error");
  16548. }
  16549. return NULL;
  16550. }
  16551. if (origin != NULL) {
  16552. if (extensions != NULL) {
  16553. i = mg_printf(conn,
  16554. "GET %s HTTP/1.1\r\n"
  16555. "Host: %s\r\n"
  16556. "Upgrade: websocket\r\n"
  16557. "Connection: Upgrade\r\n"
  16558. "Sec-WebSocket-Key: %s\r\n"
  16559. "Sec-WebSocket-Version: 13\r\n"
  16560. "Sec-WebSocket-Extensions: %s\r\n"
  16561. "Origin: %s\r\n"
  16562. "\r\n",
  16563. path,
  16564. host,
  16565. magic,
  16566. extensions,
  16567. origin);
  16568. } else {
  16569. i = mg_printf(conn,
  16570. "GET %s HTTP/1.1\r\n"
  16571. "Host: %s\r\n"
  16572. "Upgrade: websocket\r\n"
  16573. "Connection: Upgrade\r\n"
  16574. "Sec-WebSocket-Key: %s\r\n"
  16575. "Sec-WebSocket-Version: 13\r\n"
  16576. "Origin: %s\r\n"
  16577. "\r\n",
  16578. path,
  16579. host,
  16580. magic,
  16581. origin);
  16582. }
  16583. } else {
  16584. if (extensions != NULL) {
  16585. i = mg_printf(conn,
  16586. "GET %s HTTP/1.1\r\n"
  16587. "Host: %s\r\n"
  16588. "Upgrade: websocket\r\n"
  16589. "Connection: Upgrade\r\n"
  16590. "Sec-WebSocket-Key: %s\r\n"
  16591. "Sec-WebSocket-Version: 13\r\n"
  16592. "Sec-WebSocket-Extensions: %s\r\n"
  16593. "\r\n",
  16594. path,
  16595. host,
  16596. magic,
  16597. extensions);
  16598. } else {
  16599. i = mg_printf(conn,
  16600. "GET %s HTTP/1.1\r\n"
  16601. "Host: %s\r\n"
  16602. "Upgrade: websocket\r\n"
  16603. "Connection: Upgrade\r\n"
  16604. "Sec-WebSocket-Key: %s\r\n"
  16605. "Sec-WebSocket-Version: 13\r\n"
  16606. "\r\n",
  16607. path,
  16608. host,
  16609. magic);
  16610. }
  16611. }
  16612. if (i <= 0) {
  16613. mg_snprintf(conn,
  16614. NULL, /* No truncation check for ebuf */
  16615. error_buffer,
  16616. error_buffer_size,
  16617. "%s",
  16618. "Error sending request");
  16619. mg_close_connection(conn);
  16620. return NULL;
  16621. }
  16622. conn->data_len = 0;
  16623. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16624. mg_close_connection(conn);
  16625. return NULL;
  16626. }
  16627. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16628. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16629. #if defined(__clang__)
  16630. #pragma clang diagnostic pop
  16631. #endif
  16632. if (conn->response_info.status_code != 101) {
  16633. /* We sent an "upgrade" request. For a correct websocket
  16634. * protocol handshake, we expect a "101 Continue" response.
  16635. * Otherwise it is a protocol violation. Maybe the HTTP
  16636. * Server does not know websockets. */
  16637. if (!*error_buffer) {
  16638. /* set an error, if not yet set */
  16639. mg_snprintf(conn,
  16640. NULL, /* No truncation check for ebuf */
  16641. error_buffer,
  16642. error_buffer_size,
  16643. "Unexpected server reply");
  16644. }
  16645. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16646. mg_close_connection(conn);
  16647. return NULL;
  16648. }
  16649. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16650. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16651. if (!thread_data) {
  16652. DEBUG_TRACE("%s\r\n", "Out of memory");
  16653. mg_close_connection(conn);
  16654. return NULL;
  16655. }
  16656. thread_data->conn = conn;
  16657. thread_data->data_handler = data_func;
  16658. thread_data->close_handler = close_func;
  16659. thread_data->callback_data = user_data;
  16660. conn->phys_ctx->worker_threadids =
  16661. (cw_thread_handle_t *)mg_calloc_ctx(1, sizeof(cw_thread_handle_t), conn->phys_ctx);
  16662. if (!conn->phys_ctx->worker_threadids) {
  16663. DEBUG_TRACE("%s\r\n", "Out of memory");
  16664. mg_free(thread_data);
  16665. mg_close_connection(conn);
  16666. return NULL;
  16667. }
  16668. /* Now upgrade to ws/wss client context */
  16669. conn->phys_ctx->user_data = user_data;
  16670. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16671. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16672. /* Start a thread to read the websocket client connection
  16673. * This thread will automatically stop when mg_disconnect is
  16674. * called on the client connection */
  16675. if (mg_start_thread_with_id(websocket_client_thread,
  16676. thread_data,
  16677. conn->phys_ctx->worker_threadids)
  16678. != 0) {
  16679. conn->phys_ctx->cfg_worker_threads = 0;
  16680. mg_free(thread_data);
  16681. mg_close_connection(conn);
  16682. conn = NULL;
  16683. DEBUG_TRACE("%s",
  16684. "Websocket client connect thread could not be started\r\n");
  16685. }
  16686. #else
  16687. /* Appease "unused parameter" warnings */
  16688. (void)client_options;
  16689. (void)use_ssl;
  16690. (void)error_buffer;
  16691. (void)error_buffer_size;
  16692. (void)path;
  16693. (void)origin;
  16694. (void)extensions;
  16695. (void)user_data;
  16696. (void)data_func;
  16697. (void)close_func;
  16698. #endif
  16699. return conn;
  16700. }
  16701. CIVETWEB_API struct mg_connection *
  16702. mg_connect_websocket_client(const char *host,
  16703. int port,
  16704. int use_ssl,
  16705. char *error_buffer,
  16706. size_t error_buffer_size,
  16707. const char *path,
  16708. const char *origin,
  16709. mg_websocket_data_handler data_func,
  16710. mg_websocket_close_handler close_func,
  16711. void *user_data)
  16712. {
  16713. struct mg_client_options client_options;
  16714. memset(&client_options, 0, sizeof(client_options));
  16715. client_options.host = host;
  16716. client_options.port = port;
  16717. return mg_connect_websocket_client_impl(&client_options,
  16718. use_ssl,
  16719. error_buffer,
  16720. error_buffer_size,
  16721. path,
  16722. origin,
  16723. NULL,
  16724. data_func,
  16725. close_func,
  16726. user_data);
  16727. }
  16728. CIVETWEB_API struct mg_connection *
  16729. mg_connect_websocket_client_secure(
  16730. const struct mg_client_options *client_options,
  16731. char *error_buffer,
  16732. size_t error_buffer_size,
  16733. const char *path,
  16734. const char *origin,
  16735. mg_websocket_data_handler data_func,
  16736. mg_websocket_close_handler close_func,
  16737. void *user_data)
  16738. {
  16739. if (!client_options) {
  16740. return NULL;
  16741. }
  16742. return mg_connect_websocket_client_impl(client_options,
  16743. 1,
  16744. error_buffer,
  16745. error_buffer_size,
  16746. path,
  16747. origin,
  16748. NULL,
  16749. data_func,
  16750. close_func,
  16751. user_data);
  16752. }
  16753. CIVETWEB_API struct mg_connection *
  16754. mg_connect_websocket_client_extensions(const char *host,
  16755. int port,
  16756. int use_ssl,
  16757. char *error_buffer,
  16758. size_t error_buffer_size,
  16759. const char *path,
  16760. const char *origin,
  16761. const char *extensions,
  16762. mg_websocket_data_handler data_func,
  16763. mg_websocket_close_handler close_func,
  16764. void *user_data)
  16765. {
  16766. struct mg_client_options client_options;
  16767. memset(&client_options, 0, sizeof(client_options));
  16768. client_options.host = host;
  16769. client_options.port = port;
  16770. return mg_connect_websocket_client_impl(&client_options,
  16771. use_ssl,
  16772. error_buffer,
  16773. error_buffer_size,
  16774. path,
  16775. origin,
  16776. extensions,
  16777. data_func,
  16778. close_func,
  16779. user_data);
  16780. }
  16781. CIVETWEB_API struct mg_connection *
  16782. mg_connect_websocket_client_secure_extensions(
  16783. const struct mg_client_options *client_options,
  16784. char *error_buffer,
  16785. size_t error_buffer_size,
  16786. const char *path,
  16787. const char *origin,
  16788. const char *extensions,
  16789. mg_websocket_data_handler data_func,
  16790. mg_websocket_close_handler close_func,
  16791. void *user_data)
  16792. {
  16793. if (!client_options) {
  16794. return NULL;
  16795. }
  16796. return mg_connect_websocket_client_impl(client_options,
  16797. 1,
  16798. error_buffer,
  16799. error_buffer_size,
  16800. path,
  16801. origin,
  16802. extensions,
  16803. data_func,
  16804. close_func,
  16805. user_data);
  16806. }
  16807. /* Prepare connection data structure */
  16808. static void
  16809. init_connection(struct mg_connection *conn)
  16810. {
  16811. /* Is keep alive allowed by the server */
  16812. int keep_alive_enabled =
  16813. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16814. if (!keep_alive_enabled) {
  16815. conn->must_close = 1;
  16816. }
  16817. /* Important: on new connection, reset the receiving buffer. Credit
  16818. * goes to crule42. */
  16819. conn->data_len = 0;
  16820. conn->handled_requests = 0;
  16821. conn->connection_type = CONNECTION_TYPE_INVALID;
  16822. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  16823. mg_set_user_connection_data(conn, NULL);
  16824. #if defined(USE_SERVER_STATS)
  16825. conn->conn_state = 2; /* init */
  16826. #endif
  16827. /* call the init_connection callback if assigned */
  16828. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16829. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16830. void *conn_data = NULL;
  16831. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16832. mg_set_user_connection_data(conn, conn_data);
  16833. }
  16834. }
  16835. }
  16836. /* Process a connection - may handle multiple requests
  16837. * using the same connection.
  16838. * Must be called with a valid connection (conn and
  16839. * conn->phys_ctx must be valid).
  16840. */
  16841. static void
  16842. process_new_connection(struct mg_connection *conn)
  16843. {
  16844. struct mg_request_info *ri = &conn->request_info;
  16845. int keep_alive, discard_len;
  16846. char ebuf[100];
  16847. const char *hostend;
  16848. int reqerr, uri_type;
  16849. #if defined(USE_SERVER_STATS)
  16850. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16851. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16852. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16853. #endif
  16854. DEBUG_TRACE("Start processing connection from %s",
  16855. conn->request_info.remote_addr);
  16856. /* Loop over multiple requests sent using the same connection
  16857. * (while "keep alive"). */
  16858. do {
  16859. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16860. conn->handled_requests + 1);
  16861. #if defined(USE_SERVER_STATS)
  16862. conn->conn_state = 3; /* ready */
  16863. #endif
  16864. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16865. /* The request sent by the client could not be understood by
  16866. * the server, or it was incomplete or a timeout. Send an
  16867. * error message and close the connection. */
  16868. if (reqerr > 0) {
  16869. DEBUG_ASSERT(ebuf[0] != '\0');
  16870. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16871. }
  16872. } else if (strcmp(ri->http_version, "1.0")
  16873. && strcmp(ri->http_version, "1.1")) {
  16874. /* HTTP/2 is not allowed here */
  16875. mg_snprintf(conn,
  16876. NULL, /* No truncation check for ebuf */
  16877. ebuf,
  16878. sizeof(ebuf),
  16879. "Bad HTTP version: [%s]",
  16880. ri->http_version);
  16881. mg_send_http_error(conn, 505, "%s", ebuf);
  16882. }
  16883. if (ebuf[0] == '\0') {
  16884. uri_type = get_uri_type(conn->request_info.request_uri);
  16885. switch (uri_type) {
  16886. case 1:
  16887. /* Asterisk */
  16888. conn->request_info.local_uri_raw = 0;
  16889. /* TODO: Deal with '*'. */
  16890. break;
  16891. case 2:
  16892. /* relative uri */
  16893. conn->request_info.local_uri_raw =
  16894. conn->request_info.request_uri;
  16895. break;
  16896. case 3:
  16897. case 4:
  16898. /* absolute uri (with/without port) */
  16899. hostend = get_rel_url_at_current_server(
  16900. conn->request_info.request_uri, conn);
  16901. if (hostend) {
  16902. conn->request_info.local_uri_raw = hostend;
  16903. } else {
  16904. conn->request_info.local_uri_raw = NULL;
  16905. }
  16906. break;
  16907. default:
  16908. mg_snprintf(conn,
  16909. NULL, /* No truncation check for ebuf */
  16910. ebuf,
  16911. sizeof(ebuf),
  16912. "Invalid URI");
  16913. mg_send_http_error(conn, 400, "%s", ebuf);
  16914. conn->request_info.local_uri_raw = NULL;
  16915. break;
  16916. }
  16917. conn->request_info.local_uri =
  16918. (char *)conn->request_info.local_uri_raw;
  16919. }
  16920. if (ebuf[0] != '\0') {
  16921. conn->protocol_type = -1;
  16922. } else {
  16923. /* HTTP/1 allows protocol upgrade */
  16924. conn->protocol_type = should_switch_to_protocol(conn);
  16925. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16926. /* This will occur, if a HTTP/1.1 request should be upgraded
  16927. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16928. * Since most (all?) major browsers only support HTTP/2 using
  16929. * ALPN, this is hard to test and very low priority.
  16930. * Deactivate it (at least for now).
  16931. */
  16932. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16933. }
  16934. }
  16935. DEBUG_TRACE("http: %s, error: %s",
  16936. (ri->http_version ? ri->http_version : "none"),
  16937. (ebuf[0] ? ebuf : "none"));
  16938. if (ebuf[0] == '\0') {
  16939. if (conn->request_info.local_uri) {
  16940. /* handle request to local server */
  16941. handle_request_stat_log(conn);
  16942. } else {
  16943. /* TODO: handle non-local request (PROXY) */
  16944. conn->must_close = 1;
  16945. }
  16946. } else {
  16947. conn->must_close = 1;
  16948. }
  16949. /* Response complete. Free header buffer */
  16950. free_buffered_response_header_list(conn);
  16951. if (ri->remote_user != NULL) {
  16952. mg_free((void *)ri->remote_user);
  16953. /* Important! When having connections with and without auth
  16954. * would cause double free and then crash */
  16955. ri->remote_user = NULL;
  16956. }
  16957. /* NOTE(lsm): order is important here. should_keep_alive() call
  16958. * is using parsed request, which will be invalid after
  16959. * memmove's below.
  16960. * Therefore, memorize should_keep_alive() result now for later
  16961. * use in loop exit condition. */
  16962. /* Enable it only if this request is completely discardable. */
  16963. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16964. && should_keep_alive(conn) && (conn->content_len >= 0)
  16965. && (conn->request_len > 0)
  16966. && ((conn->is_chunked == 4)
  16967. || (!conn->is_chunked
  16968. && ((conn->consumed_content == conn->content_len)
  16969. || ((conn->request_len + conn->content_len)
  16970. <= conn->data_len))))
  16971. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16972. if (keep_alive) {
  16973. /* Discard all buffered data for this request */
  16974. discard_len =
  16975. ((conn->request_len + conn->content_len) < conn->data_len)
  16976. ? (int)(conn->request_len + conn->content_len)
  16977. : conn->data_len;
  16978. conn->data_len -= discard_len;
  16979. if (conn->data_len > 0) {
  16980. DEBUG_TRACE("discard_len = %d", discard_len);
  16981. memmove(conn->buf,
  16982. conn->buf + discard_len,
  16983. (size_t)conn->data_len);
  16984. }
  16985. }
  16986. DEBUG_ASSERT(conn->data_len >= 0);
  16987. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16988. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16989. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16990. (long int)conn->data_len,
  16991. (long int)conn->buf_size);
  16992. break;
  16993. }
  16994. conn->handled_requests++;
  16995. } while (keep_alive);
  16996. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16997. conn->request_info.remote_addr,
  16998. difftime(time(NULL), conn->conn_birth_time));
  16999. close_connection(conn);
  17000. #if defined(USE_SERVER_STATS)
  17001. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17002. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17003. #endif
  17004. }
  17005. #if defined(ALTERNATIVE_QUEUE)
  17006. static void
  17007. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17008. {
  17009. unsigned int i;
  17010. while (!ctx->stop_flag) {
  17011. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17012. /* find a free worker slot and signal it */
  17013. if (ctx->client_socks[i].in_use == 2) {
  17014. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17015. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17016. ctx->client_socks[i] = *sp;
  17017. ctx->client_socks[i].in_use = 1;
  17018. /* socket has been moved to the consumer */
  17019. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17020. (void)event_signal(ctx->client_wait_events[i]);
  17021. return;
  17022. }
  17023. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17024. }
  17025. }
  17026. /* queue is full */
  17027. mg_sleep(1);
  17028. }
  17029. /* must consume */
  17030. set_blocking_mode(sp->sock);
  17031. closesocket(sp->sock);
  17032. }
  17033. static int
  17034. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  17035. {
  17036. DEBUG_TRACE("%s", "going idle");
  17037. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17038. ctx->client_socks[thread_index].in_use = 2;
  17039. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17040. event_wait(ctx->client_wait_events[thread_index]);
  17041. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17042. *sp = ctx->client_socks[thread_index];
  17043. if (ctx->stop_flag) {
  17044. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17045. if (sp->in_use == 1) {
  17046. /* must consume */
  17047. set_blocking_mode(sp->sock);
  17048. closesocket(sp->sock);
  17049. }
  17050. return 0;
  17051. }
  17052. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17053. if (sp->in_use == 1) {
  17054. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17055. return 1;
  17056. }
  17057. /* must not reach here */
  17058. DEBUG_ASSERT(0);
  17059. return 0;
  17060. }
  17061. #else /* ALTERNATIVE_QUEUE */
  17062. /* Worker threads take accepted socket from the queue */
  17063. static int
  17064. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  17065. {
  17066. (void)thread_index;
  17067. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17068. DEBUG_TRACE("%s", "going idle");
  17069. /* If the queue is empty, wait. We're idle at this point. */
  17070. while ((ctx->sq_head == ctx->sq_tail)
  17071. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17072. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17073. }
  17074. /* If we're stopping, sq_head may be equal to sq_tail. */
  17075. if (ctx->sq_head > ctx->sq_tail) {
  17076. /* Copy socket from the queue and increment tail */
  17077. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17078. ctx->sq_tail++;
  17079. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17080. /* Wrap pointers if needed */
  17081. while (ctx->sq_tail > ctx->sq_size) {
  17082. ctx->sq_tail -= ctx->sq_size;
  17083. ctx->sq_head -= ctx->sq_size;
  17084. }
  17085. }
  17086. (void)pthread_cond_signal(&ctx->sq_empty);
  17087. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17088. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17089. }
  17090. /* Master thread adds accepted socket to a queue */
  17091. static void
  17092. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17093. {
  17094. int queue_filled;
  17095. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17096. queue_filled = ctx->sq_head - ctx->sq_tail;
  17097. /* If the queue is full, wait */
  17098. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17099. && (queue_filled >= ctx->sq_size)) {
  17100. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17101. #if defined(USE_SERVER_STATS)
  17102. if (queue_filled > ctx->sq_max_fill) {
  17103. ctx->sq_max_fill = queue_filled;
  17104. }
  17105. #endif
  17106. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17107. ctx->sq_blocked = 0; /* Not blocked now */
  17108. queue_filled = ctx->sq_head - ctx->sq_tail;
  17109. }
  17110. if (queue_filled < ctx->sq_size) {
  17111. /* Copy socket to the queue and increment head */
  17112. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17113. ctx->sq_head++;
  17114. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17115. }
  17116. queue_filled = ctx->sq_head - ctx->sq_tail;
  17117. #if defined(USE_SERVER_STATS)
  17118. if (queue_filled > ctx->sq_max_fill) {
  17119. ctx->sq_max_fill = queue_filled;
  17120. }
  17121. #endif
  17122. (void)pthread_cond_signal(&ctx->sq_full);
  17123. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17124. }
  17125. #endif /* ALTERNATIVE_QUEUE */
  17126. static void
  17127. worker_thread_run(struct mg_connection *conn)
  17128. {
  17129. struct mg_context *ctx = conn->phys_ctx;
  17130. int thread_index;
  17131. struct mg_workerTLS tls;
  17132. mg_set_thread_name("worker");
  17133. tls.is_master = 0;
  17134. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17135. #if defined(_WIN32)
  17136. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17137. #endif
  17138. /* Initialize thread local storage before calling any callback */
  17139. pthread_setspecific(sTlsKey, &tls);
  17140. /* Check if there is a user callback */
  17141. if (ctx->callbacks.init_thread) {
  17142. /* call init_thread for a worker thread (type 1), and store the
  17143. * return value */
  17144. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17145. } else {
  17146. /* No callback: set user pointer to NULL */
  17147. tls.user_ptr = NULL;
  17148. }
  17149. /* Connection structure has been pre-allocated */
  17150. thread_index = (int)(conn - ctx->worker_connections);
  17151. if ((thread_index < 0)
  17152. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  17153. mg_cry_ctx_internal(ctx,
  17154. "Internal error: Invalid worker index %i",
  17155. thread_index);
  17156. return;
  17157. }
  17158. /* Request buffers are not pre-allocated. They are private to the
  17159. * request and do not contain any state information that might be
  17160. * of interest to anyone observing a server status. */
  17161. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17162. if (conn->buf == NULL) {
  17163. mg_cry_ctx_internal(
  17164. ctx,
  17165. "Out of memory: Cannot allocate buffer for worker %i",
  17166. thread_index);
  17167. return;
  17168. }
  17169. conn->buf_size = (int)ctx->max_request_size;
  17170. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17171. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17172. conn->request_info.user_data = ctx->user_data;
  17173. /* Allocate a mutex for this connection to allow communication both
  17174. * within the request handler and from elsewhere in the application
  17175. */
  17176. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17177. mg_free(conn->buf);
  17178. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17179. return;
  17180. }
  17181. #if defined(USE_SERVER_STATS)
  17182. conn->conn_state = 1; /* not consumed */
  17183. #endif
  17184. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17185. * signal sq_empty condvar to wake up the master waiting in
  17186. * produce_socket() */
  17187. while (consume_socket(ctx, &conn->client, thread_index)) {
  17188. /* New connections must start with new protocol negotiation */
  17189. tls.alpn_proto = NULL;
  17190. #if defined(USE_SERVER_STATS)
  17191. conn->conn_close_time = 0;
  17192. #endif
  17193. conn->conn_birth_time = time(NULL);
  17194. /* Fill in IP, port info early so even if SSL setup below fails,
  17195. * error handler would have the corresponding info.
  17196. * Thanks to Johannes Winkelmann for the patch.
  17197. */
  17198. conn->request_info.remote_port =
  17199. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17200. conn->request_info.server_port =
  17201. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17202. sockaddr_to_string(conn->request_info.remote_addr,
  17203. sizeof(conn->request_info.remote_addr),
  17204. &conn->client.rsa);
  17205. DEBUG_TRACE("Incomming %sconnection from %s",
  17206. (conn->client.is_ssl ? "SSL " : ""),
  17207. conn->request_info.remote_addr);
  17208. conn->request_info.is_ssl = conn->client.is_ssl;
  17209. if (conn->client.is_ssl) {
  17210. #if defined(USE_MBEDTLS)
  17211. /* HTTPS connection */
  17212. if (mbed_ssl_accept(&(conn->ssl),
  17213. conn->dom_ctx->ssl_ctx,
  17214. (int *)&(conn->client.sock),
  17215. conn->phys_ctx)
  17216. == 0) {
  17217. /* conn->dom_ctx is set in get_request */
  17218. /* process HTTPS connection */
  17219. init_connection(conn);
  17220. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17221. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17222. process_new_connection(conn);
  17223. } else {
  17224. /* make sure the connection is cleaned up on SSL failure */
  17225. close_connection(conn);
  17226. }
  17227. #elif !defined(NO_SSL)
  17228. /* HTTPS connection */
  17229. if (sslize(conn, SSL_accept, NULL)) {
  17230. /* conn->dom_ctx is set in get_request */
  17231. /* Get SSL client certificate information (if set) */
  17232. struct mg_client_cert client_cert;
  17233. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17234. conn->request_info.client_cert = &client_cert;
  17235. }
  17236. /* process HTTPS connection */
  17237. #if defined(USE_HTTP2)
  17238. if ((tls.alpn_proto != NULL)
  17239. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17240. /* process HTTPS/2 connection */
  17241. init_connection(conn);
  17242. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17243. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17244. conn->content_len =
  17245. -1; /* content length is not predefined */
  17246. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17247. process_new_http2_connection(conn);
  17248. } else
  17249. #endif
  17250. {
  17251. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17252. init_connection(conn);
  17253. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17254. /* Start with HTTP, WS will be an "upgrade" request later */
  17255. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17256. process_new_connection(conn);
  17257. }
  17258. /* Free client certificate info */
  17259. if (conn->request_info.client_cert) {
  17260. mg_free((void *)(conn->request_info.client_cert->subject));
  17261. mg_free((void *)(conn->request_info.client_cert->issuer));
  17262. mg_free((void *)(conn->request_info.client_cert->serial));
  17263. mg_free((void *)(conn->request_info.client_cert->finger));
  17264. /* Free certificate memory */
  17265. X509_free(
  17266. (X509 *)conn->request_info.client_cert->peer_cert);
  17267. conn->request_info.client_cert->peer_cert = 0;
  17268. conn->request_info.client_cert->subject = 0;
  17269. conn->request_info.client_cert->issuer = 0;
  17270. conn->request_info.client_cert->serial = 0;
  17271. conn->request_info.client_cert->finger = 0;
  17272. conn->request_info.client_cert = 0;
  17273. }
  17274. } else {
  17275. /* make sure the connection is cleaned up on SSL failure */
  17276. close_connection(conn);
  17277. }
  17278. #endif
  17279. } else {
  17280. /* process HTTP connection */
  17281. init_connection(conn);
  17282. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17283. /* Start with HTTP, WS will be an "upgrade" request later */
  17284. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17285. process_new_connection(conn);
  17286. }
  17287. DEBUG_TRACE("%s", "Connection closed");
  17288. #if defined(USE_SERVER_STATS)
  17289. conn->conn_close_time = time(NULL);
  17290. #endif
  17291. }
  17292. /* Call exit thread user callback */
  17293. if (ctx->callbacks.exit_thread) {
  17294. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17295. }
  17296. /* delete thread local storage objects */
  17297. pthread_setspecific(sTlsKey, NULL);
  17298. #if defined(_WIN32)
  17299. CloseHandle(tls.pthread_cond_helper_mutex);
  17300. #endif
  17301. pthread_mutex_destroy(&conn->mutex);
  17302. /* Free the request buffer. */
  17303. conn->buf_size = 0;
  17304. mg_free(conn->buf);
  17305. conn->buf = NULL;
  17306. /* Free cleaned URI (if any) */
  17307. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17308. mg_free((void *)conn->request_info.local_uri);
  17309. conn->request_info.local_uri = NULL;
  17310. }
  17311. #if defined(USE_SERVER_STATS)
  17312. conn->conn_state = 9; /* done */
  17313. #endif
  17314. DEBUG_TRACE("%s", "exiting");
  17315. }
  17316. /* Threads have different return types on Windows and Unix. */
  17317. #if defined(_WIN32)
  17318. static unsigned __stdcall worker_thread(void *thread_func_param)
  17319. {
  17320. worker_thread_run((struct mg_connection *)thread_func_param);
  17321. return 0;
  17322. }
  17323. #else
  17324. static void *
  17325. worker_thread(void *thread_func_param)
  17326. {
  17327. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17328. struct sigaction sa;
  17329. /* Ignore SIGPIPE */
  17330. memset(&sa, 0, sizeof(sa));
  17331. sa.sa_handler = SIG_IGN;
  17332. sigaction(SIGPIPE, &sa, NULL);
  17333. #endif
  17334. worker_thread_run((struct mg_connection *)thread_func_param);
  17335. return NULL;
  17336. }
  17337. #endif /* _WIN32 */
  17338. /* This is an internal function, thus all arguments are expected to be
  17339. * valid - a NULL check is not required. */
  17340. static void
  17341. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17342. {
  17343. struct socket so;
  17344. char src_addr[IP_ADDR_STR_LEN];
  17345. socklen_t len = sizeof(so.rsa);
  17346. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17347. int on = 1;
  17348. #endif
  17349. memset(&so, 0, sizeof(so));
  17350. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17351. == INVALID_SOCKET) {
  17352. } else if (check_acl(ctx, &so.rsa) != 1) {
  17353. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17354. mg_cry_ctx_internal(ctx,
  17355. "%s: %s is not allowed to connect",
  17356. __func__,
  17357. src_addr);
  17358. closesocket(so.sock);
  17359. } else {
  17360. /* Put so socket structure into the queue */
  17361. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17362. set_close_on_exec(so.sock, NULL, ctx);
  17363. so.is_ssl = listener->is_ssl;
  17364. so.ssl_redir = listener->ssl_redir;
  17365. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17366. mg_cry_ctx_internal(ctx,
  17367. "%s: getsockname() failed: %s",
  17368. __func__,
  17369. strerror(ERRNO));
  17370. }
  17371. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17372. if ((so.lsa.sa.sa_family == AF_INET)
  17373. || (so.lsa.sa.sa_family == AF_INET6)) {
  17374. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17375. * This is needed because if HTTP-level keep-alive
  17376. * is enabled, and client resets the connection, server won't get
  17377. * TCP FIN or RST and will keep the connection open forever. With
  17378. * TCP keep-alive, next keep-alive handshake will figure out that
  17379. * the client is down and will close the server end.
  17380. * Thanks to Igor Klopov who suggested the patch. */
  17381. if (setsockopt(so.sock,
  17382. SOL_SOCKET,
  17383. SO_KEEPALIVE,
  17384. (SOCK_OPT_TYPE)&on,
  17385. sizeof(on))
  17386. != 0) {
  17387. mg_cry_ctx_internal(
  17388. ctx,
  17389. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17390. __func__,
  17391. strerror(ERRNO));
  17392. }
  17393. }
  17394. #endif
  17395. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17396. * to effectively fill up the underlying IP packet payload and
  17397. * reduce the overhead of sending lots of small buffers. However
  17398. * this hurts the server's throughput (ie. operations per second)
  17399. * when HTTP 1.1 persistent connections are used and the responses
  17400. * are relatively small (eg. less than 1400 bytes).
  17401. */
  17402. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17403. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17404. if (set_tcp_nodelay(&so, 1) != 0) {
  17405. mg_cry_ctx_internal(
  17406. ctx,
  17407. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17408. __func__,
  17409. strerror(ERRNO));
  17410. }
  17411. }
  17412. /* The "non blocking" property should already be
  17413. * inherited from the parent socket. Set it for
  17414. * non-compliant socket implementations. */
  17415. set_non_blocking_mode(so.sock);
  17416. so.in_use = 0;
  17417. produce_socket(ctx, &so);
  17418. }
  17419. }
  17420. static void
  17421. master_thread_run(struct mg_context *ctx)
  17422. {
  17423. struct mg_workerTLS tls;
  17424. struct mg_pollfd *pfd;
  17425. unsigned int i;
  17426. unsigned int workerthreadcount;
  17427. if (!ctx) {
  17428. return;
  17429. }
  17430. mg_set_thread_name("master");
  17431. /* Increase priority of the master thread */
  17432. #if defined(_WIN32)
  17433. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17434. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17435. int min_prio = sched_get_priority_min(SCHED_RR);
  17436. int max_prio = sched_get_priority_max(SCHED_RR);
  17437. if ((min_prio >= 0) && (max_prio >= 0)
  17438. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17439. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17440. struct sched_param sched_param = {0};
  17441. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17442. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17443. }
  17444. #endif
  17445. /* Initialize thread local storage */
  17446. #if defined(_WIN32)
  17447. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17448. #endif
  17449. tls.is_master = 1;
  17450. pthread_setspecific(sTlsKey, &tls);
  17451. if (ctx->callbacks.init_thread) {
  17452. /* Callback for the master thread (type 0) */
  17453. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17454. } else {
  17455. tls.user_ptr = NULL;
  17456. }
  17457. /* Lua background script "start" event */
  17458. #if defined(USE_LUA)
  17459. if (ctx->lua_background_state) {
  17460. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17461. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17462. /* call "start()" in Lua */
  17463. lua_getglobal(lstate, "start");
  17464. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17465. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17466. if (ret != 0) {
  17467. struct mg_connection fc;
  17468. lua_cry(fake_connection(&fc, ctx),
  17469. ret,
  17470. lstate,
  17471. "lua_background_script",
  17472. "start");
  17473. }
  17474. } else {
  17475. lua_pop(lstate, 1);
  17476. }
  17477. /* determine if there is a "log()" function in Lua background script */
  17478. lua_getglobal(lstate, "log");
  17479. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17480. ctx->lua_bg_log_available = 1;
  17481. }
  17482. lua_pop(lstate, 1);
  17483. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17484. }
  17485. #endif
  17486. /* Server starts *now* */
  17487. ctx->start_time = time(NULL);
  17488. /* Server accept loop */
  17489. pfd = ctx->listening_socket_fds;
  17490. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17491. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17492. pfd[i].fd = ctx->listening_sockets[i].sock;
  17493. pfd[i].events = POLLIN;
  17494. }
  17495. if (mg_poll(pfd,
  17496. ctx->num_listening_sockets,
  17497. SOCKET_TIMEOUT_QUANTUM,
  17498. &(ctx->stop_flag))
  17499. > 0) {
  17500. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17501. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17502. * successful poll, and POLLIN is defined as
  17503. * (POLLRDNORM | POLLRDBAND)
  17504. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17505. * pfd[i].revents == POLLIN. */
  17506. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17507. && (pfd[i].revents & POLLIN)) {
  17508. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17509. }
  17510. }
  17511. }
  17512. }
  17513. /* Here stop_flag is 1 - Initiate shutdown. */
  17514. DEBUG_TRACE("%s", "stopping workers");
  17515. /* Stop signal received: somebody called mg_stop. Quit. */
  17516. close_all_listening_sockets(ctx);
  17517. /* Wakeup workers that are waiting for connections to handle. */
  17518. #if defined(ALTERNATIVE_QUEUE)
  17519. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17520. event_signal(ctx->client_wait_events[i]);
  17521. }
  17522. #else
  17523. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17524. pthread_cond_broadcast(&ctx->sq_full);
  17525. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17526. #endif
  17527. /* Join all worker threads to avoid leaking threads. */
  17528. workerthreadcount = ctx->cfg_worker_threads;
  17529. for (i = 0; i < workerthreadcount; i++) {
  17530. if (!cw_is_thread_null(&ctx->worker_threadids[i])) {
  17531. mg_join_thread(ctx->worker_threadids[i]);
  17532. }
  17533. }
  17534. #if defined(USE_LUA)
  17535. /* Free Lua state of lua background task */
  17536. if (ctx->lua_background_state) {
  17537. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17538. ctx->lua_bg_log_available = 0;
  17539. /* call "stop()" in Lua */
  17540. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17541. lua_getglobal(lstate, "stop");
  17542. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17543. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17544. if (ret != 0) {
  17545. struct mg_connection fc;
  17546. lua_cry(fake_connection(&fc, ctx),
  17547. ret,
  17548. lstate,
  17549. "lua_background_script",
  17550. "stop");
  17551. }
  17552. }
  17553. lua_close(lstate);
  17554. ctx->lua_background_state = 0;
  17555. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17556. }
  17557. #endif
  17558. DEBUG_TRACE("%s", "exiting");
  17559. /* call exit thread callback */
  17560. if (ctx->callbacks.exit_thread) {
  17561. /* Callback for the master thread (type 0) */
  17562. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17563. }
  17564. #if defined(_WIN32)
  17565. CloseHandle(tls.pthread_cond_helper_mutex);
  17566. #endif
  17567. pthread_setspecific(sTlsKey, NULL);
  17568. /* Signal mg_stop() that we're done.
  17569. * WARNING: This must be the very last thing this
  17570. * thread does, as ctx becomes invalid after this line. */
  17571. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17572. }
  17573. /* Threads have different return types on Windows and Unix. */
  17574. #if defined(_WIN32)
  17575. static unsigned __stdcall master_thread(void *thread_func_param)
  17576. {
  17577. master_thread_run((struct mg_context *)thread_func_param);
  17578. return 0;
  17579. }
  17580. #else
  17581. static void *
  17582. master_thread(void *thread_func_param)
  17583. {
  17584. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17585. struct sigaction sa;
  17586. /* Ignore SIGPIPE */
  17587. memset(&sa, 0, sizeof(sa));
  17588. sa.sa_handler = SIG_IGN;
  17589. sigaction(SIGPIPE, &sa, NULL);
  17590. #endif
  17591. master_thread_run((struct mg_context *)thread_func_param);
  17592. return NULL;
  17593. }
  17594. #endif /* _WIN32 */
  17595. static void
  17596. free_context(struct mg_context *ctx)
  17597. {
  17598. int i;
  17599. struct mg_handler_info *tmp_rh;
  17600. if (ctx == NULL) {
  17601. return;
  17602. }
  17603. /* Call user callback */
  17604. if (ctx->callbacks.exit_context) {
  17605. ctx->callbacks.exit_context(ctx);
  17606. }
  17607. /* All threads exited, no sync is needed. Destroy thread mutex and
  17608. * condvars
  17609. */
  17610. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17611. #if defined(ALTERNATIVE_QUEUE)
  17612. mg_free(ctx->client_socks);
  17613. if (ctx->client_wait_events != NULL) {
  17614. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17615. event_destroy(ctx->client_wait_events[i]);
  17616. }
  17617. mg_free(ctx->client_wait_events);
  17618. }
  17619. #else
  17620. (void)pthread_cond_destroy(&ctx->sq_empty);
  17621. (void)pthread_cond_destroy(&ctx->sq_full);
  17622. mg_free(ctx->squeue);
  17623. #endif
  17624. /* Destroy other context global data structures mutex */
  17625. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17626. #if defined(USE_LUA)
  17627. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17628. #endif
  17629. /* Deallocate config parameters */
  17630. for (i = 0; i < NUM_OPTIONS; i++) {
  17631. if (ctx->dd.config[i] != NULL) {
  17632. #if defined(_MSC_VER)
  17633. #pragma warning(suppress : 6001)
  17634. #endif
  17635. mg_free(ctx->dd.config[i]);
  17636. }
  17637. }
  17638. /* Deallocate request handlers */
  17639. while (ctx->dd.handlers) {
  17640. tmp_rh = ctx->dd.handlers;
  17641. ctx->dd.handlers = tmp_rh->next;
  17642. mg_free(tmp_rh->uri);
  17643. mg_free(tmp_rh);
  17644. }
  17645. #if defined(USE_MBEDTLS)
  17646. if (ctx->dd.ssl_ctx != NULL) {
  17647. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17648. mg_free(ctx->dd.ssl_ctx);
  17649. ctx->dd.ssl_ctx = NULL;
  17650. }
  17651. #elif !defined(NO_SSL)
  17652. /* Deallocate SSL context */
  17653. if (ctx->dd.ssl_ctx != NULL) {
  17654. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17655. int callback_ret =
  17656. (ctx->callbacks.external_ssl_ctx == NULL)
  17657. ? 0
  17658. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17659. if (callback_ret == 0) {
  17660. SSL_CTX_free(ctx->dd.ssl_ctx);
  17661. }
  17662. /* else: ignore error and ommit SSL_CTX_free in case
  17663. * callback_ret is 1 */
  17664. }
  17665. #endif /* !NO_SSL */
  17666. /* Deallocate worker thread ID array */
  17667. mg_free(ctx->worker_threadids);
  17668. /* Deallocate worker thread ID array */
  17669. mg_free(ctx->worker_connections);
  17670. /* deallocate system name string */
  17671. mg_free(ctx->systemName);
  17672. /* Deallocate context itself */
  17673. mg_free(ctx);
  17674. }
  17675. CIVETWEB_API void
  17676. mg_stop(struct mg_context *ctx)
  17677. {
  17678. cw_thread_handle_t mt;
  17679. if (!ctx) {
  17680. return;
  17681. }
  17682. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17683. * two threads is not allowed. */
  17684. mt = ctx->masterthreadid;
  17685. if (cw_is_thread_null(&mt)) {
  17686. return;
  17687. }
  17688. cw_stop_thread(&ctx->masterthreadid);
  17689. /* Set stop flag, so all threads know they have to exit. */
  17690. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17691. /* Join timer thread */
  17692. #if defined(USE_TIMERS)
  17693. timers_exit(ctx);
  17694. #endif
  17695. /* Wait until everything has stopped. */
  17696. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17697. (void)mg_sleep(10);
  17698. }
  17699. /* Wait to stop master thread */
  17700. mg_join_thread(mt);
  17701. /* Close remaining Lua states */
  17702. #if defined(USE_LUA)
  17703. lua_ctx_exit(ctx);
  17704. #endif
  17705. /* Free memory */
  17706. free_context(ctx);
  17707. }
  17708. static void
  17709. get_system_name(char **sysName)
  17710. {
  17711. #if defined(_WIN32)
  17712. char name[128];
  17713. DWORD dwVersion = 0;
  17714. DWORD dwMajorVersion = 0;
  17715. DWORD dwMinorVersion = 0;
  17716. DWORD dwBuild = 0;
  17717. BOOL wowRet, isWoW = FALSE;
  17718. #if defined(_MSC_VER)
  17719. #pragma warning(push)
  17720. /* GetVersion was declared deprecated */
  17721. #pragma warning(disable : 4996)
  17722. #endif
  17723. dwVersion = GetVersion();
  17724. #if defined(_MSC_VER)
  17725. #pragma warning(pop)
  17726. #endif
  17727. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17728. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17729. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17730. (void)dwBuild;
  17731. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17732. sprintf(name,
  17733. "Windows %u.%u%s",
  17734. (unsigned)dwMajorVersion,
  17735. (unsigned)dwMinorVersion,
  17736. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17737. *sysName = mg_strdup(name);
  17738. #elif defined(__ZEPHYR__)
  17739. *sysName = mg_strdup("Zephyr OS");
  17740. #elif defined(ESP_PLATFORM)
  17741. *sysName = mg_strdup("Espressif ESP32");
  17742. #else
  17743. struct utsname name;
  17744. memset(&name, 0, sizeof(name));
  17745. uname(&name);
  17746. *sysName = mg_strdup(name.sysname);
  17747. #endif
  17748. }
  17749. static void
  17750. legacy_init(const char **options)
  17751. {
  17752. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17753. if (options) {
  17754. const char **run_options = options;
  17755. const char *optname = config_options[LISTENING_PORTS].name;
  17756. /* Try to find the "listening_ports" option */
  17757. while (*run_options) {
  17758. if (!strcmp(*run_options, optname)) {
  17759. ports_option = run_options[1];
  17760. }
  17761. run_options += 2;
  17762. }
  17763. }
  17764. if (is_ssl_port_used(ports_option)) {
  17765. /* Initialize with SSL support */
  17766. mg_init_library(MG_FEATURES_TLS);
  17767. } else {
  17768. /* Initialize without SSL support */
  17769. mg_init_library(MG_FEATURES_DEFAULT);
  17770. }
  17771. }
  17772. CIVETWEB_API struct mg_context *
  17773. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17774. {
  17775. struct mg_context *ctx;
  17776. const char *name, *value, *default_value;
  17777. int idx, ok, workerthreadcount;
  17778. unsigned int i;
  17779. int itmp;
  17780. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17781. const char **options =
  17782. ((init != NULL) ? (init->configuration_options) : (NULL));
  17783. struct mg_workerTLS tls;
  17784. if (error != NULL) {
  17785. error->code = MG_ERROR_DATA_CODE_OK;
  17786. error->code_sub = 0;
  17787. if (error->text_buffer_size > 0) {
  17788. *error->text = 0;
  17789. }
  17790. }
  17791. if (mg_init_library_called == 0) {
  17792. /* Legacy INIT, if mg_start is called without mg_init_library.
  17793. * Note: This will cause a memory leak when unloading the library.
  17794. */
  17795. legacy_init(options);
  17796. }
  17797. if (mg_init_library_called == 0) {
  17798. if (error != NULL) {
  17799. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17800. mg_snprintf(NULL,
  17801. NULL, /* No truncation check for error buffers */
  17802. error->text,
  17803. error->text_buffer_size,
  17804. "%s",
  17805. "Library uninitialized");
  17806. }
  17807. return NULL;
  17808. }
  17809. /* Allocate context and initialize reasonable general case defaults. */
  17810. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17811. if (ctx == NULL) {
  17812. if (error != NULL) {
  17813. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17814. error->code_sub = (unsigned)sizeof(*ctx);
  17815. mg_snprintf(NULL,
  17816. NULL, /* No truncation check for error buffers */
  17817. error->text,
  17818. error->text_buffer_size,
  17819. "%s",
  17820. "Out of memory");
  17821. }
  17822. return NULL;
  17823. }
  17824. /* Random number generator will initialize at the first call */
  17825. ctx->dd.auth_nonce_mask =
  17826. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17827. /* Save started thread index to reuse in other external API calls
  17828. * For the sake of thread synchronization all non-civetweb threads
  17829. * can be considered as single external thread */
  17830. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17831. tls.is_master = -1; /* Thread calling mg_start */
  17832. tls.thread_idx = ctx->starter_thread_idx;
  17833. #if defined(_WIN32)
  17834. tls.pthread_cond_helper_mutex = NULL;
  17835. #endif
  17836. pthread_setspecific(sTlsKey, &tls);
  17837. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17838. #if !defined(ALTERNATIVE_QUEUE)
  17839. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17840. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17841. ctx->sq_blocked = 0;
  17842. #endif
  17843. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17844. #if defined(USE_LUA)
  17845. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17846. #endif
  17847. if (!ok) {
  17848. unsigned error_id = (unsigned)ERRNO;
  17849. const char *err_msg =
  17850. "Cannot initialize thread synchronization objects";
  17851. /* Fatal error - abort start. However, this situation should never
  17852. * occur in practice. */
  17853. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17854. if (error != NULL) {
  17855. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17856. error->code_sub = error_id;
  17857. mg_snprintf(NULL,
  17858. NULL, /* No truncation check for error buffers */
  17859. error->text,
  17860. error->text_buffer_size,
  17861. "%s",
  17862. err_msg);
  17863. }
  17864. mg_free(ctx);
  17865. pthread_setspecific(sTlsKey, NULL);
  17866. return NULL;
  17867. }
  17868. if ((init != NULL) && (init->callbacks != NULL)) {
  17869. /* Set all callbacks except exit_context. */
  17870. ctx->callbacks = *init->callbacks;
  17871. exit_callback = init->callbacks->exit_context;
  17872. /* The exit callback is activated once the context is successfully
  17873. * created. It should not be called, if an incomplete context object
  17874. * is deleted during a failed initialization. */
  17875. ctx->callbacks.exit_context = 0;
  17876. }
  17877. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17878. ctx->dd.handlers = NULL;
  17879. ctx->dd.next = NULL;
  17880. #if defined(USE_LUA)
  17881. lua_ctx_init(ctx);
  17882. #endif
  17883. /* Store options */
  17884. while (options && (name = *options++) != NULL) {
  17885. idx = get_option_index(name);
  17886. if (idx == -1) {
  17887. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17888. if (error != NULL) {
  17889. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17890. error->code_sub = (unsigned)-1;
  17891. mg_snprintf(NULL,
  17892. NULL, /* No truncation check for error buffers */
  17893. error->text,
  17894. error->text_buffer_size,
  17895. "Invalid configuration option: %s",
  17896. name);
  17897. }
  17898. free_context(ctx);
  17899. pthread_setspecific(sTlsKey, NULL);
  17900. return NULL;
  17901. } else if ((value = *options++) == NULL) {
  17902. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17903. if (error != NULL) {
  17904. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17905. error->code_sub = (unsigned)idx;
  17906. mg_snprintf(NULL,
  17907. NULL, /* No truncation check for error buffers */
  17908. error->text,
  17909. error->text_buffer_size,
  17910. "Invalid configuration option value: %s",
  17911. name);
  17912. }
  17913. free_context(ctx);
  17914. pthread_setspecific(sTlsKey, NULL);
  17915. return NULL;
  17916. }
  17917. if (ctx->dd.config[idx] != NULL) {
  17918. /* A duplicate configuration option is not an error - the last
  17919. * option value will be used. */
  17920. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17921. mg_free(ctx->dd.config[idx]);
  17922. }
  17923. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17924. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17925. }
  17926. /* Set default value if needed */
  17927. for (i = 0; config_options[i].name != NULL; i++) {
  17928. default_value = config_options[i].default_value;
  17929. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17930. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17931. }
  17932. }
  17933. /* Request size option */
  17934. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17935. if (itmp < 1024) {
  17936. mg_cry_ctx_internal(ctx,
  17937. "%s too small",
  17938. config_options[MAX_REQUEST_SIZE].name);
  17939. if (error != NULL) {
  17940. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17941. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17942. mg_snprintf(NULL,
  17943. NULL, /* No truncation check for error buffers */
  17944. error->text,
  17945. error->text_buffer_size,
  17946. "Invalid configuration option value: %s",
  17947. config_options[MAX_REQUEST_SIZE].name);
  17948. }
  17949. free_context(ctx);
  17950. pthread_setspecific(sTlsKey, NULL);
  17951. return NULL;
  17952. }
  17953. ctx->max_request_size = (unsigned)itmp;
  17954. /* Queue length */
  17955. #if !defined(ALTERNATIVE_QUEUE)
  17956. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17957. if (itmp < 1) {
  17958. mg_cry_ctx_internal(ctx,
  17959. "%s too small",
  17960. config_options[CONNECTION_QUEUE_SIZE].name);
  17961. if (error != NULL) {
  17962. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17963. error->code_sub = CONNECTION_QUEUE_SIZE;
  17964. mg_snprintf(NULL,
  17965. NULL, /* No truncation check for error buffers */
  17966. error->text,
  17967. error->text_buffer_size,
  17968. "Invalid configuration option value: %s",
  17969. config_options[CONNECTION_QUEUE_SIZE].name);
  17970. }
  17971. free_context(ctx);
  17972. pthread_setspecific(sTlsKey, NULL);
  17973. return NULL;
  17974. }
  17975. ctx->squeue =
  17976. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17977. if (ctx->squeue == NULL) {
  17978. mg_cry_ctx_internal(ctx,
  17979. "Out of memory: Cannot allocate %s",
  17980. config_options[CONNECTION_QUEUE_SIZE].name);
  17981. if (error != NULL) {
  17982. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17983. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17984. mg_snprintf(NULL,
  17985. NULL, /* No truncation check for error buffers */
  17986. error->text,
  17987. error->text_buffer_size,
  17988. "Out of memory: Cannot allocate %s",
  17989. config_options[CONNECTION_QUEUE_SIZE].name);
  17990. }
  17991. free_context(ctx);
  17992. pthread_setspecific(sTlsKey, NULL);
  17993. return NULL;
  17994. }
  17995. ctx->sq_size = itmp;
  17996. #endif
  17997. /* Worker thread count option */
  17998. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17999. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18000. if (workerthreadcount <= 0) {
  18001. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18002. } else {
  18003. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18004. }
  18005. if (error != NULL) {
  18006. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18007. error->code_sub = NUM_THREADS;
  18008. mg_snprintf(NULL,
  18009. NULL, /* No truncation check for error buffers */
  18010. error->text,
  18011. error->text_buffer_size,
  18012. "Invalid configuration option value: %s",
  18013. config_options[NUM_THREADS].name);
  18014. }
  18015. free_context(ctx);
  18016. pthread_setspecific(sTlsKey, NULL);
  18017. return NULL;
  18018. }
  18019. /* Document root */
  18020. #if defined(NO_FILES)
  18021. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18022. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18023. if (error != NULL) {
  18024. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18025. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18026. mg_snprintf(NULL,
  18027. NULL, /* No truncation check for error buffers */
  18028. error->text,
  18029. error->text_buffer_size,
  18030. "Invalid configuration option value: %s",
  18031. config_options[DOCUMENT_ROOT].name);
  18032. }
  18033. free_context(ctx);
  18034. pthread_setspecific(sTlsKey, NULL);
  18035. return NULL;
  18036. }
  18037. #endif
  18038. get_system_name(&ctx->systemName);
  18039. #if defined(USE_LUA)
  18040. /* If a Lua background script has been configured, start it. */
  18041. ctx->lua_bg_log_available = 0;
  18042. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18043. char ebuf[256];
  18044. struct vec opt_vec;
  18045. struct vec eq_vec;
  18046. const char *sparams;
  18047. memset(ebuf, 0, sizeof(ebuf));
  18048. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18049. /* Create a Lua state, load all standard libraries and the mg table */
  18050. lua_State *state = mg_lua_context_script_prepare(
  18051. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18052. if (!state) {
  18053. mg_cry_ctx_internal(ctx,
  18054. "lua_background_script load error: %s",
  18055. ebuf);
  18056. if (error != NULL) {
  18057. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18058. mg_snprintf(NULL,
  18059. NULL, /* No truncation check for error buffers */
  18060. error->text,
  18061. error->text_buffer_size,
  18062. "Error in script %s: %s",
  18063. config_options[LUA_BACKGROUND_SCRIPT].name,
  18064. ebuf);
  18065. }
  18066. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18067. free_context(ctx);
  18068. pthread_setspecific(sTlsKey, NULL);
  18069. return NULL;
  18070. }
  18071. /* Add a table with parameters into mg.params */
  18072. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18073. if (sparams && sparams[0]) {
  18074. lua_getglobal(state, "mg");
  18075. lua_pushstring(state, "params");
  18076. lua_newtable(state);
  18077. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18078. != NULL) {
  18079. reg_llstring(
  18080. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18081. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18082. break;
  18083. }
  18084. lua_rawset(state, -3);
  18085. lua_pop(state, 1);
  18086. }
  18087. /* Call script */
  18088. state = mg_lua_context_script_run(state,
  18089. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18090. ctx,
  18091. ebuf,
  18092. sizeof(ebuf));
  18093. if (!state) {
  18094. mg_cry_ctx_internal(ctx,
  18095. "lua_background_script start error: %s",
  18096. ebuf);
  18097. if (error != NULL) {
  18098. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18099. mg_snprintf(NULL,
  18100. NULL, /* No truncation check for error buffers */
  18101. error->text,
  18102. error->text_buffer_size,
  18103. "Error in script %s: %s",
  18104. config_options[DOCUMENT_ROOT].name,
  18105. ebuf);
  18106. }
  18107. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18108. free_context(ctx);
  18109. pthread_setspecific(sTlsKey, NULL);
  18110. return NULL;
  18111. }
  18112. /* state remains valid */
  18113. ctx->lua_background_state = (void *)state;
  18114. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18115. } else {
  18116. ctx->lua_background_state = 0;
  18117. }
  18118. #endif
  18119. /* Step by step initialization of ctx - depending on build options */
  18120. #if !defined(NO_FILESYSTEMS)
  18121. if (!set_gpass_option(ctx, NULL)) {
  18122. const char *err_msg = "Invalid global password file";
  18123. /* Fatal error - abort start. */
  18124. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18125. if (error != NULL) {
  18126. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18127. mg_snprintf(NULL,
  18128. NULL, /* No truncation check for error buffers */
  18129. error->text,
  18130. error->text_buffer_size,
  18131. "%s",
  18132. err_msg);
  18133. }
  18134. free_context(ctx);
  18135. pthread_setspecific(sTlsKey, NULL);
  18136. return NULL;
  18137. }
  18138. #endif
  18139. #if defined(USE_MBEDTLS)
  18140. if (!mg_sslctx_init(ctx, NULL)) {
  18141. const char *err_msg = "Error initializing SSL context";
  18142. /* Fatal error - abort start. */
  18143. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18144. if (error != NULL) {
  18145. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18146. mg_snprintf(NULL,
  18147. NULL, /* No truncation check for error buffers */
  18148. error->text,
  18149. error->text_buffer_size,
  18150. "%s",
  18151. err_msg);
  18152. }
  18153. free_context(ctx);
  18154. pthread_setspecific(sTlsKey, NULL);
  18155. return NULL;
  18156. }
  18157. #elif !defined(NO_SSL)
  18158. if (!init_ssl_ctx(ctx, NULL)) {
  18159. const char *err_msg = "Error initializing SSL context";
  18160. /* Fatal error - abort start. */
  18161. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18162. if (error != NULL) {
  18163. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18164. mg_snprintf(NULL,
  18165. NULL, /* No truncation check for error buffers */
  18166. error->text,
  18167. error->text_buffer_size,
  18168. "%s",
  18169. err_msg);
  18170. }
  18171. free_context(ctx);
  18172. pthread_setspecific(sTlsKey, NULL);
  18173. return NULL;
  18174. }
  18175. #endif
  18176. if (!set_ports_option(ctx)) {
  18177. const char *err_msg = "Failed to setup server ports";
  18178. /* Fatal error - abort start. */
  18179. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18180. if (error != NULL) {
  18181. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18182. mg_snprintf(NULL,
  18183. NULL, /* No truncation check for error buffers */
  18184. error->text,
  18185. error->text_buffer_size,
  18186. "%s",
  18187. err_msg);
  18188. }
  18189. free_context(ctx);
  18190. pthread_setspecific(sTlsKey, NULL);
  18191. return NULL;
  18192. }
  18193. #if !defined(_WIN32) && !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  18194. if (!set_uid_option(ctx)) {
  18195. const char *err_msg = "Failed to run as configured user";
  18196. /* Fatal error - abort start. */
  18197. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18198. if (error != NULL) {
  18199. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18200. mg_snprintf(NULL,
  18201. NULL, /* No truncation check for error buffers */
  18202. error->text,
  18203. error->text_buffer_size,
  18204. "%s",
  18205. err_msg);
  18206. }
  18207. free_context(ctx);
  18208. pthread_setspecific(sTlsKey, NULL);
  18209. return NULL;
  18210. }
  18211. #endif
  18212. if (!set_acl_option(ctx)) {
  18213. const char *err_msg = "Failed to setup access control list";
  18214. /* Fatal error - abort start. */
  18215. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18216. if (error != NULL) {
  18217. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18218. mg_snprintf(NULL,
  18219. NULL, /* No truncation check for error buffers */
  18220. error->text,
  18221. error->text_buffer_size,
  18222. "%s",
  18223. err_msg);
  18224. }
  18225. free_context(ctx);
  18226. pthread_setspecific(sTlsKey, NULL);
  18227. return NULL;
  18228. }
  18229. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  18230. ctx->worker_threadids = (cw_thread_handle_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18231. sizeof(cw_thread_handle_t),
  18232. ctx);
  18233. if (ctx->worker_threadids == NULL) {
  18234. const char *err_msg = "Not enough memory for worker thread ID array";
  18235. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18236. if (error != NULL) {
  18237. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18238. error->code_sub =
  18239. (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(cw_thread_handle_t);
  18240. mg_snprintf(NULL,
  18241. NULL, /* No truncation check for error buffers */
  18242. error->text,
  18243. error->text_buffer_size,
  18244. "%s",
  18245. err_msg);
  18246. }
  18247. free_context(ctx);
  18248. pthread_setspecific(sTlsKey, NULL);
  18249. return NULL;
  18250. }
  18251. ctx->worker_connections =
  18252. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18253. sizeof(struct mg_connection),
  18254. ctx);
  18255. if (ctx->worker_connections == NULL) {
  18256. const char *err_msg =
  18257. "Not enough memory for worker thread connection array";
  18258. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18259. if (error != NULL) {
  18260. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18261. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18262. * (unsigned)sizeof(struct mg_connection);
  18263. mg_snprintf(NULL,
  18264. NULL, /* No truncation check for error buffers */
  18265. error->text,
  18266. error->text_buffer_size,
  18267. "%s",
  18268. err_msg);
  18269. }
  18270. free_context(ctx);
  18271. pthread_setspecific(sTlsKey, NULL);
  18272. return NULL;
  18273. }
  18274. #if defined(ALTERNATIVE_QUEUE)
  18275. ctx->client_wait_events =
  18276. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18277. sizeof(ctx->client_wait_events[0]),
  18278. ctx);
  18279. if (ctx->client_wait_events == NULL) {
  18280. const char *err_msg = "Not enough memory for worker event array";
  18281. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18282. mg_free(ctx->worker_threadids);
  18283. if (error != NULL) {
  18284. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18285. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18286. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18287. mg_snprintf(NULL,
  18288. NULL, /* No truncation check for error buffers */
  18289. error->text,
  18290. error->text_buffer_size,
  18291. "%s",
  18292. err_msg);
  18293. }
  18294. free_context(ctx);
  18295. pthread_setspecific(sTlsKey, NULL);
  18296. return NULL;
  18297. }
  18298. ctx->client_socks =
  18299. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18300. sizeof(ctx->client_socks[0]),
  18301. ctx);
  18302. if (ctx->client_socks == NULL) {
  18303. const char *err_msg = "Not enough memory for worker socket array";
  18304. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18305. mg_free(ctx->client_wait_events);
  18306. mg_free(ctx->worker_threadids);
  18307. if (error != NULL) {
  18308. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18309. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18310. * (unsigned)sizeof(ctx->client_socks[0]);
  18311. mg_snprintf(NULL,
  18312. NULL, /* No truncation check for error buffers */
  18313. error->text,
  18314. error->text_buffer_size,
  18315. "%s",
  18316. err_msg);
  18317. }
  18318. free_context(ctx);
  18319. pthread_setspecific(sTlsKey, NULL);
  18320. return NULL;
  18321. }
  18322. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18323. ctx->client_wait_events[i] = event_create();
  18324. if (ctx->client_wait_events[i] == 0) {
  18325. const char *err_msg = "Error creating worker event %i";
  18326. mg_cry_ctx_internal(ctx, err_msg, i);
  18327. while (i > 0) {
  18328. i--;
  18329. event_destroy(ctx->client_wait_events[i]);
  18330. }
  18331. mg_free(ctx->client_socks);
  18332. mg_free(ctx->client_wait_events);
  18333. mg_free(ctx->worker_threadids);
  18334. if (error != NULL) {
  18335. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18336. error->code_sub = ERRNO;
  18337. mg_snprintf(NULL,
  18338. NULL, /* No truncation check for error buffers */
  18339. error->text,
  18340. error->text_buffer_size,
  18341. err_msg,
  18342. i);
  18343. }
  18344. free_context(ctx);
  18345. pthread_setspecific(sTlsKey, NULL);
  18346. return NULL;
  18347. }
  18348. }
  18349. #endif
  18350. #if defined(USE_TIMERS)
  18351. if (timers_init(ctx) != 0) {
  18352. const char *err_msg = "Error creating timers";
  18353. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18354. if (error != NULL) {
  18355. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18356. error->code_sub = ERRNO;
  18357. mg_snprintf(NULL,
  18358. NULL, /* No truncation check for error buffers */
  18359. error->text,
  18360. error->text_buffer_size,
  18361. "%s",
  18362. err_msg);
  18363. }
  18364. free_context(ctx);
  18365. pthread_setspecific(sTlsKey, NULL);
  18366. return NULL;
  18367. }
  18368. #endif
  18369. /* Context has been created - init user libraries */
  18370. if (ctx->callbacks.init_context) {
  18371. ctx->callbacks.init_context(ctx);
  18372. }
  18373. /* From now, the context is successfully created.
  18374. * When it is destroyed, the exit callback should be called. */
  18375. ctx->callbacks.exit_context = exit_callback;
  18376. ctx->context_type = CONTEXT_SERVER; /* server context */
  18377. /* Start worker threads */
  18378. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18379. /* worker_thread sets up the other fields */
  18380. ctx->worker_connections[i].phys_ctx = ctx;
  18381. if (mg_start_thread_with_id(worker_thread,
  18382. &ctx->worker_connections[i],
  18383. &ctx->worker_threadids[i])
  18384. != 0) {
  18385. long error_no = (long)ERRNO;
  18386. /* thread was not created */
  18387. if (i > 0) {
  18388. /* If the second, third, ... thread cannot be created, set a
  18389. * warning, but keep running. */
  18390. mg_cry_ctx_internal(ctx,
  18391. "Cannot start worker thread %i: error %ld",
  18392. i + 1,
  18393. error_no);
  18394. /* If the server initialization should stop here, all
  18395. * threads that have already been created must be stopped
  18396. * first, before any free_context(ctx) call.
  18397. */
  18398. } else {
  18399. /* If the first worker thread cannot be created, stop
  18400. * initialization and free the entire server context. */
  18401. mg_cry_ctx_internal(ctx,
  18402. "Cannot create threads: error %ld",
  18403. error_no);
  18404. if (error != NULL) {
  18405. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18406. error->code_sub = (unsigned)error_no;
  18407. mg_snprintf(
  18408. NULL,
  18409. NULL, /* No truncation check for error buffers */
  18410. error->text,
  18411. error->text_buffer_size,
  18412. "Cannot create first worker thread: error %ld",
  18413. error_no);
  18414. }
  18415. free_context(ctx);
  18416. pthread_setspecific(sTlsKey, NULL);
  18417. return NULL;
  18418. }
  18419. break;
  18420. }
  18421. }
  18422. /* Start master (listening) thread */
  18423. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18424. pthread_setspecific(sTlsKey, NULL);
  18425. return ctx;
  18426. }
  18427. CIVETWEB_API struct mg_context *
  18428. mg_start(const struct mg_callbacks *callbacks,
  18429. void *user_data,
  18430. const char **options)
  18431. {
  18432. struct mg_init_data init = {0};
  18433. init.callbacks = callbacks;
  18434. init.user_data = user_data;
  18435. init.configuration_options = options;
  18436. return mg_start2(&init, NULL);
  18437. }
  18438. /* Add an additional domain to an already running web server. */
  18439. CIVETWEB_API int
  18440. mg_start_domain2(struct mg_context *ctx,
  18441. const char **options,
  18442. struct mg_error_data *error)
  18443. {
  18444. const char *name;
  18445. const char *value;
  18446. const char *default_value;
  18447. struct mg_domain_context *new_dom;
  18448. struct mg_domain_context *dom;
  18449. int idx, i;
  18450. if (error != NULL) {
  18451. error->code = MG_ERROR_DATA_CODE_OK;
  18452. error->code_sub = 0;
  18453. if (error->text_buffer_size > 0) {
  18454. *error->text = 0;
  18455. }
  18456. }
  18457. if ((ctx == NULL) || (options == NULL)) {
  18458. if (error != NULL) {
  18459. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18460. mg_snprintf(NULL,
  18461. NULL, /* No truncation check for error buffers */
  18462. error->text,
  18463. error->text_buffer_size,
  18464. "%s",
  18465. "Invalid parameters");
  18466. }
  18467. return -1;
  18468. }
  18469. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18470. if (error != NULL) {
  18471. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18472. mg_snprintf(NULL,
  18473. NULL, /* No truncation check for error buffers */
  18474. error->text,
  18475. error->text_buffer_size,
  18476. "%s",
  18477. "Server already stopped");
  18478. }
  18479. return -7;
  18480. }
  18481. new_dom = (struct mg_domain_context *)
  18482. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18483. if (!new_dom) {
  18484. /* Out of memory */
  18485. if (error != NULL) {
  18486. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18487. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18488. mg_snprintf(NULL,
  18489. NULL, /* No truncation check for error buffers */
  18490. error->text,
  18491. error->text_buffer_size,
  18492. "%s",
  18493. "Out or memory");
  18494. }
  18495. return -6;
  18496. }
  18497. /* Store options - TODO: unite duplicate code */
  18498. while (options && (name = *options++) != NULL) {
  18499. idx = get_option_index(name);
  18500. if (idx == -1) {
  18501. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18502. if (error != NULL) {
  18503. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18504. error->code_sub = (unsigned)-1;
  18505. mg_snprintf(NULL,
  18506. NULL, /* No truncation check for error buffers */
  18507. error->text,
  18508. error->text_buffer_size,
  18509. "Invalid option: %s",
  18510. name);
  18511. }
  18512. mg_free(new_dom);
  18513. return -2;
  18514. } else if ((value = *options++) == NULL) {
  18515. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18516. if (error != NULL) {
  18517. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18518. error->code_sub = idx;
  18519. mg_snprintf(NULL,
  18520. NULL, /* No truncation check for error buffers */
  18521. error->text,
  18522. error->text_buffer_size,
  18523. "Invalid option value: %s",
  18524. name);
  18525. }
  18526. mg_free(new_dom);
  18527. return -2;
  18528. }
  18529. if (new_dom->config[idx] != NULL) {
  18530. /* Duplicate option: Later values overwrite earlier ones. */
  18531. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18532. mg_free(new_dom->config[idx]);
  18533. }
  18534. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18535. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18536. }
  18537. /* Authentication domain is mandatory */
  18538. /* TODO: Maybe use a new option hostname? */
  18539. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18540. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18541. if (error != NULL) {
  18542. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18543. error->code_sub = AUTHENTICATION_DOMAIN;
  18544. mg_snprintf(NULL,
  18545. NULL, /* No truncation check for error buffers */
  18546. error->text,
  18547. error->text_buffer_size,
  18548. "Mandatory option %s missing",
  18549. config_options[AUTHENTICATION_DOMAIN].name);
  18550. }
  18551. mg_free(new_dom);
  18552. return -4;
  18553. }
  18554. /* Set default value if needed. Take the config value from
  18555. * ctx as a default value. */
  18556. for (i = 0; config_options[i].name != NULL; i++) {
  18557. default_value = ctx->dd.config[i];
  18558. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18559. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18560. }
  18561. }
  18562. new_dom->handlers = NULL;
  18563. new_dom->next = NULL;
  18564. new_dom->nonce_count = 0;
  18565. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18566. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18567. new_dom->shared_lua_websockets = NULL;
  18568. #endif
  18569. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18570. if (!init_ssl_ctx(ctx, new_dom)) {
  18571. /* Init SSL failed */
  18572. if (error != NULL) {
  18573. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18574. mg_snprintf(NULL,
  18575. NULL, /* No truncation check for error buffers */
  18576. error->text,
  18577. error->text_buffer_size,
  18578. "%s",
  18579. "Initializing SSL context failed");
  18580. }
  18581. mg_free(new_dom);
  18582. return -3;
  18583. }
  18584. #endif
  18585. /* Add element to linked list. */
  18586. mg_lock_context(ctx);
  18587. idx = 0;
  18588. dom = &(ctx->dd);
  18589. for (;;) {
  18590. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18591. dom->config[AUTHENTICATION_DOMAIN])) {
  18592. /* Domain collision */
  18593. mg_cry_ctx_internal(ctx,
  18594. "domain %s already in use",
  18595. new_dom->config[AUTHENTICATION_DOMAIN]);
  18596. if (error != NULL) {
  18597. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18598. mg_snprintf(NULL,
  18599. NULL, /* No truncation check for error buffers */
  18600. error->text,
  18601. error->text_buffer_size,
  18602. "Domain %s specified by %s is already in use",
  18603. new_dom->config[AUTHENTICATION_DOMAIN],
  18604. config_options[AUTHENTICATION_DOMAIN].name);
  18605. }
  18606. mg_free(new_dom);
  18607. mg_unlock_context(ctx);
  18608. return -5;
  18609. }
  18610. /* Count number of domains */
  18611. idx++;
  18612. if (dom->next == NULL) {
  18613. dom->next = new_dom;
  18614. break;
  18615. }
  18616. dom = dom->next;
  18617. }
  18618. mg_unlock_context(ctx);
  18619. /* Return domain number */
  18620. return idx;
  18621. }
  18622. CIVETWEB_API int
  18623. mg_start_domain(struct mg_context *ctx, const char **options)
  18624. {
  18625. return mg_start_domain2(ctx, options, NULL);
  18626. }
  18627. /* Feature check API function */
  18628. CIVETWEB_API unsigned
  18629. mg_check_feature(unsigned feature)
  18630. {
  18631. static const unsigned feature_set = 0
  18632. /* Set bits for available features according to API documentation.
  18633. * This bit mask is created at compile time, according to the active
  18634. * preprocessor defines. It is a single const value at runtime. */
  18635. #if !defined(NO_FILES)
  18636. | MG_FEATURES_FILES
  18637. #endif
  18638. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18639. | MG_FEATURES_SSL
  18640. #endif
  18641. #if !defined(NO_CGI)
  18642. | MG_FEATURES_CGI
  18643. #endif
  18644. #if defined(USE_IPV6)
  18645. | MG_FEATURES_IPV6
  18646. #endif
  18647. #if defined(USE_WEBSOCKET)
  18648. | MG_FEATURES_WEBSOCKET
  18649. #endif
  18650. #if defined(USE_LUA)
  18651. | MG_FEATURES_LUA
  18652. #endif
  18653. #if defined(USE_DUKTAPE)
  18654. | MG_FEATURES_SSJS
  18655. #endif
  18656. #if !defined(NO_CACHING)
  18657. | MG_FEATURES_CACHE
  18658. #endif
  18659. #if defined(USE_SERVER_STATS)
  18660. | MG_FEATURES_STATS
  18661. #endif
  18662. #if defined(USE_ZLIB)
  18663. | MG_FEATURES_COMPRESSION
  18664. #endif
  18665. #if defined(USE_HTTP2)
  18666. | MG_FEATURES_HTTP2
  18667. #endif
  18668. #if defined(USE_X_DOM_SOCKET)
  18669. | MG_FEATURES_X_DOMAIN_SOCKET
  18670. #endif
  18671. /* Set some extra bits not defined in the API documentation.
  18672. * These bits may change without further notice. */
  18673. #if defined(MG_LEGACY_INTERFACE)
  18674. | 0x80000000u
  18675. #endif
  18676. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18677. | 0x40000000u
  18678. #endif
  18679. #if !defined(NO_RESPONSE_BUFFERING)
  18680. | 0x20000000u
  18681. #endif
  18682. #if defined(MEMORY_DEBUGGING)
  18683. | 0x10000000u
  18684. #endif
  18685. ;
  18686. return (feature & feature_set);
  18687. }
  18688. static size_t
  18689. mg_str_append(char **dst, char *end, const char *src)
  18690. {
  18691. size_t len = strlen(src);
  18692. if (*dst != end) {
  18693. /* Append src if enough space, or close dst. */
  18694. if ((size_t)(end - *dst) > len) {
  18695. strcpy(*dst, src);
  18696. *dst += len;
  18697. } else {
  18698. *dst = end;
  18699. }
  18700. }
  18701. return len;
  18702. }
  18703. /* Get system information. It can be printed or stored by the caller.
  18704. * Return the size of available information. */
  18705. CIVETWEB_API int
  18706. mg_get_system_info(char *buffer, int buflen)
  18707. {
  18708. char *end, *append_eoobj = NULL, block[256];
  18709. size_t system_info_length = 0;
  18710. #if defined(_WIN32)
  18711. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18712. #else
  18713. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18714. #endif
  18715. if ((buffer == NULL) || (buflen < 1)) {
  18716. buflen = 0;
  18717. end = buffer;
  18718. } else {
  18719. *buffer = 0;
  18720. end = buffer + buflen;
  18721. }
  18722. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18723. /* has enough space to append eoobj */
  18724. append_eoobj = buffer;
  18725. if (end) {
  18726. end -= sizeof(eoobj) - 1;
  18727. }
  18728. }
  18729. system_info_length += mg_str_append(&buffer, end, "{");
  18730. /* Server version */
  18731. {
  18732. const char *version = mg_version();
  18733. mg_snprintf(NULL,
  18734. NULL,
  18735. block,
  18736. sizeof(block),
  18737. "%s\"version\" : \"%s\"",
  18738. eol,
  18739. version);
  18740. system_info_length += mg_str_append(&buffer, end, block);
  18741. }
  18742. /* System info */
  18743. {
  18744. #if defined(_WIN32)
  18745. DWORD dwVersion = 0;
  18746. DWORD dwMajorVersion = 0;
  18747. DWORD dwMinorVersion = 0;
  18748. SYSTEM_INFO si;
  18749. GetSystemInfo(&si);
  18750. #if defined(_MSC_VER)
  18751. #pragma warning(push)
  18752. /* GetVersion was declared deprecated */
  18753. #pragma warning(disable : 4996)
  18754. #endif
  18755. dwVersion = GetVersion();
  18756. #if defined(_MSC_VER)
  18757. #pragma warning(pop)
  18758. #endif
  18759. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18760. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18761. mg_snprintf(NULL,
  18762. NULL,
  18763. block,
  18764. sizeof(block),
  18765. ",%s\"os\" : \"Windows %u.%u\"",
  18766. eol,
  18767. (unsigned)dwMajorVersion,
  18768. (unsigned)dwMinorVersion);
  18769. system_info_length += mg_str_append(&buffer, end, block);
  18770. mg_snprintf(NULL,
  18771. NULL,
  18772. block,
  18773. sizeof(block),
  18774. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18775. eol,
  18776. (unsigned)si.wProcessorArchitecture,
  18777. (unsigned)si.dwNumberOfProcessors,
  18778. (unsigned)si.dwActiveProcessorMask);
  18779. system_info_length += mg_str_append(&buffer, end, block);
  18780. #elif defined(__ZEPHYR__)
  18781. mg_snprintf(NULL,
  18782. NULL,
  18783. block,
  18784. sizeof(block),
  18785. ",%s\"os\" : \"%s %s\"",
  18786. eol,
  18787. "Zephyr OS",
  18788. ZEPHYR_VERSION);
  18789. system_info_length += mg_str_append(&buffer, end, block);
  18790. #elif defined(ESP_PLATFORM)
  18791. mg_snprintf(NULL,
  18792. NULL,
  18793. block,
  18794. sizeof(block),
  18795. ",%s\"os\" : \"%s %s\"",
  18796. eol,
  18797. "Espressif",
  18798. "Bell");
  18799. system_info_length += mg_str_append(&buffer, end, block);
  18800. #else
  18801. struct utsname name;
  18802. memset(&name, 0, sizeof(name));
  18803. uname(&name);
  18804. mg_snprintf(NULL,
  18805. NULL,
  18806. block,
  18807. sizeof(block),
  18808. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18809. eol,
  18810. name.sysname,
  18811. name.version,
  18812. name.release,
  18813. name.machine);
  18814. system_info_length += mg_str_append(&buffer, end, block);
  18815. #endif
  18816. }
  18817. /* Features */
  18818. {
  18819. mg_snprintf(NULL,
  18820. NULL,
  18821. block,
  18822. sizeof(block),
  18823. ",%s\"features\" : %lu"
  18824. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18825. eol,
  18826. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18827. eol,
  18828. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18829. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18830. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18831. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18832. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18833. : "",
  18834. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18835. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18836. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18837. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18838. system_info_length += mg_str_append(&buffer, end, block);
  18839. #if defined(USE_LUA)
  18840. mg_snprintf(NULL,
  18841. NULL,
  18842. block,
  18843. sizeof(block),
  18844. ",%s\"lua_version\" : \"%u (%s)\"",
  18845. eol,
  18846. (unsigned)LUA_VERSION_NUM,
  18847. LUA_RELEASE);
  18848. system_info_length += mg_str_append(&buffer, end, block);
  18849. #endif
  18850. #if defined(USE_DUKTAPE)
  18851. mg_snprintf(NULL,
  18852. NULL,
  18853. block,
  18854. sizeof(block),
  18855. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18856. eol,
  18857. (unsigned)DUK_VERSION / 10000,
  18858. ((unsigned)DUK_VERSION / 100) % 100,
  18859. (unsigned)DUK_VERSION % 100);
  18860. system_info_length += mg_str_append(&buffer, end, block);
  18861. #endif
  18862. }
  18863. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18864. {
  18865. #if defined(BUILD_DATE)
  18866. const char *bd = BUILD_DATE;
  18867. #else
  18868. #if defined(GCC_DIAGNOSTIC)
  18869. #if GCC_VERSION >= 40900
  18870. #pragma GCC diagnostic push
  18871. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18872. * does not work in some versions. If "BUILD_DATE" is defined to some
  18873. * string, it is used instead of __DATE__. */
  18874. #pragma GCC diagnostic ignored "-Wdate-time"
  18875. #endif
  18876. #endif
  18877. const char *bd = __DATE__;
  18878. #if defined(GCC_DIAGNOSTIC)
  18879. #if GCC_VERSION >= 40900
  18880. #pragma GCC diagnostic pop
  18881. #endif
  18882. #endif
  18883. #endif
  18884. mg_snprintf(
  18885. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18886. system_info_length += mg_str_append(&buffer, end, block);
  18887. }
  18888. /* Compiler information */
  18889. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18890. {
  18891. #if defined(_MSC_VER)
  18892. mg_snprintf(NULL,
  18893. NULL,
  18894. block,
  18895. sizeof(block),
  18896. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18897. eol,
  18898. (unsigned)_MSC_VER,
  18899. (unsigned)_MSC_FULL_VER);
  18900. system_info_length += mg_str_append(&buffer, end, block);
  18901. #elif defined(__MINGW64__)
  18902. mg_snprintf(NULL,
  18903. NULL,
  18904. block,
  18905. sizeof(block),
  18906. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18907. eol,
  18908. (unsigned)__MINGW64_VERSION_MAJOR,
  18909. (unsigned)__MINGW64_VERSION_MINOR);
  18910. system_info_length += mg_str_append(&buffer, end, block);
  18911. mg_snprintf(NULL,
  18912. NULL,
  18913. block,
  18914. sizeof(block),
  18915. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18916. eol,
  18917. (unsigned)__MINGW32_MAJOR_VERSION,
  18918. (unsigned)__MINGW32_MINOR_VERSION);
  18919. system_info_length += mg_str_append(&buffer, end, block);
  18920. #elif defined(__MINGW32__)
  18921. mg_snprintf(NULL,
  18922. NULL,
  18923. block,
  18924. sizeof(block),
  18925. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18926. eol,
  18927. (unsigned)__MINGW32_MAJOR_VERSION,
  18928. (unsigned)__MINGW32_MINOR_VERSION);
  18929. system_info_length += mg_str_append(&buffer, end, block);
  18930. #elif defined(__clang__)
  18931. mg_snprintf(NULL,
  18932. NULL,
  18933. block,
  18934. sizeof(block),
  18935. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18936. eol,
  18937. __clang_major__,
  18938. __clang_minor__,
  18939. __clang_patchlevel__,
  18940. __clang_version__);
  18941. system_info_length += mg_str_append(&buffer, end, block);
  18942. #elif defined(__GNUC__)
  18943. mg_snprintf(NULL,
  18944. NULL,
  18945. block,
  18946. sizeof(block),
  18947. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18948. eol,
  18949. (unsigned)__GNUC__,
  18950. (unsigned)__GNUC_MINOR__,
  18951. (unsigned)__GNUC_PATCHLEVEL__);
  18952. system_info_length += mg_str_append(&buffer, end, block);
  18953. #elif defined(__INTEL_COMPILER)
  18954. mg_snprintf(NULL,
  18955. NULL,
  18956. block,
  18957. sizeof(block),
  18958. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18959. eol,
  18960. (unsigned)__INTEL_COMPILER);
  18961. system_info_length += mg_str_append(&buffer, end, block);
  18962. #elif defined(__BORLANDC__)
  18963. mg_snprintf(NULL,
  18964. NULL,
  18965. block,
  18966. sizeof(block),
  18967. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18968. eol,
  18969. (unsigned)__BORLANDC__);
  18970. system_info_length += mg_str_append(&buffer, end, block);
  18971. #elif defined(__SUNPRO_C)
  18972. mg_snprintf(NULL,
  18973. NULL,
  18974. block,
  18975. sizeof(block),
  18976. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18977. eol,
  18978. (unsigned)__SUNPRO_C);
  18979. system_info_length += mg_str_append(&buffer, end, block);
  18980. #else
  18981. mg_snprintf(NULL,
  18982. NULL,
  18983. block,
  18984. sizeof(block),
  18985. ",%s\"compiler\" : \"other\"",
  18986. eol);
  18987. system_info_length += mg_str_append(&buffer, end, block);
  18988. #endif
  18989. }
  18990. /* Determine 32/64 bit data mode.
  18991. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18992. {
  18993. mg_snprintf(NULL,
  18994. NULL,
  18995. block,
  18996. sizeof(block),
  18997. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18998. "char:%u/%u, "
  18999. "ptr:%u, size:%u, time:%u\"",
  19000. eol,
  19001. (unsigned)sizeof(short),
  19002. (unsigned)sizeof(int),
  19003. (unsigned)sizeof(long),
  19004. (unsigned)sizeof(long long),
  19005. (unsigned)sizeof(float),
  19006. (unsigned)sizeof(double),
  19007. (unsigned)sizeof(long double),
  19008. (unsigned)sizeof(char),
  19009. (unsigned)sizeof(wchar_t),
  19010. (unsigned)sizeof(void *),
  19011. (unsigned)sizeof(size_t),
  19012. (unsigned)sizeof(time_t));
  19013. system_info_length += mg_str_append(&buffer, end, block);
  19014. }
  19015. /* Terminate string */
  19016. if (append_eoobj) {
  19017. strcat(append_eoobj, eoobj);
  19018. }
  19019. system_info_length += sizeof(eoobj) - 1;
  19020. return (int)system_info_length;
  19021. }
  19022. /* Get context information. It can be printed or stored by the caller.
  19023. * Return the size of available information. */
  19024. CIVETWEB_API int
  19025. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19026. {
  19027. #if defined(USE_SERVER_STATS)
  19028. char *end, *append_eoobj = NULL, block[256];
  19029. size_t context_info_length = 0;
  19030. #if defined(_WIN32)
  19031. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19032. #else
  19033. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19034. #endif
  19035. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19036. if ((buffer == NULL) || (buflen < 1)) {
  19037. buflen = 0;
  19038. end = buffer;
  19039. } else {
  19040. *buffer = 0;
  19041. end = buffer + buflen;
  19042. }
  19043. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19044. /* has enough space to append eoobj */
  19045. append_eoobj = buffer;
  19046. end -= sizeof(eoobj) - 1;
  19047. }
  19048. context_info_length += mg_str_append(&buffer, end, "{");
  19049. if (ms) { /* <-- should be always true */
  19050. /* Memory information */
  19051. int blockCount = (int)ms->blockCount;
  19052. int64_t totalMemUsed = ms->totalMemUsed;
  19053. int64_t maxMemUsed = ms->maxMemUsed;
  19054. if (totalMemUsed > maxMemUsed) {
  19055. maxMemUsed = totalMemUsed;
  19056. }
  19057. mg_snprintf(NULL,
  19058. NULL,
  19059. block,
  19060. sizeof(block),
  19061. "%s\"memory\" : {%s"
  19062. "\"blocks\" : %i,%s"
  19063. "\"used\" : %" INT64_FMT ",%s"
  19064. "\"maxUsed\" : %" INT64_FMT "%s"
  19065. "}",
  19066. eol,
  19067. eol,
  19068. blockCount,
  19069. eol,
  19070. totalMemUsed,
  19071. eol,
  19072. maxMemUsed,
  19073. eol);
  19074. context_info_length += mg_str_append(&buffer, end, block);
  19075. }
  19076. if (ctx) {
  19077. /* Declare all variables at begin of the block, to comply
  19078. * with old C standards. */
  19079. char start_time_str[64] = {0};
  19080. char now_str[64] = {0};
  19081. time_t start_time = ctx->start_time;
  19082. time_t now = time(NULL);
  19083. int64_t total_data_read, total_data_written;
  19084. int active_connections = (int)ctx->active_connections;
  19085. int max_active_connections = (int)ctx->max_active_connections;
  19086. int total_connections = (int)ctx->total_connections;
  19087. if (active_connections > max_active_connections) {
  19088. max_active_connections = active_connections;
  19089. }
  19090. if (active_connections > total_connections) {
  19091. total_connections = active_connections;
  19092. }
  19093. /* Connections information */
  19094. mg_snprintf(NULL,
  19095. NULL,
  19096. block,
  19097. sizeof(block),
  19098. ",%s\"connections\" : {%s"
  19099. "\"active\" : %i,%s"
  19100. "\"maxActive\" : %i,%s"
  19101. "\"total\" : %i%s"
  19102. "}",
  19103. eol,
  19104. eol,
  19105. active_connections,
  19106. eol,
  19107. max_active_connections,
  19108. eol,
  19109. total_connections,
  19110. eol);
  19111. context_info_length += mg_str_append(&buffer, end, block);
  19112. /* Queue information */
  19113. #if !defined(ALTERNATIVE_QUEUE)
  19114. mg_snprintf(NULL,
  19115. NULL,
  19116. block,
  19117. sizeof(block),
  19118. ",%s\"queue\" : {%s"
  19119. "\"length\" : %i,%s"
  19120. "\"filled\" : %i,%s"
  19121. "\"maxFilled\" : %i,%s"
  19122. "\"full\" : %s%s"
  19123. "}",
  19124. eol,
  19125. eol,
  19126. ctx->sq_size,
  19127. eol,
  19128. ctx->sq_head - ctx->sq_tail,
  19129. eol,
  19130. ctx->sq_max_fill,
  19131. eol,
  19132. (ctx->sq_blocked ? "true" : "false"),
  19133. eol);
  19134. context_info_length += mg_str_append(&buffer, end, block);
  19135. #endif
  19136. /* Requests information */
  19137. mg_snprintf(NULL,
  19138. NULL,
  19139. block,
  19140. sizeof(block),
  19141. ",%s\"requests\" : {%s"
  19142. "\"total\" : %lu%s"
  19143. "}",
  19144. eol,
  19145. eol,
  19146. (unsigned long)ctx->total_requests,
  19147. eol);
  19148. context_info_length += mg_str_append(&buffer, end, block);
  19149. /* Data information */
  19150. total_data_read =
  19151. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19152. total_data_written =
  19153. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19154. mg_snprintf(NULL,
  19155. NULL,
  19156. block,
  19157. sizeof(block),
  19158. ",%s\"data\" : {%s"
  19159. "\"read\" : %" INT64_FMT ",%s"
  19160. "\"written\" : %" INT64_FMT "%s"
  19161. "}",
  19162. eol,
  19163. eol,
  19164. total_data_read,
  19165. eol,
  19166. total_data_written,
  19167. eol);
  19168. context_info_length += mg_str_append(&buffer, end, block);
  19169. /* Execution time information */
  19170. gmt_time_string(start_time_str,
  19171. sizeof(start_time_str) - 1,
  19172. &start_time);
  19173. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19174. mg_snprintf(NULL,
  19175. NULL,
  19176. block,
  19177. sizeof(block),
  19178. ",%s\"time\" : {%s"
  19179. "\"uptime\" : %.0f,%s"
  19180. "\"start\" : \"%s\",%s"
  19181. "\"now\" : \"%s\"%s"
  19182. "}",
  19183. eol,
  19184. eol,
  19185. difftime(now, start_time),
  19186. eol,
  19187. start_time_str,
  19188. eol,
  19189. now_str,
  19190. eol);
  19191. context_info_length += mg_str_append(&buffer, end, block);
  19192. }
  19193. /* Terminate string */
  19194. if (append_eoobj) {
  19195. strcat(append_eoobj, eoobj);
  19196. }
  19197. context_info_length += sizeof(eoobj) - 1;
  19198. return (int)context_info_length;
  19199. #else
  19200. (void)ctx;
  19201. if ((buffer != NULL) && (buflen > 0)) {
  19202. *buffer = 0;
  19203. }
  19204. return 0;
  19205. #endif
  19206. }
  19207. CIVETWEB_API void
  19208. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19209. {
  19210. /* https://github.com/civetweb/civetweb/issues/727 */
  19211. if (conn != NULL) {
  19212. conn->must_close = 1;
  19213. }
  19214. }
  19215. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19216. /* Get connection information. It can be printed or stored by the caller.
  19217. * Return the size of available information. */
  19218. CIVETWEB_API int
  19219. mg_get_connection_info(const struct mg_context *ctx,
  19220. int idx,
  19221. char *buffer,
  19222. int buflen)
  19223. {
  19224. const struct mg_connection *conn;
  19225. const struct mg_request_info *ri;
  19226. char *end, *append_eoobj = NULL, block[256];
  19227. size_t connection_info_length = 0;
  19228. int state = 0;
  19229. const char *state_str = "unknown";
  19230. #if defined(_WIN32)
  19231. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19232. #else
  19233. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19234. #endif
  19235. if ((buffer == NULL) || (buflen < 1)) {
  19236. buflen = 0;
  19237. end = buffer;
  19238. } else {
  19239. *buffer = 0;
  19240. end = buffer + buflen;
  19241. }
  19242. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19243. /* has enough space to append eoobj */
  19244. append_eoobj = buffer;
  19245. end -= sizeof(eoobj) - 1;
  19246. }
  19247. if ((ctx == NULL) || (idx < 0)) {
  19248. /* Parameter error */
  19249. return 0;
  19250. }
  19251. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  19252. /* Out of range */
  19253. return 0;
  19254. }
  19255. /* Take connection [idx]. This connection is not locked in
  19256. * any way, so some other thread might use it. */
  19257. conn = (ctx->worker_connections) + idx;
  19258. /* Initialize output string */
  19259. connection_info_length += mg_str_append(&buffer, end, "{");
  19260. /* Init variables */
  19261. ri = &(conn->request_info);
  19262. #if defined(USE_SERVER_STATS)
  19263. state = conn->conn_state;
  19264. /* State as string */
  19265. switch (state) {
  19266. case 0:
  19267. state_str = "undefined";
  19268. break;
  19269. case 1:
  19270. state_str = "not used";
  19271. break;
  19272. case 2:
  19273. state_str = "init";
  19274. break;
  19275. case 3:
  19276. state_str = "ready";
  19277. break;
  19278. case 4:
  19279. state_str = "processing";
  19280. break;
  19281. case 5:
  19282. state_str = "processed";
  19283. break;
  19284. case 6:
  19285. state_str = "to close";
  19286. break;
  19287. case 7:
  19288. state_str = "closing";
  19289. break;
  19290. case 8:
  19291. state_str = "closed";
  19292. break;
  19293. case 9:
  19294. state_str = "done";
  19295. break;
  19296. }
  19297. #endif
  19298. /* Connection info */
  19299. if ((state >= 3) && (state < 9)) {
  19300. mg_snprintf(NULL,
  19301. NULL,
  19302. block,
  19303. sizeof(block),
  19304. "%s\"connection\" : {%s"
  19305. "\"remote\" : {%s"
  19306. "\"protocol\" : \"%s\",%s"
  19307. "\"addr\" : \"%s\",%s"
  19308. "\"port\" : %u%s"
  19309. "},%s"
  19310. "\"handled_requests\" : %u%s"
  19311. "}",
  19312. eol,
  19313. eol,
  19314. eol,
  19315. get_proto_name(conn),
  19316. eol,
  19317. ri->remote_addr,
  19318. eol,
  19319. ri->remote_port,
  19320. eol,
  19321. eol,
  19322. conn->handled_requests,
  19323. eol);
  19324. connection_info_length += mg_str_append(&buffer, end, block);
  19325. }
  19326. /* Request info */
  19327. if ((state >= 4) && (state < 6)) {
  19328. mg_snprintf(NULL,
  19329. NULL,
  19330. block,
  19331. sizeof(block),
  19332. "%s%s\"request_info\" : {%s"
  19333. "\"method\" : \"%s\",%s"
  19334. "\"uri\" : \"%s\",%s"
  19335. "\"query\" : %s%s%s%s"
  19336. "}",
  19337. (connection_info_length > 1 ? "," : ""),
  19338. eol,
  19339. eol,
  19340. ri->request_method,
  19341. eol,
  19342. ri->request_uri,
  19343. eol,
  19344. ri->query_string ? "\"" : "",
  19345. ri->query_string ? ri->query_string : "null",
  19346. ri->query_string ? "\"" : "",
  19347. eol);
  19348. connection_info_length += mg_str_append(&buffer, end, block);
  19349. }
  19350. /* Execution time information */
  19351. if ((state >= 2) && (state < 9)) {
  19352. char start_time_str[64] = {0};
  19353. char close_time_str[64] = {0};
  19354. time_t start_time = conn->conn_birth_time;
  19355. time_t close_time = 0;
  19356. double time_diff;
  19357. gmt_time_string(start_time_str,
  19358. sizeof(start_time_str) - 1,
  19359. &start_time);
  19360. #if defined(USE_SERVER_STATS)
  19361. close_time = conn->conn_close_time;
  19362. #endif
  19363. if (close_time != 0) {
  19364. time_diff = difftime(close_time, start_time);
  19365. gmt_time_string(close_time_str,
  19366. sizeof(close_time_str) - 1,
  19367. &close_time);
  19368. } else {
  19369. time_t now = time(NULL);
  19370. time_diff = difftime(now, start_time);
  19371. close_time_str[0] = 0; /* or use "now" ? */
  19372. }
  19373. mg_snprintf(NULL,
  19374. NULL,
  19375. block,
  19376. sizeof(block),
  19377. "%s%s\"time\" : {%s"
  19378. "\"uptime\" : %.0f,%s"
  19379. "\"start\" : \"%s\",%s"
  19380. "\"closed\" : \"%s\"%s"
  19381. "}",
  19382. (connection_info_length > 1 ? "," : ""),
  19383. eol,
  19384. eol,
  19385. time_diff,
  19386. eol,
  19387. start_time_str,
  19388. eol,
  19389. close_time_str,
  19390. eol);
  19391. connection_info_length += mg_str_append(&buffer, end, block);
  19392. }
  19393. /* Remote user name */
  19394. if ((ri->remote_user) && (state < 9)) {
  19395. mg_snprintf(NULL,
  19396. NULL,
  19397. block,
  19398. sizeof(block),
  19399. "%s%s\"user\" : {%s"
  19400. "\"name\" : \"%s\",%s"
  19401. "}",
  19402. (connection_info_length > 1 ? "," : ""),
  19403. eol,
  19404. eol,
  19405. ri->remote_user,
  19406. eol);
  19407. connection_info_length += mg_str_append(&buffer, end, block);
  19408. }
  19409. /* Data block */
  19410. if (state >= 3) {
  19411. mg_snprintf(NULL,
  19412. NULL,
  19413. block,
  19414. sizeof(block),
  19415. "%s%s\"data\" : {%s"
  19416. "\"read\" : %" INT64_FMT ",%s"
  19417. "\"written\" : %" INT64_FMT "%s"
  19418. "}",
  19419. (connection_info_length > 1 ? "," : ""),
  19420. eol,
  19421. eol,
  19422. conn->consumed_content,
  19423. eol,
  19424. conn->num_bytes_sent,
  19425. eol);
  19426. connection_info_length += mg_str_append(&buffer, end, block);
  19427. }
  19428. /* State */
  19429. mg_snprintf(NULL,
  19430. NULL,
  19431. block,
  19432. sizeof(block),
  19433. "%s%s\"state\" : \"%s\"",
  19434. (connection_info_length > 1 ? "," : ""),
  19435. eol,
  19436. state_str);
  19437. connection_info_length += mg_str_append(&buffer, end, block);
  19438. /* Terminate string */
  19439. if (append_eoobj) {
  19440. strcat(append_eoobj, eoobj);
  19441. }
  19442. connection_info_length += sizeof(eoobj) - 1;
  19443. return (int)connection_info_length;
  19444. }
  19445. #if 0
  19446. /* Get handler information. It can be printed or stored by the caller.
  19447. * Return the size of available information. */
  19448. CIVETWEB_API int
  19449. mg_get_handler_info(struct mg_context *ctx,
  19450. char *buffer,
  19451. int buflen)
  19452. {
  19453. int handler_info_len = 0;
  19454. struct mg_handler_info *tmp_rh;
  19455. mg_lock_context(ctx);
  19456. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19457. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19458. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19459. }
  19460. handler_info_len += tmp_rh->uri_len;
  19461. switch (tmp_rh->handler_type) {
  19462. case REQUEST_HANDLER:
  19463. (void)tmp_rh->handler;
  19464. break;
  19465. case WEBSOCKET_HANDLER:
  19466. (void)tmp_rh->connect_handler;
  19467. (void) tmp_rh->ready_handler;
  19468. (void) tmp_rh->data_handler;
  19469. (void) tmp_rh->close_handler;
  19470. break;
  19471. case AUTH_HANDLER:
  19472. (void) tmp_rh->auth_handler;
  19473. break;
  19474. }
  19475. (void)cbdata;
  19476. }
  19477. mg_unlock_context(ctx);
  19478. return handler_info_len;
  19479. }
  19480. #endif
  19481. #endif
  19482. /* Initialize this library. This function does not need to be thread safe.
  19483. */
  19484. CIVETWEB_API unsigned
  19485. mg_init_library(unsigned features)
  19486. {
  19487. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19488. unsigned features_inited = features_to_init;
  19489. if (mg_init_library_called <= 0) {
  19490. /* Not initialized yet */
  19491. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19492. return 0;
  19493. }
  19494. }
  19495. mg_global_lock();
  19496. if (mg_init_library_called <= 0) {
  19497. int i, len;
  19498. #if defined(_WIN32)
  19499. int file_mutex_init = 1;
  19500. int wsa = 1;
  19501. #else
  19502. int mutexattr_init = 1;
  19503. #endif
  19504. int failed = 1;
  19505. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19506. if (key_create == 0) {
  19507. #if defined(_WIN32)
  19508. file_mutex_init =
  19509. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19510. if (file_mutex_init == 0) {
  19511. #ifdef WINSOCK_START
  19512. /* Start WinSock */
  19513. WSADATA data;
  19514. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19515. #else
  19516. failed = wsa = 0;
  19517. #endif
  19518. }
  19519. #else
  19520. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19521. if (mutexattr_init == 0) {
  19522. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19523. PTHREAD_MUTEX_RECURSIVE);
  19524. }
  19525. #endif
  19526. }
  19527. if (failed) {
  19528. #if defined(_WIN32)
  19529. if (wsa == 0) {
  19530. #ifdef WINSOCK_START
  19531. (void)WSACleanup();
  19532. #endif
  19533. }
  19534. if (file_mutex_init == 0) {
  19535. (void)pthread_mutex_destroy(&global_log_file_lock);
  19536. }
  19537. #else
  19538. if (mutexattr_init == 0) {
  19539. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19540. }
  19541. #endif
  19542. if (key_create == 0) {
  19543. (void)pthread_key_delete(sTlsKey);
  19544. }
  19545. mg_global_unlock();
  19546. (void)pthread_mutex_destroy(&global_lock_mutex);
  19547. return 0;
  19548. }
  19549. len = 1;
  19550. for (i = 0; http_methods[i].name != NULL; i++) {
  19551. size_t sl = strlen(http_methods[i].name);
  19552. len += (int)sl;
  19553. if (i > 0) {
  19554. len += 2;
  19555. }
  19556. }
  19557. all_methods = mg_malloc(len);
  19558. if (!all_methods) {
  19559. /* Must never happen */
  19560. mg_global_unlock();
  19561. (void)pthread_mutex_destroy(&global_lock_mutex);
  19562. return 0;
  19563. }
  19564. all_methods[0] = 0;
  19565. for (i = 0; http_methods[i].name != NULL; i++) {
  19566. if (i > 0) {
  19567. strcat(all_methods, ", ");
  19568. strcat(all_methods, http_methods[i].name);
  19569. } else {
  19570. strcpy(all_methods, http_methods[i].name);
  19571. }
  19572. }
  19573. }
  19574. #if defined(USE_LUA)
  19575. lua_init_optional_libraries();
  19576. #endif
  19577. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19578. || defined(OPENSSL_API_3_0)) \
  19579. && !defined(NO_SSL)
  19580. if (features_to_init & MG_FEATURES_SSL) {
  19581. if (!mg_openssl_initialized) {
  19582. char ebuf[128];
  19583. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19584. mg_openssl_initialized = 1;
  19585. } else {
  19586. (void)ebuf;
  19587. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19588. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19589. }
  19590. } else {
  19591. /* ssl already initialized */
  19592. }
  19593. }
  19594. #endif
  19595. if (mg_init_library_called <= 0) {
  19596. mg_init_library_called = 1;
  19597. } else {
  19598. mg_init_library_called++;
  19599. }
  19600. mg_global_unlock();
  19601. return features_inited;
  19602. }
  19603. /* Un-initialize this library. */
  19604. CIVETWEB_API unsigned
  19605. mg_exit_library(void)
  19606. {
  19607. if (mg_init_library_called <= 0) {
  19608. return 0;
  19609. }
  19610. mg_global_lock();
  19611. mg_init_library_called--;
  19612. if (mg_init_library_called == 0) {
  19613. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19614. if (mg_openssl_initialized) {
  19615. uninitialize_openssl();
  19616. mg_openssl_initialized = 0;
  19617. }
  19618. #endif
  19619. #if defined(_WIN32)
  19620. #ifdef WINSOCK_START
  19621. (void)WSACleanup();
  19622. #endif
  19623. (void)pthread_mutex_destroy(&global_log_file_lock);
  19624. #else
  19625. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19626. #endif
  19627. (void)pthread_key_delete(sTlsKey);
  19628. #if defined(USE_LUA)
  19629. lua_exit_optional_libraries();
  19630. #endif
  19631. mg_free(all_methods);
  19632. all_methods = NULL;
  19633. mg_global_unlock();
  19634. (void)pthread_mutex_destroy(&global_lock_mutex);
  19635. return 1;
  19636. }
  19637. mg_global_unlock();
  19638. return 1;
  19639. }
  19640. /* End of civetweb.c */